mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 12:47:48 +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>
455 lines
17 KiB
TypeScript
455 lines
17 KiB
TypeScript
/**
|
|
* "Your changes" — the loop closing on the owner's own site.
|
|
*
|
|
* Until now the panel's story ended at "On it — Loki tells you when", and on
|
|
* the site Loki never did: the telling went to a push notification and a
|
|
* Telegram chat, and the page the owner came back to said nothing. This strip
|
|
* is the other half of that sentence. It lists what the owner asked for and
|
|
* where each thing is (Building · On its way · Live · Needs you), asks Loki
|
|
* again every half minute while something is moving, and when a change goes
|
|
* live since the last look, Loki says so — in the thread when the panel is
|
|
* open, beside the launcher when it is not — with one tap to see it.
|
|
*
|
|
* Words come from the server (owner-view.ts). This side renders, remembers
|
|
* what it has already seen (localStorage, per site), and notices the one
|
|
* transition that matters.
|
|
*/
|
|
import { h } from "./dom";
|
|
import { knownFor, parseKnown, type KnownFix } from "./known-fixes";
|
|
import { isThemePreference, type ThemePreference } from "./theme-mode";
|
|
|
|
export type OwnerChange = {
|
|
id: string;
|
|
text: string;
|
|
at: string;
|
|
label: string;
|
|
tone: "neutral" | "accent" | "warning" | "positive";
|
|
detail: string;
|
|
live: boolean;
|
|
settled: boolean;
|
|
href: string | null;
|
|
action: string | null;
|
|
/** Waiting on the owner's decision — a saved note, one not started, a
|
|
* failed attempt (owner-view.ts). The one thing the header counts. */
|
|
needsYou: boolean;
|
|
};
|
|
|
|
/** Mirrors OWNER_CHANGES_MAX in src/lib/feedback/owner-view.ts. */
|
|
export const CHANGES_MAX = 12;
|
|
/** Rows shown before "all N in Loki". The strip sits above the thread. */
|
|
export const CHANGES_SHOWN = 3;
|
|
export const CHANGES_POLL_MS = 30_000;
|
|
/** Stop asking after this long with nothing moving — a tab left open all day
|
|
* must not poll Loki all day. */
|
|
export const CHANGES_POLL_FOR_MS = 2 * 60 * 60_000;
|
|
|
|
const seenKey = (token: string) => `loki-changes-seen:${token}`;
|
|
|
|
/** What this browser last saw of each change: live or not. */
|
|
export function readSeen(token: string): Record<string, boolean> {
|
|
try {
|
|
const raw = JSON.parse(localStorage.getItem(seenKey(token)) ?? "{}") as unknown;
|
|
if (!raw || typeof raw !== "object") return {};
|
|
const out: Record<string, boolean> = {};
|
|
for (const [k, v] of Object.entries(raw)) if (typeof v === "boolean") out[k] = v;
|
|
return out;
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
export function writeSeen(token: string, seen: Record<string, boolean>): void {
|
|
try {
|
|
localStorage.setItem(seenKey(token), JSON.stringify(seen));
|
|
} catch {
|
|
/* storage blocked: the announcement may repeat next visit */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The changes that went live since the last look. A change never seen before
|
|
* is not announced — the first open after a long absence should not shout
|
|
* about everything that ever shipped — only one this browser saw building.
|
|
*/
|
|
export function newlyLive(
|
|
prev: Record<string, boolean>,
|
|
next: readonly OwnerChange[],
|
|
): OwnerChange[] {
|
|
return next.filter((c) => c.live && prev[c.id] === false);
|
|
}
|
|
|
|
export function toSeen(next: readonly OwnerChange[]): Record<string, boolean> {
|
|
return Object.fromEntries(next.map((c) => [c.id, c.live]));
|
|
}
|
|
|
|
/**
|
|
* The collapsed line: what is moving and what landed, in the order the owner
|
|
* cares — what needs them, what is being built, what is waiting its turn,
|
|
* what is live. "Your changes · 1 needs you · 1 building · 2 live".
|
|
*/
|
|
export function changesSummary(
|
|
changes: readonly OwnerChange[],
|
|
visitors = 0,
|
|
waiting: Waiting = {},
|
|
): string {
|
|
const count = (label: string) => changes.filter((c) => c.label === label).length;
|
|
const parts: Array<[number, string, string]> = [
|
|
[needsYouCount(changes, waiting), "needs you", "need you"],
|
|
[count("Building") + count("Starting"), "building", "building"],
|
|
[count("In line"), "in line", "in line"],
|
|
[count("On its way"), "on its way", "on their way"],
|
|
[changes.filter((c) => c.live).length, "live", "live"],
|
|
];
|
|
const said = parts.filter(([n]) => n > 0).map(([n, one, many]) => `${n} ${n === 1 ? one : many}`);
|
|
if (visitors) said.push(`${visitors} from visitors`);
|
|
return said.length ? `Your changes · ${said.join(" · ")}` : `Your changes · ${changes.length}`;
|
|
}
|
|
|
|
/** What waits on the owner beyond the rows the list carries. */
|
|
export type Waiting = {
|
|
/** The server's count of every row that needs the owner — past the twelve
|
|
* rows it sends, too (api/widget/owner/changes). */
|
|
total?: number;
|
|
/** Changes said on the open card and not saved yet. */
|
|
unsaved?: number;
|
|
};
|
|
|
|
/**
|
|
* How many things wait on the owner's decision: saved notes, notes not
|
|
* started, failed attempts, and changes said but not saved. The ONLY number
|
|
* the header shows.
|
|
*/
|
|
export function needsYouCount(changes: readonly OwnerChange[], waiting: Waiting = {}): number {
|
|
const rows = changes.filter((c) => c.needsYou).length;
|
|
return Math.max(rows, waiting.total ?? 0) + (waiting.unsaved ?? 0);
|
|
}
|
|
|
|
/**
|
|
* The one fragment the panel's status line carries about changes: how many
|
|
* need the owner, and nothing else. It used to fall back to "2 being built",
|
|
* "4 changes live"… and before that counted only failed attempts inside a
|
|
* window of the newest twelve, so the line said "9 changes need you" over a
|
|
* list that showed none of them, then 6 with nothing done (2026-10-20).
|
|
* Empty when nothing needs the owner: the line then says just "Watching".
|
|
*/
|
|
export function changesHeadline(changes: readonly OwnerChange[], waiting: Waiting = {}): string {
|
|
const n = needsYouCount(changes, waiting);
|
|
return n ? `${n} ${n === 1 ? "change needs you" : "changes need you"}` : "";
|
|
}
|
|
|
|
/**
|
|
* The owner's saved notes — said while Loki watched, kept for later. The
|
|
* server's word for them is "Review note" (src/lib/feedback/owner-view.ts);
|
|
* "Build them" starts every one (api/widget/owner/build).
|
|
*/
|
|
export const SAVED_NOTE_LABEL = "Review note";
|
|
export const savedNotes = (changes: readonly OwnerChange[]): number =>
|
|
changes.filter((c) => c.label === SAVED_NOTE_LABEL).length;
|
|
|
|
/** What "Build them" said, in one sentence for the conversation. */
|
|
export function builtSay(r: {
|
|
started: number;
|
|
total: number;
|
|
builds?: number;
|
|
note?: string;
|
|
}): string {
|
|
if (!r.total) return "There are no saved notes waiting.";
|
|
const builds = r.builds ?? r.started;
|
|
if (r.started === r.total)
|
|
return r.total === 1
|
|
? "Started your saved note — Loki builds it and tells you when it is live."
|
|
: builds === 1
|
|
? `Started your ${r.total} saved notes as one build — they are all about the same page. Loki tells you when it is live.`
|
|
: `Started your ${r.total} saved notes as ${builds} builds, one per page. Loki tells you as each goes live.`;
|
|
return `Started ${r.started} of ${r.total} saved notes. ${r.note ?? "The rest wait in Loki under Feedback."}`;
|
|
}
|
|
|
|
export function parseChanges(body: unknown): OwnerChange[] {
|
|
const raw = (body as { changes?: unknown })?.changes;
|
|
if (!Array.isArray(raw)) return [];
|
|
return raw
|
|
.map((c) => (c ?? {}) as Partial<OwnerChange>)
|
|
.filter(
|
|
(c) => typeof c.id === "string" && typeof c.text === "string" && typeof c.label === "string",
|
|
)
|
|
.map((c) => ({
|
|
id: c.id as string,
|
|
text: String(c.text).slice(0, 200),
|
|
at: typeof c.at === "string" ? c.at : "",
|
|
label: String(c.label).slice(0, 40),
|
|
tone: (["neutral", "accent", "warning", "positive"] as const).includes(
|
|
c.tone as OwnerChange["tone"],
|
|
)
|
|
? (c.tone as OwnerChange["tone"])
|
|
: "neutral",
|
|
detail: typeof c.detail === "string" ? c.detail.slice(0, 300) : "",
|
|
live: c.live === true,
|
|
settled: c.settled === true,
|
|
href: typeof c.href === "string" && /^https?:\/\//.test(c.href) ? c.href : null,
|
|
action: typeof c.action === "string" ? c.action.slice(0, 40) : null,
|
|
needsYou: c.needsYou === true,
|
|
}))
|
|
.slice(0, CHANGES_MAX);
|
|
}
|
|
|
|
/** The server's count of rows waiting on the owner (0 when absent). */
|
|
export function parseNeedsYou(body: unknown): number {
|
|
const n = (body as { needsYou?: unknown })?.needsYou;
|
|
return typeof n === "number" && Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
|
}
|
|
|
|
/**
|
|
* The rows the open list shows: EVERY one that needs the owner, then the
|
|
* newest of the rest up to CHANGES_SHOWN — so the number on the line is
|
|
* always the rows under it.
|
|
*/
|
|
export function shownChanges(changes: readonly OwnerChange[]): OwnerChange[] {
|
|
const mine = changes.filter((c) => c.needsYou);
|
|
const rest = changes.filter((c) => !c.needsYou);
|
|
return [...mine, ...rest.slice(0, Math.max(0, CHANGES_SHOWN - mine.length))];
|
|
}
|
|
|
|
export function createChanges(opts: {
|
|
apiBase: string;
|
|
token: string;
|
|
pass: () => string | null;
|
|
/** A change went live since this browser last looked. */
|
|
onLive: (change: OwnerChange) => void;
|
|
/** The server no longer honours the pass. */
|
|
onPassRefused: () => void;
|
|
/** The owner's light/dark choice in Loki, each time the server reports it. */
|
|
onTheme?: (pref: ThemePreference) => void;
|
|
/** The list was re-read: cards keyed to a fix follow its status. */
|
|
onUpdate?: () => void;
|
|
/** Drawn again — the status line that carries changesHeadline repaints. */
|
|
onRender?: () => void;
|
|
/** Said in the conversation (what "Build them" started). */
|
|
onSay?: (text: string) => void;
|
|
/** Changes said on the open card and not saved yet (conversation.ts). */
|
|
unsaved?: () => number;
|
|
/** The "not saved yet" row: bring the card into view. */
|
|
onUnsaved?: () => void;
|
|
}) {
|
|
// No line of its own: the panel's one status line carries the most urgent
|
|
// fragment ("4 live") and opens this list under it (thoughts-view.ts). It
|
|
// was a header with three rows open all the time, then a second status row.
|
|
const body = h("div", "yours-body");
|
|
const list = h("div", "yours-list");
|
|
const all = h("a", "yours-all");
|
|
all.target = "_blank";
|
|
all.rel = "noopener";
|
|
// Visitors' notes are not the owner's changes; they are counted, and read
|
|
// in Loki, where the inbox has the room to show who said what.
|
|
const visitorsLine = h("a", "yours-visitors");
|
|
visitorsLine.target = "_blank";
|
|
visitorsLine.rel = "noopener";
|
|
visitorsLine.style.display = "none";
|
|
// Record while Loki watches, save, then build them all — one tap.
|
|
const buildBtn = h("button", "yours-build");
|
|
buildBtn.type = "button";
|
|
buildBtn.style.display = "none";
|
|
buildBtn.addEventListener("click", () => void buildSaved());
|
|
body.append(buildBtn, list, all, visitorsLine);
|
|
|
|
let changes: OwnerChange[] = [];
|
|
/** Every row waiting on the owner, as the server counted them. */
|
|
let needsYouTotal = 0;
|
|
const waiting = (): Waiting => ({ total: needsYouTotal, unsaved: opts.unsaved?.() ?? 0 });
|
|
/** Every keyed fix the server knows, open or settled (known-fixes.ts). */
|
|
let known: KnownFix[] = [];
|
|
let firstRead: (() => void) | null = null;
|
|
/** Settles after the first answer (or refusal), so Watch can look before it speaks. */
|
|
const ready = new Promise<void>((resolve) => {
|
|
firstRead = resolve;
|
|
});
|
|
let inbox: string | null = null;
|
|
let visitors = 0;
|
|
let timer = 0;
|
|
let startedAt = 0;
|
|
let inflight = false;
|
|
|
|
function render() {
|
|
list.textContent = "";
|
|
const saved = savedNotes(changes);
|
|
buildBtn.style.display = saved ? "" : "none";
|
|
if (!buildBtn.disabled)
|
|
buildBtn.textContent =
|
|
saved === 1 ? "Build your saved note" : `Build all ${saved} saved notes`;
|
|
visitorsLine.style.display = visitors && inbox ? "" : "none";
|
|
if (visitors && inbox) {
|
|
visitorsLine.textContent = `${visitors} note${visitors === 1 ? "" : "s"} from visitors, in Loki →`;
|
|
visitorsLine.href = inbox;
|
|
}
|
|
// Said but not saved: it needs the owner too, and its tap is the card.
|
|
const unsaved = opts.unsaved?.() ?? 0;
|
|
if (unsaved) {
|
|
const row = h("button", "yours-row tone-warning");
|
|
row.type = "button";
|
|
row.addEventListener("click", () => opts.onUnsaved?.());
|
|
row.append(
|
|
h("span", "yours-dot"),
|
|
h(
|
|
"span",
|
|
"yours-text",
|
|
unsaved === 1
|
|
? "1 change you said is not saved yet"
|
|
: `${unsaved} changes you said are not saved yet`,
|
|
),
|
|
h("span", "yours-status", "Save or discard ↓"),
|
|
);
|
|
list.appendChild(row);
|
|
}
|
|
const shown = shownChanges(changes);
|
|
for (const c of shown) {
|
|
// The row IS the link when there is somewhere to go — no second line.
|
|
const row = c.href
|
|
? h("a", `yours-row tone-${c.tone}`)
|
|
: h("div", `yours-row tone-${c.tone}`);
|
|
if (row instanceof HTMLAnchorElement && c.href) {
|
|
row.href = c.href;
|
|
row.rel = "noopener";
|
|
row.target = "_blank";
|
|
}
|
|
// The whole request on hover; the row itself wraps to two lines.
|
|
row.title = c.detail ? `${c.text}\n\n${c.detail}` : c.text;
|
|
const text = h("span", "yours-text", c.text);
|
|
// A row waiting on the owner says it is a tap (the row is the link).
|
|
const status = h("span", "yours-status", c.needsYou && c.href ? `${c.label} →` : c.label);
|
|
if (c.needsYou && c.action) row.setAttribute("aria-label", `${c.text} — ${c.action}`);
|
|
row.append(h("span", "yours-dot"), text, status);
|
|
list.appendChild(row);
|
|
}
|
|
const more = changes.length - shown.length;
|
|
all.textContent = more > 0 ? `All ${changes.length} in Loki →` : "Open in Loki →";
|
|
all.style.display = inbox ? "" : "none";
|
|
if (inbox) all.href = inbox;
|
|
opts.onRender?.();
|
|
}
|
|
|
|
async function refresh(): Promise<void> {
|
|
const pass = opts.pass();
|
|
if (!pass) {
|
|
firstRead?.();
|
|
firstRead = null;
|
|
return;
|
|
}
|
|
if (inflight) return;
|
|
inflight = true;
|
|
try {
|
|
const res = await fetch(`${opts.apiBase}/api/widget/owner/changes`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ token: opts.token, ownerPass: pass }),
|
|
});
|
|
const body = (await res.json().catch(() => null)) as {
|
|
owner?: boolean;
|
|
inbox?: unknown;
|
|
visitors?: unknown;
|
|
theme?: unknown;
|
|
} | null;
|
|
if (!res.ok || !body) return;
|
|
if (body.owner === false) {
|
|
opts.onPassRefused();
|
|
return;
|
|
}
|
|
// The mode the owner chose in Loki — the panel follows it (theme-mode.ts).
|
|
if (isThemePreference(body.theme)) opts.onTheme?.(body.theme);
|
|
const next = parseChanges(body);
|
|
known = parseKnown(body);
|
|
needsYouTotal = parseNeedsYou(body);
|
|
opts.onUpdate?.();
|
|
inbox = typeof body.inbox === "string" && /^https?:\/\//.test(body.inbox) ? body.inbox : null;
|
|
visitors =
|
|
typeof body.visitors === "number" && body.visitors > 0 ? Math.floor(body.visitors) : 0;
|
|
const prev = readSeen(opts.token);
|
|
for (const c of newlyLive(prev, next)) opts.onLive(c);
|
|
writeSeen(opts.token, { ...prev, ...toSeen(next) });
|
|
changes = next;
|
|
render();
|
|
// Keep asking only while something can still change.
|
|
if (!next.some((c) => !c.settled)) stop();
|
|
} catch {
|
|
/* Loki unreachable: the strip keeps what it had */
|
|
} finally {
|
|
inflight = false;
|
|
firstRead?.();
|
|
firstRead = null;
|
|
}
|
|
}
|
|
|
|
async function buildSaved(): Promise<void> {
|
|
const pass = opts.pass();
|
|
if (!pass || buildBtn.disabled) return;
|
|
buildBtn.disabled = true;
|
|
buildBtn.textContent = "Starting…";
|
|
try {
|
|
const res = await fetch(`${opts.apiBase}/api/widget/owner/build`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ token: opts.token, ownerPass: pass }),
|
|
});
|
|
const b = (await res.json().catch(() => null)) as {
|
|
owner?: boolean;
|
|
started?: number;
|
|
total?: number;
|
|
builds?: number;
|
|
note?: string;
|
|
} | null;
|
|
if (b?.owner === false) return opts.onPassRefused();
|
|
if (!res.ok || !b) throw new Error();
|
|
opts.onSay?.(
|
|
builtSay({
|
|
started: b.started ?? 0,
|
|
total: b.total ?? 0,
|
|
...(typeof b.builds === "number" ? { builds: b.builds } : {}),
|
|
...(b.note ? { note: b.note.slice(0, 300) } : {}),
|
|
}),
|
|
);
|
|
} catch {
|
|
opts.onSay?.(
|
|
"Your saved notes could not be started just now. They wait in Loki under Feedback.",
|
|
);
|
|
} finally {
|
|
buildBtn.disabled = false;
|
|
start();
|
|
}
|
|
}
|
|
|
|
function stop() {
|
|
window.clearInterval(timer);
|
|
timer = 0;
|
|
}
|
|
|
|
/** Ask now, then every half minute while something is moving. */
|
|
function start() {
|
|
if (!opts.pass()) return;
|
|
void refresh();
|
|
if (timer) return;
|
|
startedAt = Date.now();
|
|
timer = window.setInterval(() => {
|
|
if (Date.now() - startedAt > CHANGES_POLL_FOR_MS) return stop();
|
|
void refresh();
|
|
}, CHANGES_POLL_MS);
|
|
}
|
|
|
|
return {
|
|
refresh,
|
|
start,
|
|
stop,
|
|
count: () => changes.length,
|
|
/** The list itself, for a status line that opens it (thoughts-view.ts). */
|
|
body,
|
|
/** The status line's fragment, and whether something needs the owner. */
|
|
has: () => changes.length > 0 || visitors > 0 || (opts.unsaved?.() ?? 0) > 0,
|
|
headline: () => changesHeadline(changes, waiting()),
|
|
summary: () => changesSummary(changes, visitors, waiting()),
|
|
attention: () => needsYouCount(changes, waiting()) > 0,
|
|
/** Draw the list again (the open card changed: its "not saved" row follows). */
|
|
repaint: () => render(),
|
|
/** The fix a remark's key already has, if any — see known-fixes.ts. */
|
|
known: (key: string) => knownFor(known, key),
|
|
/** Resolves once Loki has answered (or could not), never later than the caller's own wait. */
|
|
ready: () => ready,
|
|
};
|
|
}
|