Files
loki/scripts/test/widget-walk-read.ts
CatoandClaude Opus 5.5 3024426a65 fix: Voice says why studio voices are off, Watching says each thing once, Prompts in words (#1358)
* fix(prompts): one card per saved prompt, schedules in words, dialogs that say why

What the owner found on /prompts from an Android phone, item by item:

1. Saved prompts: saving the same name + words again no longer inserts a
   row — POST /api/prompts answers with the prompt already saved
   (existing: true); the form opens it, the default's save button says
   "Already in your prompts". A card that stands for identical copies says
   how many and offers "Remove N extra copies" — one explicit tap, the
   caller's own rows only, the same soft delete as Delete
   (DELETE /api/prompts/<id>/copies). Same name with different words says
   "2 versions with this name, worded differently".
2. Filters: the scope filter is a <Segmented> (All / Any project / One
   project) sitting with the category row on the list they both filter,
   under "Loki's prompts". Category counts follow the scope. Filter chip
   rows on a phone get a wider fade, snap to a chip's start and leave room
   after the last chip, so the edge reads as "more" rather than a cut word.
3. New prompt: Create stays disabled until there is a name and a prompt,
   and says what is missing beside it. Opening or closing the form never
   saved anything; the copy glyph on every default card did, in one tap
   with no label on a phone — it is now a labelled "save a copy" button.
4. Schedule: pick Every day / Weekdays / Every week / Every month, a day
   and a time; Loki writes the cron (lib/cron-words), with "Write it as a
   cron line instead" for experts. The schedule reads back in words with
   the time zone it runs in ("Every Monday at 10:00, Zurich time
   (Europe/Zurich)") and a link to change it; the zone is sent with the
   job. The API refuses a cron line the scheduler cannot read, in words.
   Create is the primary button and says why when it cannot be pressed.
5. Run: a prompt that names {{project_name}} asks for a project whatever
   its scope (a saved copy is global), defaulting to the project in use;
   the prompt is shown only once complete. Each action says in one line
   who does the work; Send to terminal works for any of your projects
   (tab-inject starts or queues the session) and says why when it cannot.
   Project pickers list projectTitle(), not folder keys.
6. Category chips are neutral (ui-tag-neutral); the ui-cat-* rainbow and
   the featured star's amber are gone. "control" was a second id for the
   fleet prompts — one category now, "Fleet control".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* fix(voice): spoken sentences start with a capital and name a repeated project once

The briefing read "one run is waiting for a builder: loki ... three runs
failed: loki, loki and loki". Sentences now open with a capital, and the
runs' projects are said once each: "Three runs failed on loki.", "Four runs
failed: loki three times and heidi once." The same for runs waiting for a
builder, agents working, and the announcements between turns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* fix(voice): say why the studio voice is off, with the link that fixes it

POST /api/voice/speak answered 502 with Groq's reason only in the server
console, and the phone fell back to its own voice in silence, so every voice
in the picker sounded the same. Groq's refusal is now classified
(lib/voice/tts-failure: terms gate, bad key, limit, model gone, vendor down,
no key) into one plain sentence and, where one exists, the link that fixes
it — for the Orpheus terms gate, Groq's voice page and "press Accept". The
route returns it in the 502/503 body and records it in debug_logs (once per
reason per half hour) so System shows it. The speaker reports the fallback
to the page; useStudioVoiceStatus keeps it for the tab's session and
StudioVoiceNotice shows it. The phone-voice fallback stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* feat(voice): change Loki's voice by saying so, and answer questions about voice mode truthfully

"I don't like your voice, can I change your voice" was answered like a
generic chatbot ("in most voice-enabled AI chat apps... look in settings").
Now "use Troy", "change your voice to Diana", "other voice" and
"switch voice" are a spoken command (config/no-screen.ts, lib/voice/commands)
that the phone answers itself; with no name it lists the voices. A question
that does reach Loki carries voiceModeContext (lib/voice/self.ts), built from
the SSOT: the voices by name, how to change one, the three switches with the
same one-line notes the screen shows (NO_SCREEN_OPTIONS), every command, the
current settings and why studio voices are off, if they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* fix(voice): a music bed a phone can actually play, and keep its sound awake

The bed sat at about -38 dBFS RMS alone and -50 under the voice, every note
98-370 Hz behind a 900 Hz low-pass: below what a phone speaker or many
earbuds reproduce, so "music bed on" was silence. It is now an octave
higher (196-740 Hz), about 12 dB louder, ducks by 10 dB instead of 11 more on
top, and earcons sit above it. The AudioContext is resumed inside the Start
tap, on every tap on the circle or headphone button, on return to the page,
and when the phone suspends it mid-session.

useSoundscape also returned a new object every render, so effects keyed on
it re-ran ~20 times a second while listening: the gain was re-ramped every
frame and the 20-second fleet poll was cleared before it could fire. It is
memoized now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* fix(voice): one h1 per screen, End clear of the feedback launcher, voices as an even grid

- Speaking screen: an h1 below md, where the app top bar steps aside; the
  start screen's big "Voice" is no longer a second h1 beside the top bar's.
- The speaking screen sets data-fc-place="tab", so the feedback launcher
  and its Watching pill become the slim edge handle instead of sitting on
  End; End is larger, with room below it, and the stage scrolls rather than
  pushing End off a short screen.
- The voice picker is a <Segmented> grid of four columns (seven voices as
  4 + 3, the last two cells wide) instead of a chip row cut off at the edge;
  the setting groups have real headings.
- The unclear note under the switches is one short line under each switch,
  shared with what Loki is told about itself.
- The page wires the studio-voice notice (under the picker and under the
  circle, said aloud once), the spoken voice change, the page's state sent
  with each question, and the sound resume on every tap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* fix(widget): one card per finding, settled page checks, honest fix status, a count that means what needs you

Watching on Loki's own /voice from an Android phone showed six problems in
one panel. Each is fixed where it starts:

- Notices no longer stack. A page's checks own ONE card (checksSlot), which
  each new reading replaces in place and a clean reading takes back
  (thread.ts pushNoticed / dropNoticed); a remark whose words are already on
  screen is not said again; a finding's signature ignores its count and its
  placeholder example (findingKind), and the card names its page.
- The heading miscount: the check counted headings inside aria-hidden and
  inert subtrees, and measured the page once, mid-swap — /voice's setup
  screen (top bar h1 + page h1) leaving for its speaking screen (immersive
  mode hides the top bar: no h1). Checks now count only rendered elements and
  run once the page has held still, twice, keeping only what both readings
  agree on (settledPageChecks / stableChecks). The Voice page itself now has
  one h1 on each screen.
- A fix Watch started that failed no longer promises it "goes live by
  itself": it says the fix did not finish, and "Open it in Loki to see why"
  is a real link to that run's Watch page (owner-view ownerTap; watch-fix
  now resolves a failed run's Watch page even without a live page).
- Self-watch: "I couldn't check on your changes just now" replaces the old
  sentence; a request that lived through the page being put away (a phone
  locking) is never a failure; background reads count only after three
  failures in a row; the changes route always answers with CORS headers and
  logs what failed.
- The header's one number is what waits on the owner's decision (failed
  attempts, saved notes, notes not started, changes said but not saved),
  counted by the server over ALL of the owner's rows, not inside the newest
  twelve; the open list shows every one of them first. Nothing waiting:
  just "Watching".
- The save receipt never quotes a cut sentence: several changes are listed
  one per line under it, clamped to whole lines with "Show all".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* docs(changelog): voice, Watching and Prompts fixes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-21 00:38:11 +02:00

214 lines
9.7 KiB
TypeScript

/**
* Loki reads a spoken note before it is saved (widget/walk-read.ts): what a
* read may contain, the card's "did it hear me" line, the walk handed to Ask,
* and a site-wide finding said once per visit (watch-trail.ts).
*
* The fixture is the owner's own walk through Petvity, 2026-10-18.
* Run: npx tsx scripts/test/widget-walk-read.ts
*/
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { cleanWalkRead, heardLine, itemsAsk, walkPages, walkSession } from "../../widget/walk-read";
import { onceSiteWide } from "../../widget/watch-trail";
import { parseWalkRead, walkReadPrompt } from "../../src/lib/feedback/walk-read-prompt";
import type { ReportMoment } from "../../widget/moments-contract";
const walk: ReportMoment[] = [
{
at: 0,
page: "/de",
label: "Dein Tier sendet ein Signal. Jetzt kannst du es lesen.",
said: "I think the design is inconsistent. Here's my homepage, design is one, and then we will go to...",
},
{
at: 22_000,
page: "/de/features",
label: "Jede Funktion, die dein Tier wirklich braucht",
said: "We will actually log in.",
},
{
at: 33_000,
page: "/portal/dashboard",
label: "What would you like to do?",
said: "No, no, I'm just making a coffee.",
},
{
at: 40_000,
page: "/portal/settings",
label: "Your data",
text: "Download my data",
said: "In general, I would like you to look at all these things and let me know what you think.",
},
{ at: 43_000, page: "/portal/settings", label: "Profile", marked: true },
];
// ── What a read may contain ────────────────────────────────────────────────
const read = cleanWalkRead({
ask: " Look at the design of the home page, Features, the dashboard and Settings,\n say where it is inconsistent, and tell me what you think. ",
kind: "question",
asides: ["No, no, I'm just making a coffee.", "", 42, "We will actually log in."],
});
assert.ok(read);
assert.equal(read.kind, "question");
assert.match(read.ask, /^Look at the design .* what you think\.$/, "whitespace folded");
assert.deepEqual(read.asides, ["No, no, I'm just making a coffee.", "We will actually log in."]);
assert.equal(cleanWalkRead({ ask: "", kind: "change" }), null, "no ask, no read");
assert.equal(cleanWalkRead({ ask: "null" }), null);
assert.equal(cleanWalkRead(null), null);
assert.equal(cleanWalkRead({ ask: "Make the button bigger", kind: "build it" })?.kind, "change");
assert.equal(
cleanWalkRead({ ask: "x".repeat(2000) })?.items[0].text.length,
900,
"a runaway answer is cut to the limit",
);
assert.equal(
cleanWalkRead({ ask: "a", asides: Array.from({ length: 20 }, (_, i) => `aside ${i}`) })?.asides
.length,
6,
);
// The model's answer goes through the same rule, fenced or not.
const parsed = parseWalkRead(
'```json\n{"ask":"Make the Features link bigger","kind":"change","asides":[]}\n```',
);
assert.deepEqual(parsed, {
ask: "Make the Features link bigger",
kind: "change",
items: [{ text: "Make the Features link bigger", kind: "change", where: null, parts: [] }],
asides: [],
});
// ── A walk talked about freely is a list, one thing per line ───────────────
// The owner's walk through Loki's own home page, 2026-10-18: one sentence
// about signed-in visitors, cut across two headings, and a question.
const listed = cleanWalkRead(
{
items: [
{
text: " Signed-in people should not land on this page; show their chats or the terminal, with an easy way to switch. ",
kind: "change",
where: "Home page, signed in",
parts: [0, 1, 1, 99, -1, 2.5, "3"],
},
{
text: "Check for stale pages and documents.",
kind: "change",
where: "Whole site",
parts: [],
},
{ text: "Is Fleet Runner still used?", kind: "question", where: "", parts: [4] },
{ text: "", kind: "change" },
],
asides: ["Thank you."],
},
5,
);
assert.ok(listed);
assert.equal(listed.items.length, 3, "an empty item is dropped");
assert.deepEqual(listed.items[0].parts, [0, 1], "parts: whole, in range, once");
assert.match(listed.items[0].text, /^Signed-in .* switch\.$/);
assert.equal(listed.items[2].where, null, "no where is null, not empty");
assert.equal(listed.kind, "change", "a list with a change is a change");
assert.equal(
listed.ask,
"1. Home page, signed in: Signed-in people should not land on this page; show their chats or the terminal, with an easy way to switch.\n2. Whole site: Check for stale pages and documents.\n3. Is Fleet Runner still used?",
"an old card shows the list as one instruction",
);
assert.equal(
cleanWalkRead({ items: [{ text: "What do you think?", kind: "question" }] })?.kind,
"question",
);
assert.equal(itemsAsk([{ text: "One", kind: "change", where: "Footer", parts: [] }]), "One");
assert.equal(
cleanWalkRead({ items: Array.from({ length: 20 }, (_, i) => ({ text: `t${i}` })) })?.items.length,
8,
);
assert.equal(parseWalkRead("I could not read that."), null);
// ── "Did it hear me?" ──────────────────────────────────────────────────────
assert.deepEqual(walkPages(walk), ["/de", "/de/features", "/portal/dashboard", "/portal/settings"]);
assert.equal(heardLine(walk, 45_000), "Loki heard you · 0:45 across 4 pages");
assert.equal(
heardLine(walk),
"Loki heard you · 0:43 across 4 pages",
"the last moment, without a clock",
);
assert.equal(heardLine([{ at: 0, page: "/", label: "Home" }], 12_000), "Loki heard you · 0:12");
assert.equal(heardLine([], 0), "Loki heard you");
// ── Ask sees the whole walk, not only the page the panel is open on ────────
const session = walkSession(walk);
assert.match(session, /^A spoken walk through the site, in order:/);
for (const m of walk) assert.ok(session.includes(m.page), `${m.page} is in the walk`);
assert.match(
session,
/0:40 \/portal\/settings — “Your data” \| on screen: Download my data \| said: In general/,
);
assert.match(session, /“Profile” \(marked\)/);
assert.ok(walkSession(walk, 120).length <= 120, "bounded");
// ── The prompt carries the pages and the words, and says what they are ─────
const prompt = walkReadPrompt({ project: "Petvity", note: "On /de — x:\nwords", moments: walk });
assert.match(prompt, /Site: Petvity/);
assert.match(
prompt,
/Pages they went through, in order: \/de, \/de\/features, \/portal\/dashboard, \/portal\/settings/,
);
assert.match(prompt, /```\nOn \/de — x:\nwords\n```/);
// The moments are numbered for the items' parts, with what was pointed at.
assert.match(prompt, /#0 0:00 \/de — “Dein Tier/);
assert.match(prompt, /#4 0:43 \/portal\/settings — “Profile” \| marked/);
assert.match(prompt, /#3 .* on screen: Download my data/);
// ── A site-wide finding is said once per visit ─────────────────────────────
const lang =
"The page does not declare its language (<html lang>), so screen readers guess the pronunciation";
const taps = "6 tap target(s) are under 24px and crowded by their neighbours";
const said = new Set<string>();
const first = onceSiteWide([taps, lang], said);
assert.deepEqual(first.checks, [taps, lang], "said on the first page");
for (const k of first.keys) said.add(k);
const second = onceSiteWide(["3 button(s)/link(s) have no name", lang], said);
assert.deepEqual(second.checks, ["3 button(s)/link(s) have no name"], "not on the next");
assert.deepEqual(second.keys, []);
assert.deepEqual(onceSiteWide([taps], said).checks, [taps], "page findings are always said");
// The page it was first said on keeps it: that page's card is re-read on a
// revisit, and dropping the line there made the finding look fixed.
const onPath = new Set<string>();
for (const k of onceSiteWide([lang], onPath, "/a").keys) onPath.add(k);
assert.deepEqual(onceSiteWide([lang], onPath, "/a").checks, [lang], "back on /a: still said");
assert.deepEqual(onceSiteWide([lang], onPath, "/b").checks, [], "on /b: said once already");
// ── Wiring: the pieces are where they must be ──────────────────────────────
const model = readFileSync("widget/conversation-model.ts", "utf8");
assert.match(model, /understandNote\(/, "a recorded note is read");
assert.match(model, /const untouched = draft\.text === note\.verbatim;/, "edited words are kept");
const view = readFileSync("widget/conversation.ts", "utf8");
assert.match(view, /heardLine\(draft\.moments/, "the card says what it heard");
assert.match(view, /noteExtras\(draft/, "the asides and the words as spoken are drawn");
assert.match(
readFileSync("widget/voice-note-card.ts", "utf8"),
/Use my exact words instead/,
"the words as spoken are one tap away",
);
assert.match(view, /model\.askAboutNote\(text\)/, "Ask takes the whole walk");
assert.match(
readFileSync("src/proxy.ts", "utf8"),
/api\/widget\/understand\|/,
"the route answers cross-origin without a Loki session",
);
assert.match(readFileSync("widget/watch.ts", "utf8"), /onceSiteWide\(checks, said, path\)/);
// The read is one call per note, read before anything is built: the strong
// model, with instructions that say what "these things" must become.
const route = readFileSync("src/app/api/widget/understand/route.ts", "utf8");
assert.match(route, /model: GROQ_STRONG_MODEL/);
assert.match(
readFileSync("src/lib/feedback/walk-read-prompt.ts", "utf8"),
/That is only what was on screen\. People talk freely while they scroll/,
"what was on screen is background, not what they meant",
);
assert.match(view, /model\.sendItems\(contact\.value, intent\)/, "each change is saved on its own");
console.log("widget-walk-read: ok");