feat(feedback): Watch the fix tells the story; the reporter gets their own (#1074)

The walkthrough could only show WHERE a change was: it had the report, the
handoff's one line and a PR title. The owner asked for how it was solved,
why so, what the alternatives were and who it helps.

- Design note: every fix prompt asks the agent for a `## Walkthrough`
  section in the PR description (problem, change, why, considered,
  helps, where, a plain line for the reporter). fix-note.ts holds the
  field list once, rendering both the instruction and the parser; the
  fix ledger keeps the parsed note on FixShipping.pr.note.
- Chapters: buildTourBeats turns report + screenshot + note + live steps
  into a ~60s story. The widget plays it with Back / Pause / Next,
  reading time scaled to each caption, the reporter's own screenshot as
  the before picture, and no second click when going back.
- Reporter audience: tour tokens carry an audience inside the signed
  payload (owner tokens unchanged, so old links still work; reporter
  tokens last 7 days). /my-feedback offers "Watch your fix" on a live
  fix. The reporter's story keeps their words, the live demo and the
  plain line — no reasoning, PR or repository.


Claude-Session: https://claude.ai/code/session_01MqXhtjrmVb4vKE6oKSyHVg

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
CatoandClaude authored and GitHub committed 2026-10-07 09:23:57 -07:00
1 parent 227c7529f6
commit c65ead0f6b
17 files changed
+727 -104

No files matched your search

+11
View File
@@ -8,6 +8,17 @@ CHANGELOG.md. Format: `docs/architecture/building-in-public-records.md`.
## 2026-10-07 — The record points both ways
- **Watch the fix tells the whole story.** The walkthrough now plays in
chapters, about a minute long: the report and its screenshot, what was
actually wrong, the change shown live on the page, why it was done that way,
what else was considered and who it helps. Back, Pause and Next set the pace.
It reads the story from a short design note the agent now writes into every
fix's pull request.
- **The person who reported it can watch too.** On "My feedback", a fix that
is live offers "Watch your fix": their own words, the change shown on the
page, and one plain sentence about what changed for them — no pull requests
and no technical reasoning.
- **The roadmap and the changelog link to each other.** A `{#id}` on a
ROADMAP.md step and on the CHANGELOG.md line that delivered it now links
them: each step on `/roadmap` names the changelog days that shipped it, and
+2
View File
@@ -160,6 +160,8 @@ A visitor's note on any fleet site becomes a pull request, a deploy, and a walkt
- [x] One click dispatches an agent; the fix ledger follows the PR to merge and deploy
- [x] The owner's own note starts the build straight from the site
- [x] "Watch the fix": a narrated cursor walks the owner through the change on the live page; a step it cannot show is filed back as a report
- [x] The walkthrough tells the story — what was wrong, why this way, what else was considered, who it helps — from a design note the agent writes with each fix
- [x] The reporter gets their own walkthrough of their fix, in plain words
- [x] Failed runs say why in one sentence
### OrangeCat project handoff
+12
View File
@@ -112,6 +112,11 @@ for (const tone of ["neutral", "accent", "warning", "positive"] satisfies Report
liveHref: "https://example.com/pricing",
});
assert.equal(s.action, null, "offered Check the live page before the fix shipped");
const withTour = reporterStatusFor(deriveFeedbackWork(FEEDBACK_STATUS.DISPATCHED, snap), {
liveHref: "https://example.com/pricing",
tourHref: "https://example.com/pricing#loki-tour=t",
});
assert.equal(withTour.action, null, "offered a walkthrough of a fix that is not live");
assert.ok(!/live/i.test(s.label), `claimed live while the PR was open: ${s.label}`);
}
@@ -122,6 +127,13 @@ for (const tone of ["neutral", "accent", "warning", "positive"] satisfies Report
const s = reporterStatusFor(shipped, { liveHref: "https://example.com/pricing" });
assert.equal(s.tone, "positive");
assert.equal(s.action?.href, "https://example.com/pricing");
// With their own ticket, the reporter is walked through it instead.
const toured = reporterStatusFor(shipped, {
liveHref: "https://example.com/pricing",
tourHref: "https://example.com/pricing#loki-tour=t",
});
assert.equal(toured.action?.label, "Watch your fix");
assert.equal(toured.action?.href, "https://example.com/pricing#loki-tour=t");
}
// No live URL to send them to = no action. An action with nowhere to go is the
+99 -3
View File
@@ -12,9 +12,16 @@ import {
tourSiteUrl,
TOUR_HASH_KEY,
} from "../../src/lib/feedback/tour-token";
import { fallbackTourSteps, parseTourSteps, tourPrompt } from "../../src/lib/feedback/tour-plan";
import {
buildTourBeats,
fallbackTourSteps,
parseTourSteps,
tourOutro,
tourPrompt,
TOUR_CHAPTER,
} from "../../src/lib/feedback/tour-plan";
import { explainRunFailure } from "../../src/lib/feedback/failure-reason";
import { bottomBarInset } from "../../widget/tour";
import { bottomBarInset, readMs } from "../../widget/tour";
// Read at call time, so setting it after the imports is enough.
process.env.AUTH_SECRET ??= "test-secret-for-tour-token";
@@ -24,7 +31,7 @@ process.env.AUTH_SECRET ??= "test-secret-for-tour-token";
const id = "3f0c7a52-1111-4222-8333-944455556666";
const now = Date.now();
const token = createTourToken(id, now);
assert.equal(verifyTourToken(token, now), id);
assert.deepEqual(verifyTourToken(token, now), { feedbackId: id, audience: "owner" });
assert.equal(verifyTourToken(token, now + 25 * 60 * 60 * 1000), null, "expires within a day");
assert.equal(verifyTourToken(`${token}x`, now), null, "a tampered signature is refused");
const [, exp, sig] = token.split(".");
@@ -35,6 +42,26 @@ process.env.AUTH_SECRET ??= "test-secret-for-tour-token";
"rides the fragment",
);
assert.ok(!url.includes("#old"), "the page's own fragment is replaced, not doubled");
// The reporter's ticket: a week, its own audience, and no way to become the owner's.
const forReporter = createTourToken(id, now, "reporter");
assert.deepEqual(verifyTourToken(forReporter, now + 6 * 24 * 60 * 60 * 1000), {
feedbackId: id,
audience: "reporter",
});
assert.equal(verifyTourToken(forReporter, now + 8 * 24 * 60 * 60 * 1000), null);
const [rid, rexp, , rsig] = forReporter.split(".");
assert.equal(
verifyTourToken(`${rid}.${rexp}.${rsig}`, now),
null,
"dropping the mark is refused",
);
assert.equal(verifyTourToken(`${id}.${exp}.r.${sig}`, now), null, "adding the mark is refused");
assert.equal(
verifyTourToken(`${rid}.${rexp}.x.${rsig}`, now),
null,
"an unknown mark is refused",
);
}
// ---- script ----
@@ -110,6 +137,75 @@ const outline = [
assert.doesNotMatch(silent, /builder is online/);
}
// ---- the story: chapters for the owner, plain words for the reporter ----
// 2026-10-07: the owner watched a fix and asked for the walkthrough to show
// "how the problem was solved, why so, what the alternatives were, how it
// benefits users". The reporter gets the same change without the reasoning.
{
const note = {
problem: "The menu link pointed at an anchor that no longer existed.",
change: "The footer now has a Back to top link.",
why: "A footer link is where people look after reading to the end.",
considered: [{ option: "A floating button", whyNot: "it covered the chat widget" }],
helps: "Anyone on a phone at the bottom of a long page.",
where: "The footer.",
plain: "There is now a link at the bottom that takes you straight back up.",
};
const story = {
asked: "Add a back to top link",
note,
didLine: "Added the link.",
steps: [{ target: 3, action: "click" as const, say: "Down here — tap it." }],
before: "data:image/png;base64,AAAA",
};
const owner = buildTourBeats({ ...story, audience: "owner" });
const chapters = owner.map((b) => b.chapter);
for (const c of [
TOUR_CHAPTER.ASKED,
TOUR_CHAPTER.PROBLEM,
TOUR_CHAPTER.CHANGE,
TOUR_CHAPTER.WHY,
TOUR_CHAPTER.CONSIDERED,
TOUR_CHAPTER.HELPS,
])
assert.ok(chapters.includes(c), `owner story has "${c}"`);
assert.ok(
chapters.indexOf(TOUR_CHAPTER.CHANGE) < chapters.indexOf(TOUR_CHAPTER.WHY),
"show the change before arguing for it",
);
assert.equal(owner[0].image, story.before, "the report opens with what it looked like");
assert.ok(
owner.some((b) => b.target === 3 && b.action === "click"),
"the live demo is in it",
);
assert.match(owner.find((b) => b.chapter === TOUR_CHAPTER.CONSIDERED)?.say ?? "", /not chosen/);
const reporter = buildTourBeats({ ...story, audience: "reporter" });
const said = reporter.map((b) => b.say).join(" ");
for (const internal of [note.problem, note.why, note.helps, note.change, "floating button"])
assert.ok(!said.includes(internal), `the reporter is not told: ${internal}`);
assert.ok(said.includes(note.plain), "the reporter gets the plain sentence");
assert.ok(
reporter.some((b) => b.target === 3),
"and the same live demonstration",
);
assert.doesNotMatch(tourOutro("reporter", "Added the link."), /Added the link/);
// No note (a PR from before it was asked for): the owner still gets a story.
const bare = buildTourBeats({ ...story, note: null, before: null, audience: "owner" });
assert.deepEqual(
bare.map((b) => b.chapter),
[TOUR_CHAPTER.ASKED, TOUR_CHAPTER.CHANGE, TOUR_CHAPTER.CHANGE],
);
assert.equal(bare[1].say, "Added the link.", "falls back to the handoff's line");
// Roughly a minute for a full story, never a blink per beat.
assert.equal(readMs("Short."), 3200);
assert.equal(readMs("word ".repeat(200)), 9500);
const total = owner.reduce((ms, b) => ms + readMs(b.say), 0);
assert.ok(total > 25_000 && total < 90_000, `a full owner story reads in ~a minute (${total}ms)`);
}
// ---- caption clears the host's bottom bar ----
// 2026-10-07: on Substrata at 390px the phone tab bar and the floating ASK
// button sat on top of the caption and its "Looks right" button.
+102
View File
@@ -0,0 +1,102 @@
// The design note a fix carries in its PR description (src/lib/feedback/fix-note.ts):
// the instruction the agent gets and the parser that reads it back must agree,
// and a PR without the section must read as "no note", never as a half note.
import assert from "node:assert/strict";
import {
fixNoteInstruction,
parseFixNote,
FIX_NOTE_HEADING,
} from "../../src/lib/feedback/fix-note";
import { deriveShippingFromPr } from "../../src/lib/feedback/fix-shipping";
// ---- a well-formed note ----
{
const body = [
"Fixes the overlap.",
"",
"## Walkthrough",
"- Problem: The caption card had no stacking order, so the site's tab bar drew over it.",
"- Change: The caption now sits above everything and rises clear of a bottom tab bar.",
"- Why: The tour is something the owner started on purpose; it should win.",
"- Considered: Hide the site's tab bar during the tour — changes their page under them",
"- Considered: Move the caption to the top — covers the headline the tour points at",
"- Helps: Anyone watching a fix on a phone.",
"- Where: The caption at the bottom of the screen during a walkthrough.",
"- For the reporter: The walkthrough card no longer hides behind the menu bar.",
"",
"## Verification",
"- Problem: not part of the note",
].join("\n");
const note = parseFixNote(body);
assert.ok(note);
assert.match(note.problem ?? "", /no stacking order/);
assert.match(note.change ?? "", /rises clear/);
assert.equal(note.considered.length, 2);
assert.equal(note.considered[0].option, "Hide the site's tab bar during the tour");
assert.match(note.considered[0].whyNot ?? "", /changes their page/);
assert.match(note.plain ?? "", /no longer hides/);
assert.match(note.where ?? "", /bottom of the screen/);
}
// ---- tolerant of how agents actually write markdown ----
{
const note = parseFixNote(
[
"### walkthrough",
"**Problem**: wrapped over",
" two lines.",
"* Change: bold labels and star bullets",
].join("\r\n"),
);
assert.equal(note?.problem, "wrapped over two lines.");
assert.equal(note?.change, "bold labels and star bullets");
}
// ---- absent, empty or placeholder-only reads as no note ----
assert.equal(parseFixNote(null), null);
assert.equal(parseFixNote("Just a description."), null);
assert.equal(parseFixNote(`## ${FIX_NOTE_HEADING}\n- Problem: <what was actually wrong>`), null);
// ---- the instruction lists every label the parser reads ----
{
const instruction = fixNoteInstruction();
const filled = instruction
.split("\n")
.filter((l) => l.startsWith("- "))
.map((l) => l.replace(/<[^>]*>/, "filled in"))
.join("\n");
const note = parseFixNote(`## ${FIX_NOTE_HEADING}\n${filled}`);
assert.ok(note);
for (const k of ["problem", "change", "why", "helps", "where", "plain"] as const)
assert.equal(note[k], "filled in", `instruction and parser agree on ${k}`);
assert.equal(note.considered[0]?.option, "filled in");
}
// ---- caps: at most three alternatives, fields bounded ----
{
const many = Array.from({ length: 6 }, (_, i) => `- Considered: option ${i} — no`).join("\n");
const note = parseFixNote(`## Walkthrough\n${many}\n- Why: ${"x".repeat(2000)}`);
assert.equal(note?.considered.length, 3);
assert.ok((note?.why ?? "").length <= 400);
}
// ---- the ledger keeps it ----
{
const fix = deriveShippingFromPr(
{
number: 7,
html_url: "https://github.com/o/r/pull/7",
title: "fix",
state: "open",
merged_at: null,
merge_commit_sha: null,
body: "## Walkthrough\n- Change: kept on the ledger",
},
null,
"2026-10-07T00:00:00Z",
);
assert.equal(fix.pr?.note?.change, "kept on the ledger");
}
console.log("fix-note: ok");
+22 -9
View File
@@ -14,8 +14,10 @@ import { stripReasoning } from "@/lib/agent/llm";
import { checkAiBudget, recordAiSpend } from "@/lib/ai-budget/gate";
import { verifyTourToken } from "@/lib/feedback/tour-token";
import {
buildTourBeats,
fallbackTourSteps,
parseTourSteps,
tourOutro,
tourPrompt,
tourSystemPrompt,
type TourInput,
@@ -100,8 +102,9 @@ export async function POST(req: NextRequest) {
if (!parsed.success) return corsJson({ error: "Invalid walkthrough request" }, 400);
const data = parsed.data;
const feedbackId = verifyTourToken(data.t);
if (!feedbackId) return corsJson({ error: "This walkthrough link has expired" }, 403);
const ticket = verifyTourToken(data.t);
if (!ticket) return corsJson({ error: "This walkthrough link has expired" }, 403);
const { feedbackId, audience } = ticket;
const row = await getFeedbackForTour(feedbackId);
if (!row) return corsJson({ error: "Feedback not found" }, 404);
const f = row.feedback;
@@ -149,6 +152,8 @@ export async function POST(req: NextRequest) {
prTitle: fix?.pr?.title ?? null,
selectors: (f.selectedElements ?? []).map((el) => el.selector).filter(Boolean),
outline,
note: fix?.pr?.note ?? null,
audience,
};
let steps = [] as ReturnType<typeof fallbackTourSteps>;
@@ -160,7 +165,7 @@ export async function POST(req: NextRequest) {
try {
const answered = await callTextDetailed(tourPrompt(input), {
feature: "widget-tour",
systemPrompt: tourSystemPrompt(),
systemPrompt: tourSystemPrompt(audience),
maxTokens: 1400,
temperature: 0.2,
timeoutMs: HTTP_TIMEOUT_LONG_MS,
@@ -175,16 +180,24 @@ export async function POST(req: NextRequest) {
if (steps.length === 0) steps = fallbackTourSteps(input);
const asked = f.suggestion.replace(/\s+/g, " ").trim();
// The reporter's own first screenshot is the closest thing to "before".
const before =
(f.screenshots ?? []).find((src) => /^data:image\/(png|jpeg|webp);base64,/.test(src)) ?? null;
const forReporter = audience === "reporter";
return corsJson({
ok: true,
theme: PALETTE.widget,
title: "Watch the fix",
title: forReporter ? "Your fix" : "Watch the fix",
intro: `You asked: “${asked.length > 140 ? `${asked.slice(0, 139)}…` : asked}” — let me show you what changed.`,
steps,
outro: didLine
? `That's it. ${didLine} Does it look right to you?`
: "That's the change. Does it look right to you?",
lokiHref: `${appUrl()}/feedback?project=${encodeURIComponent(f.projectId)}`,
prUrl: fix?.pr?.url ?? null,
beats: buildTourBeats({ audience, asked, note: fix?.pr?.note ?? null, didLine, steps, before }),
outro: tourOutro(audience, didLine),
// The reporter's way back is their own list, never the owner's inbox; and
// the pull request is the maintainer's business (reporter-view.ts).
lokiHref: forReporter
? `${appUrl()}/my-feedback`
: `${appUrl()}/feedback?project=${encodeURIComponent(f.projectId)}`,
lokiLabel: forReporter ? "Back to my feedback" : null,
prUrl: forReporter ? null : (fix?.pr?.url ?? null),
});
}
+8 -4
View File
@@ -212,10 +212,14 @@ export default function FeedbackWidgetDocsPage() {
<h2 className="ui-public-prose-h2">8. You close the loop</h2>
<p>
Every report remembers the run that worked on it, so you can see what shipped against
it. Once a fix is out, <strong>Watch the fix</strong> opens your page and plays a short
walkthrough: a pointer moves to each changed part and a caption says what changed. If a
step cannot be shown, it says so and files that back into your inbox, so a fix that did
not really land comes back to you.
it. Once a fix is out, <strong>Watch the fix</strong> opens your page and tells the
story of the change in about a minute: the report and the screenshot that came with it,
what was actually wrong, the change shown live with a pointer, why it was done that way,
what else was considered, and who it helps. Back, Pause and Next set the pace. If a step
cannot be shown, it says so and files that back into your inbox, so a fix that did not
really land comes back to you. The person who reported it gets their own shorter version
on their feedback page: their words, the change shown live, and one plain sentence about
what changed for them, without the technical reasoning.
</p>
<p>
Marking a report resolved is your call — a finished run is not proof the problem went
+8 -1
View File
@@ -23,6 +23,7 @@ import { runToFeedbackSnapshot } from "@/lib/feedback/attach-work";
import { deriveFeedbackWork, FEEDBACK_WORK_PHASE } from "@/lib/feedback/work-phase";
import { livePageHref } from "@/lib/feedback/fix-shipping";
import { reporterStatusFor, type ReporterStatus } from "@/lib/feedback/reporter-view";
import { createTourToken, tourSiteUrl } from "@/lib/feedback/tour-token";
import type { UserFeedbackListItem } from "@/db/queries/site-feedback";
export type ReporterFeedbackRow = {
@@ -57,6 +58,12 @@ export async function attachReporterView(
const run = item.dispatchedRunId ? runs.get(item.dispatchedRunId) : null;
const work = deriveFeedbackWork(item.status, runToFeedbackSnapshot(run));
const liveHref = livePageHref(item.liveUrl, item.url, item.page);
// Minted for every row with a live page and a run behind it; the status
// only offers it once the fix is actually live. A signature, not a write.
const tourHref =
liveHref && run
? tourSiteUrl(liveHref, createTourToken(item.id, Date.now(), "reporter"))
: null;
return {
id: item.id,
projectId: item.projectId,
@@ -64,7 +71,7 @@ export async function attachReporterView(
projectName: item.projectName,
suggestion: item.suggestion,
createdAt: item.createdAt,
status: reporterStatusFor(work, { liveHref }),
status: reporterStatusFor(work, { liveHref, tourHref }),
};
});
}
+3
View File
@@ -3,6 +3,7 @@
* SSOT so single-row Implement and batch "Implement all as one" stay aligned.
*/
import { fenceUntrusted, inlineUntrusted, UNTRUSTED_PREAMBLE } from "@/lib/feedback/untrusted";
import { fixNoteInstruction } from "@/lib/feedback/fix-note";
export type FeedbackPromptFields = {
suggestion: string;
@@ -72,6 +73,7 @@ export function composeFeedbackFixPrompt(
"",
"Scope: address exactly this feedback — no unrelated refactors.",
SHIP_INSTRUCTION,
fixNoteInstruction(),
);
return lines.join("\n");
}
@@ -95,6 +97,7 @@ export function composeFeedbackBatchFixPrompt(
"Address every item below. Prefer one coherent change set when items share a root cause; otherwise fix them independently, most recent first.",
"Scope: only these reports — no unrelated refactors.",
SHIP_INSTRUCTION,
fixNoteInstruction(),
"",
];
items.forEach((f, i) => {
+123
View File
@@ -0,0 +1,123 @@
/**
* The design note an agent leaves with a fix: what was wrong, what changed,
* why this way, what else it considered, who it helps — and one plain
* sentence for the person who reported it.
*
* "Watch the fix" used to have one line to go on (the handoff's `done`) and a
* PR title, so it could show WHERE a change was and never WHY. The reasoning
* existed only inside the agent's session and died with it (2026-10-07).
*
* It travels in the pull request description, not the handoff: every runner
* and every agent CLI already opens the PR, the fix ledger already reads it
* (fix-shipping-refresh.ts), and a person reading the PR on GitHub gets the
* same account the walkthrough gives. One section, one format, defined here —
* the instruction the agent receives is rendered from the same field list the
* parser reads, so the two cannot drift.
*
* Everything here is text an agent wrote after reading a stranger's report, so
* it is capped and only ever rendered as text, never markup.
*/
export const FIX_NOTE_HEADING = "Walkthrough";
/** Line label → field. Order is the order the agent is asked to write them. */
const FIELDS = [
{ label: "Problem", key: "problem", ask: "what was actually wrong, in one or two sentences" },
{ label: "Change", key: "change", ask: "what you changed, as the user will see it" },
{ label: "Why", key: "why", ask: "why this approach" },
{
label: "Considered",
key: "considered",
ask: "one line per alternative you rejected, as `<option> — <why not>` (repeat the line, at most 3)",
},
{ label: "Helps", key: "helps", ask: "who benefits and how" },
{ label: "Where", key: "where", ask: "where on the live page to look" },
{
label: "For the reporter",
key: "plain",
ask: "one or two plain sentences for the person who reported it — no code, file names or internals",
},
] as const;
const FIELD_MAX = 400;
const CONSIDERED_MAX = 3;
export type FixNote = {
problem: string | null;
change: string | null;
why: string | null;
considered: { option: string; whyNot: string | null }[];
helps: string | null;
where: string | null;
plain: string | null;
};
/** The instruction appended to every fix prompt. */
export function fixNoteInstruction(): string {
return [
`In the pull request description, include a section headed \`## ${FIX_NOTE_HEADING}\` with these lines — Loki plays it to the owner and the reporter as a guided walkthrough of the change on the live site, so write for a person, not a reviewer:`,
...FIELDS.map((f) => `- ${f.label}: <${f.ask}>`),
].join("\n");
}
const clean = (s: string) => s.replace(/\s+/g, " ").trim();
const cap = (s: string) => (s.length > FIELD_MAX ? `${s.slice(0, FIELD_MAX - 1)}…` : s);
/** Read the note out of a PR description. Null when there is no section or
* nothing usable in it — the walkthrough then falls back to what it had. */
export function parseFixNote(body: string | null | undefined): FixNote | null {
if (!body) return null;
const lines = body.replace(/\r\n/g, "\n").split("\n");
const heading = new RegExp(`^#{2,4}\\s*${FIX_NOTE_HEADING}\\s*$`, "i");
const start = lines.findIndex((l) => heading.test(l.trim()));
if (start < 0) return null;
const note: FixNote = {
problem: null,
change: null,
why: null,
considered: [],
helps: null,
where: null,
plain: null,
};
const byLabel = new Map<string, (typeof FIELDS)[number]["key"]>(
FIELDS.map((f) => [f.label.toLowerCase(), f.key]),
);
const labelRe = /^\s*(?:[-*]\s*)?\**([A-Za-z][A-Za-z ]{1,24}?)\**\s*:\s*(.*)$/;
let current: (typeof FIELDS)[number]["key"] | null = null;
let buffer = "";
const flush = () => {
const text = clean(buffer);
buffer = "";
if (!current || !text || /^<.*>$/.test(text)) return;
if (current === "considered") {
if (note.considered.length >= CONSIDERED_MAX) return;
const [option, ...rest] = text.split(/\s+[—–-]{1,2}\s+/);
note.considered.push({
option: cap(option),
whyNot: rest.length ? cap(rest.join(" — ")) : null,
});
} else if (!note[current]) {
note[current] = cap(text);
}
};
for (const raw of lines.slice(start + 1)) {
if (/^#{1,6}\s/.test(raw.trim())) break;
const m = raw.match(labelRe);
const key = m ? byLabel.get(m[1].trim().toLowerCase()) : undefined;
if (m && key) {
flush();
current = key;
buffer = m[2];
} else if (current && raw.trim()) {
buffer += ` ${raw.trim().replace(/^[-*]\s*/, "")}`;
}
}
flush();
const any = note.problem || note.change || note.why || note.helps || note.where || note.plain;
return any || note.considered.length ? note : null;
}
+2
View File
@@ -78,6 +78,7 @@ async function fetchPr(ref: PrRef, token: string): Promise<GithubPrDetail | null
head?: { sha?: string };
base?: { ref?: string };
created_at?: string;
body?: string | null;
};
const j = raw;
if (typeof j.number !== "number" || typeof j.html_url !== "string") return null;
@@ -93,6 +94,7 @@ async function fetchPr(ref: PrRef, token: string): Promise<GithubPrDetail | null
headSha: typeof raw.head?.sha === "string" ? raw.head.sha : null,
createdAt: typeof raw.created_at === "string" ? raw.created_at : null,
baseRef: typeof raw.base?.ref === "string" ? raw.base.ref : null,
body: typeof raw.body === "string" ? raw.body : null,
};
}
+9
View File
@@ -15,6 +15,8 @@
* and caches the result on the run.
*/
import { parseFixNote, type FixNote } from "@/lib/feedback/fix-note";
export const FIX_SHIP_STATE = {
/** Run said success, but no PR, push or commit could be found. */
NO_EVIDENCE: "no_evidence",
@@ -48,6 +50,10 @@ export type FixShipping = {
title: string;
mergedAt?: string | null;
mergeSha?: string | null;
/** The agent's design note from the PR description (fix-note.ts) — what
* "Watch the fix" tells the story from. Absent on PRs written before the
* note was asked for, and on PRs whose author left it out. */
note?: FixNote | null;
};
push?: { url: string; title: string };
deploy?: { url: string | null; name: string; conclusion: string | null; status: string | null };
@@ -299,6 +305,8 @@ export type GithubPrDetail = {
createdAt?: string | null;
/** The branch it merged into (`base.ref`) — whose later deploys carry it. */
baseRef?: string | null;
/** The description, read only for its design note (parseFixNote). */
body?: string | null;
};
/** GitHub's workflow run object, only the fields the ledger reads. */
export type GithubWorkflowRun = {
@@ -343,6 +351,7 @@ export function deriveShippingFromPr(
title: pr.title,
mergedAt: pr.merged_at,
mergeSha: pr.merge_commit_sha,
note: parseFixNote(pr.body),
},
checkedAt,
};
+9 -2
View File
@@ -60,10 +60,17 @@ const ON_THE_WAY: ReadonlySet<string> = new Set([
export function reporterStatusFor(
work: FeedbackWorkView,
opts: { liveHref?: string | null } = {},
/** `tourHref`: the live page with the reporter's own walkthrough ticket
* (tour-token.ts, audience "reporter"). When present it replaces the bare
* link — "check the live page" left them to find the change themselves. */
opts: { liveHref?: string | null; tourHref?: string | null } = {},
): ReporterStatus {
const liveHref = opts.liveHref ?? null;
const checkLive = liveHref ? { href: liveHref, label: "Check the live page" } : null;
const checkLive = opts.tourHref
? { href: opts.tourHref, label: "Watch your fix" }
: liveHref
? { href: liveHref, label: "Check the live page" }
: null;
switch (work.phase) {
case FEEDBACK_WORK_PHASE.NOT_STARTED:
+98 -2
View File
@@ -1,4 +1,6 @@
import type { TourOutlineItem, TourStep } from "../../../widget/tour";
import type { TourBeat, TourOutlineItem, TourStep } from "../../../widget/tour";
import type { FixNote } from "./fix-note";
import type { TourAudience } from "./tour-token";
/**
* The script of a fix walkthrough — which parts of the live page to show, in
@@ -19,6 +21,10 @@ export type TourInput = {
/** Elements the reporter pointed at with the picker. */
selectors: string[];
outline: TourOutlineItem[];
/** The agent's design note, when its PR carried one — its `change` and
* `where` lines are the best map of what to point at. */
note?: FixNote | null;
audience?: TourAudience;
};
const WORD = /[\p{L}\p{N}]{4,}/gu;
@@ -92,7 +98,7 @@ export function fallbackTourSteps(input: TourInput): TourStep[] {
return steps;
}
export function tourSystemPrompt(): string {
export function tourSystemPrompt(audience: TourAudience = "owner"): string {
return [
"You direct a short guided walkthrough of a website, like a developer showing a client a change they asked for.",
"A fake cursor moves to each element you choose while your caption is shown. You see only a numbered outline of the visible page, not pixels.",
@@ -103,6 +109,9 @@ export function tourSystemPrompt(): string {
'- Use target null with action "scroll" only to return to the top of the page after a click demonstrates it.',
"- Only use outline numbers that exist. If the change is not visible in the outline, return the single most relevant element and say it should be here.",
"- Never invent text the outline does not contain.",
audience === "reporter"
? "- You are speaking to the person who reported the problem, not a developer: plain words, no code, file names or technical terms."
: "- You are speaking to the site's owner, who asked for this change.",
].join("\n");
}
@@ -114,6 +123,8 @@ export function tourPrompt(input: TourInput): string {
`The request: ${cut(input.suggestion, 1200)}`,
input.didLine ? `What the developer says they did: ${cut(input.didLine, 400)}` : null,
input.prTitle ? `Change title: ${cut(input.prTitle, 200)}` : null,
input.note?.change ? `The change, as the developer describes it: ${input.note.change}` : null,
input.note?.where ? `Where the developer says to look: ${input.note.where}` : null,
"",
"Visible page outline (document order, top to bottom):",
outline || "(empty)",
@@ -156,3 +167,88 @@ export function parseTourSteps(text: string, outlineLength: number): TourStep[]
// A walkthrough of nothing but scrolling shows nothing.
return steps.some((s) => s.target !== null) ? steps : [];
}
/** Chapter names. One list, so the card header and the tests agree. */
export const TOUR_CHAPTER = {
ASKED: "You asked",
PROBLEM: "The problem",
CHANGE: "The change",
SEE_IT: "Here it is",
WHY: "Why this way",
CONSIDERED: "Also considered",
HELPS: "Who it helps",
FOR_YOU: "What changed for you",
} as const;
export type TourStory = {
audience: TourAudience;
/** The report, in the reporter's own words. */
asked: string;
note: FixNote | null;
/** The handoff's one-line account — the owner's fallback when there is no note. */
didLine: string | null;
/** The live, on-page steps (planned by the model or the fallback). */
steps: TourStep[];
/** A screenshot the reporter attached — the closest thing to "before". */
before: string | null;
};
/**
* The whole walkthrough as a story in chapters: what was asked, what was
* wrong, the change shown live on the page, then — for the owner — why it was
* done this way, what else was considered and who it helps.
*
* The reporter's version keeps only their own words, the live demonstration
* and the note's plain sentence. Everything else in the note is reasoning a
* maintainer wrote for a maintainer, and it never reaches a stranger's screen:
* that boundary lives here and nowhere else.
*/
export function buildTourBeats(story: TourStory): TourBeat[] {
const beats: TourBeat[] = [];
const asked = cut(story.asked.replace(/\s+/g, " ").trim(), 220);
const note = story.note;
const live = (chapter: string) => story.steps.map((step): TourBeat => ({ chapter, ...step }));
if (story.audience === "reporter") {
beats.push({
chapter: TOUR_CHAPTER.ASKED,
action: "say",
say: `You reported: “${asked}” It has been fixed — here is the change.`,
image: story.before,
});
beats.push(...live(TOUR_CHAPTER.SEE_IT));
if (note?.plain) beats.push({ chapter: TOUR_CHAPTER.FOR_YOU, action: "say", say: note.plain });
return beats;
}
beats.push({
chapter: TOUR_CHAPTER.ASKED,
action: "say",
say: `The report: “${asked}”`,
image: story.before,
});
if (note?.problem)
beats.push({ chapter: TOUR_CHAPTER.PROBLEM, action: "say", say: note.problem });
const change = note?.change ?? story.didLine;
if (change) beats.push({ chapter: TOUR_CHAPTER.CHANGE, action: "say", say: change });
beats.push(...live(TOUR_CHAPTER.CHANGE));
if (note?.why) beats.push({ chapter: TOUR_CHAPTER.WHY, action: "say", say: note.why });
for (const alt of note?.considered ?? []) {
beats.push({
chapter: TOUR_CHAPTER.CONSIDERED,
action: "say",
say: alt.whyNot ? `${alt.option} — not chosen: ${alt.whyNot}` : alt.option,
});
}
if (note?.helps) beats.push({ chapter: TOUR_CHAPTER.HELPS, action: "say", say: note.helps });
return beats;
}
/** The closing line on the end card. */
export function tourOutro(audience: TourAudience, didLine: string | null): string {
if (audience === "reporter")
return "That's your fix, live. Thank you for reporting it — if it still isn't right, tell us the same way.";
return didLine
? `That's it. ${didLine} Does it look right to you?`
: "That's the change. Does it look right to you?";
}
+40 -8
View File
@@ -5,14 +5,31 @@ import { TOUR_HASH_KEY, tourSiteUrl } from "../../../widget/tour";
* The ticket for "Watch the fix": a signed, expiring reference to ONE
* feedback item, carried to the live site in the URL fragment (never sent to
* that site's server). What it grants is a walkthrough of that item's fix —
* the report's words and the agent's one-line account — and the right to flag
* the report's words and the agent's account of the change — and the right to flag
* a step the walkthrough could not show. Nothing that changes the project.
*
* Same shape as the claim token and the owner pass, domain-separated so none
* of the three can stand in for another.
*/
const TOUR_TTL_MS = 24 * 60 * 60 * 1000;
/**
* Who the walkthrough is for. The owner's tells the whole story — why, what
* else was considered, the PR — and ends at "confirm in Loki". The reporter's
* is the same change in plain words, with nothing of the maintainer's: no PR,
* no repository, no reasoning about code (lib/feedback/tour-plan.ts).
*/
export type TourAudience = "owner" | "reporter";
/** The owner opens it from Loki a moment after minting it. A reporter is
* handed it on /my-feedback and may come back to it days later. */
const TOUR_TTL_MS: Record<TourAudience, number> = {
owner: 24 * 60 * 60 * 1000,
reporter: 7 * 24 * 60 * 60 * 1000,
};
/** Marker for a reporter ticket. An owner ticket carries none, so every
* link minted before audiences existed still reads as the owner's. */
const REPORTER_MARK = "r";
function secret(): string {
const value = process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET;
@@ -24,19 +41,34 @@ function signature(payload: string): string {
return createHmac("sha256", secret()).update(`feedback-tour:${payload}`).digest("base64url");
}
export function createTourToken(feedbackId: string, now = Date.now()): string {
const payload = `${feedbackId}.${now + TOUR_TTL_MS}`;
export function createTourToken(
feedbackId: string,
now = Date.now(),
audience: TourAudience = "owner",
): string {
const base = `${feedbackId}.${now + TOUR_TTL_MS[audience]}`;
// The mark is inside the signed payload, so a reporter ticket cannot be
// promoted to the owner's by dropping it (nor the reverse by adding it).
const payload = audience === "reporter" ? `${base}.${REPORTER_MARK}` : base;
return `${payload}.${signature(payload)}`;
}
export function verifyTourToken(token: string, now = Date.now()): string | null {
const [feedbackId, expiresRaw, supplied] = token.split(".");
export function verifyTourToken(
token: string,
now = Date.now(),
): { feedbackId: string; audience: TourAudience } | null {
const parts = token.split(".");
if (parts.length !== 3 && parts.length !== 4) return null;
const [feedbackId, expiresRaw] = parts;
const supplied = parts[parts.length - 1];
const audience: TourAudience = parts.length === 4 ? "reporter" : "owner";
if (parts.length === 4 && parts[2] !== REPORTER_MARK) return null;
if (!feedbackId || !expiresRaw || !supplied || !/^\d+$/.test(expiresRaw)) return null;
if (Number(expiresRaw) < now) return null;
const expected = signature(`${feedbackId}.${expiresRaw}`);
const expected = signature(parts.slice(0, -1).join("."));
const a = Buffer.from(supplied);
const b = Buffer.from(expected);
return a.length === b.length && timingSafeEqual(a, b) ? feedbackId : null;
return a.length === b.length && timingSafeEqual(a, b) ? { feedbackId, audience } : null;
}
// The fragment key and the link shape are defined once, on the widget's side.
+28 -12
View File
@@ -49,18 +49,34 @@ proven in a browser by `scripts/test/widget-watch-browser.ts`.
## "Watch the fix" — the walkthrough
When a fix has shipped, Loki's feedback row offers **Watch the fix**. It opens
the live page with `#loki-tour=<token>` (a signed, 24-hour ticket for that one
report, carried in the fragment so the site's server never sees it). This
bundle reads a numbered outline of the visible page, asks `/api/widget/tour`
for a script, and plays it: a cursor glides to each element, a caption says
why, and in-page controls (an `#anchor` link, a disclosure, a plain button)
are really clicked — anything that would navigate away or submit is only
pointed at. A step it cannot show is said out loud ("Oops — …, it has been
flagged") and reported back; Loki files it as an AI-review item on the
project, so a fix that is not really live comes back into the loop. Nothing
for a host to install: every site with the widget gets it. Code:
`widget/tour.ts`, `src/app/api/widget/tour/route.ts`,
`src/lib/feedback/tour-plan.ts`.
the live page with `#loki-tour=<token>` (a signed ticket for that one report,
carried in the fragment so the site's server never sees it). This bundle reads
a numbered outline of the visible page, asks `/api/widget/tour` for the story,
and plays it in chapters: the report (with the reporter's screenshot, if they
attached one), what was wrong, the change demonstrated live, why this way, what
else was considered, who it helps. On the page, a cursor glides to each
element and in-page controls (an `#anchor` link, a disclosure, a plain button)
are really clicked; anything that would navigate away or submit is only
pointed at. Back, Pause and Next put the pace in the viewer's hands.
The story comes from the **design note** the agent writes in the fix's pull
request (`## Walkthrough`, `src/lib/feedback/fix-note.ts`). A PR without one
still gets a walkthrough, built from the report and the agent's one-line
account.
The ticket has an **audience**. The owner's (24 hours, minted from Loki) gets
the whole story and ends at "confirm in Loki" and the PR. The reporter's
(seven days, minted on `/my-feedback` once the fix is live) gets their own
words, the live demonstration and the note's plain sentence — never the
maintainer's reasoning, the PR or the repository. That boundary lives in
`buildTourBeats` (`src/lib/feedback/tour-plan.ts`) and nowhere else.
A step it cannot show is said out loud ("Oops — …, it has been flagged") and
reported back; Loki files it as an AI-review item on the project, so a fix
that is not really live comes back into the loop. Nothing for a host to
install: every site with the widget gets it. Code: `widget/tour.ts`,
`src/app/api/widget/tour/route.ts`, `src/lib/feedback/tour-plan.ts`,
`src/lib/feedback/fix-note.ts`, `src/lib/feedback/tour-token.ts`.
## Where the launcher sits
+151 -63
View File
@@ -34,17 +34,45 @@ export type TourStep = {
say: string;
};
/**
* One beat of the story: a sentence under a chapter name, optionally shown on
* the page (a target to point at or click) or beside a picture (the "before"
* screenshot). A beat with neither is the narrator talking.
*/
export type TourBeat = {
chapter: string;
action: TourStep["action"] | "say";
say: string;
target?: number | null;
selector?: string | null;
/** A data: URL of an image (the reporter's own screenshot). */
image?: string | null;
};
type TourPlan = {
ok: true;
theme: WidgetTheme;
title: string;
intro: string;
/** Kept for a widget bundle cached from before chapters existed. */
steps: TourStep[];
/** The chaptered story (lib/feedback/tour-plan.ts → buildTourBeats). */
beats?: TourBeat[];
outro: string;
lokiHref: string | null;
/** The end card's way back. Defaults to the owner's wording. */
lokiLabel?: string | null;
prUrl: string | null;
};
/** How long a sentence stays up: enough to read it at an unhurried pace,
* never a blink, never a wait. A full story of ten-odd beats lands near a
* minute; Next and Back put the pace in the viewer's hands. */
export function readMs(text: string): number {
const words = text.trim().split(/\s+/).filter(Boolean).length;
return Math.max(3200, Math.min(9500, 1600 + words * 320));
}
/** The owner's link: the live page with the tour token in the fragment. */
export function tourSiteUrl(pageUrl: string, token: string): string {
const base = pageUrl.split("#")[0];
@@ -206,6 +234,7 @@ function tourCSS(t: WidgetTheme): string {
@keyframes rip { to { transform: translate(-50%,-50%) scale(3.2); opacity: 0; } }
.card { position: fixed; left: 12px; right: 12px; bottom: calc(12px + var(--bar, 0px)); margin: 0 auto;
max-width: 440px; z-index: 2147483647; transition: top .35s, bottom .35s;
max-height: min(72vh, 560px); overflow-y: auto;
pointer-events: auto; background: ${t.surface}; color: ${t.text};
border: 1px solid ${t.borderStrong}; border-radius: ${rs}; padding: 12px 14px;
font-size: 14px; line-height: 1.45; }
@@ -215,7 +244,11 @@ function tourCSS(t: WidgetTheme): string {
font-family: ${mono}; font-size: 10px; letter-spacing: .08em; text-transform: uppercase; }
.dot { width: 7px; height: 7px; border-radius: 50%; background: ${t.accent}; }
.count { font-family: ${mono}; font-size: 10px; color: ${t.textMuted}; }
.chap { color: ${t.accent}; font-family: ${mono}; font-size: 10px; letter-spacing: .08em;
text-transform: uppercase; margin-bottom: 4px; min-height: 1.2em; }
.say { min-height: 2.9em; }
.shot { display: block; max-width: 100%; max-height: 32vh; margin-top: 10px; object-fit: contain;
border: 1px solid ${t.border}; border-radius: ${rc}; }
.say.bad { color: ${t.error}; }
.bar { height: 2px; background: ${t.border}; border-radius: 2px; margin-top: 10px; overflow: hidden; }
.fill { height: 100%; width: 0; background: ${t.accent}; transition: width .4s; }
@@ -224,6 +257,7 @@ button, a.btn { cursor: pointer; font: inherit; font-size: 12px; padding: 7px 12
border-radius: ${rc}; border: 1px solid ${t.borderStrong}; background: transparent;
color: ${t.textSecondary}; text-decoration: none; display: inline-flex; align-items: center; }
button.primary, a.btn.primary { background: ${t.accent}; border-color: ${t.accent}; color: ${ink}; }
button:disabled { opacity: .4; cursor: default; }
button:focus-visible, a.btn:focus-visible { outline: 2px solid ${t.accent}; outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
.ring, .cursor, .fill { transition: none; }
@@ -286,12 +320,17 @@ export async function runTour(apiBase: string, token: string): Promise<void> {
brand.append(h("span", "dot"), h("span", undefined, `Loki · ${plan.title}`));
const count = h("span", "count");
top.append(brand, count);
const chap = h("p", "chap");
const say = h("p", "say");
const shot = h("img", "shot") as HTMLImageElement;
shot.alt = "The screenshot attached to the report";
shot.style.display = "none";
shot.addEventListener("error", () => (shot.style.display = "none"));
const bar = h("div", "bar");
const fill = h("div", "fill");
bar.appendChild(fill);
const row = h("div", "row");
card.append(top, say, bar, row);
card.append(top, chap, say, shot, bar, row);
layer.append(ring, cursor);
root.append(style, layer, card);
let barInset = 0;
@@ -328,8 +367,13 @@ export async function runTour(apiBase: string, token: string): Promise<void> {
pauseBtn.textContent = paused ? "Play" : "Pause";
if (!paused) skip?.();
});
let goBack = false;
const backBtn = btn("Back", () => {
goBack = true;
skip?.();
});
const nextBtn = btn("Next", () => skip?.());
row.append(pauseBtn, nextBtn, btn("Close", close));
row.append(backBtn, pauseBtn, nextBtn, btn("Close", close));
/** Hold a beat — cut short by Next, extended while paused. */
const hold = (ms: number) =>
@@ -378,15 +422,32 @@ export async function runTour(apiBase: string, token: string): Promise<void> {
layer.appendChild(rip);
setTimeout(() => rip.remove(), 700);
};
const beat = (text: string, n: number, total: number, bad = false) => {
const beat = (text: string, n: number, total: number, bad = false, chapter = "") => {
chap.textContent = chapter;
say.textContent = text;
say.classList.toggle("bad", bad);
count.textContent = total ? `${Math.min(n, total)} / ${total}` : "";
fill.style.width = total ? `${Math.round((Math.min(n, total) / total) * 100)}%` : "0";
};
const picture = (src: string | null | undefined) => {
// Only an image the server sent as a data URL; a host CSP that refuses
// data: images just hides it — the sentence still carries the beat.
if (src && /^data:image\/(png|jpeg|webp);base64,/.test(src)) {
shot.src = src;
shot.style.display = "block";
} else {
shot.removeAttribute("src");
shot.style.display = "none";
}
};
const park = () => {
ring.classList.remove("on");
card.classList.remove("up");
moveCursor(window.innerWidth / 2, window.innerHeight * 0.3);
};
const find = (step: TourStep): Element | null => {
if (step.target !== null && outline.els[step.target]?.isConnected)
const find = (step: TourBeat): Element | null => {
if (typeof step.target === "number" && outline.els[step.target]?.isConnected)
return outline.els[step.target];
if (step.selector) {
try {
@@ -398,77 +459,100 @@ export async function runTour(apiBase: string, token: string): Promise<void> {
return null;
};
// A bundle cached from before chapters still gets a plan it can play.
const beats: TourBeat[] = plan.beats?.length
? plan.beats
: [
{ chapter: "", action: "say", say: plan.intro },
...plan.steps.map((st): TourBeat => ({ chapter: "", ...st })),
];
const total = beats.length;
moveCursor(cx.x, cx.y);
cursor.classList.add("on");
const total = plan.steps.length;
beat(plan.intro, 0, total);
await hold(2600);
let problem = false;
for (let n = 0; n < total && !closed; n++) {
const step = plan.steps[n];
if (step.target === null && !step.selector) {
ring.classList.remove("on");
const flagged = new Set<number>();
const visited = new Set<number>();
let n = 0;
while (n < total && !closed) {
goBack = false;
backBtn.disabled = n === 0;
const step = beats[n];
const again = visited.has(n);
visited.add(n);
picture(step.image);
const onPage = typeof step.target === "number" || !!step.selector;
if (!onPage) {
park();
if (step.action === "scroll") window.scrollTo({ top: 0, behavior: "smooth" });
beat(step.say, n + 1, total);
await hold(3000);
continue;
}
const el = find(step);
if (!el || !shown(el)) {
problem = true;
ring.classList.remove("on");
card.classList.remove("up");
moveCursor(window.innerWidth / 2, window.innerHeight * 0.3);
beat(
`Oops — I wanted to show you this, but it isn't on the page: “${step.say}”. That's on us, not you — I've flagged it and it will be investigated.`,
n + 1,
total,
true,
);
reportProblem(
apiBase,
token,
n,
step.say,
el ? "element is hidden or has no size" : "element not found",
);
await hold(6000);
continue;
}
el.scrollIntoView({ behavior: "smooth", block: "center" });
await sleep(750);
if (closed) break;
const r = frame(el);
moveCursor(r.left + Math.min(r.width / 2, 40), r.top + Math.min(r.height / 2, 20));
beat(step.say, n + 1, total);
await sleep(950);
if (step.action === "click" && !closed) {
tap(cx.x, cx.y);
if (safeToClick(el)) {
await sleep(250);
(el as HTMLElement).click();
// A click usually moves the page (an anchor scrolls): follow the
// element if it is still in view, otherwise let the page speak.
await sleep(900);
const after = el.getBoundingClientRect();
if (after.bottom < 0 || after.top > window.innerHeight) {
ring.classList.remove("on");
card.classList.remove("up");
moveCursor(window.innerWidth / 2, window.innerHeight * 0.3);
} else {
const r2 = frame(el);
moveCursor(r2.left + Math.min(r2.width / 2, 40), r2.top + Math.min(r2.height / 2, 20));
beat(step.say, n + 1, total, false, step.chapter);
await hold(readMs(step.say) + (step.image ? 1500 : 0));
} else {
const el = find(step);
if (!el || !shown(el)) {
problem = true;
park();
beat(
`Oops — I wanted to show you this, but it isn't on the page: “${step.say}”. That's on us, not you — I've flagged it and it will be investigated.`,
n + 1,
total,
true,
step.chapter,
);
if (!flagged.has(n)) {
flagged.add(n);
reportProblem(
apiBase,
token,
n,
step.say,
el ? "element is hidden or has no size" : "element not found",
);
}
await hold(6000);
} else {
el.scrollIntoView({ behavior: "smooth", block: "center" });
await sleep(750);
if (closed) break;
const r = frame(el);
moveCursor(r.left + Math.min(r.width / 2, 40), r.top + Math.min(r.height / 2, 20));
beat(step.say, n + 1, total, false, step.chapter);
await sleep(950);
// Going back shows the element again but does not click it twice:
// a second click on a disclosure would undo what the first showed.
if (step.action === "click" && !again && !closed) {
tap(cx.x, cx.y);
if (safeToClick(el)) {
await sleep(250);
(el as HTMLElement).click();
// A click usually moves the page (an anchor scrolls): follow the
// element if it is still in view, otherwise let the page speak.
await sleep(900);
const after = el.getBoundingClientRect();
if (after.bottom < 0 || after.top > window.innerHeight) {
park();
} else {
const r2 = frame(el);
moveCursor(
r2.left + Math.min(r2.width / 2, 40),
r2.top + Math.min(r2.height / 2, 20),
);
}
}
}
await hold(Math.max(3400, readMs(step.say)));
}
}
await hold(3400);
n = goBack ? Math.max(0, n - 1) : n + 1;
}
if (closed) return;
ring.classList.remove("on");
cursor.classList.remove("on");
card.classList.remove("up");
picture(null);
beat(
problem
? "Part of this did not show up the way it should. It has been flagged — nothing more for you to do here."
@@ -479,7 +563,11 @@ export async function runTour(apiBase: string, token: string): Promise<void> {
);
row.replaceChildren();
if (plan.lokiHref) {
const back = h("a", "btn primary", problem ? "Back to Loki" : "Looks right — confirm in Loki");
const back = h(
"a",
"btn primary",
plan.lokiLabel ?? (problem ? "Back to Loki" : "Looks right — confirm in Loki"),
);
back.href = plan.lokiHref;
row.appendChild(back);
}