Public: anyone can read this; the crew can change it.

Talk draws the reply as it is written: the runner's pieces reach /talk as live frames #16102

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

talk/02-live → main 0 commits 5 threads · 5 unresolved

  • Merged. talk/02-live was merged into main as 3f562bd.

Review

Sign in to review this change.
17 files changed +1738 −38
AGENTS.md +1 −1

Diff not shown — a line 4,238 characters wide (limit 2,000). +1 −1

View file
docs/design/size-budget.json +1 −1
@@ -68,7 +68,7 @@
6868 "css": 48384
6969 },
7070 "/talk": {
71 "js": 27392,
71 "js": 28160,
7272 "css": 50432
7373 },
7474 "/:owner/:name/pulls/:number": {
docs/features/talk.md +16 −3
@@ -8,7 +8,7 @@ One door, `talk()` in `src/actions/talk.ts`, three ways in. It sends the words a
88
99 - **API:** `POST /api/v1/conversation/messages {"text"}` answers 202; `GET /api/v1/conversation/turns` reads the conversation and whether an answer is being written.
1010 - **MCP:** `say` with `text` and no `repo` or `number`. The agent's own token is refused, so it cannot wake itself.
11 - **Terminal:** `ssh <forge> talk <words>` (the words are not passed to a shell), and `forge talk <words>`, which prints the answer.
11 - **Terminal:** `ssh <forge> talk <words>` (the words are not passed to a shell), `ssh <forge> talk --follow <words>`, which prints the answer as it is written, and `forge talk <words>`, which prints the answer.
1212
1313 It needs a way to spend on a model: a granted Claude account, a monthly dollar grant, or credit the host lent this forge (a forge admin uses the forge's own key). With none you get `no_account` (403), and the words say to ask an admin; the grant is set at /settings/accounts, which only an admin can open. It says `resting` (429) when the account is resting, a dollar grant is spent for the month, or your daily ceiling is spent. A turn on a grant or lent credit is budgeted at most what is left of it, and is booked against it. When the copy of the lent credit is short, the refusal also starts the one refresh of it from the host (at most once in 15 s), so the next message sees the fresh figure. At most four turns run across the forge at once (`TURNS_LIVE_MAX`); a new one past that is `busy` (429, `retry-after: 60`), while a message into your running turn always goes through. A message that is refused is not kept in the conversation.
1414
@@ -22,10 +22,22 @@ Reached from the Talk icon in every page's top bar, "Talk to the forge" in the p
2222
2323 On a phone the composer is sticky and lifts above the on-screen keyboard (the script sets `--kb` from `visualViewport`); the log is a `role=log` (polite, additions only) and the status line `role=status`, each already a polite live region, so a reply is announced once.
2424
25 A reply streams in over `GET /talk/stream?after=<turn id>` (server-sent events, one `turn` frame per turn, each carrying the server-rendered markup). The stream ends with the turn (`done`), or after 40 seconds (`more`), well inside the edge's timeout; the page then reconnects from the last turn id it saw (`Last-Event-ID` works too). Without the script the composer is a plain form and a reload shows the answer.
25 A reply streams in over `GET /talk/stream?after=<turn id>` (server-sent events, one `turn` frame per stored turn, each carrying the server-rendered markup, and `live` frames for the block being written, see "Live" below). The stream ends with the turn (`done`), or after 40 seconds (`more`), well inside the edge's timeout; the page then reconnects from the last turn id it saw (`Last-Event-ID` works too). Without the script the composer is a plain form and a reload shows the answer.
2626
2727 When the agent asks first (`needs_confirm`), the turn draws **Do it** (the existing yes) and **Not now** (a no: the confirm is spent, nothing runs, a turn says it was cancelled). A result shown once (an invite link) is drawn by Settings → Confirms instead, where Do it leads.
outdated

Wrong: the page draws Do it and Not now (talk.ts btn calls), and talk_follow.ts's own ANSWER_CONFIRM says Do it or Not now. Restore main's wording; this doc now contradicts the terminal text it describes two sections down.

2828
29 ## Live
30
31 The reply is drawn as it is written. The runner reports each piece of the block it is writing (`onDelta` in `src/crew/agent_runner.ts`; the Claude adapter asks for partial output with `--include-partial-messages` only for a Talk turn, so a crew run is unchanged). `src/crew/conversation_live.ts` holds the block in process memory, per conversation: the text so far (at most 20,000 characters, as a stored turn), whether the agent is thinking, and the tool call it is waiting on. It is cleared when the block is stored and when the turn ends, however it ends.
32
33 - **Frames:** the stream sends `live` `{html, thinking, tool}` at once when something changes, at most one every 125 ms, always the latest. `html` is the text so far drawn by the same Markdown renderer as a stored reply (an unfinished fence is closed for drawing); `tool` is the step in plain words while it runs ("Reading src/a.ts…", `runningStep` in `src/core/talk_steps.ts`, or "Working: <tool words>…" for a tool with no words of its own), never its arguments as JSON; `thinking` is true or false, and the thoughts themselves arrive only in the stored, folded turn. A stream that connects mid-block gets the whole block in its first `live` frame. When the block is stored its `turn` frame is followed, in the same look, by an empty `live` frame, which removes the element: the server alone takes it away, so a turn from another door lands above the block and leaves it in place. A fresh attempt after a lost session starts from an empty block.
34 - **The page:** one element, `<li id="live">`, last in the log before any queued message, `aria-hidden` so a screen reader hears the stored reply once. When you were at the end, the page goes to its true end with each frame (the talk column where it scrolls on its own, from 56.25rem, judged from the column's own position; else the window), below the composer; scrolled up, nothing moves. A lost stream removes it; the stream that comes back draws it again.
35 - **Who sees it:** only the conversation's owner: the stream finds the conversation by its owner, and another person naming it gets 404.
36 - **Secrets:** what leaves the block is redacted as the stored turn is (`redactHeld`: held values and credential shapes, which the stored turn now masks too), and the end of the text that could be the start of a held value is held back until the rest arrives, so a value cut across two pieces never shows in part; a word at the end that is, or could still become, a short held value waits for the letter that settles it, so nothing shows masked and then clear; the run of token characters being written (a credential shape is masked only once it is long enough) waits for the character after it, so the text grows a word at a time.
37 - **Other turns:** every turn is stored through `appendTurn` (`src/core/conversations.ts`), which wakes the open streams of its conversation, so a confirm, a receipt, an undo, a routine's post or a slash answer arrives at once too. A look once a second stays as the net.
38 - **Terminal:** the page's part is `liveJs` in `src/web/pages/talk_client.ts`. `ssh <forge> talk --follow <words>` (`src/tui/talk_follow.ts`) prints the reply as it is written and exits when the turn ends; when a block is stored the rest of the stored reply is printed, so the terminal ends with what the record holds. What is printed is never printed again: text that parts from it (a stop, a failure line, a fresh attempt after a lost session) prints only from where they differ, on a line of its own. A held action prints its sentence and how to answer it (Do it or Not now on /talk, or `:` Confirms in the terminal). `forge talk` still prints each finished turn: the only live source is the page's stream, whose frames carry the page's markup and not the reply's words, so following it from the command line would mean parsing that markup or adding a field to every frame; the terminal's live door is `ssh talk --follow`.
39 - **Without the script**, or with a runner that reports no pieces, the page draws whole turns, as before.
40
2941 ## The crew's line
3042
3143 `/talk` shows one line above the composer from the live runs only (`liveCrewRows` in `src/actions/crew_now.ts`, with `crewNow`'s visibility filters but none of its planner or review-wait reads, so the common request stays fast): "The crew is working: <who> on <what>" (with the count first when several, "(3)") while an agent run is live, else "The crew is idle." It is rendered with the page, never polled, and holds a fixed one-line height so nothing shifts. The terminal twin is `ssh <forge> talk /crew`, which prints the same line (`crewLine()` in `src/web/crew_now.ts`); signed out it says the crew is idle.
@@ -99,6 +111,7 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha
99111 | Queue and Steer while an answer runs | #8819 | `Queue` / `PromptInput` |
100112 | Cost under each reply and how full the context is (header, and in the terminal) | this pull | the run's own usage record, never an estimate |
101113 | Attachments: pick, paste or drop | have | `docs/features/talk-attachments.md` |
outdated

Main has 'Attachments: pick, paste or drop | have' and a row for code highlighting and tables; this replaces them with 'later', which says attachments and tables do not exist. Restore the attachments row and keep only your new rows.

114 | The reply drawn as it is written | have | see "Live" |
102115 | Code highlighting and tables in replies | this pull (#8816) | a reply is stored whole and drawn whole, so no half-open fence is ever tokenised |
103116
104117 **Without the script** the page is a plain form: Enter adds a line, starters are links that prefill the box, and Copy and Latest are not drawn (the script draws them, along with the "Enter sends" hint). The log is `role="log"`; with the script, a new message while you are scrolled up is announced in the status line.
@@ -113,7 +126,7 @@ Prior art read: Vercel AI Elements (Apache-2.0 React on shadcn; anatomy and beha
113126
114127 An agent reply is Markdown, drawn on the server by the same renderer as a README: fenced code is highlighted, tables and links render, and everything else is escaped (a `<script>` in a reply shows as text). A table wider than the column scrolls inside it; the page does not. The reply sits in the column like a person's turn, with none of the README's padding or line measure.
115128
116 A reply arrives as one finished turn, never as growing text, and the page only appends a turn whose id it has not drawn (a repeat is ignored). Turns already on the page are not touched, so nothing above a new reply moves, and the page follows the end only if you were already there (otherwise "Latest" appears). An unfinished fence in a stored reply is closed for drawing. The page's own bytes are held by a test (`test/talk-page.test.ts`): the stylesheet under 6,300 B, the script under 18,900 B, and a page with a code reply under 40,000 B.
129 A reply grows in one live element while it is written (see "Live") and is then stored as one finished turn; the page only appends a turn whose id it has not drawn (a repeat is ignored). Turns already on the page are not touched, so nothing above a new reply moves, and the page follows the end only if you were already there (otherwise "Latest" appears). An unfinished fence in a stored reply is closed for drawing. The page's own bytes are held by a test (`test/talk-page.test.ts`): the stylesheet under 6,300 B, the script under 20,700 B, and a page with a code reply under 40,000 B.
117130
118131 **Copy:** each code block and each message has a Copy button, which copies the text, not the markup. The buttons are drawn by the script: with JavaScript off there are none, and the code is still there to select.
119132
src/core/conversations.ts +13
@@ -249,6 +249,18 @@ export function undoneBy(db: Database, userId: string, conversationId: string, t
249249 );
250250 }
251251
252 /**
253 * The one listener told a conversation's id each time a turn is stored, through any door: how an
254 * open /talk stream hears it at once (`crew/conversation_live.ts` sets it). A wake-up in process
255 * memory, not an event: it carries no data, and nothing is lost when no one hears it.
256 */
257 let appended: ((db: Database, conversationId: string) => void) | undefined;
258
259 /** Set (or with undefined clear) the listener `appendTurn` tells. */
260 export function onTurnAppended(listener: ((db: Database, conversationId: string) => void) | undefined): void {
261 appended = listener;
262 }
263
252264 /** Add a turn at the end. Text is 1 to `MAX_TURN_CHARS` characters. */
253265 export function appendTurn(
254266 db: Database,
@@ -277,6 +289,7 @@ export function appendTurn(
277289 db.query(
278290 "DELETE FROM conversation_turn WHERE conversation_id = ?1 AND rowid < (SELECT rowid FROM conversation_turn WHERE conversation_id = ?1 ORDER BY rowid DESC LIMIT 1 OFFSET ?2)",
279291 ).run(conversationId, TURNS_KEPT - 1);
292 appended?.(db, conversationId);
280293 return ok(turnOf(row));
281294 }
282295
src/core/talk_steps.ts +44 −15
@@ -17,7 +17,8 @@ export interface Step {
1717 readonly details: readonly string[];
1818 }
1919
20 const PREFIX = /^mcp__[a-z0-9-]+__/;
20 /** The `mcp__<server>__` a harness puts before a tool's name; a server name may hold one `_`. */
21 const PREFIX = /^mcp__[a-z0-9-]+(?:_[a-z0-9-]+)*__/;
2122 const TOOL = /^[a-z0-9_]{1,60}$/;
2223 const REPO = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}$/;
2324 const VALUE_MAX = 160;
@@ -68,6 +69,36 @@ function filedStep(text: string): Step | undefined {
6869 return { label: cut(`${verb} ${object}${title === "" ? "" : ` ${title}`}`), details: [href] };
6970 }
7071
72 /** A step said done and said while it runs. */
73 export interface StepWords {
74 readonly done: string;
75 readonly running: string;
76 }
77
78 /**
79 * The words of a call with words of its own, both forms from one place, so a step cannot ship
80 * without the words for it running; undefined for a tool that has none (it is called by its name).
81 */
82 export function stepWords(tool: string, args: Record<string, unknown>): StepWords | undefined {
83 const path = cut(str(args["path"]));
84 const both = (done: string, running: string): StepWords => ({ done, running });
85 if (tool === "read_file") return path === "" ? both("Read a file", "Reading a file") : both(`Read ${path}`, `Reading ${path}`);
86 if (tool === "write_file") {
87 const content = args["content"];
88 const added = typeof content === "string" ? ` (+${String(lines(content))})` : "";
89 return path === "" ? both(`Edited a file${added}`, "Editing a file") : both(`Edited ${path}${added}`, `Editing ${path}`);
90 }
91 const n = typeof args["number"] === "number" && Number.isInteger(args["number"]) && args["number"] > 0 ? `#${String(args["number"])}` : undefined;
92 if (n === undefined) return undefined;
93 if (tool === "issue") return both(`Opened issue ${n}`, `Opening issue ${n}`);
94 if (tool === "pull") return both(`Opened pull ${n}`, `Opening pull ${n}`);
95 if (tool === "merge") return args["dryRun"] === true ? both(`Checked that pull ${n} can merge`, `Checking that pull ${n} can merge`) : both(`Merged pull ${n} and deployed`, `Merging pull ${n}`);
96 if (tool === "review") return both(`Reviewed pull ${n}`, `Reviewing pull ${n}`);
97 if (tool === "say") return both(`Commented on ${n}`, `Commenting on ${n}`);
98 if (tool === "keep_plan") return both(`Updated the plan on ${n}`, `Updating the plan on ${n}`);
99 return undefined;
100 }
101
71102 /** The step a call stands for. */
72103 export function stepOf(text: string): Step | undefined {
73104 const filed = filedStep(text);
@@ -75,23 +106,21 @@ export function stepOf(text: string): Step | undefined {
75106 const call = parseCall(text);
76107 if (call === undefined) return undefined;
77108 const { tool, args } = call;
78 const path = cut(str(args["path"]));
79 const n = typeof args["number"] === "number" && Number.isInteger(args["number"]) && args["number"] > 0 ? args["number"] : undefined;
80109 const details = Object.entries(args)
81110 .slice(0, 8)
82111 .map(([k, v]) => `${k.slice(0, 40)}: ${cut(typeof v === "string" ? v : JSON.stringify(v) ?? "")}`);
83 let label = words(tool);
84 if (tool === "read_file") label = path === "" ? "Read a file" : `Read ${path}`;
85 else if (tool === "write_file") {
86 const content = args["content"];
87 label = `${path === "" ? "Edited a file" : `Edited ${path}`}${typeof content === "string" ? ` (+${String(lines(content))})` : ""}`;
88 } else if (tool === "issue" && n !== undefined) label = `Opened issue #${String(n)}`;
89 else if (tool === "pull" && n !== undefined) label = `Opened pull #${String(n)}`;
90 else if (tool === "merge" && n !== undefined) label = args["dryRun"] === true ? `Checked that pull #${String(n)} can merge` : `Merged pull #${String(n)} and deployed`;
91 else if (tool === "review" && n !== undefined) label = `Reviewed pull #${String(n)}`;
92 else if (tool === "say" && n !== undefined) label = `Commented on #${String(n)}`;
93 else if (tool === "keep_plan" && n !== undefined) label = `Updated the plan on #${String(n)}`;
94 return { label: cut(label), details };
112 return { label: cut(stepWords(tool, args)?.done ?? words(tool)), details };
113 }
114
115 /**
116 * A call still running (`<tool> <json args>`, or its tool's name alone) as plain words: "Reading
117 * src/a.ts…", or "Working: <tool words>…" for a tool with no words of its own; never its arguments.
118 */
119 export function runningStep(text: string): string {
120 const call = parseCall(text);
121 if (call === undefined) return "Working…";
122 const running = stepWords(call.tool, call.args)?.running;
123 return `${cut(running ?? `Working: ${call.tool.replaceAll("_", " ")}`).replace(/…$/, "")}…`;
95124 }
96125
97126 /** The repository the last call that named a good one worked on. */
src/crew/agent_runner.ts +23 −4
@@ -1,10 +1,10 @@
11 /**
22 * The agent-runner seam (#12122): every crew run starts here. A runner takes
33 * a brief (prompt, system prompt, model, budget) and a sandbox, streams the
4 * run's steps (`log`, `onSaid`), reports spend (`onUsage`, `onMeasure`),
5 * pauses (`onCleared`, a rate-limited outcome) and its end (`AgentOutcome`),
6 * as plain data in and out. `crew/claude.ts` is the first runner; callers
7 * import this module, never a runner.
4 * run's steps (`log`, `onSaid`, and `onDelta` as they are written), reports spend (`onUsage`,
5 * `onMeasure`), pauses (`onCleared`, a rate-limited outcome) and its end (`AgentOutcome`), as plain
6 * data in and out. `crew/claude.ts` is the first runner; callers import this module, never a
7 * runner.
88 */
99
1010 import type { Measure } from "../core/measure.ts";
@@ -75,6 +75,14 @@ export interface AgentRun {
7575 readonly onSession?: ((sessionId: string) => void) | undefined;
7676 /** What the agent said or called, as each assistant message arrives. */
7777 readonly onSaid?: ((said: { readonly kind: "text" | "tool" | "thinking"; readonly text: string }) => void) | undefined;
78 /**
79 * What the agent is writing, before `onSaid` reports it whole: text (or thinking) appended to the
80 * block being written, which may begin as empty text, and a tool call starting and ending, named
81 * as `onSaid` names it. A block reported through `onSaid` is over; the next text starts a new
82 * one. Absent, the runner asks for no partial output; a runner that never calls it reports
83 * whole blocks alone, as before.
84 */
85 readonly onDelta?: ((delta: Delta) => void) | undefined;
7886 /**
7987 * How long a session may stay silent after a result while its input is
8088 * still open (a steer was pending) before it is closed and settled as
@@ -90,6 +98,17 @@ export interface AgentRun {
9098 readonly settleMs?: number | undefined;
9199 }
92100
101 /** A piece of a block still being written (`AgentRun.onDelta`). */
102 export type Delta =
103 | { readonly kind: "text" | "thinking"; readonly text: string }
104 | {
105 readonly kind: "tool";
106 readonly name: string;
107 readonly state: "started" | "ended";
108 readonly ok?: boolean | undefined;
109 /** The runner's own id for the call, opaque, when it has one: which of two calls ended. */
110 readonly id?: string | undefined;
111 };
93112
94113 export interface RunAccount {
95114 readonly token: string;
src/crew/claude.ts +55
@@ -146,6 +146,8 @@ export function claudeArgs(input: ClaudeInput): string[] {
146146 "--append-system-prompt",
147147 input.appendSystemPrompt,
148148 ];
149 // Text as it is written, for a caller that shows it (`onDelta`); a crew run asks for none.
150 if (input.onDelta !== undefined) args.push("--include-partial-messages");
149151 if (input.mcp !== undefined) args.push("--mcp-config", input.mcp.config);
150152 if (input.model !== undefined && input.model !== "")
151153 args.push("--model", input.model);
@@ -154,6 +156,47 @@ export function claudeArgs(input: ClaudeInput): string[] {
154156 return args;
155157 }
156158
159 type Delta = Parameters<NonNullable<ClaudeInput["onDelta"]>>[0];
160
161 const recordOf = (v: unknown): Record<string, unknown> => (typeof v === "object" && v !== null ? (v as Record<string, unknown>) : {});
162
163 /**
164 * One partial event (`--include-partial-messages`) as `onDelta`'s plain data: text and thinking
165 * as they are written, a tool call as it starts. Everything else (signatures, a call's arguments
166 * being written, message bounds) says nothing a person reads.
167 */
168 export function partialOf(event: unknown, calling: Map<string, string>, onDelta: (delta: Delta) => void): void {
169 const e = recordOf(event);
170 if (e["type"] === "content_block_start") {
171 const block = recordOf(e["content_block"]);
172 if (block["type"] === "thinking") onDelta({ kind: "thinking", text: "" });
173 else if (block["type"] === "tool_use" && typeof block["name"] === "string") {
174 if (typeof block["id"] === "string") {
175 calling.set(block["id"], block["name"]);
176 onDelta({ kind: "tool", name: block["name"], state: "started", id: block["id"] });
177 } else onDelta({ kind: "tool", name: block["name"], state: "started" });
178 }
179 } else if (e["type"] === "content_block_delta") {
180 const delta = recordOf(e["delta"]);
181 if (delta["type"] === "text_delta" && typeof delta["text"] === "string" && delta["text"] !== "") onDelta({ kind: "text", text: delta["text"] });
182 else if (delta["type"] === "thinking_delta" && typeof delta["thinking"] === "string") onDelta({ kind: "thinking", text: delta["thinking"] });
183 }
184 }
185
186 /** The tool calls a `user` record answers, each ended once, `ok` unless its result is an error. */
187 export function answeredOf(message: unknown, calling: Map<string, string>): Delta[] {
188 const content = recordOf(message)["content"];
189 const ended: Delta[] = [];
190 for (const block of Array.isArray(content) ? content : []) {
191 const b = recordOf(block);
192 const name = typeof b["tool_use_id"] === "string" ? calling.get(b["tool_use_id"]) : undefined;
193 if (b["type"] !== "tool_result" || name === undefined) continue;
194 calling.delete(b["tool_use_id"] as string);
195 ended.push({ kind: "tool", name, state: "ended", ok: b["is_error"] !== true, id: b["tool_use_id"] as string });
196 }
197 return ended;
198 }
199
157200 /** Run Claude Code to completion. Never throws; every ending is an outcome. */
158201 export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> {
159202 return withLimit(await runClaudeRaw(input), new Date());
@@ -307,6 +350,8 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
307350 // The workdir as the forge named it and as the agent's process reports
308351 // it: a tool line reads `CREW.md` under either spelling.
309352 const workdir = spellings([input.cwd]);
353 // The tool calls started and not yet answered, by call id, for `onDelta`'s end of each.
354 const calling = new Map<string, string>();
310355 const onLine = (line: string): void => {
311356 if (line.trim() === "") return;
312357 if (sawResult && !finished) armIdle();
@@ -331,6 +376,16 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
331376 if (cleared !== undefined) input.onCleared?.(cleared);
332377 return;
333378 }
379 // A piece of a block being written: only asked for with `onDelta`, never logged, never spend
380 // (the whole message that follows carries its usage).
381 if (type === "stream_event") {
382 if (input.onDelta !== undefined) partialOf(e["event"], calling, input.onDelta);
383 return;
384 }
385 if (type === "user" && input.onDelta !== undefined) {
386 for (const ended of answeredOf(e["message"], calling)) input.onDelta(ended);
387 return;
388 }
334389 if (type === "system") {
335390 if (e["subtype"] === "init")
336391 input.log(`session ${sessionId} (${String(e["model"] ?? "")})`);
src/crew/conversation.ts +9 −3
@@ -36,13 +36,14 @@ import { PLATFORM, pickSubscription, type Pick } from "../core/subscriptions.ts"
3636 import { getUserById } from "../core/users.ts";
3737 import { mintViaToken, VIA_TOKEN_MAX_MS } from "../core/via_token.ts";
3838 import { id } from "../kernel/id.ts";
39 import { redactValues, releaseValues } from "../kernel/log.ts";
39 import { redactHeld, releaseValues } from "../kernel/log.ts";
4040 import { running } from "../kernel/version.ts";
4141 import { err, ok, type Result } from "../kernel/result.ts";
4242 import { appendRunLog } from "../runs/log.ts";
4343 import { runAgent, type AgentOutcome, type RunnerLimit } from "./agent_runner.ts";
4444 import { runAccount } from "./runner_env.ts";
4545 import { CONVERSATION_BRIEF } from "./conversation_brief.ts";
46 import { liveDelta, liveEnd, liveReset, liveSaid } from "./conversation_live.ts";
4647 import { isRateLimited, takeLimit, whenText } from "./limits.ts";
4748 import { turnBudget } from "./model_access.ts";
4849 import { credentialEnv, holdModelCredential, listenForSteer, steerRun } from "./runner.ts";
@@ -570,8 +571,9 @@ function begin(
570571 stoppers.set(conversation.id, { runId, userId, stop: () => stopper.abort() });
571572 const signal = AbortSignal.any([options.signal, stopper.signal]);
572573 const put = (role: "agent" | "tool", text: string): void => {
573 // Kept with every held value taken out: a turn that says its credential leaves `[redacted]`.
574 const stored = appendTurn(app.db, userId, conversation.id, { role, text: redactValues(text).slice(0, 20_000) });
574 // Kept with every held value and credential shape taken out: a turn that says its credential
575 // leaves `[redacted]`, as the live block showed it.
576 const stored = appendTurn(app.db, userId, conversation.id, { role, text: redactHeld(text).slice(0, 20_000) });
575577 if (stored.ok && role === "agent") streamed.push({ id: stored.value.id, text });
576578 };
577579 let lastText = "";
@@ -599,6 +601,7 @@ function begin(
599601 let fresh = prompt;
600602 for (let session = resumeSession; ; session = undefined) {
601603 let named = false;
604 liveReset(app.db, conversation.id);
602605 if (session !== undefined) appendRunLog(app.config.dataDir, runId, `resuming session ${session}`);
603606 outcome = await runAgent({
604607 binary: options.binary,
@@ -636,7 +639,9 @@ function begin(
636639 app.db.query("UPDATE conversation_run SET session_id = ?2 WHERE id = ?1").run(runId, sessionId);
637640 setClaudeSession(app.db, userId, conversation.id, sessionId);
638641 },
642 onDelta: (delta) => liveDelta(app.db, conversation.id, delta),
639643 onSaid: (said) => {
644 liveSaid(app.db, conversation.id, said.kind, said.text);
640645 if (said.kind === "text") lastText = said.text;
641646 if (said.text.trim() === "") return;
642647 // Thinking is kept as a tool turn of its own shape, so the page can fold it.
@@ -726,6 +731,7 @@ function begin(
726731 } finally {
727732 if (live.get(conversation.id) === runId) live.delete(conversation.id);
728733 if (stoppers.get(conversation.id)?.runId === runId) stoppers.delete(conversation.id);
734 liveEnd(app.db, conversation.id);
729735 // A restart leaves the next message unsent (its turn would be cut again); anything else sends
730736 // it.
731737 if (options.signal.aborted) queues.delete(conversation.id);
src/crew/conversation_live.ts added +191
@@ -0,0 +1,191 @@
1 /**
2 * The block a Talk turn is writing, before it is stored: per conversation,
3 * the text so far, whether the agent is thinking, and the tool call it is waiting on, from the
4 * runner's `onDelta`. It lives in process memory and is not state: a stored turn replaces it the
5 * moment the block is whole, and a restart loses nothing a stored turn does not have.
6 *
7 * A small hub goes with it: `subscribe` hears `notify`, called when a delta arrives ("live"), when
8 * the answer ends, and when any turn is stored through any door ("turn", by `appendTurn`'s one
9 * listener, set below), so the page's stream sends at once instead of looking.
10 *
11 * Both are kept per forge, by its database (every caller holds one, `appendTurn` included), so two
12 * forges in one process never hear each other's conversations.
13 *
14 * What leaves this module is redacted as the stored turn is (`redactValues`), and the end of the
15 * text that could be the start of a held value is held back until the rest of it arrives
16 * (`heldTail`), so a value cut across two pieces never shows in part.
17 */
18
19 import type { Database } from "bun:sqlite";
20 import type { Delta } from "./agent_runner.ts";
21 import { MAX_TURN_CHARS, onTurnAppended } from "../core/conversations.ts";
22 import { heldTail, heldWordTail, redactHeld } from "../kernel/log.ts";
23
24 /** What a subscriber is told: a piece of the block arrived, or a turn was stored or ended. */
25 export type LiveChange = "live" | "turn";
26
27 /** The block being written, as it may be shown: redacted, held back, capped. */
28 export interface LiveBlock {
29 /** The text so far, at most a stored turn's length. */
30 readonly text: string;
31 /** Whether the agent is thinking (its thoughts are stored folded, never streamed). */
32 readonly thinking: boolean;
33 /** The call being waited on, as it is stored (`<tool> <json args>`), or its tool's name alone. */
34 readonly tool: string | undefined;
35 }
36
37 interface Held {
38 text: string;
39 thinking: boolean;
40 /**
41 * Calls started and not ended, oldest first; `call` is filled when the call is reported whole.
42 */
43 tools: { name: string; id: string | undefined; call: string }[];
44 }
45
46 /** Text held beyond a stored turn's cap is never shown; a little more is kept for redaction. */
47 const HELD_CHARS = MAX_TURN_CHARS + 1_000;
48
49 /** One forge's blocks being written and stream listeners, by conversation id. */
50 interface Live {
51 readonly blocks: Map<string, Held>;
52 readonly listeners: Map<string, Set<(change: LiveChange) => void>>;
53 }
54
55 const forges = new WeakMap<Database, Live>();
56
57 const liveOf = (db: Database): Live => {
58 let live = forges.get(db);
59 if (live === undefined) {
60 live = { blocks: new Map(), listeners: new Map() };
61 forges.set(db, live);
62 }
63 return live;
64 };
65
66 const heldOf = (db: Database, conversationId: string): Held => {
67 const { blocks } = liveOf(db);
68 let held = blocks.get(conversationId);
69 if (held === undefined) {
70 held = { text: "", thinking: false, tools: [] };
71 blocks.set(conversationId, held);
72 }
73 return held;
74 };
75
76 /** Hear every change to a conversation's block and turns; returns the way to stop hearing. */
77 export function subscribe(
78 db: Database,
79 conversationId: string,
80 listener: (change: LiveChange) => void,
81 ): () => void {
82 const { listeners } = liveOf(db);
83 let set = listeners.get(conversationId);
84 if (set === undefined) {
85 set = new Set();
86 listeners.set(conversationId, set);
87 }
88 set.add(listener);
89 return () => {
90 const now = listeners.get(conversationId);
91 if (now === undefined) return;
92 now.delete(listener);
93 if (now.size === 0) listeners.delete(conversationId);
94 };
95 }
96
97 /** Tell a conversation's listeners. A listener that throws is its own trouble, never the turn's. */
98 export function notify(
99 db: Database,
100 conversationId: string,
101 change: LiveChange = "turn",
102 ): void {
103 for (const listener of [...(liveOf(db).listeners.get(conversationId) ?? [])])
104 try {
105 listener(change);
106 } catch {
107 // the turn goes on
108 }
109 }
110
111 // A confirm, a receipt, a routine's post or a slash answer is stored by its own door; each wakes
112 // the streams here, and the stream's slow look stays as the net.
113 onTurnAppended((db, conversationId) => notify(db, conversationId, "turn"));
114
115 /** A piece of the block being written (`AgentRun.onDelta`). */
116 export function liveDelta(db: Database, conversationId: string, delta: Delta): void {
117 const held = heldOf(db, conversationId);
118 if (delta.kind === "tool") {
119 if (delta.state === "started")
120 held.tools.push({ name: delta.name, id: delta.id, call: "" });
121 else {
122 // By its id when the runner gives one, so of two calls of one tool the right one ends.
123 const at = delta.id === undefined ? held.tools.findLastIndex((t) => t.name === delta.name) : held.tools.findIndex((t) => t.id === delta.id);
124 if (at >= 0) held.tools.splice(at, 1);
125 }
126 } else if (delta.kind === "thinking") held.thinking = true;
127 else {
128 if (held.text.length < HELD_CHARS)
129 held.text = (held.text + delta.text).slice(0, HELD_CHARS);
130 held.thinking = false;
131 }
132 notify(db, conversationId, "live");
133 }
134
135 /**
136 * A block reported whole (`AgentRun.onSaid`), about to be stored: its text or thinking is over. A
137 * call is not: it is still waited on, now with its arguments, until its end arrives.
138 */
139 export function liveSaid(
140 db: Database,
141 conversationId: string,
142 kind: "text" | "tool" | "thinking",
143 text: string,
144 ): void {
145 const held = liveOf(db).blocks.get(conversationId);
146 if (held === undefined) return;
147 if (kind === "text") held.text = "";
148 else if (kind === "thinking") held.thinking = false;
149 else {
150 const name = text.split(" ", 1)[0] ?? "";
151 // Calls are reported whole in the order they started: the oldest one still unnamed is this.
152 const call = held.tools.find((t) => t.name === name && t.call === "");
153 if (call !== undefined) call.call = text;
154 }
155 }
156
157 /**
158 * A new attempt at the answer begins (a lost session started fresh): what the last one was writing
159 * is gone, never joined to the next.
160 */
161 export function liveReset(db: Database, conversationId: string): void {
162 if (liveOf(db).blocks.delete(conversationId)) notify(db, conversationId, "live");
163 }
164
165 /** The answer ended, however it ended: nothing is being written. */
166 export function liveEnd(db: Database, conversationId: string): void {
167 liveOf(db).blocks.delete(conversationId);
168 notify(db, conversationId, "turn");
169 }
170
171 /** The block being written, as it may be shown; undefined when nothing is. */
172 export function liveBlock(db: Database, conversationId: string): LiveBlock | undefined {
173 const held = liveOf(db).blocks.get(conversationId);
174 if (held === undefined) return undefined;
175 // Redacted as the stored turn is (`redactHeld`: held values and credential shapes). What could
176 // still become one waits for the character that settles it, so what is shown never goes from
177 // redacted to clear: a word that is or could become a short held value, and the run of token
178 // characters being written (a credential shape is masked only once it is long enough).
179 const settled = held.text.slice(0, held.text.length - heldWordTail(held.text));
180 const redacted = redactHeld(settled.slice(0, settled.length - (/[A-Za-z0-9._~+/=-]+$/.exec(settled)?.[0].length ?? 0)));
181 const text = redacted
182 .slice(0, redacted.length - heldTail(redacted))
183 .slice(0, MAX_TURN_CHARS);
184 const last = held.tools.at(-1);
185 const tool =
186 last === undefined
187 ? undefined
188 : redactHeld(last.call === "" ? last.name : last.call);
189 if (text === "" && !held.thinking && tool === undefined) return undefined;
190 return { text, thinking: held.thinking, tool };
191 }
src/kernel/log.ts +35 −1
@@ -29,6 +29,7 @@ export function redactSecrets(text: string): string {
2929 const held = new Map<string, string[]>();
3030 let heldForms: string[] = [];
3131 let heldWords: RegExp | undefined;
32 let heldShort: string[] = [];
3233 /** Shorter than this is not held: a three-letter value is a word, not a secret. */
3334 const MIN_HELD = 4;
3435 /**
@@ -64,7 +65,8 @@ export function wordsPattern(values: readonly string[]): RegExp | undefined {
6465 const rebuild = (): void => {
6566 const all = [...new Set([...held.values()].flat())];
6667 heldForms = all.filter((v) => v.length >= MIN_ANYWHERE).sort((a, b) => b.length - a.length);
67 heldWords = wordsPattern(all.filter((v) => v.length < MIN_ANYWHERE));
68 heldShort = all.filter((v) => v.length < MIN_ANYWHERE);
69 heldWords = wordsPattern(heldShort);
6870 };
6971
7072 /** Start redacting these values everywhere, until `releaseValues(key)`. */
@@ -98,6 +100,38 @@ export function redactValues(
98100 return out;
99101 }
100102
103 /**
104 * How many characters at the end of `text` could be the start of a long held value (a short one is
105 * `heldWordTail`'s): what text still
106 * being written holds back, so a value that arrives in two pieces never shows its first one.
107 */
108 export function heldTail(text: string): number {
109 let longest = 0;
110 for (const form of heldForms)
111 for (let k = Math.min(form.length - 1, text.length); k > longest; k -= 1)
112 if (text.endsWith(form.slice(0, k))) {
113 longest = k;
114 break;
115 }
116 return longest;
117 }
118
119 /**
120 * How many characters at the end of `text` are a word that is, or could still become, a short held
121 * value (one masked only as a whole word, so the next letter decides it): what text still being
122 * written holds back, so it never shows a value masked and then clear, or clear and then masked.
123 */
124 export function heldWordTail(text: string): number {
125 let longest = 0;
126 for (const value of heldShort)
127 for (let k = Math.min(value.length, text.length); k > longest; k -= 1)
128 if (text.endsWith(value.slice(0, k)) && !/[\p{L}\p{N}_]/u.test(text.charAt(text.length - k - 1))) {
129 longest = k;
130 break;
131 }
132 return longest;
133 }
134
101135 /** Credential shapes and every held value. */
102136 export function redactHeld(text: string): string {
103137 return redactValues(redactSecrets(text));
src/tui/ssh-talk.ts +6 −1
@@ -2,7 +2,8 @@
22 * `ssh <forge> talk <words>`: the forge's own agent, in one line from any
33 * shell. An exec of `talk` calls the same `talk()` the API and the MCP use,
44 * as the account the presented key belongs to, and prints that the agent is
5 * answering; the answer is read back with `forge talk` or on the feed. The
5 * answering; the answer is read back with `forge talk` or on the feed, or
6 * printed as it is written with `talk --follow <words>` (`talk_follow.ts`). The
67 * words are the rest of the command line as given: no shell, no expansion; a
78 * control character is refused before anything runs. `talk /stop` (or
89 * `--stop`) ends the running answer, as Stop does on /talk: what the agent
@@ -40,6 +41,7 @@ import type { App } from "../app.ts";
4041 import type { RedoHow } from "../crew/conversation.ts";
4142 import type { User } from "../core/users.ts";
4243 import { CONTROL_WORDS } from "./ssh-tell.ts";
44 import { followTalk } from "./talk_follow.ts";
4345 import type { SshSession } from "../ssh/server.ts";
4446
4547 const CRLF = "\r\n";
@@ -137,6 +139,8 @@ export function serveTalk(app: App, session: SshSession, user: User | undefined,
137139 session.write(`cancelled${CRLF}`);
138140 return session.exit(0);
139141 }
142 const follow = /^--follow(?:[ \t]|$)/.test(words.trim());
143 if (follow) words = words.trim().slice("--follow".length);
140144 const subject = parseAbout(words);
141145 const about = subject?.about ?? null;
142146 if (subject !== undefined) {
@@ -174,6 +178,7 @@ export function serveTalk(app: App, session: SshSession, user: User | undefined,
174178 const total = conversationTotal(app.db, conversation.id);
175179 if (total !== undefined) session.write(`${totalText(total)}${CRLF}`);
176180 if (context !== undefined) session.write(`${contextText(context)}${CRLF}`);
181 if (follow && (said.value.how === "started" || said.value.how === "steered")) return followTalk(app, session, user.id, conversation.id);
177182 }
178183 session.exit(0);
179184 };
src/tui/talk_follow.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * `ssh <forge> talk --follow <words>`: the answer printed as it is written, then the exec ends with
3 * the turn. Each piece of text comes from the block being written (`crew/conversation_live.ts`,
4 * redacted as the stored turn is); when the block is stored, the rest of the stored reply is
5 * printed, so the terminal ends holding what the record holds.
6 *
7 * What is printed is never printed again: when the text shown parts from what was printed (a stop,
8 * a failure line, a fresh attempt after a lost session), what was printed stands and only the part
9 * after where they differ follows, on a line of its own. A held action the agent asks for (a
10 * `confirm` turn) is printed as its sentence and how to answer it; the exec still ends with the
11 * turn. Steps and thinking are left to /talk and `forge talk`. Every control character but a line
12 * break is a space.
13 */
14
15 import type { App } from "../app.ts";
16 import { listTurns, turnsAfter } from "../core/conversations.ts";
17 import { turnRunning } from "../crew/conversation.ts";
18 import { liveBlock, subscribe } from "../crew/conversation_live.ts";
19 import type { SshSession } from "../ssh/server.ts";
20
21 const CRLF = "\r\n";
22 const CONTROL = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/g;
23
24 /** How a held action is answered, from the terminal or the page. */
25 export const ANSWER_CONFIRM =
26 "answer within 10 minutes: Do it or Not now on /talk, or in the terminal, `ssh <forge>`, then `:` Confirms (y does it once)";
27
28 /** Text for a terminal: its line breaks as CRLF, every other control character a space. */
29 const plain = (text: string): string =>
30 text
31 .split("\n")
32 .map((l) => l.replace(CONTROL, " "))
33 .join(CRLF);
34
35 /** How many characters `a` and `b` begin with in common. */
36 const shared = (a: string, b: string): number => {
37 let i = 0;
38 while (i < a.length && i < b.length && a[i] === b[i]) i += 1;
39 return i;
40 };
41
42 /** The sentence of a stored confirm turn, or undefined when it has none. */
43 const confirmOf = (text: string): string | undefined => {
44 try {
45 const data: unknown = JSON.parse(text);
46 const does = typeof data === "object" && data !== null ? (data as Record<string, unknown>)["does"] : undefined;
47 return typeof does === "string" && does !== "" ? does : undefined;
48 } catch {
49 return undefined;
50 }
51 };
52
53 /**
54 * Print the conversation's answer as it is written; exits 0 when the turn ends or the channel goes.
55 */
56 export function followTalk(app: App, session: SshSession, userId: string, conversationId: string): void {
57 const newest = listTurns(app.db, userId, conversationId, { limit: 1 });
58 let cursor = newest.ok ? (newest.value.at(-1)?.id ?? "") : "";
59 // What this block has printed, and whether a line is begun and not ended.
60 let printed = "";
61 let midLine = false;
62 let over = false;
63 const write = (text: string): void => {
64 if (text === "") return;
65 session.write(plain(text));
66 midLine = !text.endsWith("\n");
67 };
68 const endLine = (): void => {
69 if (midLine) write("\n");
70 };
71 // The text as it is shown now: only what is new is printed, never what already was. Text that
72 // only shrank (a block cleared for a fresh attempt) prints nothing and is remembered as printed.
73 const show = (text: string): void => {
74 const same = shared(printed, text);
75 if (same === text.length) return;
76 if (same < printed.length) endLine();
77 write(text.slice(same));
78 printed = text;
79 };
80 const look = (): void => {
81 if (over) return;
82 for (const turn of turnsAfter(app.db, userId, conversationId, cursor)) {
83 cursor = turn.id;
84 if (turn.role === "agent") {
85 show(turn.text);
86 endLine();
87 printed = "";
88 } else if (turn.role === "confirm") {
89 const does = confirmOf(turn.text);
90 if (does === undefined) continue;
91 endLine();
92 printed = "";
93 write(`waiting for your yes: ${does}\n${ANSWER_CONFIRM}\n`);
94 }
95 }
96 show(liveBlock(app.db, conversationId)?.text ?? "");
97 if (turnRunning(app, userId, conversationId)) return;
98 over = true;
99 stop();
100 endLine();
101 session.exit(0);
102 };
103 const stop = subscribe(app.db, conversationId, look);
104 session.onClose(() => {
105 over = true;
106 stop();
107 });
108 look();
109 }
src/web/pages/talk.ts +74 −7
@@ -51,6 +51,8 @@ import { ASKING } from "../../crew/conversation_confirm.ts";
5151 import { INVERSES, readReceipt, type Receipt } from "../../crew/receipt.ts";
5252 import { pastTime } from "../../core/fence.ts";
5353 import { turnRunning, type RedoHow } from "../../crew/conversation.ts";
54 import { liveBlock, subscribe } from "../../crew/conversation_live.ts";
55 import { during } from "../../perf/jobs.ts";
5456 import type { Ctx } from "../../http/context.ts";
5557 import { json } from "../../http/respond.ts";
5658 import { eventStream } from "../../http/sse.ts";
@@ -65,21 +67,26 @@ import { renderMarkdown } from "../markdown.ts";
6567 import { badge, btn, row, time } from "../ui.ts";
6668 import { buildBox, buildCss, chosenTemplate, panelFor } from "../talk_build.ts";
6769 import { chatBuildOf } from "../../core/chat_build.ts";
68 import { stepOf, repoOf, type Step } from "../../core/talk_steps.ts";
70 import { runningStep, stepOf, repoOf, type Step } from "../../core/talk_steps.ts";
6971 import { VIEWS, talkPane, type View } from "./talk_preview.ts";
7072 import { TALK_KEYS, talkCss, talkJs } from "./talk_client.ts";
7173
7274 /** A stream lasts this long at most; the client reconnects from its last turn id. */
7375 export const STREAM_MS = 40_000;
74 /** How often a stream looks for a turn the agent has written. */
75 export const POLL_MS = 400;
76 /**
77 * How often a stream looks for itself. Every stored turn and every piece of a block being written
78 * arrive at once (`crew/conversation_live.ts`); this is the net under that wake.
79 */
80 export const TICK_MS = 1_000;
81 /** The block being written is sent at most once in this long, always as it is then. */
82 export const LIVE_MS = 125;
7683 /** Streams one person may hold open at once; a fourth is told to wait. */
7784 export const STREAMS_MAX = 3;
7885 /**
7986 * What a stream consults: how long it lasts and whether a turn runs. Tests move it; nothing else
8087 * does.
8188 */
82 export const clock = { streamMs: STREAM_MS, running: turnRunning };
89 export const clock = { streamMs: STREAM_MS, tickMs: TICK_MS, running: turnRunning, now: (): number => Date.now() };
8390 const open = new Map<string, number>();
8491 const TURN_ID = /^[0-9a-z]{0,40}$/;
8592 const HERE = "/talk";
@@ -688,7 +695,41 @@ export function talkStream(ctx: Ctx): Response {
688695 // The repository the chat works on, kept across batches instead of re-reading the turns.
689696 const before = listTurns(app.db, user.id, conversation.id, { limit: DEFAULT_PAGE });
690697 let cited: string | undefined = before.ok ? repoOf(before.value) : undefined;
698 // The block being written, drawn as a stored reply is, never more than one frame each
699 // `LIVE_MS`: a change inside that time waits for the one timer, which builds the frame when it
700 // goes, so what is sent is always the latest.
701 const idle = JSON.stringify({ html: "", thinking: false, tool: "" });
702 let liveSent = idle;
703 let liveAt = Number.NEGATIVE_INFINITY;
704 let liveTimer: ReturnType<typeof setTimeout> | undefined;
705 let ended = false;
706 // `now`: send at once, past the wait (a timer that is due, or the frame right after turns).
707 const sendLive = (now = false): void => {
708 if (now) {
709 clearTimeout(liveTimer);
710 liveTimer = undefined;
711 } else if (liveTimer !== undefined) return;
712 if (ended) return;
713 const block = liveBlock(app.db, conversation.id);
714 const refs = refTarget(app.db, user, cited);
715 const frame = {
716 html: block === undefined || block.text === "" ? "" : html`<div class="talk-body prose">${linkRefs(renderMarkdown(block.text), refs)}</div>`.text,
717 thinking: block?.thinking === true,
718 tool: block?.tool === undefined ? "" : runningStep(block.tool),
719 };
720 const key = JSON.stringify(frame);
721 if (key === liveSent) return;
722 const wait = liveAt + LIVE_MS - clock.now();
723 if (!now && wait > 0) {
724 liveTimer = setTimeout(() => during("talk-live", () => sendLive(true), undefined, app), wait);
725 return;
726 }
727 liveSent = key;
728 liveAt = clock.now();
729 emit("live", frame);
730 };
691731 const tick = (): void => {
732 if (ended) return;
692733 // Asked before the read: a turn that ends after this look is read whole next time.
693734 const running = clock.running(app, user.id, conversation.id);
694735 const fresh = turnsAfter(app.db, user.id, conversation.id, cursor);
@@ -705,6 +746,10 @@ export function talkStream(ctx: Ctx): Response {
705746 emit("turn", { id: turn.id, role: turn.role, html: turnHtml(turn, waiting, undefined, undefined, works.get(turn.id), sent.get(turn.id), expired, undone, refs).text }, turn.id);
706747 cursor = turn.id;
707748 }
749 // The page is told at once what the block holds after these turns, empty once it is
750 // stored: the server alone takes the live element away, so a turn from another door
751 // never makes it blink.
752 sendLive(true);
708753 }
709754 // Every tab and viewer sees what waits: sent whenever the list changes.
710755 const waits = queuedTalk(app, user, conversation.id);
@@ -725,19 +770,41 @@ export function talkStream(ctx: Ctx): Response {
725770 context: context === undefined ? "" : contextText(context),
726771 acts: [...exchangeActs(app.db, user.id, conversation.id, false, ((c) => (c.id === conversation.id ? HERE : urlOf(conversation)))(openConversation(app.db, user.id)))].map(([id, act]) => ({ id: `t-${id}`, html: act.text })),
727772 });
773 ended = true;
728774 close();
729 } else if (Date.now() - started >= clock.streamMs) {
775 return;
776 }
777 if (Date.now() - started >= clock.streamMs) {
730778 emit("more", {});
779 ended = true;
731780 close();
732 } else if (!told) {
781 return;
782 }
783 if (!told) {
733784 told = true;
734785 emit("running", {});
735786 }
787 sendLive();
736788 };
737789 open.set(user.id, (open.get(user.id) ?? 0) + 1);
738 const timer = setInterval(tick, POLL_MS);
790 const timer = setInterval(tick, clock.tickMs);
791 // The conversation is found by its owner above, so only they hear it. A burst of changes in one
792 // task is one look.
793 let looking = false;
794 const unsubscribe = subscribe(app.db, conversation.id, (change) => {
795 if (change === "live") return told ? sendLive() : undefined;
796 if (looking) return;
797 looking = true;
798 queueMicrotask(() => {
799 looking = false;
800 tick();
801 });
802 });
739803 queueMicrotask(tick);
740804 return () => {
805 ended = true;
806 unsubscribe();
807 clearTimeout(liveTimer);
741808 clearInterval(timer);
742809 const left = (open.get(user.id) ?? 1) - 1;
743810 if (left <= 0) open.delete(user.id);
src/web/pages/talk_client.ts +55
@@ -189,6 +189,59 @@ export const draftJs = `
189189 };
190190 `;
191191
192 /**
193 * The block being written, on /talk: a `live` frame from `talkStream` (`{ html, thinking, tool }`)
194 * draws one element, `#live`, at the end of the log and before any queued message. Its markup is
195 * the server's, escaped and rendered as a stored reply is; a running step or "Thinking…" is set as
196 * text. The server alone says what it holds: right after a batch of `turn` frames it sends the
197 * block as it is then, empty once the block is stored, which takes the element away; a turn that
198 * lands meanwhile is drawn above it. The stream's `done`, or a lost stream, also takes it away (a
199 * stream that comes back draws it again). It is hidden from screen readers: the stored turn is
200 * what is announced, once.
201 *
202 * Following: when the reader was at the end before a frame, the page goes to the true end after
203 * it (the composer sits below the log's end, so the log's own end is not enough); the scroller is
204 * the talk column where it scrolls on its own (from 56.25rem), else the window. Where the column
205 * scrolls, "at the end" is the page's own follow rule (`follows`) read on the column itself, since
206 * the page's `stuck` follows the window's scroll only, and measured to the log's end (`#end`, where
207 * the page's own `toEnd` puts the reader after Send), not past the composer below it. A reader who
208 * scrolled up is left where they are.
209 *
210 * Defines `liveOn(source)`, called once for each stream; needs `root`, `log`, `stuck` and `follows`
211 * in scope.
212 */
213 export const liveJs = `
214 const liveDrop = () => { const l = document.getElementById("live"); if (l) l.remove(); };
215 const liveOwn = () => /auto|scroll/.test(window.getComputedStyle(root).overflowY) && root.scrollHeight > root.clientHeight;
216 const liveAtEnd = () => {
217 const e = document.getElementById("end");
218 return !liveOwn() ? stuck : !!e && follows(root.clientHeight, root.scrollTop, e.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop);
219 };
220 const liveEnd = () => {
221 if (liveOwn()) root.scrollTop = root.scrollHeight;
222 else { window.scrollTo(0, document.documentElement.scrollHeight); stuck = true; }
223 };
224 const liveOn = (src) => {
225 src.addEventListener("live", (e) => {
226 const f = JSON.parse(e.data), was = liveAtEnd();
227 if (!f.html && !f.tool && !f.thinking) return liveDrop();
228 let l = document.getElementById("live");
229 if (!l) {
230 l = Object.assign(document.createElement("li"), { id: "live", className: "talk-turn talk-agent talk-live" });
231 l.setAttribute("aria-hidden", "true");
232 log.insertBefore(l, log.querySelector("[data-queued]"));
233 }
234 l.innerHTML = f.html;
235 if (f.tool || !f.html) l.append(Object.assign(document.createElement("p"), { className: "talk-steps small muted", textContent: f.tool || "Thinking…" }));
236 if (f.tool && status.textContent !== f.tool) say(f.tool);
237 if (was) liveEnd();
238 });
239 src.addEventListener("turn", () => queueMicrotask(() => { const l = document.getElementById("live"); if (l) log.insertBefore(l, log.querySelector("[data-queued]")); }));
240 src.addEventListener("done", liveDrop);
241 src.addEventListener("error", liveDrop);
242 };
243 `;
244
192245 /**
193246 * Runs after DOMContentLoaded (`pageScriptAsset`). Reads the page's own `data-talk-*`; sends with
194247 * fetch, follows with EventSource.
@@ -361,11 +414,13 @@ if (root) {
361414 say("That was not cancelled: no connection.");
362415 }
363416 });
417 ${liveJs}
364418 const follow = () => {
365419 if (paged) return;
366420 if (source) source.close();
367421 dropActs();
368422 source = new EventSource("/talk/stream?c=" + encodeURIComponent(cid) + "&after=" + encodeURIComponent(last));
423 liveOn(source);
369424 source.addEventListener("turn", (e) => {
370425 const turn = JSON.parse(e.data);
371426 last = turn.id;
test/job-slices.test.ts +1
@@ -266,6 +266,7 @@ const UNTIMED: Record<string, string> = {
266266 "git-pace": "a one-shot timer in git/pace.ts that only resolves the promise a paced pack write waits on: no work of its own, armed per pack chunk while a page response is in flight; git-pace.test.ts drives the pacer with a fake clock",
267267 "drill-watch": "a /proc read of the drill child's memory and a state write every WATCH_MS, only while a restore drill runs in its own process; drill-job tests drive runDrillInChild directly",
268268 "meter-watch": "one indexed read of held-full windows every 15 minutes, and a status fetch only while one is held full; meter-watch.test.ts drives it with a fake fetcher; the fixture holds no window",
269 "talk-live": "a one-shot timer in talkStream (web/pages/talk.ts), armed only while a person has /talk open and a reply is being written: it sends that one stream its latest live frame, at most one per 125 ms, drawing a block of at most 20,000 characters; talk-live.test.ts drives the stream and counts its frames",
269270 "view-stream-send": "re-reads the forge view for one open stream, at most once per VIEW_GAP_MS, only while an agent follows the view; the view is cached and forge-view-stream.test.ts drives it",
270271 "view-stream-token-check": "one user read and one token read every 30 s per open stream; forge-view-stream.test.ts drives revocation",
271272 desk: "expires notes past their time: one indexed delete on the desk table every 30 s (actions/desk.ts); the fixture has no notes",
test/talk-live.test.ts added +1008
@@ -0,0 +1,1008 @@
1 /**
2 * The reply written in front of the person: the runner's partial output (`onDelta`) reaches the
3 * page's stream as `live` frames, drawn as a stored reply is, and the stored turn takes their
4 * place. Proven over a real server with a stand-in agent that pauses on a gate file, so each step
5 * is waited for as a signal: the Claude adapter's mapping of a recorded transcript, the frames from
6 * first piece to stored turn, a stream that connects mid-block, another person's stream, a value
7 * held for redaction, a stop mid-block, and the terminal's `talk --follow`.
8 */
9
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { Database } from "bun:sqlite";
12 import { chmodSync, readFileSync, writeFileSync } from "node:fs";
13 import { mkdtemp, rm } from "node:fs/promises";
14 import { tmpdir } from "node:os";
15 import { join } from "node:path";
16 import { createApp, type App } from "../src/app.ts";
17 import { listTurns, openConversation } from "../src/core/conversations.ts";
18 import { createSession } from "../src/core/sessions.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import type { Delta } from "../src/crew/agent_runner.ts";
21 import { claudeArgs, runClaude } from "../src/crew/claude.ts";
22 import {
23 say,
24 STOPPED_LINE,
25 stopTurn,
26 type ConversationOptions,
27 } from "../src/crew/conversation.ts";
28 import { liveBlock, liveDelta, liveEnd, liveSaid } from "../src/crew/conversation_live.ts";
29 import { appendTurn, setClaudeSession } from "../src/core/conversations.ts";
30 import { sandboxPolicy } from "../src/crew/sandbox.ts";
31 import { serve, type Servers } from "../src/http/server.ts";
32 import { holdValues, releaseValues } from "../src/kernel/log.ts";
33 import { serveTalk } from "../src/tui/ssh-talk.ts";
34 import { ANSWER_CONFIRM } from "../src/tui/talk_follow.ts";
35 import { configureConversation } from "../src/crew/conversation.ts";
36 import type { SshSession } from "../src/ssh/server.ts";
37 import { clock } from "../src/web/pages/talk.ts";
38 import { createRepo } from "../src/actions/repos.ts";
39 import { createConversation } from "../src/core/conversations.ts";
40 import { runningStep, stepOf, stepWords } from "../src/core/talk_steps.ts";
41 import { mintViaToken } from "../src/core/via_token.ts";
42 import * as mcpTools from "../src/http/mcp/tools/index.ts";
43 import { claudeInput } from "./helpers/claude-input.ts";
44 import { quietLogs } from "./helpers/globals.ts";
45
46 quietLogs();
47
48 let dir: string;
49 let app: App;
50 let servers: Servers;
51 let alice: User;
52 let bob: User;
53
54 const options = (binary: string): ConversationOptions => ({
55 binary,
56 localUrl: "http://127.0.0.1:9",
57 budgetUsd: 1,
58 timeoutMs: 30_000,
59 signal: new AbortController().signal,
60 });
61
62 const sid = "s-live";
63 const line = (o: unknown): string => JSON.stringify(o);
64 const start = (index: number, block: unknown) =>
65 line({
66 type: "stream_event",
67 session_id: sid,
68 event: { type: "content_block_start", index, content_block: block },
69 });
70 const piece = (index: number, delta: unknown) =>
71 line({
72 type: "stream_event",
73 session_id: sid,
74 event: { type: "content_block_delta", index, delta },
75 });
76 const stop = (index: number) =>
77 line({
78 type: "stream_event",
79 session_id: sid,
80 event: { type: "content_block_stop", index },
81 });
82 const text = (t: string) => piece(0, { type: "text_delta", text: t });
83 const assistant = (id: string, content: unknown[]) =>
84 line({
85 type: "assistant",
86 session_id: sid,
87 message: { id, content, usage: { input_tokens: 10, output_tokens: 5 } },
88 });
89 const result = (said: string) =>
90 line({
91 type: "result",
92 subtype: "success",
93 is_error: false,
94 result: said,
95 total_cost_usd: 0.01,
96 num_turns: 1,
97 session_id: sid,
98 terminal_reason: "completed",
99 usage: { input_tokens: 10, output_tokens: 5 },
100 });
101
102 /**
103 * A stand-in agent that prints `steps` in order; `gate:<name>` waits until the test writes that
104 * file, `hang` waits to be stopped.
105 */
106 function stub(name: string, steps: readonly string[]): string {
107 const path = join(dir, name);
108 const body = steps
109 .map((s) =>
110 s.startsWith("gate:")
111 ? `while [ ! -f "${dir}/${name}.${s.slice(5)}" ]; do sleep 0.02; done`
112 : s === "hang"
113 ? "sleep 300"
114 : `printf '%s\\n' '${s}'`,
115 )
116 .join("\n");
117 writeFileSync(
118 path,
119 `#!/bin/sh
120 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
121 IFS= read -r first
122 printf '%s\\n' "$@" > "${dir}/${name}.argv"
123 printf '%s\\n' '${line({ type: "system", subtype: "init", session_id: sid, model: "fake" })}'
124 ${body}
125 `,
126 );
127 chmodSync(path, 0o755);
128 return path;
129 }
130 const open = (name: string, gate: string): void =>
131 writeFileSync(join(dir, `${name}.${gate}`), "");
132
133 interface Frame {
134 readonly event: string;
135 readonly data: Record<string, unknown>;
136 }
137
138 /** A stream read as it arrives; `until` resolves with the first frame that matches. */
139 async function stream(path: string, u: User) {
140 const abort = new AbortController();
141 const res = await fetch(`${servers.url}${path}`, {
142 headers: { cookie: `forge_session=${createSession(app.db, u.id).token}` },
143 signal: abort.signal,
144 });
145 const frames: Frame[] = [];
146 const waiting: (() => void)[] = [];
147 let over = false;
148 const wake = (): void => {
149 for (const w of waiting.splice(0)) w();
150 };
151 const ended = (async () => {
152 if (res.body === null) return;
153 const reader = res.body.getReader();
154 const decoder = new TextDecoder();
155 let buffered = "";
156 try {
157 for (;;) {
158 const { done, value } = await reader.read();
159 if (done) break;
160 buffered += decoder.decode(value, { stream: true });
161 for (
162 let at = buffered.indexOf("\n\n");
163 at >= 0;
164 at = buffered.indexOf("\n\n")
165 ) {
166 const raw = buffered.slice(0, at);
167 buffered = buffered.slice(at + 2);
168 const event = /^event: (.*)$/m.exec(raw)?.[1];
169 const data = /^data: (.*)$/m.exec(raw)?.[1];
170 if (event !== undefined)
171 frames.push({
172 event,
173 data:
174 data === undefined
175 ? {}
176 : (JSON.parse(data) as Record<string, unknown>),
177 });
178 }
179 wake();
180 }
181 } catch {
182 // aborted
183 }
184 over = true;
185 wake();
186 })();
187 const until = async (match: (f: Frame) => boolean): Promise<Frame> => {
188 for (;;) {
189 const found = frames.find(match);
190 if (found !== undefined) return found;
191 if (over)
192 throw new Error(
193 `the stream ended first: ${frames.map((f) => f.event).join(" ")}`,
194 );
195 await new Promise<void>((resolve) => waiting.push(resolve));
196 }
197 };
198 return {
199 status: res.status,
200 frames,
201 until,
202 ended,
203 close: () => abort.abort(),
204 };
205 }
206
207 const live = (f: Frame): boolean => f.event === "live";
208 const htmlOf = (f: Frame): string => String(f.data["html"] ?? "");
209 /** The reply's body as a stored turn's frame draws it. */
210 const bodyOf = (html: string): string =>
211 /<div class="talk-body prose">[\s\S]*?<\/div>/.exec(html)?.[0] ?? "";
212 const stored = (u: User): string[] => {
213 const r = listTurns(app.db, u.id, openConversation(app.db, u.id).id);
214 return r.ok ? r.value.map((t) => `${t.role}:${t.text}`) : [];
215 };
216
217 beforeAll(async () => {
218 dir = await mkdtemp(join(tmpdir(), "forge-talk-live-"));
219 app = createApp({ dataDir: dir, port: 0 });
220 servers = await serve(app);
221 const mk = async (username: string, first: boolean) => {
222 const u = await createUser(app.db, {
223 origin: "seed",
224 trusted: true,
225 username,
226 email: `${username}@forge.local`,
227 password: "a-good-passphrase",
228 adminIfFirst: first,
229 });
230 if (!u.ok) throw new Error(u.error);
231 return u.value;
232 };
233 alice = await mk("alice", true);
234 bob = await mk("bob", false);
235 }, 30_000);
236
237 afterAll(async () => {
238 servers.stop();
239 app.close();
240 await rm(dir, { recursive: true, force: true });
241 });
242
243 describe("the Claude adapter", () => {
244 // Recorded from the CLI's `--include-partial-messages` output (2.1.330), ids and account fields
245 // taken out: thinking (its text not shown), a tool call and its result, then text in pieces.
246 const transcript = [
247 start(0, { type: "thinking", thinking: "", signature: "" }),
248 piece(0, { type: "thinking_delta", thinking: "", estimated_tokens: null }),
249 piece(0, { type: "signature_delta", signature: "c2ln" }),
250 assistant("m1", [{ type: "thinking", thinking: "", signature: "c2ln" }]),
251 stop(0),
252 start(1, {
253 type: "tool_use",
254 id: "toolu_1",
255 name: "mcp__forge__now",
256 input: {},
257 caller: { type: "direct" },
258 }),
259 piece(1, { type: "input_json_delta", partial_json: "" }),
260 piece(1, { type: "input_json_delta", partial_json: '{"what": "all"}' }),
261 assistant("m1", [
262 {
263 type: "tool_use",
264 id: "toolu_1",
265 name: "mcp__forge__now",
266 input: { what: "all" },
267 },
268 ]),
269 stop(1),
270 line({
271 type: "stream_event",
272 session_id: sid,
273 event: {
274 type: "message_delta",
275 delta: { stop_reason: "tool_use" },
276 usage: { input_tokens: 10, output_tokens: 82 },
277 },
278 }),
279 line({
280 type: "stream_event",
281 session_id: sid,
282 event: { type: "message_stop" },
283 }),
284 line({
285 type: "user",
286 session_id: sid,
287 message: {
288 role: "user",
289 content: [
290 { tool_use_id: "toolu_1", type: "tool_result", content: "quiet" },
291 ],
292 },
293 }),
294 line({
295 type: "stream_event",
296 session_id: sid,
297 event: {
298 type: "message_start",
299 message: { id: "m2", usage: { input_tokens: 999, output_tokens: 999 } },
300 },
301 }),
302 start(0, { type: "text", text: "" }),
303 text("The first word of"),
304 text(" `note.txt` is **"),
305 text("banana**."),
306 line({
307 type: "assistant",
308 session_id: sid,
309 message: {
310 id: "m2",
311 content: [
312 { type: "text", text: "The first word of `note.txt` is **banana**." },
313 ],
314 usage: { input_tokens: 20, output_tokens: 18 },
315 },
316 }),
317 stop(0),
318 result("The first word of `note.txt` is **banana**."),
319 ];
320
321 const run = async (name: string, withDelta: boolean) => {
322 const binary = stub(name, transcript);
323 const said: string[] = [];
324 const usage: string[] = [];
325 const log: string[] = [];
326 const deltas: Delta[] = [];
327 const outcome = await runClaude({
328 binary,
329 cwd: dir,
330 prompt: "hi",
331 appendSystemPrompt: "",
332 budgetUsd: 1,
333 env: {},
334 timeoutMs: 20_000,
335 sandbox: sandboxPolicy({ dataDir: dir, agentName: "bot", urls: [] }),
336 log: (l) => log.push(l),
337 signal: new AbortController().signal,
338 settleMs: 1_000,
339 onSaid: (s) => said.push(`${s.kind}:${s.text}`),
340 onUsage: (u) => usage.push(JSON.stringify(u)),
341 ...(withDelta ? { onDelta: (d: Delta) => deltas.push(d) } : {}),
342 });
343 const argv = readFileSync(join(dir, `${name}.argv`), "utf8")
344 .trim()
345 .split("\n");
346 return {
347 said,
348 usage,
349 log,
350 deltas,
351 argv,
352 outcome: { ...outcome, sessionId: "" },
353 };
354 };
355
356 test("a recorded partial transcript becomes plain deltas, and nothing else a run reports changes", async () => {
357 const partial = await run("adapter-partial", true);
358 const whole = await run("adapter-whole", false);
359 expect(partial.deltas).toEqual([
360 { kind: "thinking", text: "" },
361 { kind: "thinking", text: "" },
362 { kind: "tool", name: "mcp__forge__now", state: "started", id: "toolu_1" },
363 { kind: "tool", name: "mcp__forge__now", state: "ended", ok: true, id: "toolu_1" },
364 { kind: "text", text: "The first word of" },
365 { kind: "text", text: " `note.txt` is **" },
366 { kind: "text", text: "banana**." },
367 ]);
368 // What is stored, spent and logged is the same with or without the pieces.
369 expect(partial.said).toEqual(whole.said);
370 expect(partial.said).toEqual([
371 "thinking:",
372 'tool:mcp__forge__now {"what":"all"}',
373 "text:The first word of `note.txt` is **banana**.",
374 ]);
375 expect(partial.usage).toEqual(whole.usage);
376 expect(partial.log).toEqual(whole.log);
377 expect(partial.outcome).toEqual(whole.outcome);
378 // A partial message_start carries usage too; it is never counted.
379 expect(partial.usage.join()).not.toContain("999");
380 expect(partial.usage).toContain(JSON.stringify({ tokensIn: 30, tokensOut: 23 }));
381 // The flag is asked for only with `onDelta`; a crew run's argv is what it was.
382 expect(partial.argv).toContain("--include-partial-messages");
383 expect(whole.argv).not.toContain("--include-partial-messages");
384 const input = claudeInput(dir, { config: "{}", allow: ["mcp__forge"] });
385 const without = claudeArgs(input);
386 expect(without).not.toContain("--include-partial-messages");
387 expect(
388 claudeArgs({ ...input, onDelta: () => {} }).filter(
389 (a) => a !== "--include-partial-messages",
390 ),
391 ).toEqual(without);
392 expect(claudeArgs(claudeInput(dir))).not.toContain(
393 "--include-partial-messages",
394 );
395 });
396
397 test("a tool result that ends in an error says so", async () => {
398 const binary = stub("adapter-error", [
399 start(0, {
400 type: "tool_use",
401 id: "toolu_9",
402 name: "mcp__forge__merge",
403 input: {},
404 }),
405 line({
406 type: "user",
407 session_id: sid,
408 message: {
409 role: "user",
410 content: [
411 {
412 tool_use_id: "toolu_9",
413 type: "tool_result",
414 content: "no",
415 is_error: true,
416 },
417 ],
418 },
419 }),
420 line({
421 type: "user",
422 session_id: sid,
423 message: {
424 role: "user",
425 content: [
426 { tool_use_id: "toolu_9", type: "tool_result", content: "again" },
427 ],
428 },
429 }),
430 result("done"),
431 ]);
432 const deltas: Delta[] = [];
433 await runClaude({
434 binary,
435 cwd: dir,
436 prompt: "hi",
437 appendSystemPrompt: "",
438 budgetUsd: 1,
439 env: {},
440 timeoutMs: 20_000,
441 sandbox: sandboxPolicy({ dataDir: dir, agentName: "bot", urls: [] }),
442 log: () => {},
443 signal: new AbortController().signal,
444 settleMs: 1_000,
445 onDelta: (d) => deltas.push(d),
446 });
447 // Ended once: a second result for the same call is not a second end.
448 expect(deltas).toEqual([
449 { kind: "tool", name: "mcp__forge__merge", state: "started", id: "toolu_9" },
450 { kind: "tool", name: "mcp__forge__merge", state: "ended", ok: false, id: "toolu_9" },
451 ]);
452 });
453 });
454
455 describe("the stream", () => {
456 test("the reply arrives in pieces, then as the stored turn, then the end; a late stream gets the block so far", async () => {
457 const was = clock.now;
458 // A frozen clock: after the first frame only the stream's own timer may send, so the frames are
459 // counted against the pieces, not against a wall clock.
460 clock.now = () => 0;
461 try {
462 const words = Array.from({ length: 40 }, (_, i) => `word${String(i)} `);
463 // It ends in a space: the last run of letters is held back until what follows settles it.
464 const whole = `${words.join("")}and **done**. `;
465 const name = "pieces";
466 const bin = stub(name, [
467 start(0, { type: "text", text: "" }),
468 ...words.map(text),
469 text("and **done**. "),
470 "gate:one",
471 assistant("m1", [{ type: "text", text: whole }]),
472 stop(0),
473 result(whole),
474 ]);
475 const said = say(app, options(bin), alice.id, "tell me");
476 if (!said.ok) throw new Error(said.error);
477 const conversation = openConversation(app.db, alice.id);
478 const first = await stream(
479 `/talk/stream?c=${conversation.id}&after=`,
480 alice,
481 );
482 expect(first.status).toBe(200);
483 const full = await first.until(
484 (f) => live(f) && htmlOf(f).includes("done"),
485 );
486 // Fewer frames than pieces: coalesced, and the last one is the whole block.
487 expect(first.frames.filter(live).length).toBeLessThan(10);
488 // A stream that connects mid-block gets all of it in its first live frame.
489 const late = await stream(
490 `/talk/stream?c=${conversation.id}&after=`,
491 alice,
492 );
493 const caught = await late.until(live);
494 expect(htmlOf(caught)).toBe(htmlOf(full));
495 late.close();
496 open(name, "one");
497 const turn = await first.until(
498 (f) => f.event === "turn" && f.data["role"] === "agent",
499 );
500 await first.until((f) => f.event === "done");
501 await first.ended;
502 // The last live frame's markup is the stored reply's, drawn by the same renderer.
503 expect(htmlOf(full)).toBe(bodyOf(String(turn.data["html"])));
504 // Right after the stored turn, in the same look, the server says the block is empty.
505 expect(first.frames[first.frames.indexOf(turn) + 1]).toEqual({ event: "live", data: { html: "", thinking: false, tool: "" } });
506 expect(htmlOf(full)).toContain("<strong>done</strong>");
507 const order = first.frames.map((f) => f.event);
508 expect(order.lastIndexOf("live")).toBeLessThan(order.indexOf("done"));
509 expect(first.frames.indexOf(full)).toBeLessThan(
510 first.frames.indexOf(turn),
511 );
512 // Nothing is held once the turn is over, and what is stored is the whole reply once.
513 expect(liveBlock(app.db, conversation.id)).toBeUndefined();
514 expect(stored(alice).slice(-2)).toEqual([
515 "person:tell me",
516 `agent:${whole}`,
517 ]);
518 await said.value.done;
519 } finally {
520 clock.now = was;
521 }
522 });
523
524 test("only the conversation's owner hears its block", async () => {
525 const name = "owner";
526 const bin = stub(name, [
527 start(0, { type: "text", text: "" }),
528 text("Mine alone. "),
529 "gate:one",
530 assistant("m1", [{ type: "text", text: "Mine alone." }]),
531 result("Mine alone."),
532 ]);
533 const said = say(app, options(bin), alice.id, "private?");
534 if (!said.ok) throw new Error(said.error);
535 const conversation = openConversation(app.db, alice.id);
536 const mine = await stream(
537 `/talk/stream?c=${conversation.id}&after=`,
538 alice,
539 );
540 await mine.until((f) => live(f) && htmlOf(f).includes("Mine alone"));
541 // Bob cannot name it, and his own stream hears nothing of it.
542 const named = await stream(`/talk/stream?c=${conversation.id}&after=`, bob);
543 expect(named.status).toBe(404);
544 named.close();
545 const his = await stream("/talk/stream?after=", bob);
546 await his.until((f) => f.event === "done");
547 await his.ended;
548 expect(his.frames.filter(live)).toEqual([]);
549 expect(JSON.stringify(his.frames)).not.toContain("Mine alone");
550 open(name, "one");
551 await mine.until((f) => f.event === "done");
552 await said.value.done;
553 });
554
555 test("a value held for redaction never shows, not even its first piece", async () => {
556 const secret = "sk-live-0123456789abcdef";
557 holdValues("talk-live-test", [secret]);
558 try {
559 const name = "secret";
560 const bin = stub(name, [
561 start(0, { type: "text", text: "" }),
562 text("The key is sk-live-01"),
563 "gate:one",
564 text("23456789abcdef and that is all."),
565 "gate:two",
566 assistant("m1", [
567 { type: "text", text: `The key is ${secret} and that is all.` },
568 ]),
569 result(`The key is ${secret} and that is all.`),
570 ]);
571 const said = say(app, options(bin), alice.id, "what is the key?");
572 if (!said.ok) throw new Error(said.error);
573 const conversation = openConversation(app.db, alice.id);
574 const s = await stream(`/talk/stream?c=${conversation.id}&after=`, alice);
575 const before = await s.until(
576 (f) => live(f) && htmlOf(f).includes("The key is"),
577 );
578 // The start of the value is held back until the rest of it arrives.
579 expect(htmlOf(before)).not.toContain("sk-live");
580 open(name, "one");
581 const after = await s.until(
582 (f) => live(f) && htmlOf(f).includes("that is"),
583 );
584 expect(htmlOf(after)).toContain("[redacted]");
585 open(name, "two");
586 await s.until((f) => f.event === "done");
587 await said.value.done;
588 expect(JSON.stringify(s.frames)).not.toContain("sk-live");
589 expect(stored(alice).at(-1)).toBe(
590 "agent:The key is [redacted] and that is all.",
591 );
592 } finally {
593 releaseValues("talk-live-test");
594 }
595 });
596
597 test("a stop mid-block clears the block; the stored words and Stopped. are as before", async () => {
598 const name = "stopped";
599 const bin = stub(name, [
600 assistant("m0", [{ type: "text", text: "First, a whole block." }]),
601 start(1, { type: "text", text: "" }),
602 text("Half of a "),
603 "hang",
604 ]);
605 const said = say(app, options(bin), alice.id, "go on");
606 if (!said.ok) throw new Error(said.error);
607 const conversation = openConversation(app.db, alice.id);
608 const s = await stream(`/talk/stream?c=${conversation.id}&after=`, alice);
609 await s.until((f) => live(f) && htmlOf(f).includes("Half of a"));
610 expect(stopTurn(app, alice.id)).toBe(true);
611 await s.until((f) => f.event === "done");
612 await said.value.done;
613 expect(liveBlock(app.db, conversation.id)).toBeUndefined();
614 // The words a stop keeps are the whole blocks, as before: the half block was never stored.
615 expect(stored(alice).slice(-3)).toEqual([
616 "person:go on",
617 "agent:First, a whole block.",
618 `agent:${STOPPED_LINE}`,
619 ]);
620 });
621
622 test("a running tool is said in the step's plain words, never its arguments as JSON", async () => {
623 const name = "tool";
624 const bin = stub(name, [
625 start(0, {
626 type: "tool_use",
627 id: "toolu_2",
628 name: "mcp__forge__read_file",
629 input: {},
630 }),
631 assistant("m1", [
632 {
633 type: "tool_use",
634 id: "toolu_2",
635 name: "mcp__forge__read_file",
636 input: { repo: "alice/app", path: "src/a.ts" },
637 },
638 ]),
639 "gate:one",
640 line({
641 type: "user",
642 session_id: sid,
643 message: {
644 role: "user",
645 content: [
646 { tool_use_id: "toolu_2", type: "tool_result", content: "x" },
647 ],
648 },
649 }),
650 assistant("m2", [{ type: "text", text: "Read it." }]),
651 result("Read it."),
652 ]);
653 const said = say(app, options(bin), alice.id, "read a.ts");
654 if (!said.ok) throw new Error(said.error);
655 const conversation = openConversation(app.db, alice.id);
656 const s = await stream(`/talk/stream?c=${conversation.id}&after=`, alice);
657 const running = await s.until(
658 (f) => live(f) && f.data["tool"] === "Reading src/a.ts…",
659 );
660 expect(htmlOf(running)).toBe("");
661 open(name, "one");
662 await s.until((f) => f.event === "done");
663 await said.value.done;
664 expect(JSON.stringify(s.frames.filter(live))).not.toContain("alice/app");
665 });
666 });
667
668 describe("a running step", () => {
669 // Every call `stepWords` gives words to, both forms: a step stored as done and the same step
670 // while it runs. `stepOf` takes its label nowhere else, so a new step brings its running form.
671 const calls: readonly [string, string, string][] = [
672 ['read_file {"repo":"a/b","path":"src/a.ts"}', "Read src/a.ts", "Reading src/a.ts…"],
673 ["read_file {}", "Read a file", "Reading a file…"],
674 ['write_file {"path":"src/a.ts","content":"x\\ny\\n"}', "Edited src/a.ts (+2)", "Editing src/a.ts…"],
675 ['write_file {"content":"x"}', "Edited a file (+1)", "Editing a file…"],
676 ['issue {"number":12}', "Opened issue #12", "Opening issue #12…"],
677 ['pull {"number":3}', "Opened pull #3", "Opening pull #3…"],
678 ['merge {"number":3,"dryRun":true}', "Checked that pull #3 can merge", "Checking that pull #3 can merge…"],
679 ['merge {"number":3}', "Merged pull #3 and deployed", "Merging pull #3…"],
680 ['review {"number":3}', "Reviewed pull #3", "Reviewing pull #3…"],
681 ['say {"number":7}', "Commented on #7", "Commenting on #7…"],
682 ['keep_plan {"number":7}', "Updated the plan on #7", "Updating the plan on #7…"],
683 ];
684 test("every step stepOf can name has its running words, and they never read as finished", () => {
685 for (const [call, done, running] of calls) {
686 expect(stepOf(`mcp__forge__${call}`)?.label).toBe(done);
687 expect(runningStep(`mcp__forge__${call}`)).toBe(running);
688 }
689 });
690 test("every tool the forge serves runs as plain words, never its name's shape or its arguments", () => {
691 const args = { number: 5, path: "src/x.ts", repo: "a/b", content: "z", token: "s3cret" };
692 for (const t of Object.values(mcpTools) as { name: string }[]) {
693 const call = `mcp__forge__${t.name} ${JSON.stringify(args)}`;
694 const words = runningStep(call);
695 expect(words.endsWith("…")).toBe(true);
696 expect(words).not.toMatch(/[{}"_]|mcp|s3cret|a\/b/);
697 // A tool with words of its own says them running, not as stored.
698 const own = stepWords(t.name, args);
699 if (own !== undefined) expect(words).not.toBe(`${stepOf(call)?.label}…`);
700 }
701 expect(runningStep("mcp__forge__now")).toBe("Working: now…");
702 expect(runningStep("{not a call")).toBe("Working…");
703 });
704 });
705
706 describe("the block held", () => {
707 test("of two calls of one tool, the one that ends is the one named by its id", () => {
708 const id = "c-two-calls";
709 liveDelta(app.db, id, { kind: "tool", name: "mcp__forge__issue", state: "started", id: "a" });
710 liveDelta(app.db, id, { kind: "tool", name: "mcp__forge__issue", state: "started", id: "b" });
711 liveSaid(app.db, id, "tool", 'mcp__forge__issue {"number":1}');
712 liveSaid(app.db, id, "tool", 'mcp__forge__issue {"number":2}');
713 // The later call ends first: the earlier one is still the one waited on.
714 liveDelta(app.db, id, { kind: "tool", name: "mcp__forge__issue", state: "ended", ok: true, id: "b" });
715 expect(liveBlock(app.db, id)?.tool).toBe('mcp__forge__issue {"number":1}');
716 liveDelta(app.db, id, { kind: "tool", name: "mcp__forge__issue", state: "ended", ok: true, id: "a" });
717 expect(liveBlock(app.db, id)).toBeUndefined();
718 liveEnd(app.db, id);
719 // Kept per forge: another forge's database holds nothing of it.
720 liveDelta(app.db, id, { kind: "text", text: "mine " });
721 expect(liveBlock(new Database(":memory:"), id)).toBeUndefined();
722 liveEnd(app.db, id);
723 });
724
725 test("a short held value at the end of the text is never shown masked and then clear, or clear and then masked", () => {
726 holdValues("talk-live-short", ["hello"]);
727 try {
728 const id = "c-short";
729 const write = (t: string) => {
730 liveDelta(app.db, id, { kind: "text", text: t });
731 return liveBlock(app.db, id)?.text;
732 };
733 // It could still become "hellos": held back until the next letter says.
734 expect(write("say hel")).toBe("say ");
735 expect(write("lo")).toBe("say ");
736 expect(write("s, and")).toBe("say hellos, ");
737 // The other way: held back while it could be the value, masked once it is.
738 expect(write(" hello")).toBe("say hellos, and ");
739 expect(write(" there")).toBe("say hellos, and [redacted] ");
740 // A word that only ends in it is not it.
741 expect(write(" othe")).toBe("say hellos, and [redacted] there ");
742 expect(write("llo ")).toBe("say hellos, and [redacted] there othello ");
743 liveEnd(app.db, id);
744 } finally {
745 releaseValues("talk-live-short");
746 }
747 });
748 });
749
750 describe("a session lost mid-block", () => {
751 test("the dead attempt's words never join the fresh one", async () => {
752 const conversation = openConversation(app.db, alice.id);
753 setClaudeSession(app.db, alice.id, conversation.id, "sess-lost");
754 const path = join(dir, "retry");
755 const lost = line({ type: "result", subtype: "error_during_execution", is_error: true, result: "", errors: ["No conversation found with session ID: sess-lost"], total_cost_usd: 0, num_turns: 0, session_id: "sess-lost" });
756 writeFileSync(
757 path,
758 `#!/bin/sh
759 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
760 IFS= read -r first
761 printf '%s\\n' '${line({ type: "system", subtype: "init", session_id: sid, model: "fake" })}'
762 printf '%s\\n' '${start(0, { type: "text", text: "" })}'
763 case "$*" in
764 *--resume*)
765 printf '%s\\n' '${text("Dead attempt words ")}'
766 while [ ! -f "${dir}/retry.one" ]; do sleep 0.02; done
767 printf '%s\\n' '${lost}'
768 exit 0 ;;
769 esac
770 printf '%s\\n' '${text("Fresh words")}'
771 while [ ! -f "${dir}/retry.two" ]; do sleep 0.02; done
772 printf '%s\\n' '${assistant("m2", [{ type: "text", text: "Fresh words" }])}'
773 printf '%s\\n' '${result("Fresh words")}'
774 `,
775 );
776 chmodSync(path, 0o755);
777 const said = say(app, options(path), alice.id, "again?");
778 if (!said.ok) throw new Error(said.error);
779 const s = await stream(`/talk/stream?c=${conversation.id}&after=`, alice);
780 const dead = await s.until((f) => live(f) && htmlOf(f).includes("Dead attempt"));
781 open("retry", "one");
782 const fresh = await s.until((f) => live(f) && htmlOf(f).includes("Fresh"));
783 expect(htmlOf(fresh)).not.toContain("Dead attempt");
784 open("retry", "two");
785 await s.until((f) => f.event === "done");
786 await said.value.done;
787 const after = s.frames.slice(s.frames.indexOf(dead) + 1).filter(live);
788 expect(after.some((f) => htmlOf(f).includes("Dead attempt"))).toBe(false);
789 expect(stored(alice).at(-1)).toBe("agent:Fresh words");
790 });
791 });
792
793 describe("a turn stored by another door mid-block", () => {
794 test("lands as a turn and leaves the block being written as it was", async () => {
795 const name = "side";
796 const bin = stub(name, [start(0, { type: "text", text: "" }), text("Block A still being written"), "gate:one", text(" and more."), "gate:two", assistant("m1", [{ type: "text", text: "Block A still being written and more." }]), result("Block A still being written and more.")]);
797 const said = say(app, options(bin), alice.id, "long one");
798 if (!said.ok) throw new Error(said.error);
799 const conversation = openConversation(app.db, alice.id);
800 const s = await stream(`/talk/stream?c=${conversation.id}&after=`, alice);
801 await s.until((f) => live(f) && htmlOf(f).includes("Block A"));
802 appendTurn(app.db, alice.id, conversation.id, { role: "tool", text: JSON.stringify({ filed: false, says: "A note from another door." }) });
803 const side = await s.until((f) => f.event === "turn" && String(f.data["html"]).includes("another door"));
804 open(name, "one");
805 const more = await s.until((f) => live(f) && htmlOf(f).includes("written and"));
806 // Between the two, no frame emptied the block.
807 expect(s.frames.slice(s.frames.indexOf(side), s.frames.indexOf(more)).filter(live)).toEqual([]);
808 open(name, "two");
809 await s.until((f) => f.event === "done");
810 await said.value.done;
811 });
812 });
813
814 describe("a turn stored by another door", () => {
815 test("a confirm the hold path draws reaches an open stream at once, with the slow look off", async () => {
816 const tick = clock.tickMs;
817 const running = clock.running;
818 // The fallback look cannot fire inside this test: only the wake from `appendTurn` can deliver.
819 clock.tickMs = 600_000;
820 clock.running = () => true;
821 try {
822 const repo = await createRepo(app, alice, { name: "held-live", visibility: "public" });
823 if (!repo.ok) throw new Error(String(repo.error));
824 const made = createConversation(app.db, alice.id);
825 if (!made.ok) throw new Error(made.error);
826 const id = made.value.id;
827 const via = `conversation:${id}`;
828 const minted = mintViaToken(app.db, alice.id, via, "archive held-live", new Date(Date.now() + 600_000).toISOString());
829 if (!minted.ok) throw new Error(minted.error);
830 const s = await stream(`/talk/stream?c=${id}&after=`, alice);
831 await s.until((f) => f.event === "running");
832 const res = await fetch(`${servers.url}/mcp`, {
833 method: "POST",
834 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${minted.value.token}` },
835 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "archive", arguments: { repo: "alice/held-live", archived: true, dryRun: false } } }),
836 });
837 expect(await res.text()).toContain("needs_confirm");
838 const confirm = await s.until((f) => f.event === "turn" && f.data["role"] === "confirm");
839 expect(String(confirm.data["html"])).toContain("Do it");
840 s.close();
841 await s.ended;
842 } finally {
843 clock.tickMs = tick;
844 clock.running = running;
845 }
846 });
847 });
848
849 /** `ssh talk <words>` run as alice on a session that records what it is sent. */
850 function terminal(words: string) {
851 let out = "";
852 let code: number | undefined;
853 const wrote: (() => void)[] = [];
854 const exited = new Promise<void>((resolve) => {
855 const take = (d: Uint8Array | string): void => {
856 out += typeof d === "string" ? d : Buffer.from(d).toString();
857 for (const w of wrote.splice(0)) w();
858 };
859 const session: SshSession = {
860 key: { algo: "ssh-ed25519", blob: new Uint8Array(), fingerprint: "", line: "" },
861 username: "alice",
862 remoteAddress: "203.0.113.9",
863 kind: "exec",
864 command: `talk ${words}`,
865 term: undefined,
866 env: {},
867 cols: 0,
868 rows: 0,
869 widthPx: 0,
870 heightPx: 0,
871 ended: false,
872 pending: 0,
873 write: take,
874 writeStderr: take,
875 exit: (c: number) => {
876 code = c;
877 resolve();
878 },
879 onData() {},
880 onResize() {},
881 onEof() {},
882 onClose() {},
883 drain: async () => {},
884 };
885 serveTalk(app, session, alice, words);
886 });
887 const until = async (part: string): Promise<void> => {
888 while (!out.includes(part)) await new Promise<void>((resolve) => wrote.push(resolve));
889 };
890 return { out: () => out, code: () => code, exited, until };
891 }
892
893 describe("the terminal", () => {
894 test("`talk --follow` prints the reply as it is written and ends with the turn", async () => {
895 const name = "follow";
896 const whole = "Line one.\nLine two is longer.";
897 const bin = stub(name, [start(0, { type: "text", text: "" }), text("Line one.\nLine "), "gate:one", text("two is longer."), assistant("m1", [{ type: "text", text: whole }]), result(whole)]);
898 configureConversation(app, options(bin));
899 const t = terminal("--follow say two lines");
900 await t.until("Line one.\r\nLine ");
901 // Printed while the turn still runs, before the block is stored.
902 expect(t.code()).toBeUndefined();
903 open(name, "one");
904 await t.exited;
905 expect(t.code()).toBe(0);
906 expect(t.out().endsWith("Line one.\r\nLine two is longer.\r\n")).toBe(true);
907 expect(t.out().split("Line one.").length).toBe(2);
908 });
909
910 test("a held action is printed with how to answer it, and the exec still ends with the turn", async () => {
911 const made = await createRepo(app, alice, { name: "follow-held", visibility: "public" });
912 if (!made.ok) throw new Error(String(made.error));
913 const name = "held";
914 const ask = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "archive", arguments: { repo: "alice/follow-held", archived: true, dryRun: false } } });
915 const path = stub(name, [start(0, { type: "text", text: "" }), text("This one asks first. "), "gate:one", assistant("m1", [{ type: "text", text: "This one asks first." }]), result("This one asks first.")]);
916 // The agent asks through the forge's own door with its turn's token, as a real turn does.
917 const script = readFileSync(path, "utf8").replace(
918 "IFS= read -r first\n",
919 `IFS= read -r first\ncurl -s -X POST "${servers.url}/mcp" -H "content-type: application/json" -H "accept: application/json, text/event-stream" -H "authorization: Bearer $FORGE_MCP_TOKEN" -d '${ask}' > "${dir}/${name}.mcp"\n`,
920 );
921 writeFileSync(path, script);
922 configureConversation(app, { ...options(path), localUrl: servers.url });
923 const t = terminal("--follow archive follow-held");
924 await t.until("waiting for your yes: ");
925 expect(t.out()).toContain(ANSWER_CONFIRM);
926 open(name, "one");
927 await t.exited;
928 expect(readFileSync(join(dir, `${name}.mcp`), "utf8")).toContain("needs_confirm");
929 expect(t.code()).toBe(0);
930 expect(t.out().split("This one asks first.").length).toBe(2);
931 });
932
933 test("text that parts from what was printed is never printed whole again", async () => {
934 const conversation = openConversation(app.db, alice.id);
935 setClaudeSession(app.db, alice.id, conversation.id, "sess-gone");
936 const path = join(dir, "follow-retry");
937 const lost = line({ type: "result", subtype: "error_during_execution", is_error: true, result: "", errors: ["No conversation found with session ID: sess-gone"], total_cost_usd: 0, num_turns: 0, session_id: "sess-gone" });
938 writeFileSync(
939 path,
940 `#!/bin/sh
941 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
942 IFS= read -r first
943 printf '%s\\n' '${line({ type: "system", subtype: "init", session_id: sid, model: "fake" })}'
944 printf '%s\\n' '${start(0, { type: "text", text: "" })}'
945 case "$*" in
946 *--resume*)
947 printf '%s\\n' '${text("The same opening, then the dead part")}'
948 while [ ! -f "${dir}/follow-retry.one" ]; do sleep 0.02; done
949 printf '%s\\n' '${lost}'
950 exit 0 ;;
951 esac
952 printf '%s\\n' '${text("The same opening, then the fresh part.")}'
953 printf '%s\\n' '${assistant("m2", [{ type: "text", text: "The same opening, then the fresh part." }])}'
954 printf '%s\\n' '${result("The same opening, then the fresh part.")}'
955 `,
956 );
957 chmodSync(path, 0o755);
958 configureConversation(app, options(path));
959 const t = terminal("--follow try again");
960 await t.until("the dead ");
961 open("follow-retry", "one");
962 await t.exited;
963 expect(t.code()).toBe(0);
964 // What was printed stands; only what is new follows, on a line of its own.
965 expect(t.out().split("The same opening").length).toBe(2);
966 expect(t.out().endsWith("The same opening, then the dead \r\nfresh part.\r\n")).toBe(true);
967 });
968 });
969
970 describe("a credential-shaped string", () => {
971 test("never shows in the live block, not even its start, and the stored turn says the same", async () => {
972 // Built from pieces, so no tracked file holds a token shape (test/no-secrets-tracked.test.ts).
973 const token = ["gh", "p_", "abcdefghijklmnopqrstuvwxyz", "0123456789"].join("");
974 const name = "credential";
975 const bin = stub(name, [
976 start(0, { type: "text", text: "" }),
977 text(`Your token is ${token.slice(0, 10)}`),
978 "gate:one",
979 text(`${token.slice(10)} and nothing else. `),
980 "gate:two",
981 assistant("m1", [{ type: "text", text: `Your token is ${token} and nothing else. ` }]),
982 result(`Your token is ${token} and nothing else. `),
983 ]);
984 const said = say(app, options(bin), alice.id, "what is my token?");
985 if (!said.ok) throw new Error(said.error);
986 const conversation = openConversation(app.db, alice.id);
987 const s = await stream(`/talk/stream?c=${conversation.id}&after=`, alice);
988 const before = await s.until((f) => live(f) && htmlOf(f).includes("Your token is"));
989 expect(htmlOf(before)).not.toContain("ghp_");
990 open(name, "one");
991 const after = await s.until((f) => live(f) && htmlOf(f).includes("nothing else"));
992 expect(htmlOf(after)).toContain("[redacted]");
993 open(name, "two");
994 const turn = await s.until((f) => f.event === "turn" && f.data["role"] === "agent" && String(f.data["html"]).includes("nothing else"));
995 await s.until((f) => f.event === "done");
996 await said.value.done;
997 expect(JSON.stringify(s.frames)).not.toContain("ghp_");
998 // What the live block showed is what the stored reply shows: it does not change when stored.
999 expect(bodyOf(String(turn.data["html"]))).toBe(htmlOf(after));
1000 expect(stored(alice).at(-1)).toBe("agent:Your token is [redacted] and nothing else. ");
1001 });
1002
1003 test("a running tool's name never shows the harness's prefix", () => {
1004 expect(runningStep("mcp__forge__now")).toBe("Working: now…");
1005 expect(runningStep("mcp__claude_ai_forge__list_repos")).toBe("Working: list repos…");
1006 expect(runningStep('mcp__claude_ai_forge__issue {"number":3}')).toBe("Opening issue #3…");
1007 });
1008 });
test/talk-page.test.ts +97 −2
@@ -369,7 +369,7 @@ describe("the page", () => {
369369 test("the page's own bytes are held: stylesheet and script stay small", async () => {
370370 const { talkCss, talkJs } = await import("../src/web/pages/talk_client.ts");
371371 expect(Buffer.byteLength(talkCss)).toBeLessThan(6_300);
372 expect(Buffer.byteLength(talkJs)).toBeLessThan(19_100);
372 expect(Buffer.byteLength(talkJs)).toBeLessThan(20_700);
373373 say(alice, "agent", "```ts\nlet x = 1;\n```");
374374 const page = await get("/talk", alice);
375375 const size = (await page.arrayBuffer()).byteLength;
@@ -465,7 +465,7 @@ describe("the page", () => {
465465 };
466466 const local = { get length() { return Object.keys(store).length; }, key: (i: number) => Object.keys(store)[i] ?? null, getItem: (k: string) => store[k] ?? null, setItem: (k: string, v: string) => { store[k] = v; }, removeItem: (k: string) => { delete store[k]; } };
467467 const nav = { clipboard: { writeText: async (t: string) => { copied.push(t); } } };
468 class ES { on: Record<string, (e: { data: string }) => void> = {}; constructor() { sources.push(this); } addEventListener(n: string, f: (e: { data: string }) => void) { this.on[n] = f; } close() {} }
468 class ES { on: Record<string, (e: { data: string }) => void> = {}; constructor() { sources.push(this); } addEventListener(n: string, f: (e: { data: string }) => void) { const was = this.on[n]; this.on[n] = was ? (e) => { was(e); f(e); } : f; } close() {} }
469469 doc.getElementById("end").scrollIntoView = () => {};
470470 new Function("document", "window", "EventSource", "fetch", "localStorage", "navigator", talkJs)(doc, window, ES, fetchStub, local, nav);
471471 const box = doc.querySelector("textarea");
@@ -754,6 +754,101 @@ describe("the page", () => {
754754 expect(t.doc.querySelectorAll("#t-2 .talk-meta [data-copy]").length).toBe(1);
755755 });
756756
757 test("a live frame draws the block being written as one hidden element before the queue; only the server takes it away", async () => {
758 const t = await boot();
759 const on = () => t.sources.at(-1)!.on;
760 const frame = (html: string, tool = "", thinking = false) => on()["live"]!({ data: JSON.stringify({ html, tool, thinking }) });
761 on()["running"]!({ data: "{}" });
762 on()["queued"]!({ data: JSON.stringify({ items: [queuedFrame("q1", "later")] }) });
763 frame('<div class="talk-body prose"><p>Hel</p></div>');
764 const live = t.doc.getElementById("live");
765 expect(live.getAttribute("aria-hidden")).toBe("true");
766 expect(live.className).toBe("talk-turn talk-agent talk-live");
767 expect(live.nextElementSibling.getAttribute("data-queued")).toBe("q1");
768 frame('<div class="talk-body prose"><p>Hello</p></div>', "Read src/a.ts…");
769 expect(t.doc.querySelectorAll("#live").length).toBe(1);
770 expect(live.textContent).toBe("HelloRead src/a.ts…");
771 // A turn from another door lands above the block, which stays, still last before the queue.
772 t.emit("2", '<li class="talk-turn talk-tool" id="t-2"><p>side note</p></li>');
773 await Promise.resolve();
774 expect(t.doc.getElementById("live")).toBe(live);
775 expect(t.doc.getElementById("t-2").nextElementSibling).toBe(live);
776 expect(live.nextElementSibling.getAttribute("data-queued")).toBe("q1");
777 // The block stored: its turn, then the server's empty frame, which takes the element away.
778 t.emit("3", '<li class="talk-turn talk-agent" id="t-3"><div class="talk-body prose"><p>Hello</p></div></li>');
779 frame("");
780 expect(t.doc.getElementById("live")).toBe(null);
781 expect(t.doc.getElementById("t-3").nextElementSibling.getAttribute("data-queued")).toBe("q1");
782 frame("", "", true);
783 expect(t.doc.getElementById("live").textContent).toBe("Thinking…");
784 frame("");
785 expect(t.doc.getElementById("live")).toBe(null);
786 // A lost stream leaves nothing stale behind; the stream that comes back draws it again.
787 frame("", "Working…");
788 on()["error"]!({ data: "" });
789 expect(t.doc.getElementById("live")).toBe(null);
790 frame("", "Working…");
791 on()["done"]!({ data: "{}" });
792 expect(t.doc.getElementById("live")).toBe(null);
793 // Announced once, by the stored turn: the live element never speaks.
794 expect(t.status.textContent).toBe("The forge replied.");
795 });
796
797 test("the page follows the block to the true end only when the reader was there; scrolled up, nothing moves", async () => {
798 const t = await boot();
799 const on = () => t.sources.at(-1)!.on;
800 const frame = (words: string) => on()["live"]!({ data: JSON.stringify({ html: `<div class="talk-body prose"><p>${words}</p></div>`, tool: "", thinking: false }) });
801 const went: number[] = [];
802 let into = 0;
803 t.doc.getElementById("end").scrollIntoView = () => { into++; };
804 Object.defineProperty(t.window, "innerHeight", { value: 800, configurable: true });
805 Object.defineProperty(t.doc.documentElement, "scrollHeight", { value: 5000, configurable: true });
806 // The composer sits below the log's end: only the document's own end is the end.
807 t.window.scrollTo = (_x: number, y: number) => {
808 went.push(y);
809 Object.defineProperty(t.window, "scrollY", { value: y - 800, configurable: true });
810 t.window.dispatchEvent(new t.window.Event("scroll"));
811 };
812 on()["running"]!({ data: "{}" });
813 for (const w of ["one", "one two", "one two three", "one two three four", "one two three four five"]) frame(w);
814 expect(went).toEqual([5000, 5000, 5000, 5000, 5000]);
815 // Scrolled up: five more frames move nothing.
816 Object.defineProperty(t.window, "scrollY", { value: 0, configurable: true });
817 t.window.dispatchEvent(new t.window.Event("scroll"));
818 for (const w of ["six", "seven", "eight", "nine", "ten"]) frame(w);
819 expect(went).toHaveLength(5);
820 expect(into).toBe(0);
821 expect(t.doc.getElementById("live").textContent).toBe("ten");
822 });
823
824 test("on a wide screen, where the talk column scrolls on its own, the column follows the block only from its end", async () => {
825 const t = await boot();
826 const on = () => t.sources.at(-1)!.on;
827 const root = t.doc.querySelector("[data-talk]");
828 let top = 2300;
829 root.style.overflowY = "auto";
830 Object.defineProperty(root, "scrollHeight", { value: 3000, configurable: true });
831 Object.defineProperty(root, "clientHeight", { value: 700, configurable: true });
832 Object.defineProperty(root, "scrollTop", { get: () => top, set: (v: number) => { top = v; }, configurable: true });
833 // The log's end sits at 2,900 px in the column, the composer below it: after Send the page's
834 // toEnd leaves the reader with #end in view, 300 px short of the column's own end.
835 root.getBoundingClientRect = () => ({ top: 0 });
836 t.doc.getElementById("end").getBoundingClientRect = () => ({ top: 2900 - top });
837 top = 2200;
838 let windowMoved = false;
839 t.window.scrollTo = () => { windowMoved = true; };
840 on()["live"]!({ data: JSON.stringify({ html: "<p>a</p>", tool: "", thinking: false }) });
841 expect(top).toBe(3000);
842 on()["live"]!({ data: JSON.stringify({ html: "<p>a b</p>", tool: "", thinking: false }) });
843 expect(top).toBe(3000);
844 expect(windowMoved).toBe(false);
845 // Scrolled up in the column: the next frame moves nothing.
846 top = 0;
847 on()["live"]!({ data: JSON.stringify({ html: "<p>ab</p>", tool: "", thinking: false }) });
848 expect(top).toBe(0);
849 expect(windowMoved).toBe(false);
850 });
851
757852 test("a turn that arrives again is not drawn twice or replaced, so what is above it keeps its place", async () => {
758853 const t = await boot();
759854 const first = t.doc.getElementById("t-1");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs