mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 05:37:19 +01:00
* 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>
1019 lines
41 KiB
TypeScript
1019 lines
41 KiB
TypeScript
/**
|
|
* Watch mode in the page: the listeners that keep the trail, and the pill
|
|
* that says, the whole time, that Loki is watching.
|
|
*
|
|
* Owner only — main.ts starts it when this browser holds the owner pass from
|
|
* Loki's "Open your site" link — and never silent: while it records, the pill
|
|
* is on screen; one tap pauses it, and paused it records nothing. The trail
|
|
* and what counts as a failure are watch-trail.ts (pure, tested).
|
|
*/
|
|
import { TARGET_SVG, h } from "./dom";
|
|
import type { WidgetTheme } from "./theme";
|
|
import { buildSuggestion, type ReportDiagnostics } from "./report-payload";
|
|
import {
|
|
failureSignature,
|
|
watchReport,
|
|
WATCH_REPORTS_PER_PAGE,
|
|
describeControl,
|
|
describeRequest,
|
|
freshTrail,
|
|
isFailedRequest,
|
|
isNoticeableRequest,
|
|
nextTapStreak,
|
|
explainChecks,
|
|
onceSiteWide,
|
|
explainNotice,
|
|
noticeSignature,
|
|
sessionForReview,
|
|
SLOW_REQUEST_MS,
|
|
trailDiagnostics,
|
|
type TapStreak,
|
|
isNoiseError,
|
|
pushTrail,
|
|
type Failure,
|
|
type Notice,
|
|
type NoticeKind,
|
|
type TrailEntry,
|
|
checksSignature,
|
|
checksSlot,
|
|
} from "./watch-trail";
|
|
import { runPageChecks, settledPageChecks } from "./page-checks";
|
|
import { pageLabel } from "./page-label";
|
|
import { sendReport } from "./send-report";
|
|
import { FIX_STARTED, remarkVerdict, type KnownFix } from "./known-fixes";
|
|
import { pressVerb } from "./press";
|
|
|
|
const pausedKey = (token: string) => `loki-watch-paused:${token}`;
|
|
/** Per tab, per site: a multi-page site reloads on every link, and Review must
|
|
* still see the whole visit. sessionStorage dies with the tab, which is the
|
|
* right lifetime for "what I just did". */
|
|
const trailKey = (token: string) => `loki-watch-trail:${token}`;
|
|
|
|
function readStoredTrail(token: string): TrailEntry[] {
|
|
try {
|
|
return freshTrail(JSON.parse(sessionStorage.getItem(trailKey(token)) ?? "[]"), Date.now());
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function writeStoredTrail(token: string, trail: TrailEntry[]): void {
|
|
try {
|
|
sessionStorage.setItem(trailKey(token), JSON.stringify(trail));
|
|
} catch {
|
|
/* storage blocked or full: the trail lasts for this page view */
|
|
}
|
|
}
|
|
|
|
/** Long tasks shorter than this are not felt; longer ones freeze taps. */
|
|
const LONG_TASK_MS = 300;
|
|
/** Remarks of one kind per page view, at most — a janky page must not fill
|
|
* the whole trail with "froze 320ms". */
|
|
const NOTICES_PER_KIND = 3;
|
|
/** Cumulative Layout Shift above this is "poor" by Google's own threshold. */
|
|
const CLS_POOR = 0.1;
|
|
/** A page that takes longer than this to load has lost some of its visitors. */
|
|
const SLOW_LOAD_MS = 3_000;
|
|
/** How long a tap has to show it did something before Loki says it didn't. */
|
|
const TAP_RESULT_MS = 1_500;
|
|
/** A remark names the tap that led to it when that tap was this recent. */
|
|
const TAP_LEADS_MS = 5_000;
|
|
|
|
export function readWatchPaused(token: string): boolean {
|
|
try {
|
|
return localStorage.getItem(pausedKey(token)) === "1";
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export function writeWatchPaused(token: string, paused: boolean): void {
|
|
try {
|
|
if (paused) localStorage.setItem(pausedKey(token), "1");
|
|
else localStorage.removeItem(pausedKey(token));
|
|
} catch {
|
|
/* private mode: the choice lasts for this page view */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Start recording. `ownOrigin` requests (the widget talking to Loki) are not
|
|
* the site's and are left out. `isActive` is read on every event, so pausing
|
|
* stops recording at once without unhooking anything.
|
|
*/
|
|
export function installWatch(opts: {
|
|
host: HTMLElement;
|
|
/** Keys the trail kept across this tab's page loads. */
|
|
token: string;
|
|
/** The widget's own calls to Loki — not the site's, so not recorded. */
|
|
isOwnRequest: (url: string) => boolean;
|
|
isActive: () => boolean;
|
|
onFailure: (failure: Failure, trail: TrailEntry[]) => void;
|
|
/** Something new went into the trail (the pill keeps its count from this). */
|
|
onChange?: (trail: TrailEntry[]) => void;
|
|
/** A remark worth saying out loud — Loki tells the owner in the thread. */
|
|
onNotice?: (notice: Notice) => void;
|
|
/** The site moved to another page (SPA navigation) — time to look at it. */
|
|
onPage?: () => void;
|
|
/** One of the widget's OWN calls to Loki finished — not the site's business,
|
|
* but Loki's (self-watch.ts). */
|
|
onOwnRequest?: (method: string, url: string, status: number | null, ms: number) => void;
|
|
}): { trail: () => TrailEntry[]; note: (kind: TrailEntry["kind"], text: string) => void } {
|
|
let trail: TrailEntry[] = readStoredTrail(opts.token);
|
|
const add = (kind: TrailEntry["kind"], text: string) => {
|
|
if (!opts.isActive()) return;
|
|
const next = pushTrail(trail, { at: Date.now(), kind, text });
|
|
if (next === trail) return;
|
|
trail = next;
|
|
writeStoredTrail(opts.token, trail);
|
|
opts.onChange?.(trail);
|
|
};
|
|
const noticed = new Map<string, number>();
|
|
/** A remark, rationed per kind per page view (see NOTICES_PER_KIND). */
|
|
const notice = (kind: NoticeKind, text: string) => {
|
|
if (!opts.isActive()) return;
|
|
const n = noticed.get(kind) ?? 0;
|
|
if (n >= NOTICES_PER_KIND) return;
|
|
noticed.set(kind, n + 1);
|
|
// The notes read "Noticed: button “Save” did nothing visible" — one line,
|
|
// not a bare control name under a separate "nothing happened".
|
|
add("notice", kind === "noeffect" ? `${text} did nothing visible` : text);
|
|
// Name the tap that led here when it was a moment ago; a freeze already
|
|
// names its own tap in the text.
|
|
const recent = lastTap && performance.now() - lastTap.at < TAP_LEADS_MS;
|
|
// A freeze or a do-nothing tap already names its own tap in the text.
|
|
const named = kind === "longtask" || kind === "noeffect";
|
|
opts.onNotice?.({ kind, text, after: !named && recent ? lastTap?.what : null });
|
|
};
|
|
let streak: TapStreak = null;
|
|
/** The last tap on the site (performance clock) — a freeze right after it
|
|
* is one the person felt (see observePerformance). */
|
|
let lastTap: { at: number; what: string } | null = null;
|
|
const fail = (failure: Failure) => {
|
|
if (!opts.isActive()) return;
|
|
// A dead tap is already in the trail as the tap itself.
|
|
if (failure.kind !== "dead-tap")
|
|
add(failure.kind === "request" ? "request" : "error", failure.text);
|
|
opts.onFailure(failure, trail);
|
|
};
|
|
|
|
// ---- what a tap DID ----
|
|
// Watching taps is only half of watching: the other half is whether the page
|
|
// answered. A tap on a button or link waits up to TAP_RESULT_MS for any sign
|
|
// — the page changing, a request, a navigation — and the notes say which.
|
|
// No sign at all is worth saying at once, not only after three taps (the
|
|
// dead-tap rule below files a fix; this one is a remark).
|
|
let pendingTap: { what: string; timer: ReturnType<typeof setTimeout> } | null = null;
|
|
const tapObserver = new MutationObserver((records) => {
|
|
if (records.some((r) => !isOurNode(r.target, opts.host))) settleTap("the page changed");
|
|
});
|
|
const settleTap = (result: string | null) => {
|
|
if (!pendingTap) return;
|
|
clearTimeout(pendingTap.timer);
|
|
pendingTap = null;
|
|
tapObserver.disconnect();
|
|
if (result) add("result", result);
|
|
};
|
|
const watchTap = (what: string) => {
|
|
settleTap(null);
|
|
const timer = setTimeout(() => {
|
|
if (!pendingTap) return;
|
|
settleTap(null);
|
|
notice("noeffect", what);
|
|
}, TAP_RESULT_MS);
|
|
pendingTap = { what, timer };
|
|
tapObserver.observe(document.documentElement, {
|
|
subtree: true,
|
|
childList: true,
|
|
attributes: true,
|
|
characterData: true,
|
|
});
|
|
};
|
|
// Leaving the page or jumping within it is an answer too.
|
|
window.addEventListener("beforeunload", () => settleTap(null));
|
|
window.addEventListener("hashchange", () => settleTap("it moved within the page"));
|
|
|
|
add("page", location.pathname);
|
|
let lastPath = location.pathname;
|
|
const notePage = () => {
|
|
if (location.pathname === lastPath) return;
|
|
lastPath = location.pathname;
|
|
settleTap(null);
|
|
streak = null;
|
|
noticed.clear();
|
|
add("page", location.pathname);
|
|
opts.onPage?.();
|
|
};
|
|
for (const name of ["pushState", "replaceState"] as const) {
|
|
const original = history[name];
|
|
history[name] = function (this: History, ...args: Parameters<History["pushState"]>) {
|
|
const out = original.apply(this, args);
|
|
notePage();
|
|
return out;
|
|
} as History["pushState"];
|
|
}
|
|
window.addEventListener("popstate", notePage);
|
|
|
|
document.addEventListener(
|
|
"click",
|
|
(e) => {
|
|
if (e.composedPath().includes(opts.host)) return;
|
|
const target = e.target instanceof Element ? e.target : null;
|
|
const el =
|
|
target?.closest("button,a,[role=button],input,select,textarea,label,summary") ?? target;
|
|
if (!el) return;
|
|
const tap = describeControl({
|
|
tag: el.tagName,
|
|
role: el.getAttribute("role"),
|
|
type: el.getAttribute("type"),
|
|
label: el.getAttribute("aria-label"),
|
|
// Text of a control, never the value of a field.
|
|
text:
|
|
el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement
|
|
? null
|
|
: controlText(el),
|
|
placeholder: el.getAttribute("placeholder"),
|
|
});
|
|
add("tap", tap);
|
|
lastTap = { at: e.timeStamp, what: tap };
|
|
if (!opts.isActive()) return;
|
|
// A disabled control or a link that opens elsewhere answers somewhere
|
|
// Loki cannot see; only what should change THIS page is waited on.
|
|
const opensElsewhere = el instanceof HTMLAnchorElement && el.target === "_blank";
|
|
const disabled = el.matches(":disabled,[aria-disabled=true]");
|
|
if (/^(button|link)\b/.test(tap) && !opensElsewhere && !disabled) watchTap(tap);
|
|
const next = nextTapStreak(streak, tap, Date.now());
|
|
streak = next.streak;
|
|
if (next.dead) fail({ kind: "dead-tap", text: tap });
|
|
},
|
|
true,
|
|
);
|
|
|
|
window.addEventListener("error", (e) => {
|
|
const message = e.error instanceof Error ? e.error.message : e.message;
|
|
if (!message || isNoiseError(message)) return;
|
|
if (e.filename && e.filename.includes("widget.js")) return;
|
|
fail({ kind: "error", text: message });
|
|
});
|
|
window.addEventListener("unhandledrejection", (e) => {
|
|
const reason = e.reason instanceof Error ? e.reason.message : String(e.reason ?? "");
|
|
if (!reason || isNoiseError(reason)) return;
|
|
fail({ kind: "error", text: reason });
|
|
});
|
|
|
|
const onRequest = (method: string, url: string, status: number | null, ms: number) => {
|
|
const href = new URL(url, location.href).href;
|
|
if (opts.isOwnRequest(href)) {
|
|
if (opts.isActive()) opts.onOwnRequest?.(method, href, status, ms);
|
|
return;
|
|
}
|
|
// The page answered the tap, so the button was not dead.
|
|
streak = null;
|
|
const text = describeRequest(method, url, status);
|
|
if (isFailedRequest(status)) fail({ kind: "request", text });
|
|
else if (isNoticeableRequest(status, ms)) {
|
|
const slow = ms >= SLOW_REQUEST_MS;
|
|
// The duration is only news when it was slow; "404 in 0.0s" is noise.
|
|
notice(slow ? "slow" : "4xx", describeRequest(method, url, status, slow ? ms : undefined));
|
|
} else if (!/^GET /.test(text)) add("request", text);
|
|
};
|
|
|
|
// A page being left cancels whatever it was still asking for, and the
|
|
// browser reports that as "never answered". That is navigation, not a
|
|
// broken server: no report for requests cut off while the page goes away
|
|
// or sits in the background (the "never answered after 0.3s" reports,
|
|
// 2026-10-16, were Loki's own pages being left mid-poll).
|
|
let leaving = false;
|
|
window.addEventListener("pagehide", () => (leaving = true));
|
|
window.addEventListener("beforeunload", () => (leaving = true));
|
|
window.addEventListener("pageshow", () => (leaving = false));
|
|
// A phone that locks or switches app suspends the page, and what it was
|
|
// asking for fails when it wakes — AFTER it is visible again, so "hidden
|
|
// now" missed it. A request that lived through the page being put away is
|
|
// cut off, whenever its failure surfaces.
|
|
let away = 0;
|
|
document.addEventListener("visibilitychange", () => {
|
|
if (document.visibilityState === "hidden") away++;
|
|
});
|
|
window.addEventListener("pagehide", () => away++);
|
|
const cutOff = (since: number) =>
|
|
leaving || since !== away || document.visibilityState === "hidden" || !navigator.onLine;
|
|
|
|
const originalFetch = window.fetch.bind(window);
|
|
window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
|
|
// A request leaving is the page responding — even a slow one is not dead.
|
|
if (!opts.isOwnRequest(new URL(url, location.href).href)) {
|
|
streak = null;
|
|
// Answered the moment it asks — a slow server is not a dead button.
|
|
settleTap("it asked the server");
|
|
}
|
|
const started = performance.now();
|
|
const since = away;
|
|
try {
|
|
const res = await originalFetch(input, init);
|
|
onRequest(method, url, res.status, performance.now() - started);
|
|
return res;
|
|
} catch (err) {
|
|
// An aborted request is the page changing its mind, not a failure.
|
|
if (!(err instanceof DOMException && err.name === "AbortError") && !cutOff(since))
|
|
onRequest(method, url, null, performance.now() - started);
|
|
throw err;
|
|
}
|
|
};
|
|
|
|
const open = XMLHttpRequest.prototype.open;
|
|
XMLHttpRequest.prototype.open = function (
|
|
this: XMLHttpRequest & { __lokiReq?: [string, string] },
|
|
method: string,
|
|
url: string | URL,
|
|
...rest: unknown[]
|
|
) {
|
|
this.__lokiReq = [method, String(url)];
|
|
if (!opts.isOwnRequest(new URL(String(url), location.href).href)) {
|
|
streak = null;
|
|
settleTap("it asked the server");
|
|
}
|
|
const started = performance.now();
|
|
const since = away;
|
|
this.addEventListener("loadend", () => {
|
|
const [m, u] = this.__lokiReq ?? ["GET", ""];
|
|
if (this.status === 0 && cutOff(since)) return;
|
|
onRequest(m, u, this.status === 0 ? null : this.status, performance.now() - started);
|
|
});
|
|
return (open as (...a: unknown[]) => void).call(this, method, url, ...rest);
|
|
} as typeof XMLHttpRequest.prototype.open;
|
|
|
|
// The site's own console.error: what its developers already know is wrong
|
|
// and left in. Never a fix by itself — frameworks log warnings here too —
|
|
// but a reviewer reading it next to the tap that caused it learns a lot.
|
|
const originalConsoleError = console.error.bind(console);
|
|
console.error = (...args: unknown[]) => {
|
|
originalConsoleError(...args);
|
|
try {
|
|
const first = args[0] instanceof Error ? args[0].message : String(args[0] ?? "");
|
|
if (first && !first.startsWith("[loki-widget]") && !isNoiseError(first))
|
|
notice("console", `console error: ${first.slice(0, 140)}`);
|
|
} catch {
|
|
/* never let recording break the site's own logging */
|
|
}
|
|
};
|
|
|
|
observePerformance(notice, opts.host, () => lastTap);
|
|
|
|
return { trail: () => trail, note: add };
|
|
}
|
|
|
|
/** A freeze this soon after a tap on the site is one the person felt. */
|
|
const FELT_FREEZE_WINDOW_MS = 1_000;
|
|
|
|
function isOurNode(node: Node | null | undefined, host: HTMLElement): boolean {
|
|
if (!node) return false;
|
|
const root = node.getRootNode();
|
|
return node === host || host.contains(node) || (root instanceof ShadowRoot && root.host === host);
|
|
}
|
|
|
|
/**
|
|
* What the page feels like rather than what it does: how long it took to load,
|
|
* the main thread freezing under a tap, content jumping as it loads. Each is
|
|
* a remark (never a fix by itself), in words a non-engineer can read.
|
|
*/
|
|
function observePerformance(
|
|
notice: (kind: NoticeKind, text: string) => void,
|
|
host: HTMLElement,
|
|
lastTap: () => { at: number; what: string } | null,
|
|
): void {
|
|
const nav = () => {
|
|
const entry = performance.getEntriesByType("navigation")[0] as
|
|
PerformanceNavigationTiming | undefined;
|
|
if (!entry || !entry.loadEventEnd) return;
|
|
const ms = entry.loadEventEnd - entry.startTime;
|
|
if (ms >= SLOW_LOAD_MS) notice("load", `this page took ${(ms / 1000).toFixed(1)}s to load`);
|
|
};
|
|
if (document.readyState === "complete") setTimeout(nav, 0);
|
|
else window.addEventListener("load", () => setTimeout(nav, 0), { once: true });
|
|
|
|
const observe = (type: string, onEntries: (list: PerformanceEntryList) => void) => {
|
|
try {
|
|
if (!PerformanceObserver.supportedEntryTypes?.includes(type)) return;
|
|
new PerformanceObserver((list) => onEntries(list.getEntries())).observe({
|
|
type,
|
|
buffered: true,
|
|
});
|
|
} catch {
|
|
/* an older browser: one signal fewer, nothing broken */
|
|
}
|
|
};
|
|
// Only a freeze that answers a tap on the SITE counts. A long task carries
|
|
// no script attribution, so one during load could be anyone's — including
|
|
// this widget booting, or Review reading the page — and a reviewer that
|
|
// blames the site for Loki's own work is worse than one that says nothing.
|
|
observe("longtask", (entries) => {
|
|
const tap = lastTap();
|
|
for (const e of entries) {
|
|
if (e.duration < LONG_TASK_MS || !tap) continue;
|
|
// Overlap, not "starts after": the task that RUNS the tap handler began
|
|
// a moment before this listener saw the tap.
|
|
const overlaps =
|
|
e.startTime + e.duration >= tap.at && e.startTime <= tap.at + FELT_FREEZE_WINDOW_MS;
|
|
if (overlaps)
|
|
notice(
|
|
"longtask",
|
|
`after ${tap.what} the page froze for ${Math.round(e.duration)}ms (clicks and taps go unanswered meanwhile)`,
|
|
);
|
|
}
|
|
});
|
|
let cls = 0;
|
|
let clsNoted = false;
|
|
observe("layout-shift", (entries) => {
|
|
for (const e of entries as (PerformanceEntry & {
|
|
value?: number;
|
|
hadRecentInput?: boolean;
|
|
sources?: { node?: Node | null }[];
|
|
})[]) {
|
|
// A shift right after the person's own input is the page responding.
|
|
// Only shifts the browser can pin on a node of the SITE count: Chrome
|
|
// reports Loki's own panel (shadow DOM) with a null node, and opening
|
|
// Review once scored 0.27 against a page that never moved.
|
|
const site = (e.sources ?? []).some((s) => s.node && !isOurNode(s.node, host));
|
|
if (!e.hadRecentInput && site) cls += e.value ?? 0;
|
|
}
|
|
if (!clsNoted && cls > CLS_POOR) {
|
|
clsNoted = true;
|
|
notice(
|
|
"cls",
|
|
`content jumped around on this page (layout shift ${cls.toFixed(2)}, poor above ${CLS_POOR})`,
|
|
);
|
|
}
|
|
});
|
|
}
|
|
|
|
export type WatchPillState =
|
|
| { kind: "watching"; latest?: string }
|
|
| { kind: "paused" }
|
|
| { kind: "sending"; what: string }
|
|
| { kind: "fixing"; what: string; followUrl: string }
|
|
| { kind: "not-sent"; what: string };
|
|
|
|
/**
|
|
* The always-visible sign that Loki is watching: a bar at the top of the page.
|
|
* It says in plain words what Loki is doing — and, the moment it notices
|
|
* something, what that was — with Show (open the conversation where Loki said
|
|
* it) and Stop watching. Nobody has to wonder whether they are being recorded,
|
|
* or hunt for how to stop it.
|
|
*/
|
|
export function createWatchPill(
|
|
root: ShadowRoot,
|
|
theme: WidgetTheme,
|
|
onToggle: () => void,
|
|
onShow: () => void,
|
|
onPoint?: () => void,
|
|
): { set: (state: WatchPillState) => void; setVisible: (visible: boolean) => void } {
|
|
const style = h("style");
|
|
style.textContent = `
|
|
.watch-pill {
|
|
position: fixed; top: max(8px, env(safe-area-inset-top)); left: 12px; right: 12px; margin: 0 auto; width: max-content;
|
|
z-index: 2147483646; display: flex; align-items: center; gap: 8px; max-width: min(560px, calc(100vw - 24px));
|
|
padding: 6px 6px 6px 12px; border-radius: 999px; border: 1px solid ${theme.borderStrong};
|
|
background: ${theme.surfaceRaised}; color: ${theme.text}; font-size: 12px; line-height: 1.3;
|
|
box-shadow: 0 4px 16px rgba(0,0,0,.18);
|
|
}
|
|
.watch-pill .wdot { width: 8px; height: 8px; border-radius: 50%; flex: none; background: ${theme.accent}; box-shadow: 0 0 0 3px ${theme.accentMuted}; animation: wpulse 2s ease-in-out infinite; }
|
|
.watch-pill.paused .wdot { background: ${theme.textMuted}; box-shadow: none; animation: none; }
|
|
.watch-pill.alert .wdot { background: ${theme.error}; box-shadow: 0 0 0 3px ${theme.errorSurface}; }
|
|
.watch-pill.said { border-color: ${theme.accent}; }
|
|
.watch-pill .wtext { min-width: 0; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
|
|
.watch-pill .wtext a { color: inherit; text-decoration: underline; }
|
|
.watch-pill .wbtn + .wbtn { margin-left: -4px; }
|
|
.watch-pill .wbtn { flex: none; min-height: 28px; padding: 0 10px; border-radius: 999px; border: 1px solid ${theme.border}; color: ${theme.textSecondary}; font-size: 11px; white-space: nowrap; }
|
|
.watch-pill .wbtn.primary { border-color: ${theme.accent}; background: ${theme.accentMuted}; color: ${theme.text}; font-weight: 600; }
|
|
.watch-pill .wpoint { padding: 0 8px; color: ${theme.accent}; display: inline-flex; align-items: center; gap: 4px; }
|
|
.watch-pill .wpoint svg { width: 16px; height: 16px; }
|
|
@media (pointer: coarse) { .watch-pill .wbtn { min-height: 32px; } }
|
|
@keyframes wpulse { 50% { opacity: .45; } }
|
|
@media (prefers-reduced-motion: reduce) { .watch-pill .wdot { animation: none; } }
|
|
`;
|
|
const pill = h("div", "watch-pill");
|
|
pill.setAttribute("role", "status");
|
|
pill.setAttribute("aria-live", "polite");
|
|
const dot = h("span", "wdot");
|
|
const text = h("span", "wtext");
|
|
const showBtn = h("button", "wbtn", "Show");
|
|
showBtn.title = "Open the conversation with Loki";
|
|
showBtn.addEventListener("click", onShow);
|
|
// The same ◎ the launcher carries, so the bar (the fallback when a site
|
|
// hides the launcher) offers exactly what the launcher does.
|
|
const pointBtn = h("button", "wbtn wpoint");
|
|
pointBtn.innerHTML = `${TARGET_SVG}<span>Point</span>`;
|
|
pointBtn.title = "Show Loki something on this page";
|
|
pointBtn.setAttribute("aria-label", "Show Loki something on this page");
|
|
pointBtn.addEventListener("click", () => onPoint?.());
|
|
const toggle = h("button", "wbtn");
|
|
toggle.addEventListener("click", onToggle);
|
|
pill.append(dot, text, showBtn, pointBtn, toggle);
|
|
root.append(style, pill);
|
|
|
|
const set = (state: WatchPillState) => {
|
|
const said = state.kind === "watching" && !!state.latest;
|
|
pill.className = `watch-pill${state.kind === "paused" ? " paused" : ""}${said ? " said" : ""}${
|
|
state.kind === "sending" || state.kind === "fixing" || state.kind === "not-sent"
|
|
? " alert"
|
|
: ""
|
|
}`;
|
|
text.textContent = "";
|
|
pill.title = "what" in state ? state.what : said ? (state.latest ?? "") : "";
|
|
toggle.textContent = state.kind === "paused" ? "Watch again" : "Stop watching";
|
|
showBtn.classList.toggle("primary", said || state.kind === "fixing");
|
|
switch (state.kind) {
|
|
case "watching":
|
|
text.textContent = state.latest
|
|
? `Loki noticed: ${state.latest}`
|
|
: "Loki is watching you use this site";
|
|
break;
|
|
case "paused":
|
|
text.textContent = "Loki stopped watching — nothing is recorded";
|
|
break;
|
|
case "sending":
|
|
text.textContent = "Something broke — telling Loki…";
|
|
break;
|
|
case "fixing": {
|
|
text.append("Something broke — Loki is fixing it · ");
|
|
const a = h("a", undefined, "Follow");
|
|
a.href = state.followUrl;
|
|
a.target = "_blank";
|
|
a.rel = "noopener";
|
|
text.append(a);
|
|
break;
|
|
}
|
|
case "not-sent":
|
|
text.textContent = `Something broke — couldn't reach Loki. ${pressVerb().Verb} Show to send it.`;
|
|
break;
|
|
}
|
|
};
|
|
set({ kind: "watching" });
|
|
return {
|
|
set,
|
|
setVisible: (visible: boolean) => {
|
|
pill.style.display = visible ? "" : "none";
|
|
},
|
|
};
|
|
}
|
|
|
|
/** The ingest's cap on `suggestion` (api/feedback FeedbackBody). */
|
|
const SUGGESTION_MAX = 2000;
|
|
|
|
/** How long "Loki is fixing …" stays before the pill goes back to watching. */
|
|
const FIXING_SHOWN_MS = 30_000;
|
|
/** Let the page settle (fonts, late images) before Loki looks at it. */
|
|
const CHECKS_DELAY_MS = 2_500;
|
|
|
|
/** What Loki says in the conversation when it noticed something. */
|
|
export type Remark = {
|
|
say: string;
|
|
fix: string;
|
|
filed?: boolean;
|
|
/** The bar's one line. */ short?: string;
|
|
/** The remark's signature: what "Fix this" files, and what its status is looked up by. */
|
|
key: string;
|
|
/** Loki fixed this before (the fix is live) and it is back. */
|
|
again?: boolean;
|
|
};
|
|
|
|
const saidKey = (token: string) => `loki-watch-said:${token}`;
|
|
|
|
/** Remarks already made this visit — a reload must not repeat them. */
|
|
function readSaid(token: string): Set<string> {
|
|
try {
|
|
const raw = JSON.parse(sessionStorage.getItem(saidKey(token)) ?? "[]") as unknown;
|
|
return new Set(Array.isArray(raw) ? raw.filter((s): s is string => typeof s === "string") : []);
|
|
} catch {
|
|
return new Set();
|
|
}
|
|
}
|
|
|
|
function writeSaid(token: string, said: Set<string>): void {
|
|
try {
|
|
sessionStorage.setItem(saidKey(token), JSON.stringify([...said].slice(-100)));
|
|
} catch {
|
|
/* storage blocked: Loki may repeat itself after a reload, nothing worse */
|
|
}
|
|
}
|
|
|
|
/** A failure, in the owner's words (watch files the fix itself). */
|
|
function failureSay(f: Failure): string {
|
|
return f.kind === "dead-tap"
|
|
? `You pressed ${f.text} three times and nothing happened.`
|
|
: f.kind === "request"
|
|
? `Something broke: the page asked for ${f.text.replace(/^[A-Z]+ /, "").replace(/ \u2192 /, " and got ")}.`
|
|
: `Something broke: the page hit an error — “${f.text}”.`;
|
|
}
|
|
|
|
/**
|
|
* Watch mode, whole: the bar, stop/start, the recorder, the fix a failure
|
|
* files, and the remarks Loki makes out loud. A failure files at most once per
|
|
* distinct cause and at most WATCH_REPORTS_PER_PAGE times per page load — one
|
|
* broken request retried in a loop must not start forty builds. A remark is
|
|
* made once per visit (signatures kept per tab), so reloading a page with a
|
|
* known problem does not repeat it.
|
|
*/
|
|
export function startWatchMode(opts: {
|
|
root: ShadowRoot;
|
|
host: HTMLElement;
|
|
theme: WidgetTheme;
|
|
token: string;
|
|
apiBase: string;
|
|
/** The owner pass as it stands now (null once the server refuses it). */
|
|
pass: () => string | null;
|
|
/** Show on the bar: open the conversation. */
|
|
onShow: () => void;
|
|
/** ◎ on the bar: point at something, as the launcher's ◎ does. */
|
|
onPoint?: () => void;
|
|
/** Loki noticed something — say it in the conversation. */
|
|
onRemark: (remark: Remark) => void;
|
|
/** The newest reading of a page found nothing: take back the card that
|
|
* slot (watch-trail.ts checksSlot) held. */
|
|
onWithdraw?: (slot: string) => void;
|
|
/** True while the launcher or the open panel already shows that Loki is
|
|
* watching — then the top bar stays out of the site's way. */
|
|
statusShown: () => boolean;
|
|
/** Stopped or started again — the panel's header follows. */
|
|
onChange?: () => void;
|
|
/** A step went into the trail — the panel's running notes follow. */
|
|
onTrail?: (trail: TrailEntry[]) => void;
|
|
/** Loki's own read of the page (loki-api READ_QUESTION): what a ruler
|
|
* cannot measure — purpose, hierarchy, content, fit. Null: nothing to say. */
|
|
read?: () => Promise<{ say: string; changes: string[] } | null>;
|
|
/** What Loki already did about a finding (widget/changes.ts → known-fixes.ts). */
|
|
known?: (key: string) => KnownFix | null;
|
|
/** Settles once the owner's fixes have been read, so Watch looks before it speaks. */
|
|
knownReady?: () => Promise<void>;
|
|
/** The widget's own calls to Loki (self-watch.ts). */
|
|
onOwnRequest?: (method: string, url: string, status: number | null, ms: number) => void;
|
|
}): WatchSession {
|
|
let paused = readWatchPaused(opts.token);
|
|
const sent = new Set<string>();
|
|
const said = readSaid(opts.token);
|
|
let latest: string | undefined;
|
|
let reverting: ReturnType<typeof setTimeout> | null = null;
|
|
let recorder: ReturnType<typeof installWatch> | null = null;
|
|
const watching = (): WatchPillState => ({ kind: "watching", latest });
|
|
const session = () => sessionForReview(recorder?.trail() ?? [], safePageChecks(), Date.now());
|
|
const setPaused = (value: boolean) => {
|
|
paused = value;
|
|
writeWatchPaused(opts.token, paused);
|
|
if (!paused) latest = undefined;
|
|
show(paused ? { kind: "paused" } : watching());
|
|
opts.onChange?.();
|
|
if (!paused) scheduleChecks();
|
|
};
|
|
const pill = createWatchPill(
|
|
opts.root,
|
|
opts.theme,
|
|
() => setPaused(!paused),
|
|
opts.onShow,
|
|
opts.onPoint,
|
|
);
|
|
// The bar is the fallback, not the main signal: shown only when neither the
|
|
// launcher nor the open panel can say that Loki is watching (a page that
|
|
// hides the launcher with data-fc-place="hidden"; a page that blocks every
|
|
// corner gets the edge tab, which counts as shown). Re-checked each second.
|
|
// A modal the site opened (a sheet, a dialog) is what the person is doing
|
|
// right now; the bar used to sit on top of it, over the sheet's own title
|
|
// (operator's phone, 2026-10-11: "Choose a model" under "Loki noticed…").
|
|
const syncBar = () => pill.setVisible(!opts.statusShown() && !hostModalOpen(opts.host));
|
|
syncBar();
|
|
window.setInterval(syncBar, 1000);
|
|
/** What the pill shows now — a remark never covers "Loki is fixing it". */
|
|
let shown: WatchPillState["kind"] = "watching";
|
|
const show = (state: WatchPillState) => {
|
|
shown = state.kind;
|
|
pill.set(state);
|
|
};
|
|
show(paused ? { kind: "paused" } : watching());
|
|
const diagnostics = (filedBy: string) => ({
|
|
"filed by": filedBy,
|
|
...trailDiagnostics(recorder?.trail() ?? [], Date.now()),
|
|
});
|
|
|
|
/**
|
|
* Say it once per visit: in the conversation, and on the bar — unless Loki
|
|
* already did something about it. A finding being fixed is not said again
|
|
* (Your changes shows it; a second card was a second commissioning); one
|
|
* fixed and back is said as such; one the owner closed is left alone.
|
|
*/
|
|
const remark = (signature: string, r: Omit<Remark, "key">) => {
|
|
if (paused || said.has(signature)) return;
|
|
said.add(signature);
|
|
writeSaid(opts.token, said);
|
|
const verdict = remarkVerdict(opts.known?.(signature) ?? null);
|
|
if (verdict === "silent") {
|
|
recorder?.note("look", `${r.short ?? r.say.split("\n")[0]} — already with Loki`);
|
|
return;
|
|
}
|
|
opts.onRemark({ ...r, key: signature, ...(verdict === "again" ? { again: true } : {}) });
|
|
latest = r.short ?? r.say.split("\n")[0];
|
|
if (shown === "watching") show(watching());
|
|
};
|
|
|
|
/** Wait for the owner's fixes once, briefly: speaking before they are read is the bug. */
|
|
const KNOWN_WAIT_MS = 4_000;
|
|
const lookFirst = () =>
|
|
Promise.race([
|
|
opts.knownReady?.() ?? Promise.resolve(),
|
|
new Promise<void>((resolve) => setTimeout(resolve, KNOWN_WAIT_MS)),
|
|
]);
|
|
|
|
const report = async (failure: Failure, trail: TrailEntry[]) => {
|
|
const pass = opts.pass();
|
|
const signature = failureSignature(failure);
|
|
if (!pass || sent.has(signature) || sent.size >= WATCH_REPORTS_PER_PAGE) return;
|
|
sent.add(signature);
|
|
if (reverting) clearTimeout(reverting);
|
|
show({ kind: "sending", what: failure.text });
|
|
const { message, diagnostics } = watchReport(failure, trail, Date.now());
|
|
const key = `${location.pathname}|fail|${signature}`;
|
|
let filed = false;
|
|
try {
|
|
await sendReport(opts.apiBase, {
|
|
token: opts.token,
|
|
suggestion: buildSuggestion(message, diagnostics, SUGGESTION_MAX),
|
|
scope: "page",
|
|
ownerPass: pass,
|
|
noticeKey: key,
|
|
});
|
|
filed = true;
|
|
show({ kind: "fixing", what: failure.text, followUrl: `${opts.apiBase}/feedback` });
|
|
reverting = setTimeout(() => {
|
|
if (!paused) show(watching());
|
|
}, FIXING_SHOWN_MS);
|
|
} catch {
|
|
show({ kind: "not-sent", what: failure.text });
|
|
}
|
|
remark(key, {
|
|
say: filed
|
|
? `${failureSay(failure)} ${FIX_STARTED}`
|
|
: `${failureSay(failure)} I couldn't reach Loki to fix it — send it from here.`,
|
|
fix: message,
|
|
filed,
|
|
});
|
|
};
|
|
|
|
// Look at each page once it has settled: what a visitor pays for that
|
|
// nobody sees (unnamed buttons, tiny targets, broken images…).
|
|
let checksTimer: ReturnType<typeof setTimeout> | null = null;
|
|
/** Which reading each page's card shows (checksSlot → checksSignature). */
|
|
const readings = readSlots(opts.token);
|
|
let looking = 0;
|
|
const scheduleChecks = () => {
|
|
if (checksTimer) clearTimeout(checksTimer);
|
|
checksTimer = setTimeout(async () => {
|
|
const turn = ++looking;
|
|
const path = location.pathname;
|
|
await lookFirst();
|
|
if (paused) return;
|
|
// Measured once the page holds still, twice, and only what both
|
|
// readings agree on — never a page caught changing screens.
|
|
const checks = await settledChecks(opts.host);
|
|
// The owner moved on while Loki was looking: that reading is not of
|
|
// the page they are on, and the next look is already scheduled.
|
|
if (paused || turn !== looking || location.pathname !== path) return;
|
|
// Said in the notes even when clean: "looked, all fine" is what the
|
|
// owner could not see while watch only spoke about problems.
|
|
recorder?.note(
|
|
"look",
|
|
checks.length
|
|
? `${checks.length} ${checks.length === 1 ? "thing stands" : "things stand"} out`
|
|
: "nothing stands out",
|
|
);
|
|
// A finding about the whole site is said on the first page only.
|
|
const fresh = onceSiteWide(checks, said, path);
|
|
const slot = checksSlot(path);
|
|
const signature = checksSignature(path, fresh.checks);
|
|
const r = explainChecks(fresh.checks, pageLabel(document.title, path));
|
|
if (!r) {
|
|
// Clean now: a card from an earlier reading of this page is no
|
|
// longer true, so it goes.
|
|
if (readings[slot]) {
|
|
delete readings[slot];
|
|
writeSlots(opts.token, readings);
|
|
opts.onWithdraw?.(slot);
|
|
}
|
|
} else if (readings[slot] !== signature) {
|
|
// One card per page, always the newest reading (thread.ts
|
|
// pushNoticed replaces it in place).
|
|
readings[slot] = signature;
|
|
writeSlots(opts.token, readings);
|
|
said.delete(signature);
|
|
remark(signature, r);
|
|
for (const key of fresh.keys) said.add(key);
|
|
writeSaid(opts.token, said);
|
|
}
|
|
void readPage();
|
|
}, CHECKS_DELAY_MS);
|
|
};
|
|
|
|
// Then READ it. The checks measure; this judges — is it clear what the
|
|
// page is for, does the right thing read first, do the parts belong
|
|
// together. One model call per page per visit, the owner's own site only,
|
|
// and silence when nothing stands out: the note says it looked.
|
|
const readingPages = new Set<string>();
|
|
const readPage = async () => {
|
|
const key = `${location.pathname}|read`;
|
|
if (!opts.read || paused || said.has(key) || readingPages.has(key)) return;
|
|
// A read whose fix is in flight is not made at all — no model call to
|
|
// say again what Loki is already changing.
|
|
const verdict = remarkVerdict(opts.known?.(key) ?? null);
|
|
if (verdict === "silent") {
|
|
said.add(key);
|
|
writeSaid(opts.token, said);
|
|
recorder?.note("look", "read it before — the changes are with Loki");
|
|
return;
|
|
}
|
|
readingPages.add(key);
|
|
const r = await opts.read().catch(() => null);
|
|
readingPages.delete(key);
|
|
if (paused) return;
|
|
if (!r) {
|
|
recorder?.note("look", "could not read this page — try again on your next visit");
|
|
return;
|
|
}
|
|
// A reload can interrupt the async page snapshot before a request is sent.
|
|
// Only a completed read earns the cross-page marker.
|
|
said.add(key);
|
|
writeSaid(opts.token, said);
|
|
if (!r.changes.length) {
|
|
recorder?.note("look", "read it — nothing stands out");
|
|
return;
|
|
}
|
|
recorder?.note(
|
|
"look",
|
|
`read it — ${r.changes.length} ${r.changes.length === 1 ? "thing" : "things"} to change`,
|
|
);
|
|
const list = r.changes.map((c) => `• ${c}`).join("\n");
|
|
opts.onRemark({
|
|
say: `Reading the ${pageLabel(document.title, location.pathname)} page as a visitor:\n${r.say}`,
|
|
fix: `Make these changes on this page, together:\n${list}`,
|
|
short: `reading it, ${r.changes.length === 1 ? "one thing" : `${r.changes.length} things`} could be better`,
|
|
key,
|
|
...(verdict === "again" ? { again: true } : {}),
|
|
});
|
|
latest = `reading it, ${r.changes.length === 1 ? "one thing" : `${r.changes.length} things`} could be better`;
|
|
if (shown === "watching") show(watching());
|
|
};
|
|
|
|
recorder = installWatch({
|
|
host: opts.host,
|
|
token: opts.token,
|
|
// Exactly the widget's own calls. A prefix match on /api/feedback also
|
|
// caught Loki's own app polling /api/feedback/summary, and filed the
|
|
// app's requests as the widget's failures.
|
|
isOwnRequest: (url) => isWidgetCall(url, opts.apiBase),
|
|
isActive: () => !paused && opts.pass() !== null,
|
|
onFailure: (failure, trail) => void report(failure, trail),
|
|
onNotice: (n) => remark(noticeSignature(location.pathname, n), explainNotice(n)),
|
|
onPage: scheduleChecks,
|
|
onChange: (trail) => opts.onTrail?.(trail),
|
|
onOwnRequest: opts.onOwnRequest,
|
|
});
|
|
if (!paused) {
|
|
show(watching());
|
|
scheduleChecks();
|
|
}
|
|
|
|
return {
|
|
on: () => !paused && opts.pass() !== null,
|
|
stop: () => setPaused(true),
|
|
resume: () => setPaused(false),
|
|
session,
|
|
trail: () => recorder?.trail() ?? [],
|
|
diagnostics: () => (paused ? null : diagnostics("Loki watch mode")),
|
|
talked: (text: string) => {
|
|
if (paused) return;
|
|
const line = text.replace(/\s+/g, " ").trim();
|
|
recorder?.note("talk", line.length > 80 ? `«${line.slice(0, 79)}…»` : `«${line}»`);
|
|
},
|
|
};
|
|
}
|
|
|
|
export type WatchSession = {
|
|
/** Recording right now: the owner's pass holds and they have not stopped it. */
|
|
on: () => boolean;
|
|
stop: () => void;
|
|
resume: () => void;
|
|
/** What Review sends: the trail and the page checks, as text. */
|
|
session: () => string;
|
|
/** What it has seen this visit — the panel's running notes. */
|
|
trail: () => TrailEntry[];
|
|
/** The trail as report lines, for a change sent while watching — null when
|
|
* stopped, when nothing may travel. */
|
|
diagnostics: () => ReportDiagnostics | null;
|
|
/** The owner said something to Loki in the panel — a step in the visit, so
|
|
* a Review reads the time it took as talking, never as the site stalling. */
|
|
talked: (text: string) => void;
|
|
};
|
|
|
|
/** The site has a modal open — a `<dialog open>` shown modally or an
|
|
* `aria-modal` element on screen — that is not Loki's own. */
|
|
export function hostModalOpen(host: HTMLElement): boolean {
|
|
for (const el of Array.from(
|
|
document.querySelectorAll<HTMLElement>('[aria-modal="true"], dialog[open]'),
|
|
)) {
|
|
if (isOurNode(el, host)) continue;
|
|
if (el instanceof HTMLDialogElement) {
|
|
// showModal() vs show(): only the first blocks the page. A browser
|
|
// without :modal counts every open dialog — erring toward stepping aside.
|
|
let modal = true;
|
|
try {
|
|
modal = el.matches(":modal");
|
|
} catch {
|
|
/* no :modal support */
|
|
}
|
|
if (!modal) continue;
|
|
}
|
|
if (el.getClientRects().length > 0) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** Page checks must never take the review down with them. */
|
|
function safePageChecks(): string[] {
|
|
try {
|
|
return runPageChecks(document);
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/** The checks Watch SAYS: of a settled page, agreed by two readings. */
|
|
async function settledChecks(host: HTMLElement): Promise<string[]> {
|
|
try {
|
|
return await settledPageChecks(document, (node) => isOurNode(node, host));
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
const slotsKey = (token: string) => `loki-watch-readings:${token}`;
|
|
|
|
/** Each page's card and the reading it shows, this visit (per tab). */
|
|
function readSlots(token: string): Record<string, string> {
|
|
try {
|
|
const raw = JSON.parse(sessionStorage.getItem(slotsKey(token)) ?? "{}") as unknown;
|
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
return Object.fromEntries(
|
|
Object.entries(raw).filter((e): e is [string, string] => typeof e[1] === "string"),
|
|
);
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
function writeSlots(token: string, slots: Record<string, string>): void {
|
|
try {
|
|
sessionStorage.setItem(
|
|
slotsKey(token),
|
|
JSON.stringify(Object.fromEntries(Object.entries(slots).slice(-50))),
|
|
);
|
|
} catch {
|
|
/* storage blocked: a reload may say the page's reading once more */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* A control's words as a person reads them. `textContent` glues a count badge
|
|
* onto its label ("Feedback to triage" + <span>11</span> → "Feedback to
|
|
* triage11", owner screenshot 2026-10-16), so child elements that are only a
|
|
* number are left out, decorative (aria-hidden) parts too, and the pieces
|
|
* are joined with spaces. A control that is nothing but a number keeps it.
|
|
*/
|
|
function controlText(el: Element): string {
|
|
const words: string[] = [];
|
|
const counts: string[] = [];
|
|
const walk = (node: Node) => {
|
|
for (const child of Array.from(node.childNodes)) {
|
|
if (child.nodeType === Node.TEXT_NODE) {
|
|
words.push(child.textContent ?? "");
|
|
} else if (child instanceof Element) {
|
|
if (child.getAttribute("aria-hidden") === "true") continue;
|
|
const own = (child.textContent ?? "").trim();
|
|
if (/^\d+\+?$/.test(own)) {
|
|
counts.push(own);
|
|
continue;
|
|
}
|
|
walk(child);
|
|
}
|
|
}
|
|
};
|
|
walk(el);
|
|
const text = words.join(" ").replace(/\s+/g, " ").trim();
|
|
return text || counts.join(" ");
|
|
}
|
|
|
|
/** Is this URL one the widget itself calls (send a note, boot, its own API)? */
|
|
export function isWidgetCall(url: string, apiBase: string): boolean {
|
|
if (!url.startsWith(apiBase)) return false;
|
|
const rest = url.slice(apiBase.length);
|
|
return /^\/api\/feedback(?:[?#]|$)/.test(rest) || /^\/api\/widget/.test(rest);
|
|
}
|