Files
loki/widget/loki-api.ts
T
CatoandClaude Fable 5.1 6c6380efb7 feat(widget): the owner's way into Loki — Continue in Loki, an advisor that knows whose site it is, a header that fits a phone (#1107)
* feat(widget): the owner's way into Loki — Continue in Loki, an advisor that knows whose site it is, a header that fits a phone

On 2026-10-09 the owner of heidi.orangecat.ch opened the widget on their
phone and asked for one new page. The widget treated them as a stranger:
it told them which heading to insert and to "keep the structure in a data
file (JSON/YAML)", wrote five invented sentences in the site's own language,
and answered "switch to Loki so I can develop it there with either chat or
terminal" with the same advice a third time. The owner's sign-in lived only
behind "Watch". Once signed in, Review + Stop watching pushed ✕ off the
right edge of the screen.

- widget/continue.ts + src/lib/widget/continue.ts: the thread as one
  message (newest kept, ≤1800 chars) and where it lands in Loki.
- GET /api/widget/continue: signs the person in if needed, checks
  getProjectAccess on the widget's project, resolves the project key and
  redirects into /loki?project=&q= or /terminal?project=&view=terminal;
  a stranger goes back to the site with #loki-owner-denied.
- widget/conversation.ts: "Continue in Loki · Chat → · Terminal →" under
  the composer for the owner; one sign-in link for anyone else after their
  first message; "This is my site — sign in with Loki →" under Loki's
  greeting, on the first screen. The owner pass travels with each question.
- /api/widget/advise + advisor.ts: the pass is verified as ingest verifies
  it; with it the advisor knows the person OWNS the site and Build this
  builds. For everyone, four hands-off rules: never explain how to edit the
  site, never write its content, a build request becomes the one change to
  tap, and "take this into Loki" is answered with where that control is.
- widget/theme.ts: the header's text column shrinks before the actions do;
  Stop watching stays on one line; the continue row wraps on a phone.
- widget/main.ts: the owner is not offered to hide their own tool.
- scripts/test/widget-continue.ts (new), widget-advise.ts: pinned.
- docs/architecture/feedback-widget.md: the row and the route.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N1Yw4cCwXWRP2S5Hj62u2Z

* feat(widget): the loop closes on the site — Your changes, a live announcement, an honest Follow link

"On it — Loki tells you when" was the end of the widget's story, and on the
site Loki never told anyone: the telling went to push and Telegram, the page
the owner came back to said nothing, and "Follow the build" toured the
unchanged page with "let me show you what changed".

- widget/changes.ts: "Your changes" above the thread for the owner — the
  project's recent changes with one word each (Building · On its way · Live ·
  Needs you …), See it → once live, Open in Loki → when something needs them,
  asked for on arrival and every 30 s while something moves. A change this
  browser saw building that is now live is announced once: in the thread when
  the panel is open, beside the launcher (bubble + unread) when it is not.
- POST /api/widget/owner/changes: the one read with the owner pass. Same
  attachFeedbackWork the inbox uses, then src/lib/feedback/owner-view.ts
  writes the owner's words; the work view never leaves the server. No valid
  pass → no rows.
- /feedback/<id>/watch-fix lands on the inbox row while the change is still
  being built; the walkthrough only once it is live.
- The owner's repeated note keeps its follow link.
- widget/continue-row.ts, widget/greeting.ts: split out of createConversation
  (the lint rule caps it at 510 lines; CI caught it at 543).
- scripts/test/widget-changes.ts (new); widget-continue.ts updated.
- docs/architecture/feedback-widget.md.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N1Yw4cCwXWRP2S5Hj62u2Z

* fix(widget): the owner's door is not an .act — the embed test counts those

widget-embed-browser asserts exactly one "as written" link (.act) under the
visitor's last message; the sign-in door under the greeting shared the class
and made it two. Its own class, same look.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N1Yw4cCwXWRP2S5Hj62u2Z

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-09 04:12:00 -07:00

124 lines
4.6 KiB
TypeScript

