packages/ui of iterate/private at 0fdfb49d5231c9526b2d319fd07ee8c8fa65123b
ui release builder, 2026-11-26 16:29 UTC · 600802a262087cbf7da88f8b09e88ba57ca93341 · parent 5ec5c87
21 files changed
- M src/agent-kind-view/bridge.ts
- M src/agent-kind-view/dash-agent-calls.ts
- M src/agent-kind-view/dash-agents.tsx
- M src/agent-kind-view/frame-view.tsx
- M src/agent-kind-view/host.ts
- M src/agent-kind-view/types.ts
- M src/components/call/call-bar.test.tsx
- M src/components/call/call-controls.test.tsx
- M src/components/call/call-controls.tsx
- M src/components/call/call-tiles.test.tsx
- M src/components/call/call-tiles.tsx
- M src/components/widget/widget-frame.test.tsx
- M src/components/widget/widget-frame.tsx
- M src/components/widget/widget-mcp.test.ts
- M src/components/widget/widget-mcp.ts
- M src/components/widget/widget-row.tsx
- M src/components/widget/widget.test.ts
- M src/components/widget/widget.ts
- M src/lib/call-engine.ts
- M src/lib/call-rules.test.ts
- M src/lib/call-rules.ts
M src/agent-kind-view/bridge.ts
@@ -88,6 +88,15 @@ readResource( read: Parameters<NonNullable<AgentKindViewProps["widgetCalls"]>["readResource"]>[0], ): Promise<unknown>; + /** A widget's read of a context, for the widget `key` of the agent at `path`. The page reads + * only when ITS OWN facts say that this widget names the context: the frame proves nothing. */ + readContext(read: { + path: string; + key: string; + context: string; + after: number; + limit: number; + }): Promise<unknown>; } export interface AgentKindViewFrameApi {
M src/agent-kind-view/dash-agent-calls.ts
@@ -171,6 +171,23 @@ await context() ).connectToMcp(server, { headers })) as unknown as WidgetMcpConnection, append: async (events) => await appendEvents(await context(), events), + // the agent's own rules, read at each of a widget's reads of a context (widget-mcp.ts) + rules: async () => + (await (await context()).rewriteRules.list(0)).map(({ match, target }) => ({ + match, + target, + })), + // THROUGH THE AGENT'S OWN CONTEXT, never from the page's root: the kernel resolves this `cd` + // by the agent's rules, so the widget reads a context only when the agent's own scripts + // could open it (and the person who looks holds the session that asks) + readEvents: async (target, after, limit) => { + const read = await (await context()).cd(target); + try { + return await read.readEvents(after, limit); + } finally { + read[Symbol.dispose](); + } + }, }); byPath.set(path, host); }
M src/agent-kind-view/dash-agents.tsx
@@ -59,6 +59,7 @@ type KindFile, type KindStarter, } from "./default-kind.ts"; +import { asksToReadContext, widgetNamesContext } from "#/components/widget/widget.ts"; import { useHeldContext } from "#/hooks/use-itx-session.ts"; import { useHasSavedTail, useSavedContext, type TailsOfMember } from "#/lib/saved-context.ts"; import { AgentChatState } from "#/components/agent-chat/agent-chat-search.ts"; @@ -1089,6 +1090,7 @@ stub, setState: patchView, loadOlder: log.older.loadOlder, + facts: log.events, }); const { hasChat } = load; return ( @@ -1155,15 +1157,21 @@ stub, setState, loadOlder, + facts, }: Pick<AgentKindViewVerbs, "setState" | "loadOlder"> & { itx: Itx; path: string; + /** The agent's facts as the page holds them now: what a widget's read is checked against. */ + facts: readonly unknown[]; stub: Parameters<typeof appendEvents>[0] | undefined; }): AgentKindViewVerbs { return { message: ({ message, files, key }) => messageAgent(itx, path, { message, files }, key), append: async (events) => { if (!stub) throw new Error("not connected"); + // a frame never writes the fact that the page would then read a context for + if (events.some(asksToReadContext)) + throw new Error("A view appends no widget that names contexts to read."); await appendEvents(stub, events); }, fileUrl: async (filePath) => { @@ -1175,6 +1183,16 @@ // as this agent alone: a call that names another path is refused (widget-mcp.ts) callTool: (call) => widgetCallsOf(itx, path).callTool(call), readResource: (read) => widgetCallsOf(itx, path).readResource(read), + // THE FRAME NAMES A WIDGET AND A CONTEXT, AND PROVES NEITHER: a kind's view is code in a + // sandbox. The page reads only when the facts that it holds itself say that this widget of + // this agent names that context (widget.ts `widgetNamesContext`). + readContext: async (read) => { + const { readContext } = widgetCallsOf(itx, path); + if (!readContext) throw new Error("This page reads no context for a widget."); + if (!widgetNamesContext(facts, path, read.key, read.context)) + throw new Error(`No widget ${read.key} of ${path} names the context ${read.context}.`); + return await readContext(read); + }, setState, loadOlder, };
M src/agent-kind-view/frame-view.tsx
@@ -102,6 +102,8 @@ widgetCalls: { callTool: async (call) => await host.callTool(call), readResource: async (read) => await host.readResource(read), + // a page older than this verb refuses the call, and the widget hears the refusal + readContext: async (read) => await host.readContext(read), }, }; }
M src/agent-kind-view/host.ts
@@ -23,9 +23,9 @@ * `storeFiles` refuses a message with files that a kind appends itself. */ export type AgentKindViewVerbs = Omit< AgentKindViewHostApi, - "loaded" | "storeFiles" | "callTool" | "readResource" + "loaded" | "storeFiles" | "callTool" | "readResource" | "readContext" > & - Partial<Pick<AgentKindViewHostApi, "storeFiles" | "callTool" | "readResource">>; + Partial<Pick<AgentKindViewHostApi, "storeFiles" | "callTool" | "readResource" | "readContext">>; /** One frame's link to the page: its handshake, its session, what it reported, what it holds. */ export class AgentKindViewLink { @@ -150,6 +150,11 @@ const { readResource } = this.#verbs(); if (!readResource) throw new Error("This page cannot read an MCP App's server for this agent."); return readResource(read); + } + readContext(read: Parameters<AgentKindViewHostApi["readContext"]>[0]) { + const { readContext } = this.#verbs(); + if (!readContext) throw new Error("This page reads no context for a widget of this agent."); + return readContext(read); } }
M src/agent-kind-view/types.ts
@@ -114,6 +114,14 @@ headers?: Record<string, string>; uri: string; }): Promise<unknown>; + /** Our own widget's read of a context that its fact names. None: a page older than it. */ + readContext?(read: { + path: string; + key: string; + context: string; + after: number; + limit: number; + }): Promise<unknown>; }; /** `true`: `AgentChat` shows who else is here and who is typing. A kind's view that wants it * also names `PRESENCE_EVENT_TYPES` (the kit's `lib/presence`) in its `ephemeralEvents`: the
M src/components/call/call-bar.test.tsx
@@ -176,7 +176,7 @@ speakerSupported: true, }, videos: [], - captions: { status: "off", text: "" }, + captions: { status: "off", text: "", unsaved: 0 }, }; // the cast: the bar calls only these of the engine's methods const engine = () =>
M src/components/call/call-controls.test.tsx
@@ -351,7 +351,7 @@ speakerSupported: true, }, videos: [], - captions: { status: "off", text: "" }, + captions: { status: "off", text: "", unsaved: 0 }, }; /** An engine of the methods the controls call; each call is kept in `steps`. `joins`: a join takes
M src/components/call/call-controls.tsx
@@ -364,7 +364,7 @@ speakerSupported: true, }, videos: [], - captions: { status: "off", text: "" }, + captions: { status: "off", text: "", unsaved: 0 }, }; /** THE CALL'S CONTROLS BEFORE THE CALL'S PART HAS LOADED: Start call in the same place, which
M src/components/call/call-tiles.test.tsx
@@ -17,7 +17,7 @@ const ui = { joined: true, videos: [] as CallVideo[], - captions: { status: "off", text: "" }, + captions: { status: "off", text: "", unsaved: 0 }, } as CallUi; const draw = (live: object) => ( <CallTiles call={engine()} ui={ui} live={CallLive.parse(live)} member /> @@ -35,7 +35,7 @@ const ui = { joined: true, videos: [] as CallVideo[], - captions: { status: "off", text: "" }, + captions: { status: "off", text: "", unsaved: 0 }, } as CallUi; const draw = (live: object | undefined) => ( <CallTiles call={engine()} ui={ui} live={live && CallLive.parse(live)} member /> @@ -46,11 +46,37 @@ expect(page.host.querySelector("[aria-live=polite]")?.textContent).toBe(""); }); +test("lines that the call did not take are named as not saved, and how they get saved", async () => { + const ui = (unsaved: number, joined = true) => + ({ + joined, + videos: [] as CallVideo[], + captions: { status: "listening", text: "", unsaved }, + }) as CallUi; + const draw = (state: CallUi) => <CallTiles call={engine()} ui={state} live={undefined} member />; + const notes = (host: HTMLElement) => + [...host.querySelectorAll("[role=status]")].map((note) => note.textContent); + using page = await mount(draw(ui(0))); + expect(notes(page.host).join(" ")).not.toContain("transcript"); + await page.render(draw(ui(3))); + expect(notes(page.host)).toContain( + "The transcript is not being saved: 3 lines that you said wait on this page. The page tries again by itself: keep it open.", + ); + await page.render(draw(ui(1, false))); + expect(notes(page.host)).toContain( + "The transcript is not being saved: 1 line that you said waits on this page. Join the call again from this page to save them.", + ); +}); + test("a tile's button keeps one name, and says by aria-pressed whether it is large", async () => { // jsdom plays no media vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue(); const video = { key: "k", name: "Ana", kind: "camera", local: true } as CallVideo; - const ui = { joined: true, videos: [video], captions: { status: "off", text: "" } } as CallUi; + const ui = { + joined: true, + videos: [video], + captions: { status: "off", text: "", unsaved: 0 }, + } as CallUi; using page = await mount(<CallTiles call={engine()} ui={ui} live={undefined} member />); const tile = page.host.querySelector("figure button")!; const state = () => [tile.getAttribute("aria-label"), tile.getAttribute("aria-pressed")]; @@ -84,7 +110,7 @@ const ui = { joined: true, videos: [screen, other], - captions: { status: "off", text: "" }, + captions: { status: "off", text: "", unsaved: 0 }, drive: { targets: [], asking: "", driving }, } as unknown as CallUi; const driveInput = vi.fn();
M src/components/call/call-tiles.tsx
@@ -68,7 +68,14 @@ if (lines.length && said.current) said.current.textContent = lines.join(" "); }, [live]); const something = Boolean( - ui.videos.length || setup || agent || ui.repair || ui.notice || ui.joined || ui.drive?.driving, + ui.videos.length || + setup || + agent || + ui.repair || + ui.notice || + ui.joined || + ui.captions.unsaved || + ui.drive?.driving, ); return ( <> @@ -105,6 +112,10 @@ ui.repair, // the captions, when they are not working: off for a reason, or failing ui.captions.status === "error" || ui.captions.status === "off" ? ui.captions.text : "", + // lines that the call did not take: they wait on this page, and are in no record yet + ui.captions.unsaved + ? `The transcript is not being saved: ${ui.captions.unsaved === 1 ? "1 line that you said waits" : `${ui.captions.unsaved} lines that you said wait`} on this page. ${ui.joined ? "The page tries again by itself: keep it open." : "Join the call again from this page to save them."}` + : "", ].filter(Boolean); return ( <section data-slot="call-tiles" className={cn("flex flex-col gap-2", className)}>
M src/components/widget/widget-frame.test.tsx
@@ -42,7 +42,10 @@ expect(frame.getAttribute("title")).toBe("A counter"); expect(frame.getAttribute("srcdoc")).toContain("<button>new</button>"); expect(frame.getAttribute("srcdoc")).not.toContain("<button>old</button>"); - expect(host.querySelector("figcaption")?.textContent).toBe("A counter"); + // our widget has no chrome: no caption, no border, no card; its title is the frame's alone + expect(host.querySelector("figcaption")).toBeNull(); + expect(host.querySelector("[data-widget-border]")).toBeNull(); + expect(host.querySelector("figure")?.className).not.toMatch(/border|bg-card|rounded/); await act(async () => root.unmount()); host.remove(); }); @@ -288,7 +291,31 @@ host.remove(); }); -const APP = { +test("an app's row has the host line, and a border only when its resource prefers one", async () => { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + for (const prefersBorder of [undefined, false, true]) { + await act(async () => { + root.render(<WidgetFrame widget={appWidget({ ...APP, prefersBorder })} />); + }); + expect(host.querySelector("[data-widget-server]")?.textContent).toBe("petshop.iterate.com"); + expect(host.querySelector("figcaption")?.className).not.toMatch(/border/); + expect(host.querySelector("figure")?.className).not.toMatch(/border|bg-card|rounded/); + expect(Boolean(host.querySelector("[data-widget-border]"))).toBe(prefersBorder === true); + } + await act(async () => root.unmount()); + host.remove(); +}); + +const APP: { + server: string; + tool: string; + resourceUri: string; + input: Record<string, unknown>; + result: { content: unknown[] }; + prefersBorder?: boolean; +} = { server: "https://petshop.iterate.com/mcp", tool: "show_pets", resourceUri: "ui://petshop/pets.html",
M src/components/widget/widget-frame.tsx
@@ -6,7 +6,8 @@ // // Another server's MCP App (`widget.app`) is drawn by the same frame: its row names the server, and // its view's `tools/call` and `resources/read` go to `onCallTool` and `onReadResource`, which the -// page makes through the agent's own context. +// page makes through the agent's own context. Our own widget's read of a context that its fact +// names (`ui.readContext`) goes to `onReadContext`, which the page answers with its own session. "use client"; import { @@ -43,6 +44,14 @@ arguments: Record<string, unknown>; }) => Promise<unknown>; onReadResource?: (read: { widget: Widget; uri: string }) => Promise<unknown>; + /** Our own widget's read of a context's log that its fact names (`ui.readContext`): one page, + * as the context's `readEvents` answers it. */ + onReadContext?: (read: { + widget: Widget; + context: string; + after: number; + limit: number; + }) => Promise<unknown>; /** A view's words for the agent's next turn (`ui/update-model-context`), from that widget. */ onModelContext?: (update: { widget: Widget; @@ -108,6 +117,7 @@ onLog, onCallTool, onReadResource, + onReadContext, onModelContext, onDraft, className, @@ -220,9 +230,19 @@ canDraft: Boolean(onDraft), canCallServer: Boolean(onCallTool && onReadResource), canModelContext: Boolean(onModelContext), + canReadContext: Boolean(onReadContext), }); if (act.reply) post(act.reply); - const { callTool, readResource } = act; + const { callTool, readResource, readContext } = act; + if (readContext && onReadContext) + answerFromServer(readContext.id, () => + onReadContext({ + widget, + context: readContext.context, + after: readContext.after, + limit: readContext.limit, + }), + ); if (callTool && onCallTool) answerFromServer(callTool.id, () => onCallTool({ widget, name: callTool.name, arguments: callTool.arguments }), @@ -276,50 +296,54 @@ useEffect(() => sendResult(), [data, text]); return ( + // NO CHROME AROUND A WIDGET: it sits in the feed as its document draws itself. The figure is + // the focus target of the press rule (widget.ts `widgetAnswer`), with no look of its own. <figure ref={box} - className={cn("my-2 overflow-hidden rounded-xl border bg-card outline-none", className)} + className={cn("my-2 outline-none", className)} tabIndex={-1} data-kind="widget" data-widget={widget.key} > {widget.app ? ( - // whose UI it is: the server's host, always, beside the widget's own title - <figcaption className="flex gap-1.5 border-b px-3 py-1.5 text-xs text-muted-foreground"> + // whose UI it is: the server's host, always, one small line above its view + <figcaption className="flex gap-1.5 pb-1 text-xs text-muted-foreground"> <span className="font-medium text-foreground" data-widget-server> {widgetServerHost(widget.app)} </span> {widget.title ? <span className="truncate">· {widget.title}</span> : null} </figcaption> - ) : widget.title ? ( - <figcaption className="border-b px-3 py-1.5 text-xs text-muted-foreground"> - {widget.title} - </figcaption> ) : null} - {!theme ? ( - <div style={{ height }} /> - ) : too || gone ? ( - <p className="whitespace-pre-wrap px-3 py-2 text-sm">{widget.text}</p> - ) : ( - <iframe - key={identity} - ref={frame} - title={widget.title || widget.text} - sandbox="allow-scripts" - referrerPolicy="no-referrer" - srcDoc={doc} - className="block w-full border-0 bg-transparent" - style={{ height }} - // the srcdoc's own load is the first; a second is the widget gone elsewhere - onLoad={() => { - loads.current += 1; - if (loads.current > 1) { - away.current = true; - setGone(true); - } - }} - /> - )} + <div + // a border only for an app whose resource asks for one (`_meta.ui.prefersBorder`) + className={cn(widget.app?.prefersBorder && "overflow-hidden rounded-xl border")} + data-widget-border={widget.app?.prefersBorder ? "" : undefined} + > + {!theme ? ( + <div style={{ height }} /> + ) : too || gone ? ( + <p className="whitespace-pre-wrap py-1 text-sm">{widget.text}</p> + ) : ( + <iframe + key={identity} + ref={frame} + title={widget.title || widget.text} + sandbox="allow-scripts" + referrerPolicy="no-referrer" + srcDoc={doc} + className="block w-full border-0 bg-transparent" + style={{ height }} + // the srcdoc's own load is the first; a second is the widget gone elsewhere + onLoad={() => { + loads.current += 1; + if (loads.current > 1) { + away.current = true; + setGone(true); + } + }} + /> + )} + </div> </figure> ); }
M src/components/widget/widget-mcp.test.ts
@@ -3,7 +3,12 @@ // refused, and each call one `widget-tool-called` fact on the agent's log. import { expect, test, vi } from "vitest"; import { WIDGET_FACT } from "./widget.ts"; -import { WIDGET_TOOLS_KEPT_MS, widgetMcpHost, type WidgetMcpConnection } from "./widget-mcp.ts"; +import { + WIDGET_TOOLS_KEPT_MS, + widgetAuthorJailed, + widgetMcpHost, + type WidgetMcpConnection, +} from "./widget-mcp.ts"; test("a tool call goes through one connection, and each call is one fact on the agent's log", async () => { const { host, open, appended, connection } = fake(); @@ -107,6 +112,81 @@ const SERVER = "https://petshop.iterate.com/mcp"; const HEADERS = { authorization: 'Bearer getSecret("/secrets/petshop")' }; + +test("a widget's read of a context goes to the page's own read, for an agent with the mind's reach", async () => { + const readEvents = vi.fn(async () => ({ events: [{ offset: 41 }], scannedThroughOffset: 41 })); + const host = widgetMcpHost({ + path: "/agents/main", + open: async () => fake().connection, + append: async () => undefined, + rules: async () => FREE, + readEvents, + }); + const read = { + path: "/agents/main", + key: "log", + context: "/agents/claude/x", + after: 40, + limit: 200, + }; + expect(await host.readContext!(read)).toEqual({ + events: [{ offset: 41 }], + scannedThroughOffset: 41, + }); + expect(readEvents).toHaveBeenCalledWith("/agents/claude/x", 40, 200); + await expect(host.readContext!({ ...read, path: "/agents/other" })).rejects.toThrow( + "A widget of /agents/main cannot call as /agents/other.", + ); + // the host holds the cap itself: a kind's frame sends its numbers as they are + await host.readContext!({ ...read, after: -5, limit: 1000 }); + expect(readEvents).toHaveBeenLastCalledWith("/agents/claude/x", 0, 500); + await host.readContext!({ ...read, after: Number.NaN, limit: 0.2 }); + expect(readEvents).toHaveBeenLastCalledWith("/agents/claude/x", 0, 1); +}); + +test("a jailed agent's widget reads nothing, and neither do rules that cannot be read", async () => { + const readEvents = vi.fn(async () => ({ events: [] })); + let rows = JAILED; + let fails = false; + const host = widgetMcpHost({ + path: "/agents/public", + open: async () => fake().connection, + append: async () => undefined, + rules: async () => { + if (fails) throw new Error("no rules"); + return rows; + }, + readEvents, + }); + const read = { + path: "/agents/public", + key: "log", + context: "/agents/engineering-manager", + after: 0, + limit: 10, + }; + await expect(host.readContext!(read)).rejects.toThrow("is jailed"); + // the rules are read at every read: a context that becomes a jail reads no more + rows = FREE; + await host.readContext!(read); + rows = JAILED; + await expect(host.readContext!(read)).rejects.toThrow("is jailed"); + fails = true; + await expect(host.readContext!(read)).rejects.toThrow("no rules"); + expect(readEvents).toHaveBeenCalledTimes(1); + expect(widgetAuthorJailed([])).toBe(true); + // a host that was given no way to read has no such call + expect(fake().host.readContext).toBeUndefined(); +}); + +const FREE = [ + { match: "itx.run", target: "itx.builtins.run" }, + { match: "itx.cd", target: "itx.builtins.cd" }, +]; +const JAILED = [ + { match: "itx", target: "null" }, + { match: "itx.run", target: 'itx.cd("/jails/public").run' }, +]; function fake(now?: () => number) { const connection = {
M src/components/widget/widget-mcp.ts
@@ -5,7 +5,7 @@ // so a widget reaches what that agent reaches, and no more. Each tool call is one fact on that // path (`widget-tool-called`). import { z } from "zod"; -import { WIDGET_FACT } from "./widget.ts"; +import { WIDGET_CONTEXT_READ_MAX, WIDGET_FACT } from "./widget.ts"; /** The connection that `itx.connectToMcp` answers, as far as an app's view uses it. */ export type WidgetMcpConnection = { @@ -31,12 +31,49 @@ uri: string; }; +/** One read of a context's log for our own widget: `path` is the agent whose feed shows the + * widget, `key` the widget, `context` the context to read. The frame of the page's own code took + * `context` from the widget's fact (widget.ts `widgetAnswer`); a page that reads for a frame it + * does not trust checks the key and the context against its own facts first + * (`widgetNamesContext`). */ +export type WidgetContextRead = { + path: string; + key: string; + context: string; + after: number; + limit: number; +}; + /** What a chat's host does for the apps in its feed. */ export type WidgetMcpCalls = { callTool(call: WidgetToolCall): Promise<unknown>; readResource(read: WidgetResourceRead): Promise<unknown>; + /** One page of a context's log, read with the page's own session. None: a host that reads no + * context for a widget. */ + readContext?(read: WidgetContextRead): Promise<unknown>; }; +/** One row of a context's rewrite rules, as far as `widgetAuthorJailed` reads it. */ +type RuleRow = { match: string; target: string | null }; + +/** WHETHER THE AGENT THAT SHOWS A WIDGET HOLDS LESS THAN THE MIND'S WHOLE REACH, by its context's + * own rules (`rewriteRules.list(0)`): the rule of lib/page-tools.ts `jailOf`. An agent whose + * scripts run in its own context with the kernel's own `itx.run` and `itx.cd` reaches every + * context already, so a read for its widget shows it nothing new. A jailed agent can still write + * a `widget-shown` fact that names any context, and a member's page would then read for it. */ +// THREE RULES STAND BEHIND ONE READ, and each closes what the others leave open: +// - the fact's stamp (widget.ts `ownContextWrote`): the agent's own context wrote the widget. +// A jail that runs the agent's scripts elsewhere never writes such a fact; +// - this check, at each read: the agent's scripts run in its own context now; +// - the read itself goes through the agent's context (`readEvents`, below), so a jail that +// is IN the agent's context (a bare `itx` mask with `run` and `cd` given back, and a rule +// that denies some context) refuses the very context that it denies its scripts. +export const widgetAuthorJailed = (rows: readonly RuleRow[]) => { + const kernels = (name: string) => + rows.some((row) => row.match === `itx.${name}` && row.target === `itx.builtins.${name}`); + return !(kernels("run") && kernels("cd")); +}; + /** A tool as the server lists it: its name, and the spec's `_meta.ui.visibility`. */ const ListedTool = z.looseObject({ name: z.string(), @@ -63,6 +100,8 @@ open, append, now = Date.now, + rules, + readEvents, }: { path: string; /** The clock a listing's age is read by. */ @@ -72,6 +111,13 @@ headers: Record<string, string> | undefined, ) => Promise<WidgetMcpConnection>; append: (events: unknown[]) => Promise<unknown>; + /** The rules of the agent's own context (`rewriteRules.list(0)`), and one page of a context's + * log, READ THROUGH THE AGENT'S OWN CONTEXT (`itx.cd(path).cd(context).readEvents(after, + * limit)`): the kernel resolves that `cd` by the agent's rules, so a context that the agent's + * own scripts cannot open is refused there, whatever rows the agent has. Both, or the host + * reads no context. */ + rules?: () => Promise<readonly RuleRow[]>; + readEvents?: (context: string, after: number, limit: number) => Promise<unknown>; }): WidgetMcpCalls { const connections = new Map< string, @@ -153,5 +199,25 @@ own(asked); return await (await held(server, headers).connection).readResource(uri); }, + ...(rules && + readEvents && { + async readContext({ path: asked, context, after, limit }: WidgetContextRead) { + own(asked); + // before every read: the agent's context may have become a jail since the last one, and + // rules that cannot be read (a throw here) read nothing + if (widgetAuthorJailed(await rules())) + throw new Error( + `The agent at ${path} is jailed: its widget reads no context of the mind.`, + ); + // the cap and the floor here too: a kind's frame sends its numbers as they are + const whole = (value: number, least: number, most: number) => + Number.isFinite(value) ? Math.min(Math.max(Math.floor(value), least), most) : least; + return await readEvents( + context, + whole(after, 0, Number.MAX_SAFE_INTEGER), + whole(limit, 1, WIDGET_CONTEXT_READ_MAX), + ); + }, + }), }; }
M src/components/widget/widget-row.tsx
@@ -41,7 +41,8 @@ onAppend?: (events: unknown[]) => Promise<unknown>; children: ReactNode; }) { - const fold = useMemo(() => widgetFold(events), [events]); + // with the path: a widget's `contexts` count only from a fact that this agent's context wrote + const fold = useMemo(() => widgetFold(events, undefined, path), [events, path]); const server = useMemo(() => serverCallsOf(path, calls, onAppend), [path, calls, onAppend]); const host = useMemo( () => ({ fold, onSend, onDraft, ...server }), @@ -51,7 +52,7 @@ } export function WidgetRow({ widgetKey, offset }: { widgetKey: string; offset: number }) { - const { fold, onSend, onDraft, onCallTool, onReadResource, onModelContext } = + const { fold, onSend, onDraft, onCallTool, onReadResource, onReadContext, onModelContext } = useContext(WidgetHostContext); const held = fold.get(widgetKey); if (!held || held.first !== offset) return null; @@ -62,6 +63,7 @@ onDraft={onDraft} onCallTool={onCallTool} onReadResource={onReadResource} + onReadContext={onReadContext} onModelContext={onModelContext} /> ); @@ -89,6 +91,12 @@ const { server, headers } = appOf(widget); return calls.readResource({ path, server, headers, uri }); }, + }), + // a host older than this verb has none: the widget's read is then refused in words + ...(path && + calls?.readContext && { + onReadContext: ({ widget, context, after, limit }) => + calls.readContext!({ path, key: widget.key, context, after, limit }), }), ...(onAppend && { onModelContext: ({ widget, content }) => {
M src/components/widget/widget.test.ts
@@ -2,8 +2,10 @@ // policy and data, and the host's answers to the MCP Apps messages. import { expect, test } from "vitest"; import { + asksToReadContext, WIDGET_APP_HTML_MAX, WIDGET_CLIENT, + WIDGET_CONTEXT_READ, WIDGET_FACT, WIDGET_HEIGHT_MAX, WIDGET_HTML_MAX, @@ -15,6 +17,7 @@ widgetFold, widgetHtmlMax, widgetInput, + widgetNamesContext, widgetOf, widgetPolicy, widgetResult, @@ -403,6 +406,123 @@ input: { species: "cat" }, result: { content: [{ type: "text", text: "3 pets" }], structuredContent: { pets: 3 } }, }; +test("our own widget reads the contexts that its fact names, and no other", () => { + const widget = widgetOf( + { + html: "<p>log</p>", + contexts: ["/agents/claude/x", "/agents/claude/x", "../secrets", "/a/../b", 7], + }, + 3, + )!; + expect(widget).toMatchObject({ contexts: ["/agents/claude/x"] }); + const reading = state({ widget, canReadContext: true }); + expect( + widgetAnswer( + rpc(WIDGET_CONTEXT_READ, { path: "/agents/claude/x", after: 40.9, limit: 9999 }, 5), + reading, + ), + ).toEqual({ readContext: { id: 5, context: "/agents/claude/x", after: 40, limit: 500 } }); + expect( + widgetAnswer(rpc(WIDGET_CONTEXT_READ, { path: "/agents/claude/x" }), reading), + ).toMatchObject({ + readContext: { id: 1, context: "/agents/claude/x", after: 0, limit: 200 }, + }); + // a path that the fact does not name, a host with no way, and a notification + expect( + widgetAnswer(rpc(WIDGET_CONTEXT_READ, { path: "/secrets" }), reading).reply?.error?.code, + ).toBe(-32602); + expect( + widgetAnswer(rpc(WIDGET_CONTEXT_READ, { path: "/agents/claude/x" }), state({ widget })).reply + ?.error?.code, + ).toBe(-32601); + expect( + widgetAnswer( + { jsonrpc: "2.0", method: WIDGET_CONTEXT_READ, params: { path: "/agents/claude/x" } }, + reading, + ), + ).toEqual({}); + // the host says which contexts in its handshake, and the client has the call + const hello = widgetAnswer(rpc("ui/initialize"), reading).reply?.result as { + hostCapabilities: { contexts?: { read: string[] } }; + }; + expect(hello.hostCapabilities).toMatchObject({ contexts: { read: ["/agents/claude/x"] } }); + expect(WIDGET_CLIENT).toContain(WIDGET_CONTEXT_READ); +}); + +test("a widget keeps its contexts only from a fact that the agent's own context wrote", () => { + const payload = { key: "log", html: "<p>log</p>", contexts: ["/agents/claude/x"] }; + const script = { origin: "/agents/main", cause: { depth: 2, parent: "/agents/main@1" } }; + const own = { ...shown(3, payload), source: script }; + const contextsOf = (facts: unknown[], path?: string) => + widgetFold(facts, undefined, path).get("log")?.widget.contexts; + expect(contextsOf([own], "/agents/main")).toEqual(["/agents/claude/x"]); + // no path, another origin (a jailed agent's write comes through the config's door), a + // session's own append (a page, a kind's frame: the member's handle stamps its person), a write + // that someone stood behind, a copy of another log's event, a cause in another log or none, + // and no stamp at all + expect(contextsOf([own])).toBeUndefined(); + for (const source of [ + { ...script, origin: "/" }, + { ...script, origin: "/jails/public/1/a" }, + { ...script, principal: { actor: "user_1", email: "member@example.com" }, grant: "g1" }, + { ...script, grant: "g1" }, + { ...script, onBehalfOf: { principal: { actor: "guest" } } }, + { ...script, copiedFrom: { path: "/agents/other", offset: 1, type: "x" } }, + { origin: "/agents/main", cause: { depth: 0, parent: "/agents/other@4" } }, + { origin: "/agents/main", cause: { depth: 0 } }, + { origin: "/agents/main" }, + undefined, + ]) + expect(contextsOf([{ ...shown(3, payload), source }], "/agents/main")).toBeUndefined(); + // the widget is still drawn, and a later fact of the agent's own replaces it with its contexts + expect(widgetFold([{ ...shown(3, payload), source: { origin: "/" } }]).get("log")).toBeDefined(); + expect( + contextsOf( + [ + { ...shown(3, payload), source: { origin: "/" } }, + { ...own, offset: 9 }, + ], + "/agents/main", + ), + ).toEqual(["/agents/claude/x"]); + // what the page asks before it reads for a frame it does not trust + expect(widgetNamesContext([own], "/agents/main", "log", "/agents/claude/x")).toBe(true); + expect(widgetNamesContext([own], "/agents/main", "log", "/agents/engineering-manager")).toBe( + false, + ); + expect(widgetNamesContext([own], "/agents/main", "other", "/agents/claude/x")).toBe(false); + expect(widgetNamesContext([own], "/agents/other", "log", "/agents/claude/x")).toBe(false); + expect(widgetNamesContext([], "/agents/main", "log", "/agents/claude/x")).toBe(false); + // what a page refuses to append for a kind's frame + expect(asksToReadContext(shown(1, payload))).toBe(true); + expect(asksToReadContext(shown(1, { html: "<p>x</p>" }))).toBe(false); + expect(asksToReadContext({ type: WIDGET_FACT.updated, payload: { contexts: ["/x"] } })).toBe( + false, + ); +}); + +test("another server's app reads no context, whatever its fact says", () => { + const widget = widgetOf( + { + html: "<p>x</p>", + contexts: ["/agents/claude/x"], + app: { + server: "https://shop.example.com/mcp", + tool: "show", + resourceUri: "ui://shop/x.html", + }, + }, + 4, + )!; + expect(widget.contexts).toBeUndefined(); + expect( + widgetAnswer( + rpc(WIDGET_CONTEXT_READ, { path: "/agents/claude/x" }), + state({ widget, canReadContext: true }), + ).reply?.error?.code, + ).toBe(-32601); +}); + const appState = (more: Partial<WidgetHostState> = {}) => state({ widget: {
M src/components/widget/widget.ts
@@ -14,6 +14,18 @@ // adds its client script. ANOTHER SERVER'S MCP APP (`app` in the fact) is that server's `ui://` // resource as it served it: the kit adds no script, only the policy, first. Its view calls its // own server's tools (`tools/call`), which the page makes through the agent's own context. +// +// A WIDGET THAT SHOWS A LOG. Our agent's own widget may name contexts of the mind in its fact +// (`contexts: ["/agents/claude/x"]`). Its HTML then reads their logs with `ui.readContext(path, +// { after, limit })` (`iterate/context/read`): the page reads for it, with the session of the +// person who looks at the feed, so the frame holds no credential. A path the fact does not name +// is refused, and so is another server's app, whose document is not ours. +// WHO MAY NAME A CONTEXT. A jailed agent holds less than the person who reads its feed, and it can +// write a `widget-shown` fact. So `contexts` counts only on a fact that the agent's OWN SCRIPT +// wrote in its own context (`widgetFold`, `ownContextWrote`): the platform's stamp says so. A +// jailed agent's script runs in its jail and reaches its log through a door of the mind's config, +// whose stamp names another origin; a session's append (a page, a kind's frame) names its person. That holds for good: a jail that is undone later leaves the old fact +// without its contexts. The page also refuses while the agent is jailed now (widget-mcp.ts). const T = "events.iterate.com/"; /** The facts. A script appends `widget-shown`; `widget-updated` gives a shown widget new data. */ @@ -54,6 +66,8 @@ csp?: WidgetCsp; /** Another server's MCP App: the call that made it. None: our agent's own widget. */ app?: WidgetApp; + /** The contexts whose logs our agent's own widget may read (`ui.readContext`). */ + contexts?: string[]; }; /** The MCP Apps spec's `_meta.ui.csp`: origins, or host patterns like `https://*.example.com`. */ @@ -117,6 +131,26 @@ return Object.keys(csp).length ? csp : undefined; } +/** A widget names at most this many contexts to read. */ +const WIDGET_CONTEXTS_MAX = 8; +/** One read answers at most this many events. */ +export const WIDGET_CONTEXT_READ_MAX = 500; +/** A context's path as a fact may name it: absolute, with no `.` or `..` part. */ +const CONTEXT_PATH = /^(?:\/[A-Za-z0-9._~@:-]+)+$/; +const isContextPath = (path: string) => + path.length <= 400 && + CONTEXT_PATH.test(path) && + path.split("/").every((part) => part !== "." && part !== ".."); + +/** A fact's `contexts`: the paths that are paths, each once. */ +function contextsOf(value: unknown): string[] | undefined { + const paths = [...new Set(strings(value, 50)?.filter(isContextPath))].slice( + 0, + WIDGET_CONTEXTS_MAX, + ); + return paths.length ? paths : undefined; +} + /** A fact's `app`, or none when it names no https server, tool and resource: a row must say whose * UI it is, and a call must know where it goes. */ function appOf(value: unknown): WidgetApp | undefined { @@ -182,22 +216,64 @@ offset, csp: cspOf(payload.csp), app, + // our own widget alone: another server's document reads no log of the mind + contexts: app ? undefined : contextsOf(payload.contexts), }; } /** Each key's newest widget, and the offset of the first fact that showed it: the row stays there. */ export type WidgetFold = Map<string, { first: number; widget: Widget }>; +/** WHETHER THE AGENT'S OWN CODE WROTE A FACT of its log at `path`, by the platform's stamp + * (`source`, core/itx/src/caller.ts). All of these hold for a script that the agent ran in its + * own context, and for nothing else: + * - its origin is that context; + * - NO SESSION wrote it: a member's handle on the context (a page's append, a kind's frame, a + * bridge) stamps its `principal` and `grant`, with this same origin; + * - nobody stood behind the write (`onBehalfOf`), and it is no copy of another log's event + * (`copiedFrom`); + * - an event of this same log caused it (`cause.parent` is `<path>@<offset>`): the run of the + * script. + * A jailed agent's script runs in its jail, and its write comes through a door of the mind's + * config, so its origin is another context. */ +function ownContextWrote(fact: Record<string, unknown>, path: string): boolean { + const source = fact.source; + if (!isRecord(source) || source.origin !== path) return false; + if (source.principal !== undefined || source.grant !== undefined) return false; + if (source.onBehalfOf !== undefined || source.copiedFrom !== undefined) return false; + const parent = isRecord(source.cause) ? source.cause.parent : undefined; + return typeof parent === "string" && parent.startsWith(`${path}@`); +} + +/** Whether an event is a widget fact that asks to read a context: one that a page never appends + * for a frame it does not trust (a kind's view). The stamp of such an append would refuse the + * grant anyway (`ownContextWrote`); the page says no at the door too. */ +export function asksToReadContext(event: unknown): boolean { + return ( + isRecord(event) && + event.type === WIDGET_FACT.shown && + isRecord(event.payload) && + event.payload.contexts !== undefined + ); +} + /** THE NEWEST WIDGET FOR EACH KEY, over the facts the page holds. A later `widget-shown` with the * same key replaces the widget; `widget-updated { key, data, text? }` gives it new data. The row - * stays where the key was first shown. A pure fold: the same facts give the same map. */ -export function widgetFold(facts: readonly unknown[], held: WidgetFold = new Map()): WidgetFold { + * stays where the key was first shown. A pure fold: the same facts give the same map. + * `path`: the agent whose log the facts are. A widget keeps its `contexts` only from a fact that + * the agent's own code wrote (`ownContextWrote`); with no `path`, no widget reads a context. */ +export function widgetFold( + facts: readonly unknown[], + held: WidgetFold = new Map(), + path?: string, +): WidgetFold { const fold: WidgetFold = new Map(held); for (const fact of facts as { type?: unknown; offset?: unknown; payload?: unknown }[]) { if (!isRecord(fact) || typeof fact.offset !== "number") continue; if (fact.type === WIDGET_FACT.shown) { const widget = widgetOf(fact.payload, fact.offset); if (!widget) continue; + if (widget.contexts && !(path && ownContextWrote(fact, path))) delete widget.contexts; fold.set(widget.key, { first: fold.get(widget.key)?.first ?? fact.offset, widget }); } else if (fact.type === WIDGET_FACT.updated && isRecord(fact.payload)) { const key = keyOf(fact.payload); @@ -213,6 +289,18 @@ return fold; } +/** Whether the widget `key`, as the facts of the log at `path` show it now, names `context` to + * read. The page asks this of the facts that IT holds before it reads for a frame it does not + * trust (a kind's view): that frame names the key and the context, and proves neither. */ +export function widgetNamesContext( + facts: readonly unknown[], + path: string, + key: string, + context: string, +): boolean { + return Boolean(widgetFold(facts, undefined, path).get(key)?.widget.contexts?.includes(context)); +} + // ── THE FRAME'S DOCUMENT ──────────────────────────────────────────────────────────────────────── /** The frame's policy: inline script and style, images and fonts from data, and no network. */ @@ -288,12 +376,18 @@ * ui.send(text) words to the agent, as the person (the host wants a press) * ui.open(url) an https link in a new tab (the host wants a press) * ui.theme "light" | "dark" + * ui.readContext(path, { after, limit }) + * one page of the log of a context that the widget's fact names in + * `contexts`: `{ events, scannedThroughOffset }`, the events with an offset + * over `after`, oldest first (iterate's own, not MCP Apps') * It does the handshake (`ui/initialize`, then `ui/notifications/initialized`), reports its height * (`ui/notifications/size-changed`) and takes the host's theme. It sends its console and its * uncaught errors as MCP's log message (`notifications/message`), at most 50 a minute, so the host * can keep them. No dependency. */ /** The widget's wheel or finger, for the host's list (not MCP Apps': iterate's own). */ export const WIDGET_SCROLLED = "iterate/notifications/scrolled"; +/** Our own widget reads one page of a context's log (iterate's own, not MCP Apps'). */ +export const WIDGET_CONTEXT_READ = "iterate/context/read"; export const WIDGET_CLIENT = `(function () { var boot = JSON.parse(document.getElementById("iterate-widget-boot").textContent); @@ -388,6 +482,9 @@ }, send: function (text) { return request("ui/message", { role: "user", content: [{ type: "text", text: String(text) }] }); }, open: function (url) { return request("ui/open-link", { url: String(url) }); }, + readContext: function (path, options) { + return request("${WIDGET_CONTEXT_READ}", { path: String(path), after: options && options.after, limit: options && options.limit }); + }, }); addEventListener("message", function (event) { if (event.source !== parent) return; @@ -479,6 +576,9 @@ callTool?: { id: string | number; name: string; arguments: Record<string, unknown> }; /** An app's view reads a resource of its own server (`resources/read`), likewise. */ readResource?: { id: string | number; uri: string }; + /** Our own widget reads a page of a context's log that its fact names (WIDGET_CONTEXT_READ): + * the host reads and posts the reply to `id` itself. */ + readContext?: { id: string | number; context: string; after: number; limit: number }; /** Words from the view for the agent's next turn (`ui/update-model-context`): that server's or * that widget's words, never the person's. */ modelContext?: { content: unknown[]; structuredContent?: unknown }; @@ -499,6 +599,8 @@ canCallServer?: boolean; /** The host takes a widget's words for the agent's next turn. */ canModelContext?: boolean; + /** The host reads a context's log for our own widget (the page gave a way). */ + canReadContext?: boolean; }; const ok = (id: unknown, result: unknown): WidgetAct["reply"] => ({ jsonrpc: "2.0", id, result }); @@ -573,6 +675,9 @@ updateModelContext: { text: {}, structuredContent: {} }, }), ...(server && { serverTools: {}, serverResources: {} }), + // iterate's own: the contexts this widget may read + ...(state.canReadContext && + state.widget.contexts && { contexts: { read: state.widget.contexts } }), // what the frame grants: the origins its policy took, and no device permission sandbox: { permissions: {}, csp: appliedCsp(state.widget.csp) }, }, @@ -683,6 +788,33 @@ const uri = words(params.uri, 2000); if (!uri) return { reply: refused(id, -32602, "A read names its resource.") }; return { readResource: { id, uri } }; + } + case WIDGET_CONTEXT_READ: { + if (!request) return {}; + if (state.widget.app || !state.canReadContext) + return { reply: refused(id, -32601, "This widget reads no context.") }; + const context = typeof params.path === "string" ? params.path : ""; + // the fact's own list alone: the widget's HTML chooses among its paths, never a new one + if (!state.widget.contexts?.includes(context)) + return { + reply: refused( + id, + -32602, + "This widget's fact does not name that context in `contexts`.", + ), + }; + const whole = (value: unknown, least: number, most: number, otherwise: number) => + typeof value === "number" && Number.isFinite(value) + ? Math.min(Math.max(Math.floor(value), least), most) + : otherwise; + return { + readContext: { + id, + context, + after: whole(params.after, 0, Number.MAX_SAFE_INTEGER, 0), + limit: whole(params.limit, 1, WIDGET_CONTEXT_READ_MAX, 200), + }, + }; } case "ui/update-model-context": { if (!request) return {};
M src/lib/call-engine.ts
Not shown: the change is larger than this page shows. A clone has it.
M src/lib/call-rules.test.ts
@@ -1,6 +1,6 @@ // The pure rules of a call in a page: Join on a fresh call, the view the engine follows, the path a // page takes, the ICE servers, a saved device, the repair loop, and the simulcast layers. -import { expect, test } from "vitest"; +import { expect, test, vi } from "vitest"; import { browserTargets, CallLive, @@ -25,6 +25,7 @@ iceServersOf, joinable, layerFor, + lineOutbox, lendCall, liveMacs, macOwner, @@ -35,6 +36,7 @@ repairLoop, rmsOf, TurnDetector, + UNSENT, udpOnly, viewOf, } from "./call-rules.ts"; @@ -560,6 +562,111 @@ ).toBe("zak@nustom.com"); }); +test("lines that the call did not take wait on the page and reach it later: each once, in order, with the time it was heard", async () => { + using call = callThatTakes(); + const { room, outbox } = call; + const start = Date.now(); + outbox.add({ id: "a", at: Date.now() }); + await outbox.flush(); + expect([room.taken, room.told]).toEqual([[{ id: "a", at: start }], []]); + // the call stops answering: the lines said meanwhile wait, and the page is told how many + room.down = true; + outbox.add({ id: "b", at: Date.now() }); + await vi.advanceTimersByTimeAsync(500); + outbox.add({ id: "c", at: Date.now() }); + outbox.add({ id: "d", at: Date.now() }); + expect(room.told.at(-1)).toEqual({ unsaved: 3, lost: 0, saved: 0 }); + // a new line makes no try of its own: the tries follow the waits + await vi.advanceTimersByTimeAsync(600 + 2_000 + 4_000); + expect([room.tries, outbox.waiting]).toEqual([["a", "b", "b", "b", "b"], 3]); + // it answers again: every line that waited, oldest first, with its own time + room.down = false; + await vi.advanceTimersByTimeAsync(8_000); + expect(room).toMatchObject({ + taken: [ + { id: "a", at: start }, + { id: "b", at: start }, + { id: "c", at: start + 500 }, + { id: "d", at: start + 500 }, + ], + }); + expect(room.told.at(-1)).toEqual({ unsaved: 0, lost: 0, saved: 3 }); + // and nothing is sent again afterwards + const tries = room.tries.length; + await vi.advanceTimersByTimeAsync(60_000); + expect([room.tries.length, outbox.waiting]).toEqual([tries, 0]); +}); + +test("a try with no answer counts as failed, and the line that had landed is not taken twice", async () => { + using call = callThatTakes(); + const { room } = call; + let hang = true; + const outbox = lineOutbox<{ id: string; at: number }>({ + send: (line) => { + room.tries.push(line.id); + if (!room.taken.some((one) => one.id === line.id)) room.taken.push(line); + // the call took the line, and its answer never came + return hang ? new Promise(() => {}) : Promise.resolve(); + }, + ready: () => true, + onChange: (change) => room.told.push(change), + }); + outbox.add({ id: "a", at: Date.now() }); + await vi.advanceTimersByTimeAsync(UNSENT.answerMs); + expect(room.told.at(-1)).toMatchObject({ unsaved: 1 }); + hang = false; + await vi.advanceTimersByTimeAsync(1_000); + expect([room.tries, room.taken.length, outbox.waiting]).toEqual([["a", "a"], 1, 0]); + expect(room.told.at(-1)).toEqual({ unsaved: 0, lost: 0, saved: 1 }); +}); + +test("a page out of the call tries nothing by itself, and sends what waits when it is in again", async () => { + using call = callThatTakes(); + const { room, outbox } = call; + room.down = true; + outbox.add({ id: "a", at: Date.now() }); + await outbox.flush(); + room.in = false; + await vi.advanceTimersByTimeAsync(60_000); + expect(room).toMatchObject({ tries: ["a"] }); + // the join's own flush + room.in = true; + room.down = false; + await outbox.flush(); + expect(room.taken.map((line) => line.id)).toEqual(["a"]); +}); + +test("what waits is bounded, each outbox holds its own lines, and a line of the voice agent is dropped at its first failure", async () => { + using call = callThatTakes(); + const { room, outbox } = call; + room.down = true; + outbox.add({ id: "voice", at: Date.now(), ai: true }); + await outbox.flush(); + expect([outbox.waiting, room.told]).toEqual([0, []]); + // more than the bound: the oldest goes, and the page is told + outbox.add({ id: "line-0", at: Date.now() }); + await outbox.flush(); + for (let n = 1; n <= UNSENT.lines; n++) outbox.add({ id: `line-${n}`, at: Date.now() }); + expect([outbox.waiting, room.told.at(-1)]).toEqual([ + UNSENT.lines, + { unsaved: UNSENT.lines, lost: 1, saved: 0 }, + ]); + // a line older than the bound is given up, never sent late + room.in = false; + await vi.advanceTimersByTimeAsync(UNSENT.ageMs + 1); + room.in = true; + room.down = false; + room.tries.length = 0; + await outbox.flush(); + expect([room.tries, outbox.waiting]).toEqual([[], 0]); + expect(room.told.at(-1)).toEqual({ unsaved: 0, lost: UNSENT.lines, saved: 0 }); + // another page's outbox, or another call's, got none of them + const other = callThatTakes(Date.now()); + other.outbox.add({ id: "theirs", at: Date.now() }); + await other.outbox.flush(); + expect(other.room.taken.map((line) => line.id)).toEqual(["theirs"]); +}); + const offerOf = (payload: object, email = "jonas@nustom.com", offset = 7) => ({ type: "device/control-configured", offset, @@ -572,3 +679,28 @@ control: "ask", displays: [{ display: 0, name: "Built-in Retina Display", screen: "shared" }], }; + +/** A call that takes lines, or refuses them while `down`: what it took, each try, and what the + * page was told. */ +function callThatTakes(start = Date.parse("2026-11-26T10:48:00Z")) { + vi.useFakeTimers({ now: start }); + const room = { + down: false, + in: true, + taken: [] as { id: string; at: number }[], + tries: [] as string[], + told: [] as { unsaved: number; lost: number; saved: number }[], + }; + const outbox = lineOutbox<{ id: string; at: number; ai?: true }>({ + send: async (line) => { + room.tries.push(line.id); + if (room.down) throw new Error("the call did not answer"); + // the call takes an id once + if (!room.taken.some((one) => one.id === line.id)) room.taken.push(line); + }, + ready: () => room.in, + expendable: (line) => Boolean(line.ai), + onChange: (change) => room.told.push(change), + }); + return { room, outbox, [Symbol.dispose]: () => void vi.useRealTimers() }; +}
M src/lib/call-rules.ts
Not shown: the change is larger than this page shows. A clone has it.