mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 07:38:43 +01:00
* feat(widget): one conversation with Loki; Watch is in the header for anyone who owns the site The panel was three tools sharing a box: Request a change (a form), Ask Loki (an advisor) and Chat, behind tabs and scope chips, each with a history that vanished on close - and Watch could only be switched on by arriving through one link on the project page in Loki, so an owner simply visiting their site never saw it. Now: - One thread (widget/conversation.ts). Type, speak, paste a screenshot or point at an element; Loki answers about this page (one tap: whole site). Every suggested change, and your own message as written, has Send to builder / Build this, which opens a confirmation card in the thread; the receipt (building / track link) lands in the thread. - The thread is kept per tab (widget/thread.ts, validated on restore), so it survives the site's own page loads. - Watch in the header: Review for the owner; for anyone else an explainer with "This is my site - sign in with Loki", via GET /api/widget/owner, which checks ownership of the widget's project and returns to the same page with a pass. The return URL must be on the project's own site (ownerReturnUrl), so the route cannot hand a pass to someone else's page; a non-owner lands back with a plain explanation. - data-fc-modes now only picks who answers: advisor (default), the studio concierge (chat), or none (report). The owner always gets the advisor. - widget/loki-api.ts holds the two calls; advise.ts and chat.ts are gone. Tests: widget-thread (new), owner-note-builds (return-URL guard), widget-embed-browser 41/41, widget-watch-browser 40/40, widget-host-avoid-browser 24/24. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(widget): style guard follows the panel's real controls; comment no longer reads as an import Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
316 lines
14 KiB
TypeScript
316 lines
14 KiB
TypeScript
// Watch mode in a real browser: the owner sees "Loki is watching" the whole
|
|
// time; a request the site makes that fails with a 500 files ONE report with
|
|
// the trail (the tap that led there included, the typed value excluded);
|
|
// Pause stops it, and paused, a failure files nothing. A visitor without the
|
|
// owner pass gets no pill and no recording at all.
|
|
// Run: npx tsx scripts/test/widget-watch-browser.ts
|
|
import { build } from "esbuild";
|
|
import { chromium, type Browser, type Page } from "playwright";
|
|
import { PALETTE } from "../../src/lib/palette";
|
|
|
|
let pass = 0;
|
|
let fail = 0;
|
|
function ok(cond: boolean, label: string) {
|
|
if (cond) pass++;
|
|
else {
|
|
fail++;
|
|
console.error(`✗ ${label}`);
|
|
}
|
|
}
|
|
|
|
const ORIGIN = "http://host.fixture";
|
|
const SITE = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Shop</title>
|
|
<meta name="viewport" content="width=device-width,initial-scale=1"></head><body>
|
|
<main><h1>Shop</h1><input id="email" placeholder="Your email">
|
|
<button id="buy">Buy now</button><button id="dead">Save</button><button id="ok">Refresh</button>
|
|
<button id="find">Find a size</button><button id="icon"><svg width="10" height="10"></svg></button>
|
|
<img src="/shop/hero.png" width="40" height="40"><button id="jank">Load more</button></main>
|
|
<script>document.getElementById("buy").onclick = () => fetch("/shop/checkout?token=secret", { method: "POST" });
|
|
document.getElementById("ok").onclick = () => fetch("/shop/ok");
|
|
document.getElementById("find").onclick = () => fetch("/shop/sizes?user=secret");
|
|
// A janky "Load more": freezes the main thread, then pushes everything down.
|
|
document.getElementById("jank").onclick = () => {
|
|
const until = performance.now() + 450; while (performance.now() < until) {}
|
|
setTimeout(() => { const b = document.createElement("div"); b.style.height = "320px";
|
|
b.textContent = "Banner"; document.querySelector("main").prepend(b); }, 900);
|
|
};</script>
|
|
<script src="${ORIGIN}/widget.js" data-fc-project="fcw_fixture" async></script></body></html>`;
|
|
|
|
type Report = { suggestion: string; ownerPass?: string };
|
|
type Advice = { question: string; scope: string; session?: string };
|
|
|
|
async function open(browser: Browser, js: string, hash: string) {
|
|
const ctx = await browser.newContext({ viewport: { width: 390, height: 800 } });
|
|
const p = await ctx.newPage();
|
|
const errors: string[] = [];
|
|
const reports: Report[] = [];
|
|
const advice: Advice[] = [];
|
|
p.on("pageerror", (e) => errors.push(e.message));
|
|
await p.route(`${ORIGIN}/**`, async (route) => {
|
|
const url = new URL(route.request().url());
|
|
const json = (body: unknown, status = 200) =>
|
|
route.fulfill({ status, body: JSON.stringify(body), contentType: "application/json" });
|
|
if (url.pathname === "/widget.js")
|
|
return route.fulfill({ body: js, contentType: "text/javascript" });
|
|
if (url.pathname === "/api/widget-boot") {
|
|
return json({
|
|
active: true,
|
|
placement: { corner: "bottom-right", offsetX: 16, offsetY: 16, autoAvoid: true },
|
|
theme: PALETTE.widget,
|
|
});
|
|
}
|
|
if (url.pathname === "/api/feedback") {
|
|
reports.push(JSON.parse(route.request().postData() ?? "{}") as Report);
|
|
return json({ ok: true, owner: true, building: true });
|
|
}
|
|
if (url.pathname === "/shop/checkout") return json({ error: "boom" }, 500);
|
|
if (url.pathname === "/api/widget/advise") {
|
|
advice.push(JSON.parse(route.request().postData() ?? "{}") as Advice);
|
|
return json({
|
|
ok: true,
|
|
reply: "You were looking for a size. **Errors:** the size lookup 404s.",
|
|
changes: ["Make “Find a size” show the size chart instead of failing"],
|
|
});
|
|
}
|
|
if (url.pathname === "/shop/ok") return json({ ok: true });
|
|
if (url.pathname === "/shop/sizes") return json({ error: "not found" }, 404);
|
|
if (url.pathname === "/shop/hero.png") return route.fulfill({ status: 404, body: "" });
|
|
return route.fulfill({ body: SITE, contentType: "text/html" });
|
|
});
|
|
await p.goto(`${ORIGIN}/${hash}`);
|
|
await p.waitForTimeout(1000);
|
|
return { p, errors, reports, advice, close: () => ctx.close() };
|
|
}
|
|
|
|
/** The recorded trail, as the tab keeps it across page loads. */
|
|
const trailText = (p: Page) =>
|
|
p.evaluate(() => sessionStorage.getItem("loki-watch-trail:fcw_fixture") ?? "");
|
|
|
|
/** Click a pill button by its label — the pill's buttons are Review, Report, Pause. */
|
|
const clickPill = (p: Page, label: string) =>
|
|
p.evaluate((label) => {
|
|
const r = document.getElementById("loki-feedback-host")!.shadowRoot!;
|
|
const btn = Array.from(r.querySelectorAll(".watch-pill .wbtn")).find(
|
|
(b) => (b as HTMLElement).innerText.trim() === label,
|
|
) as HTMLElement | undefined;
|
|
if (!btn) throw new Error(`no pill button "${label}"`);
|
|
btn.click();
|
|
}, label);
|
|
|
|
const pillText = (p: Page) =>
|
|
p.evaluate(() => {
|
|
const el = document
|
|
.getElementById("loki-feedback-host")
|
|
?.shadowRoot?.querySelector(".watch-pill .wtext") as HTMLElement | null;
|
|
return el?.innerText ?? null;
|
|
});
|
|
/** The pill's last button is Pause / Resume (Report sits before it). */
|
|
const clickPillButton = (p: Page) =>
|
|
p.evaluate(() => {
|
|
const all = document
|
|
.getElementById("loki-feedback-host")!
|
|
.shadowRoot!.querySelectorAll(".watch-pill .wbtn");
|
|
(all[all.length - 1] as HTMLElement).click();
|
|
});
|
|
|
|
async function main() {
|
|
let browser: Browser;
|
|
try {
|
|
browser = await chromium.launch(
|
|
process.env.PW_CHROMIUM ? { executablePath: process.env.PW_CHROMIUM } : {},
|
|
);
|
|
} catch (err) {
|
|
const why = err instanceof Error ? err.message.split("\n")[0] : String(err);
|
|
if (process.env.CI) {
|
|
console.error(`✗ Chromium is required under CI and could not launch: ${why}`);
|
|
process.exit(1);
|
|
}
|
|
console.log(`↷ skipped: no Chromium on this machine (${why}). CI runs it.`);
|
|
process.exit(0);
|
|
}
|
|
const out = await build({
|
|
entryPoints: ["widget/main.ts"],
|
|
bundle: true,
|
|
format: "iife",
|
|
write: false,
|
|
logLevel: "silent",
|
|
});
|
|
const js = out.outputFiles[0].text;
|
|
|
|
// ---- the owner: watched, visibly, and a failure files one report ----
|
|
{
|
|
const s = await open(browser, js, "#loki-owner=pass123");
|
|
// The owner link opens the note panel; close it to use the page.
|
|
await s.p.keyboard.press("Escape");
|
|
ok(
|
|
(await pillText(s.p))?.startsWith("Loki is watching") === true,
|
|
"owner sees the watching pill",
|
|
);
|
|
await s.p.fill("#email", "me@example.com");
|
|
await s.p.click("#email");
|
|
await s.p.click("#buy");
|
|
await s.p.waitForTimeout(600);
|
|
await s.p.click("#buy");
|
|
await s.p.waitForTimeout(600);
|
|
ok(s.reports.length === 1, `one report for one cause (got ${s.reports.length})`);
|
|
const r = s.reports[0]?.suggestion ?? "";
|
|
ok(r.includes("POST /shop/checkout → 500"), "the report names the failed request");
|
|
ok(r.includes("button “Buy now”"), "the report carries the tap that led there");
|
|
ok(!r.includes("me@example.com"), "what was typed never leaves the page");
|
|
ok(!r.includes("token=secret"), "query strings never leave the page");
|
|
ok(s.reports[0]?.ownerPass === "pass123", "the report is the owner's, so it starts a fix");
|
|
ok(
|
|
(await pillText(s.p))?.includes("Loki is fixing") === true,
|
|
"the pill says it is being fixed",
|
|
);
|
|
ok(s.errors.length === 0, `no page errors (${s.errors.join("; ")})`);
|
|
await s.close();
|
|
}
|
|
|
|
// ---- a button that does nothing, and one that works ----
|
|
{
|
|
const s = await open(browser, js, "#loki-owner=pass123");
|
|
await s.p.keyboard.press("Escape");
|
|
for (let i = 0; i < 3; i++) await s.p.click("#ok");
|
|
await s.p.waitForTimeout(400);
|
|
ok(s.reports.length === 0, "a working button tapped three times is not reported");
|
|
for (let i = 0; i < 3; i++) await s.p.click("#dead");
|
|
await s.p.waitForTimeout(400);
|
|
ok(s.reports.length === 1, `a dead button files one report (got ${s.reports.length})`);
|
|
ok(
|
|
(s.reports[0]?.suggestion ?? "").includes(
|
|
"tapped button “Save” three times and nothing happened",
|
|
),
|
|
"the report says which button did nothing",
|
|
);
|
|
// Report opens the note with the trail attached.
|
|
await clickPill(s.p, "Report");
|
|
await s.p.waitForTimeout(300);
|
|
const opened = await s.p.evaluate(() => {
|
|
const r = document.getElementById("loki-feedback-host")!.shadowRoot!;
|
|
const diag = r.querySelector(".diag") as HTMLElement | null;
|
|
return !!r.querySelector(".panel") && diag?.style.display === "block";
|
|
});
|
|
ok(opened, "Report opens the note with the trail attached");
|
|
await s.close();
|
|
}
|
|
|
|
// ---- Review: Loki judges what the owner did, from evidence ----
|
|
{
|
|
const s = await open(browser, js, "#loki-owner=pass123");
|
|
await s.p.keyboard.press("Escape");
|
|
await s.p.fill("#email", "me@example.com");
|
|
// Tap the FILLED field: a tap on a field is recorded, its value never is.
|
|
// (fill() alone types without a tap, which once made this check vacuous.)
|
|
await s.p.click("#email");
|
|
await s.p.click("#find");
|
|
await s.p.waitForTimeout(500);
|
|
ok(
|
|
(await pillText(s.p))?.includes("noticed") === true,
|
|
`a 404 is noticed on the pill (${await pillText(s.p)})`,
|
|
);
|
|
ok(s.reports.length === 0, "a 404 is a remark, not an automatic fix");
|
|
ok(s.advice.length === 0, "no model runs until Review is pressed");
|
|
|
|
// A trail survives a full page load: a multi-page site is one visit.
|
|
await s.p.reload();
|
|
await s.p.waitForTimeout(1000);
|
|
await clickPill(s.p, "Review");
|
|
await s.p.waitForTimeout(800);
|
|
const a = s.advice[0];
|
|
ok(s.advice.length === 1, `Review asks Loki once (got ${s.advice.length})`);
|
|
const session = a?.session ?? "";
|
|
ok(/^Review what I just did/.test(a?.question ?? ""), "Review asks for a review");
|
|
ok(session.includes("tap button “Find a size”"), "the session carries the tap");
|
|
ok(session.includes("GET /shop/sizes → 404"), "and what the page answered");
|
|
ok(/page \/[\s\S]*page \//.test(session), "and both page loads — the trail survived reload");
|
|
ok(
|
|
session.includes("no name a screen reader can read"),
|
|
"page checks: the unnamed icon button",
|
|
);
|
|
ok(session.includes("no alt text"), "page checks: the image without alt");
|
|
ok(session.includes("failed to load"), "page checks: the broken image");
|
|
ok(!session.includes("me@example.com"), "what was typed never leaves the page");
|
|
ok(!session.includes("user=secret"), "query strings never leave the page");
|
|
const shown = await s.p.evaluate(() => {
|
|
const r = document.getElementById("loki-feedback-host")!.shadowRoot!;
|
|
return {
|
|
reply: (
|
|
Array.from(r.querySelectorAll(".convo .msg.from-loki")).pop() as HTMLElement | undefined
|
|
)?.innerText,
|
|
change: (r.querySelector(".convo .change-text") as HTMLElement | null)?.innerText,
|
|
};
|
|
});
|
|
ok(
|
|
shown.reply?.includes("looking for a size") === true,
|
|
"the review is shown in the conversation",
|
|
);
|
|
ok(shown.change?.includes("size chart") === true, "with its change one tap away");
|
|
|
|
// Requesting that change carries the session's steps to the builder.
|
|
await s.p.evaluate(() => {
|
|
const r = document.getElementById("loki-feedback-host")!.shadowRoot!;
|
|
(r.querySelector(".convo .change-send") as HTMLElement).click();
|
|
});
|
|
await s.p.waitForTimeout(200);
|
|
const report = await s.p.evaluate(() => {
|
|
const r = document.getElementById("loki-feedback-host")!.shadowRoot!;
|
|
return {
|
|
text: (r.querySelector(".sendcard textarea") as HTMLTextAreaElement | null)?.value,
|
|
diag: (r.querySelector(".sendcard .diag") as HTMLElement | null)?.style.display,
|
|
};
|
|
});
|
|
ok(report.text?.includes("size chart") === true, "the change prefills the request");
|
|
ok(report.diag === "block", "with the watched steps attached");
|
|
// Loki's own panel opening is not the site's layout shift, and Loki's own
|
|
// boot and page reading are not the site freezing.
|
|
const after = await trailText(s.p);
|
|
ok(!after.includes("jumped around"), `Loki's panel is not blamed for a shift (${after})`);
|
|
ok(!after.includes("froze"), "nor Loki's own work for a freeze");
|
|
ok(s.errors.length === 0, `no page errors (${s.errors.join("; ")})`);
|
|
await s.close();
|
|
}
|
|
|
|
// ---- the site's own jank IS noticed (a detector that never fires reads as clean) ----
|
|
{
|
|
const s = await open(browser, js, "#loki-owner=pass123");
|
|
await s.p.keyboard.press("Escape");
|
|
await s.p.click("#jank");
|
|
await s.p.waitForTimeout(1600);
|
|
const t = await trailText(s.p);
|
|
ok(/after button “Load more” the page froze for \d+ms/.test(t), `a felt freeze (${t})`);
|
|
ok(t.includes("content jumped around on this page"), "and the content pushed down");
|
|
ok(s.reports.length === 0, "jank is a remark for Review, not an automatic fix");
|
|
await s.close();
|
|
}
|
|
|
|
// ---- paused: says so, and records nothing ----
|
|
{
|
|
const s = await open(browser, js, "#loki-owner=pass123");
|
|
await s.p.keyboard.press("Escape");
|
|
await clickPillButton(s.p);
|
|
ok((await pillText(s.p))?.startsWith("Loki paused") === true, "pause is visible");
|
|
await s.p.click("#buy");
|
|
await s.p.waitForTimeout(600);
|
|
ok(s.reports.length === 0, "paused, a failure files nothing");
|
|
await clickPillButton(s.p); // leave it resumed for the next context
|
|
await s.close();
|
|
}
|
|
|
|
// ---- a visitor: no pill, no recording ----
|
|
{
|
|
const s = await open(browser, js, "");
|
|
ok((await pillText(s.p)) === null, "a visitor gets no pill");
|
|
await s.p.click("#buy");
|
|
await s.p.waitForTimeout(600);
|
|
ok(s.reports.length === 0, "a visitor's failures are not reported automatically");
|
|
await s.close();
|
|
}
|
|
|
|
await browser.close();
|
|
console.log(`widget-watch-browser: ${pass} passed, ${fail} failed`);
|
|
if (fail) process.exit(1);
|
|
}
|
|
|
|
void main();
|