/**
* The widget's two ways of asking Loki something, as plain calls — the
* conversation (widget/conversation.ts) decides which one a site gets
* (thread.ts assistantFor) and renders the answer.
*
* advisor — POST /api/widget/advise: about THIS site, from an outline the
* visitor's own browser builds (page-snapshot.ts), plus Watch's
* session when it is a Review.
* concierge — POST /api/widget/chat: a studio front desk, answered from the
* public fleet map by the Cat and Loki.
*
* Every field is clamped to the route's own cap; the routes reject a request
* outright on one character over, and the person would lose their message.
*/
import type { SelectedEl } from "./picker";
import { SNAPSHOT_MAX_CHARS, takeSnapshot, type SnapshotScope } from "./page-snapshot";
import { REVIEW_SESSION_MAX } from "./watch-trail";
import { safeHttpUrl, type Link, type Speaker } from "./thread";
/** Mirror ADVISE_MAX_QUESTION / ADVISE_MAX_HISTORY in src/lib/widget-advise/advisor.ts. */
export const ADVISE_MAX_QUESTION = 1000;
export const ADVISE_MAX_HISTORY = 8;
/** Mirror WIDGET_CHAT_MAX_MESSAGE / _MAX_HISTORY in src/app/api/widget/chat/route.ts. */
export const CHAT_MAX_MESSAGE = 1000;
export const CHAT_MAX_HISTORY = 12;
/** What the owner "asks" when they press Review. */
export const REVIEW_QUESTION = "Review what I just did on this site. What should be improved?";
type Turn = { role: "user" | "assistant"; content: string };
export type Answer = {
messages: { speaker: Speaker; text: string }[];
changes: string[];
links: Link[];
degraded: boolean;
};
async function post(url: string, body: unknown): Promise<Record<string, unknown>> {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = (await res.json().catch(() => null)) as Record<string, unknown> | null;
if (!res.ok || !json || typeof json.reply !== "string" || !json.reply) {
throw new Error(
typeof json?.error === "string" ? json.error : `Loki could not answer (${res.status})`,
);
}
return json;
}
export async function askAdvisor(opts: {
apiBase: string;
token: string;
question: string;
scope: SnapshotScope;
selected: SelectedEl[];
history: Turn[];
/** Watch's session — present for a Review. */
session?: string;
/** The owner's pass, so Loki answers the person whose site it is as such. */
ownerPass?: string;
}): Promise<Answer> {
const snapshot = (await takeSnapshot(opts.scope, opts.selected)).slice(0, SNAPSHOT_MAX_CHARS);
const body = await post(`${opts.apiBase}/api/widget/advise`, {
token: opts.token,
question: opts.question.slice(0, ADVISE_MAX_QUESTION),
scope: opts.scope,
snapshot,
session: opts.session ? opts.session.slice(0, REVIEW_SESSION_MAX) : undefined,
ownerPass: opts.ownerPass,
history: opts.history
.slice(-ADVISE_MAX_HISTORY)
.map((t) => ({ ...t, content: t.content.slice(0, 3000) })),
});
const changes = (Array.isArray(body.changes) ? body.changes : [])
.filter((c): c is string => typeof c === "string" && c.trim().length > 0)
.map((c) => c.slice(0, 300))
.slice(0, 5);
return {
messages: [{ speaker: "loki", text: String(body.reply).slice(0, 6000) }],
changes,
links: [],
degraded: body.degraded === true,
};
}
export async function askConcierge(opts: {
apiBase: string;
token: string;
message: string;
history: Turn[];
}): Promise<Answer> {
const body = await post(`${opts.apiBase}/api/widget/chat`, {
token: opts.token,
message: opts.message.slice(0, CHAT_MAX_MESSAGE),
history: opts.history
.slice(-CHAT_MAX_HISTORY)
.map((t) => ({ ...t, content: t.content.slice(0, 2000) })),
url: location.href.slice(0, 1000),
pageTitle: document.title.slice(0, 300) || undefined,
});
const said = (Array.isArray(body.messages) ? body.messages : [])
.map((m) => (m ?? {}) as { speaker?: unknown; text?: unknown })
.filter((m) => typeof m.text === "string" && m.text.trim())
.map((m) => ({
speaker: (m.speaker === "cat" ? "cat" : "loki") as Speaker,
text: String(m.text).slice(0, 4000),
}));
const links = (Array.isArray(body.links) ? body.links : [])
.map((l) => (l ?? {}) as { label?: unknown; url?: unknown })
.map((l) => ({ label: String(l.label ?? "").slice(0, 80), url: safeHttpUrl(l.url) }))
.filter((l): l is Link => !!l.url && !!l.label)
.slice(0, 5);
return {
messages: said.length ? said : [{ speaker: "loki", text: String(body.reply).slice(0, 4000) }],
changes: [],
links,
degraded: body.degraded === true,
};
}