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

Talk keeps the card a tool answer drew for its agent, and hands the agent its handle outside the fence #16195

Merged opened this

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

Merged

talk/03-record → main 0 commits 2 threads · 2 unresolved

  • Merged. talk/03-record was merged into main as 6dab4fe.

Review

Sign in to review this change.
16 files changed +1059 −11
docs/design/areas/talk.md +6
@@ -65,3 +65,9 @@ On a phone the conversations nav is pinned under the topbar (#14943): New stays
6565 - `.talk-page` (#15734): the one wrapper around the build box and the shell. From 900 px (56.25rem) up it is a column the height of the screen less the topbar; the shell takes what the box leaves, so the composer is on screen on a first visit.
6666
6767 `.talk-keys` is the keyboard help list (#15816): a bordered block above the about line, hidden until `?` is pressed, drawn from `TALK_KEYS`.
68
69 Talk's voice (`src/web/talk_parts.ts`, docs/features/talk.md, Shown results): the forge's own data, drawn from `card` / `listCard` (`extra: "bare"`, so no box) and `row()`, so the only new classes are:
70
71 - `.talk-card` — a shown result: the forge's card, set apart from the agent's words by a hairline on its start side; a wide card scrolls inside itself, never the page.
72 - `.talk-card-from` — the quiet line under a card: the call in plain words and "as of" its time.
73 - `.talk-card-missing` — "Result not found." where a handle names no card of this conversation (markup only).
docs/features/talk.md +19
@@ -151,6 +151,25 @@ An empty `/talk` asks "What do you want to build?" with starters from the marked
151151 - **Terminal:** `:` then **Build an app**. `n` says what to build (`t` chooses the template), Enter opens a build and lists its versions newest first, Enter again shows the files that version changed, `R` restores the chosen version, `P` publishes, `r` reloads. The screen calls the same `actions/build.ts` functions as the page, so it is gated the same way (your own conversation, a writer of the repository) and what it does is what the page shows on its next read.
152152 - Proof: `test/talk-build.test.ts` runs prompt, repository, v1, v2, restore v1 and publish against a scratch forge; `test/tui-talk-build.test.ts` does the same from the terminal.
153153
154 ## Shown results (#10262)
155
156 When a tool answers the forge's agent in a conversation and the answer has a card (`cardFor`, `src/web/studio/cards.ts`), the forge keeps the card for that conversation (`conversation_card`, `src/core/talk_voice.ts`) and adds one text block after the answer, outside the fenced data:
157
158 ```
159 Shown result c7: a line `::show c7` in your reply draws this result for the person.
160 ```
161
162 The agent never receives the card itself. A line in its reply that is exactly `::show c7`, on its own line and outside a code fence, is drawn on the page as the kept card: its title and status, its rows, and a quiet line under it, "From the forge: <the call in plain words> · as of 14:02 UTC". A handle that names no card kept for this conversation and this person draws "Result not found." and nothing else. Answers to any other caller are unchanged.
163
164 - Handles count up per conversation: `c1`, `c2`, and so on. The newest 200 cards of a conversation are kept, and they go when the conversation goes. A card over 16,000 characters of JSON, or a card with no rows, is not kept and its answer carries no handle.
165 - A kept card is what the page draws: its title, status and rows. It has no buttons.
166 - A row's link is drawn as a link only when it is a rooted path (`/owner/name/issues/3`) or an address on the page's own origin; anything else (another site, `//host`, a scheme such as `javascript:`) is drawn as text. Every title, status, label and value is escaped.
167 - A kept card is a record of what the forge answered then, shown with its time. It is not read again, so it can outlive the person's access to what it shows, exactly as the reply's own words do.
168 - **Terminal:** the Conversations screen (`src/tui/screens/talk_chats.ts`) prints a placed card as where it came from, its title and status, and a `label: value` line per row. `forge talk` prints the same: `GET /api/v1/conversation/turns` carries a reply that places a card printed this way as `plain`, beside its raw text. The Markdown download keeps the raw `::show` lines.
169 - A README or any other Markdown on the forge is drawn as before: a `::show` line there is text.
170
171 The parsing is one module for every door, `src/core/talk_voice.ts`; the page's drawing is `src/web/talk_parts.ts`, called once from `turnHtml` in `src/web/pages/talk.ts`. Proof: `test/talk-shown.test.ts`.
172
154173 ## Receipts
155174
156175 After you confirm a held action, the thread shows a receipt: the verb, the object, and a link to the page it changed. For `close` (close/reopen) and `assign` (assign/unassign) it also draws an Undo form (`POST /talk/undo/:turn`, same-origin, your own session) that does the inverse and writes its own receipt. It refuses, and says so, when the object has changed since (someone else's later change is never undone) or when it was already undone. Every other confirmed call that names a repository gets a receipt with no Undo. A failed undo changes nothing and can be tried again; a second tap while one runs is refused.
scripts/doorless-allow.json −1
@@ -81,7 +81,6 @@
8181 "src/web/pages/settings.ts",
8282 "src/web/pages/signup-passkey.ts",
8383 "src/web/pages/start_claim.ts",
84 "src/web/pages/talk.ts",
8584 "src/web/pages/talk_preview.ts",
8685 "src/web/pages/tree_cache.ts",
8786 "src/web/pages/usage-tabs.ts",
src/cli/api.ts +1 −1
@@ -529,7 +529,7 @@ export class ForgeApi {
529529 }
530530
531531 /** The latest turns of the person's conversation (`GET /api/v1/conversation/turns`). */
532 async conversation(): Promise<ApiResult<{ running: boolean; turns: { id: string; role: string; text: string; work?: { steps: string; links: { href: string; label: string }[] } | null }[] }>> {
532 async conversation(): Promise<ApiResult<{ running: boolean; turns: { id: string; role: string; text: string; plain?: string; work?: { steps: string; links: { href: string; label: string }[] } | null }[] }>> {
533533 return this.call("/api/v1/conversation/turns?limit=20");
534534 }
535535
src/cli/commands/talk.ts +3 −1
@@ -52,7 +52,9 @@ async function talk(out: Out, args: Args): Promise<number> {
5252 const thought = thinkingOf(turn);
5353 if (thought !== undefined) out.line(inert(`thinking: ${oneLine(thought)}`));
5454 if (turn.role !== "agent") continue;
55 out.line(inert(turn.text));
55 // A reply that places a kept result comes printed for a terminal (`plain`), as the forge
56 // drew it.
57 out.line(inert(turn.plain ?? turn.text));
5658 if (turn.work) {
5759 out.line(inert(turn.work.steps));
5860 for (const link of turn.work.links) out.line(inert(link.href));
src/core/account_purge.ts +2
@@ -66,6 +66,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
6666 // What they wrote in other people's repositories stays, as the placeholder's.
6767 "comment.author_id": FORMER,
6868 "comment.origin_author": { do: "none", why: "the outside author's name a mirrored comment came with" },
69 // The results the forge kept for their own conversations' agent (`core/talk_voice.ts`).
70 "conversation_card.user_id": DELETE,
6971 "conversation_find.user_id": DELETE,
7072 "curated_pack_change.actor": FORMER,
7173 "decision.by": FORMER,
src/core/migration-pins/20261123032018-conversation-card.pin added +1
@@ -0,0 +1,1 @@
1 c70a71af9c4f8d0177ff97c0c5d1444d709509bd96b1f579d751438b5cdcab0d
src/core/migrations/20261123032018-conversation-card.ts added +22
@@ -0,0 +1,22 @@
1 // Shown results, the first part of Talk's voice: each card an MCP answer drew for a conversation's
2 // own agent (a via token), kept so the agent can place it in its reply with `::show c<n>` and the
3 // page draws the forge's data, never the model's retelling of it. `n` is the handle's number,
4 // counted per conversation; `said` is the call in plain words, for the provenance line. The
5 // newest 200 of a conversation are kept (`core/talk_voice.ts`), and a conversation's cards go
6 // with it, however it goes (its own delete, or its person's).
7 export default `
8 CREATE TABLE conversation_card (
9 id TEXT PRIMARY KEY,
10 via TEXT NOT NULL,
11 user_id TEXT NOT NULL,
12 n INTEGER NOT NULL,
13 tool TEXT NOT NULL,
14 said TEXT NOT NULL,
15 card TEXT NOT NULL,
16 created_at TEXT NOT NULL
17 );
18 CREATE UNIQUE INDEX conversation_card_via_n ON conversation_card (via, n);
19 CREATE TRIGGER conversation_card_gone AFTER DELETE ON conversation BEGIN
outdated

conversation_card_press is never written or read. Remove the table, the DELETE in recordCard, and regenerate the pin.

20 DELETE FROM conversation_card WHERE via = 'conversation:' || old.id;
21 END;
22 `;
src/core/talk_voice.ts added +330
@@ -0,0 +1,330 @@
1 /**
2 * Talk's voice (docs/features/talk.md, Shown results), one module for every door: the shown results
3 * the forge keeps for a conversation, and the fixed vocabulary an agent reply is parsed in.
4 *
5 * Shown results: the cards the forge's MCP drew for a conversation's own agent (a via token),
6 * kept so the agent can place one in its reply with a `::show c<n>` line. The agent never reads
7 * the card; it reads the tool's fenced text and, outside the fence, the handle. Bounded: the
8 * newest `CARDS_KEPT` of a conversation are kept (older ones go on every insert), and a card whose
9 * JSON is over `CARD_CHARS_MAX` is not kept at all. Every read checks `userId`.
10 *
11 * The vocabulary: a reply is ordinary Markdown in which a line that is exactly `::show c<n>`,
12 * outside a code fence, places a shown result. `voiceParts` cuts a reply into its parts; the page
13 * draws them (`web/talk_parts.ts`), the terminal prints them (`plainVoice`). A reply with no such
14 * line is one text part, so it is drawn exactly as before. Plain data in and out.
15 */
16
17 import type { Database } from "bun:sqlite";
18 import type { Card, CardRow } from "../web/studio/cards.ts";
19 import { id } from "../kernel/id.ts";
20
21 /** The newest cards a conversation keeps. */
22 export const CARDS_KEPT = 200;
23 /** The longest card kept, as JSON; a bigger one is not kept and the answer carries no handle. */
24 export const CARD_CHARS_MAX = 16_000;
25
26 export interface ShownCard {
27 readonly id: string;
28 readonly via: string;
29 readonly userId: string;
30 readonly n: number;
31 readonly tool: string;
32 /** The call in plain words (`core/talk_steps.ts`), for the line under the card. */
33 readonly said: string;
34 readonly card: Card;
35 readonly createdAt: string;
36 }
37
38 interface Row {
39 id: string;
40 via: string;
41 user_id: string;
42 n: number;
43 tool: string;
44 said: string;
45 card: string;
46 created_at: string;
47 }
48
49 type Obj = Record<string, unknown>;
50 const isObj = (v: unknown): v is Obj =>
51 typeof v === "object" && v !== null && !Array.isArray(v);
52 const isStr = (v: unknown): v is string => typeof v === "string";
53
54 /** A row as kept, or undefined when it is not one. */
55 function rowOf(v: unknown): CardRow | undefined {
56 if (!isObj(v) || !isStr(v["label"]) || !isStr(v["value"])) return undefined;
57 const depth = Number.isInteger(v["depth"])
58 ? Math.max(0, Math.min(8, v["depth"] as number))
59 : 0;
60 return {
61 label: v["label"],
62 value: v["value"],
63 ...(isStr(v["link"]) ? { link: v["link"] } : {}),
64 ...(depth > 0 ? { depth } : {}),
65 };
66 }
67
68 /**
69 * A card read back from its JSON, shape checked; undefined when the text is not one. A kept card
70 * has no buttons: what it shows is its rows.
71 */
72 export function readCard(text: string): Card | undefined {
73 let v: unknown;
74 try {
75 v = JSON.parse(text);
76 } catch {
77 return undefined;
78 }
79 if (
80 !isObj(v) ||
81 !isStr(v["kind"]) ||
82 !isStr(v["title"]) ||
83 !isStr(v["status"]) ||
84 !Array.isArray(v["rows"])
85 )
86 return undefined;
87 return {
88 kind: v["kind"] as Card["kind"],
89 title: v["title"],
90 status: v["status"],
91 rows: v["rows"].map(rowOf).filter((r) => r !== undefined),
92 actions: [],
93 };
94 }
95
96 const shownOf = (r: Row): ShownCard | undefined => {
97 const card = readCard(r.card);
98 return card === undefined
99 ? undefined
100 : {
101 id: r.id,
102 via: r.via,
103 userId: r.user_id,
104 n: r.n,
105 tool: r.tool,
106 said: r.said,
107 card,
108 createdAt: r.created_at,
109 };
110 };
111
112 /**
113 * A link as kept: one under `origin` (the address the agent's MCP call came in on, often the
114 * loopback listener) becomes a rooted path, so the page draws it on whatever origin serves it.
115 * Anything else is kept as it was and the page decides (`web/talk_parts.ts`).
116 */
117 const rooted = (link: string, origin: string): string =>
118 origin !== "" && link.startsWith(`${origin}/`)
119 ? link.slice(origin.length)
120 : link;
121
122 /**
123 * Keep a card the forge drew for the agent of `via`; its number in the conversation, or undefined
124 * when it was too big to keep. The oldest past `CARDS_KEPT` go. What is kept is what the page
125 * draws: the title, the status and the rows, never a button.
126 */
127 export function recordCard(
128 db: Database,
129 via: string,
130 userId: string,
131 tool: string,
132 said: string,
133 card: Card,
134 origin: string,
135 now: number = Date.now(),
136 ): number | undefined {
137 const kept: Card = {
138 kind: card.kind,
139 title: card.title,
140 status: card.status,
141 rows: card.rows.map(({ actions: _, ...r }) =>
142 r.link === undefined ? r : { ...r, link: rooted(r.link, origin) },
143 ),
144 actions: [],
145 };
146 const text = JSON.stringify(kept);
147 if (text.length > CARD_CHARS_MAX) return undefined;
148 return db.transaction(() => {
149 const n =
150 (db
151 .query<
152 { n: number | null },
153 [string]
154 >("SELECT MAX(n) AS n FROM conversation_card WHERE via = ?1")
155 .get(via)?.n ?? 0) + 1;
156 db.query(
157 "INSERT INTO conversation_card (id, via, user_id, n, tool, said, card, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
158 ).run(
159 id(),
160 via,
161 userId,
162 n,
163 tool,
164 said.slice(0, 200),
165 text,
166 new Date(now).toISOString(),
167 );
168 const floor = n - CARDS_KEPT;
169 if (floor > 0) {
170 db.query("DELETE FROM conversation_card WHERE via = ?1 AND n <= ?2").run(
171 via,
172 floor,
173 );
174 }
175 return n;
176 })();
177 }
178
179 /** The person's kept cards of the conversation `via` names with these numbers: one statement. */
180 export function cardsOf(
181 db: Database,
182 userId: string,
183 via: string,
184 ns: readonly number[],
185 ): Map<number, ShownCard> {
186 const out = new Map<number, ShownCard>();
187 if (ns.length === 0) return out;
188 const rows = db
189 .query<
190 Row,
191 [string, string, string]
192 >("SELECT * FROM conversation_card WHERE via = ?1 AND user_id = ?2 AND n IN (SELECT value FROM json_each(?3))")
193 .all(via, userId, JSON.stringify([...new Set(ns)]));
194 for (const r of rows) {
195 const shown = shownOf(r);
196 if (shown !== undefined) out.set(shown.n, shown);
197 }
198 return out;
199 }
200
201 export type Part =
202 | { readonly kind: "text"; readonly text: string }
203 | { readonly kind: "show"; readonly n: number }
204 | { readonly kind: "fold"; readonly summary: string }
205 | { readonly kind: "unfold" };
206
207 const SHOW = /^::show c([1-9]\d{0,8})[ \t]*$/;
208 const OPEN_FENCE = /^( *)(`{3,})/;
209 const CLOSE_FENCE = /^( *)(`{3,})\s*$/;
210 /** The Markdown renderer's fold (`web/markdown.ts`): its own line, a short plain title. */
211 const FOLD = /^<details><summary>([^<>&"'`]{1,80})<\/summary>$/;
212 const UNFOLD = "</details>";
213 /**
214 * A reply cut into its parts, in order. Text between placed results stays Markdown; a fold that
215 * holds one is split into its open and close, so the fold still holds it.
216 */
217 export function voiceParts(text: string): Part[] {
218 const src = text.replaceAll("\r\n", "\n").split("\n");
219 // Most replies place nothing: one text part, drawn as it always was.
220 if (!src.some((l) => SHOW.test(l))) return [{ kind: "text", text }];
221 const parts: Part[] = [];
222 let buf: string[] = [];
223 const flush = (): void => {
224 if (buf.length > 0 && buf.some((l) => l.trim() !== "")) parts.push({ kind: "text", text: buf.join("\n") });
225 buf = [];
226 };
227 let folded = false;
228 for (let i = 0; i < src.length; i++) {
229 const l = src[i]!;
230 const open = OPEN_FENCE.exec(l);
231 if (open !== null) {
232 // Any other fence is text, and nothing inside it is an addition.
233 const width = open[2]!.length;
234 const indent = open[1]!.length;
235 buf.push(l);
236 let j = i + 1;
237 for (; j < src.length; j++) {
238 buf.push(src[j]!);
239 const c = CLOSE_FENCE.exec(src[j]!);
240 if (c !== null && c[1]!.length <= indent + 3 && c[2]!.length >= width) break;
241 }
242 i = j;
243 continue;
244 }
245 const show = SHOW.exec(l);
246 if (show !== null) {
247 flush();
248 parts.push({ kind: "show", n: Number(show[1]) });
249 continue;
250 }
251 const fold = FOLD.exec(l);
252 if (fold !== null && !folded) {
253 flush();
254 parts.push({ kind: "fold", summary: fold[1]! });
255 folded = true;
256 continue;
257 }
258 if (folded && l === UNFOLD) {
259 flush();
260 parts.push({ kind: "unfold" });
261 folded = false;
262 continue;
263 }
264 buf.push(l);
265 }
266 flush();
267 if (folded) parts.push({ kind: "unfold" });
268 // Nothing placed outside a fence: the reply is drawn whole, as it was.
269 return parts.some((p) => p.kind === "show") ? parts : [{ kind: "text", text }];
270 }
271
272 /** The handles a reply places, each once. */
273 export const shownIn = (parts: readonly Part[]): number[] => [...new Set(parts.flatMap((p) => (p.kind === "show" ? [p.n] : [])))];
274
275 /** What the page says where a handle names no kept card of this conversation. */
276 export const NOT_FOUND_WORDS = "Result not found.";
277
278 /**
279 * The person's kept cards that these replies of their conversation place, by number: one
280 * statement whatever the number of replies (`test/talk-shown.test.ts` counts it).
281 */
282 export function cardsPlaced(db: Database, userId: string, conversationId: string, turns: readonly { readonly role: string; readonly text: string; readonly failed?: boolean }[], parse: (text: string) => Part[] = voiceParts): Map<number, ShownCard> {
283 const ns = turns.filter((t) => t.role === "agent" && t.failed !== true).flatMap((t) => shownIn(parse(t.text)));
284 return cardsOf(db, userId, `conversation:${conversationId}`, ns);
285 }
286
287 /**
288 * The line the agent reads beside an answer whose card was kept: a second text block the forge
289 * writes after the fenced answer, so no fenced text can write one, and a handle only ever names a
290 * card kept for the same conversation.
291 */
292 export const shownLine = (n: number): string =>
293 `Shown result c${n}: a line \`::show c${n}\` in your reply ` +
294 "draws this result for the person.";
295
296 /**
297 * A card as plain lines: its title and status, then each row as `label: value`, indented by depth.
298 */
299 export function cardLines(card: Card): string[] {
300 return [
301 `${card.title}${card.status === "" ? "" : ` · ${card.status}`}`,
302 ...card.rows.map((r) => `${" ".repeat(1 + Math.min(4, r.depth ?? 0))}${r.label}${r.value === "" ? "" : `: ${r.value}`}`),
303 ];
304 }
305
306 /**
307 * A reply as the terminal prints it: a placed result as where it came from and its card's lines
308 * (or the not-found words). `cards` are this conversation's kept cards by number (`cardsPlaced`).
309 */
310 export function plainVoice(text: string, cards: ReadonlyMap<number, ShownCard>): string {
311 const parts = voiceParts(text);
312 if (parts.length === 1 && parts[0]!.kind === "text") return text;
313 return parts
314 .flatMap((p): string[] => {
315 switch (p.kind) {
316 case "text":
317 return [p.text];
318 case "show": {
319 const shown = cards.get(p.n);
320 if (shown === undefined) return [NOT_FOUND_WORDS];
321 return [`From the forge: ${shown.said}, as of ${shown.createdAt.slice(0, 16).replace("T", " ")} UTC`, ...cardLines(shown.card)];
322 }
323 case "fold":
324 return [`${p.summary}:`];
325 case "unfold":
326 return [];
327 }
328 })
329 .join("\n");
330 }
src/http/api/conversation_talk.ts +6 −1
@@ -34,6 +34,7 @@ import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
3434 import { scopeAllows } from "../../core/tokens.ts";
3535 import type { User } from "../../core/users.ts";
3636 import { worksOf } from "../../core/talk_work.ts";
37 import { cardsPlaced, plainVoice } from "../../core/talk_voice.ts";
3738 import { fileQueued, queuedOf, turnRunning } from "../../crew/conversation.ts";
3839 import { crossOrigin, type Handler } from "../context.ts";
3940 import { holds, weakEtag } from "../etag.ts";
@@ -194,7 +195,11 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
194195 // Each agent turn carries what its run cost and the conversation its total, both from the usage
195196 // records; null when unknown, never 0.
196197 const costs = turnCosts(ctx.app.db, conversation.id);
197 const shown = all.map((t) => (t.role === "agent" ? { ...t, work: works.get(t.id) ?? null, costUsd: costs.get(t.id) ?? null } : t));
198 // A reply that places a kept result carries it printed for a terminal too (`plain`), in the one
199 // parser every door uses (`core/talk_voice.ts`); a reply that places none is its own text.
200 const kept = cardsPlaced(ctx.app.db, user.id, conversation.id, all);
201 const plainOf = (text: string) => ((p) => (p === text ? {} : { plain: p }))(plainVoice(text, kept));
202 const shown = all.map((t) => (t.role === "agent" ? { ...t, work: works.get(t.id) ?? null, costUsd: costs.get(t.id) ?? null, ...plainOf(t.text) } : t));
198203 // The tag is of the exact bytes sent (so `before` and `limit` give their own), made after the
199204 // person's own access was settled above.
200205 const text = JSON.stringify({ running: turnRunning(ctx.app, user.id, conversation.id), conversation: conversation.id, totalUsd: conversationTotal(ctx.app.db, conversation.id) ?? null, queued: queuedOf(ctx.app, user.id, conversation.id).map((q) => ({ id: q.id, text: q.text })), turns: shown });
src/http/mcp.ts +20 −1
@@ -49,6 +49,8 @@ import { adminRefusal, everydayOf } from "../core/everyday.ts";
4949 import { claimDone, completeWrite, dropWrite, recordWrite } from "../core/conversation_writes.ts";
5050 import { type Args, alreadyDone, notAdminTool, visible, plansOnly, str, REPO_ARG, lean, fenceAnswer, heldWrite, askedFirst, readThrough, type ToolShape } from "./mcp/shared.ts";
5151 import { CONVERSATION_BRIEF } from "../crew/conversation_brief.ts";
52 import { recordCard, shownLine } from "../core/talk_voice.ts";
53 import { stepOf } from "../core/talk_steps.ts";
5254 import { TOOLS } from "./mcp/tools.ts";
5355 import { runMcpRefusal } from "./run_gate.ts";
5456 import { NO_TOOL_HINT, READ_ONLY_REFUSAL, hintOf, hintOfText, noToolNamed, withNextStep } from "./mcp/hints.ts";
@@ -140,6 +142,20 @@ function cardResult(
140142 return card === undefined ? {} : { structuredContent: { card } };
141143 }
142144
145 /**
146 * A card drawn for the forge's own agent (`core/talk_voice.ts`), kept for the conversation
147 * `via` names from the answer as the tool made it, before the fence; the block naming its handle,
148 * or nothing when there is no card or it was too big to keep. The card itself is never sent to the
149 * agent.
150 */
151 function keepShown(ctx: Ctx, user: User, via: string, tool: string, args: Args, value: unknown, extra: Record<string, unknown> | undefined): { type: "text"; text: string }[] {
152 const card = cardFor(tool, value, ctx.url.origin, extra);
153 // A card of nothing (no rows) is not handed out: there is nothing to place.
154 if (card === undefined || card.rows.length === 0) return [];
155 const n = recordCard(ctx.app.db, via, user.id, tool, stepOf(`${tool} ${JSON.stringify(args)}`)?.label ?? tool, card, ctx.url.origin);
156 return n === undefined ? [] : [{ type: "text", text: shownLine(n) }];
157 }
158
143159 function rpcOne(
144160 ctx: Ctx,
145161 user: User,
@@ -280,6 +296,9 @@ function rpcOne(
280296 readThrough(ctx);
281297 return Promise.resolve(tool.run(ctx, user, args)).then((ran) => {
282298 const answer = fenceAnswer(ctx, ran);
299 // A card drawn for the forge's own agent is kept for its conversation; the agent reads its
300 // handle.
301 const shown = via !== undefined && ran.ok ? keepShown(ctx, user, via, tool.name, args, ran.value, ran.card) : [];
283302 if (recorded !== undefined) {
284303 // A refused or failed write did nothing, so a resumed turn may send it again.
285304 if (answer.ok) completeWrite(ctx.app.db, recorded, JSON.stringify(answer.value));
@@ -288,7 +307,7 @@ function rpcOne(
288307 return reply(
289308 answer.ok
290309 ? {
291 content: [{ type: "text", text: JSON.stringify(answer.value) }],
310 content: [{ type: "text", text: JSON.stringify(answer.value) }, ...shown],
292311 // The forge's agent reads the fenced text, never a card drawn around it.
293312 ...(ctx.auth.through === undefined
294313 ? cardResult(String(params["name"]), answer.value, ctx.url.origin, answer.card)
src/tui/screens/talk_chats.ts +6 −1
@@ -29,6 +29,8 @@ import {
2929 import { conversationMarkdown } from "../../core/conversation_markdown.ts";
3030 import { publicOrigin } from "../../core/public_origin.ts";
3131 import { filesOf, repoOf, stepOf } from "../../core/talk_steps.ts";
32 import { cardsPlaced, plainVoice } from "../../core/talk_voice.ts";
33 import type { ShownCard } from "../../core/talk_voice.ts";
3234 import { workspaceOf } from "../../actions/talk_workspace.ts";
3335 import type { Ctx, Screen } from "../app/app.ts";
3436 import { binding } from "../app/keys.ts";
@@ -101,11 +103,14 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
101103 let turns: Turns = [];
102104 let recent: Turns = [];
103105 let repo: string | undefined;
106 // The shown results the replies place, printed as their rows (docs/features/talk.md).
107 let cards: ReadonlyMap<number, ShownCard> = new Map();
104108 const load = (): void => {
105109 if (f.user === undefined) return;
106110 const before = around === undefined ? undefined : pageAround(f.app.db, f.user.id, chat.id, around);
107111 const listed = listTurns(f.app.db, f.user.id, chat.id, { limit: 50, ...(before === undefined ? {} : { before }) });
108112 turns = listed.ok ? listed.value : [];
113 cards = cardsPlaced(f.app.db, f.user.id, chat.id, turns);
109114 const last = before === undefined ? listed : listTurns(f.app.db, f.user.id, chat.id, { limit: 50 });
110115 recent = last.ok ? last.value : [];
111116 repo = repoOf(recent);
@@ -138,7 +143,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
138143 return turns.flatMap((t) => {
139144 if (t.id === around) mark = n;
140145 const step = t.role === "tool" ? stepOf(t.text) : undefined;
141 const said = t.role === "agent" ? pathRefs(t.text, refs) : t.text;
146 const said = t.role === "agent" ? pathRefs(plainVoice(t.text, cards), refs) : t.text;
142147 const own = (step === undefined ? said : [step.label, ...step.details.map((d) => ` ${d}`)].join("\n")).split("\n").flatMap((l) => wrap(l, Math.max(10, width - 2)));
143148 n += own.length + 2;
144149 return [
src/web/pages/talk.ts +8 −5
@@ -64,6 +64,7 @@ import { linkRefs, refTarget } from "../../text/talk_links.ts";
6464 import { liveCrewRows } from "../../actions/crew_now.ts";
6565 import { crewLineHtml } from "../crew_now.ts";
6666 import { renderMarkdown } from "../markdown.ts";
67 import { agentHtml, voiceCss, voiceOf, type Voice } from "../talk_parts.ts";
6768 import { badge, btn, row, time } from "../ui.ts";
6869 import { buildBox, buildCss, chosenTemplate, panelFor } from "../talk_build.ts";
6970 import { chatBuildOf } from "../../core/chat_build.ts";
@@ -227,7 +228,7 @@ const totalLine = (usd: number | undefined): Html =>
227228 const costLine = (spend: Spend): Html => html`<p class="talk-cost small muted">${spendWords(spend)}</p>`;
228229
229230 /** One turn as the page and the stream both draw it; `waiting` is the confirms still open. */
230 export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend, act?: Html, work?: Work, files: readonly ConversationFile[] = [], expired: ReadonlySet<string> = new Set(), undone: ReadonlySet<string> = new Set(), refs?: (n: number) => string | undefined): Html {
231 export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend, act?: Html, work?: Work, files: readonly ConversationFile[] = [], expired: ReadonlySet<string> = new Set(), undone: ReadonlySet<string> = new Set(), refs?: (n: number) => string | undefined, voice?: Voice): Html {
231232 const id = `t-${turn.id}`;
232233 const set = turn.replaced ? " talk-replaced" : "";
233234 const acts = act === undefined ? null : html`<div class="talk-acts">${act}</div>`;
@@ -245,7 +246,7 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend,
245246 </li>`;
246247 if (turn.role === "agent")
247248 return html`<li class="talk-turn talk-agent${set}" id="${id}">
248 <div class="talk-body prose">${refs === undefined ? renderMarkdown(turn.text) : linkRefs(renderMarkdown(turn.text), refs)}</div>
249 <div class="talk-body prose">${agentHtml(turn, voice, (md) => (refs === undefined ? md : linkRefs(md, refs)))}</div>
249250 ${work === undefined ? null : workHtml(work)}
250251 ${label("Forge")}
251252 ${cost === undefined ? null : costLine(cost)}${acts}
@@ -432,6 +433,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
432433 const listing = ctx.url.searchParams.get("chats") === "1";
433434 const cited = repoOf(turns);
434435 const refs = refTarget(ctx.app.db, user, cited);
436 const voice = voiceOf(ctx.app.db, user.id, conversation.id, turns, ctx.url.origin);
435437 const pane = talkPane(ctx, user, cited, works, view);
436438 const body = html`<div class="talk-page"><h1 class="sr-only">Talk</h1>
437439 ${box}
@@ -451,7 +453,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
451453 ${turns.length === 0
452454 ? html`<li class="muted talk-turn">Ask the forge anything, or tell it what to change. It acts as you, with your permissions, and asks before anything hard to undo.
453455 <div class="talk-suggest">${STARTER_PROMPTS.map((q) => html`<form method="post" action="${here}" data-starter><input type="hidden" name="text" value="${q}" />${btn(q)}</form>`)}</div></li>`
454 : turns.map((t) => turnHtml(t, waiting, costs.get(t.id), acts.get(t.id), works.get(t.id), sent.get(t.id), expired, undone, refs))}
456 : turns.map((t) => turnHtml(t, waiting, costs.get(t.id), acts.get(t.id), works.get(t.id), sent.get(t.id), expired, undone, refs, voice))}
455457 ${!paged && running ? queuedTalk(ctx.app, user, conversation.id).map(queuedHtml) : null}
456458 </ol>
457459 <div id="end"></div>
@@ -480,7 +482,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
480482 ${pane.html}
481483 ${panel}
482484 </div></div>`;
483 return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: panel === null && box === null ? talkCss : talkCss + buildCss, scriptJs: talkJs, description: "Talk to the forge.", wide: true, ...(pane.frame === undefined ? {} : { frameSrc: pane.frame }) });
485 return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: (panel === null && box === null ? talkCss : talkCss + buildCss) + voiceCss, scriptJs: talkJs, description: "Talk to the forge.", wide: true, ...(pane.frame === undefined ? {} : { frameSrc: pane.frame }) });
484486 }
485487
486488 /**
@@ -742,8 +744,9 @@ export function talkStream(ctx: Ctx): Response {
742744 const named = repoOf(fresh);
743745 if (named !== undefined) cited = named;
744746 const refs = refTarget(app.db, user, cited);
747 const voice = voiceOf(app.db, user.id, conversation.id, fresh, ctx.url.origin);
745748 for (const turn of fresh) {
746 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);
749 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, voice).text }, turn.id);
747750 cursor = turn.id;
748751 }
749752 // The page is told at once what the block holds after these turns, empty once it is
src/web/talk_parts.ts added +126
@@ -0,0 +1,126 @@
1 /**
2 * Talk's voice on the page (docs/features/talk.md, Shown results): an agent reply drawn in its
3 * fixed vocabulary (`core/talk_voice.ts`): a `::show c<n>` line draws the card the forge kept for
4 * that handle in this conversation, the forge's own data in a `.talk-card` with a provenance line
5 * under it, set apart from the model's words.
6 *
7 * Every string is escaped by the `html` tag; a card's link is a link only when it is a rooted path
8 * or an address on the page's own origin. A page of turns reads every card it places in one
9 * statement (`voiceOf`), so the count does not grow with the turns.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import type { ShownCard } from "../core/talk_voice.ts";
14 import type { Turn } from "../core/conversations.ts";
15 import { cardsPlaced, NOT_FOUND_WORDS, voiceParts, type Part } from "../core/talk_voice.ts";
16 import { escapeHtml, html, raw, type Html } from "./html.ts";
17 import { renderMarkdown } from "./markdown.ts";
18 import { card as surface, listCard, row, time } from "./ui.ts";
19
20 /** What drawing a page of agent turns needs: the cards they place. */
21 export interface Voice {
22 readonly cards: ReadonlyMap<number, ShownCard>;
23 readonly origin: string;
24 }
25
26 /** Each reply's parts by its text, per page: a page parses each reply once. */
27 const parsed = new WeakMap<object, Map<string, Part[]>>();
28 const partsOf = (key: object | undefined, text: string): Part[] => {
29 if (key === undefined) return voiceParts(text);
30 const seen = parsed.get(key) ?? new Map<string, Part[]>();
31 parsed.set(key, seen);
32 const hit = seen.get(text);
33 if (hit !== undefined) return hit;
34 const made = voiceParts(text);
35 seen.set(text, made);
36 return made;
37 };
38
39 /**
40 * What a page of `turns` of the person's conversation needs to draw its replies: one statement
41 * whatever the number of turns or cards.
42 */
43 export function voiceOf(db: Database, userId: string, conversationId: string, turns: readonly Turn[], origin: string): Voice {
44 const key = {};
45 const voice: Voice = { cards: cardsPlaced(db, userId, conversationId, turns, (text) => partsOf(key, text)), origin };
46 parsed.set(voice, parsed.get(key) ?? new Map());
47 return voice;
48 }
49
50 /**
51 * A card's link as the page draws it: a rooted path, or an address on this page's own origin;
52 * anything else (another site, `//host`, a backslash, a space, a scheme) is undefined, and the row
53 * is text.
54 */
55 export function linkOf(link: string | undefined, origin: string): string | undefined {
56 if (link === undefined || /[\s\\\p{Cc}]/u.test(link)) return undefined;
57 if (/^\/(?!\/)/.test(link)) return link;
58 return /^https?:\/\/[^/]+$/.test(origin) && link.startsWith(`${origin}/`) ? link : undefined;
59 }
60
61 const hhmm = (iso: string): string => `${iso.slice(11, 16)} UTC`;
62
63 /**
64 * A kept card as the page draws it: title and status, the rows (each a link only when `linkOf`
65 * allows it), and the line saying where it came from.
66 */
67 export function cardHtml(shown: ShownCard, voice: Pick<Voice, "origin">): Html {
68 const c = shown.card;
69 const rows = c.rows.map((r) => {
70 const href = linkOf(r.link, voice.origin);
71 return row({
72 title: r.label,
73 ...(r.value === "" ? {} : { meta: html`${r.value}` }),
74 ...(href === undefined ? {} : { href }),
75 ...(r.depth === undefined ? {} : { data: { depth: String(Math.min(3, r.depth)) } }),
76 });
77 });
78 const o = {
79 extra: "bare talk-card",
80 head: html`<strong>${c.title}</strong>${c.status === "" ? null : html` <span class="muted">${c.status}</span>`}`,
81 foot: html`<p class="talk-card-from small muted">From the forge: ${shown.said} · as of ${time(shown.createdAt, { text: hhmm(shown.createdAt) })}</p>`,
82 attrs: html`data-card="${shown.id}"`,
83 };
84 return rows.length === 0 ? surface(html``, { ...o, pad: false }) : listCard(rows, o);
85 }
86
87 /** One part of a reply that is not Markdown, as the page draws it. */
88 function partHtml(p: Exclude<Part, { kind: "text" }>, voice: Voice | undefined): Html {
89 switch (p.kind) {
90 case "show": {
91 const shown = voice?.cards.get(p.n);
92 if (shown === undefined || voice === undefined) return html`<p class="talk-card-missing small muted">${NOT_FOUND_WORDS}</p>`;
93 return cardHtml(shown, voice);
94 }
95 // The renderer's own fold, opened and closed around the parts it holds; the title is plain.
96 case "fold":
97 return raw(`<details><summary>${escapeHtml(p.summary)}</summary>`);
98 case "unfold":
99 return raw("</details>");
100 }
101 }
102
103 /**
104 * An agent reply's body: its Markdown (each run through `linked`, the page's `#12` links) and its
105 * shown results. A reply with none is `linked(renderMarkdown(text))`, as before.
106 */
107 export function agentHtml(turn: Turn, voice: Voice | undefined, linked: (md: Html) => Html): Html {
108 const parts = partsOf(voice, turn.text);
109 if (parts.length === 1 && parts[0]!.kind === "text") return linked(renderMarkdown(turn.text));
110 return html`${parts.map((p) => (p.kind === "text" ? linked(renderMarkdown(p.text)) : partHtml(p, voice)))}`;
111 }
112
113 /**
114 * The voice's rules, appended to the page's stylesheet: existing tokens, 44 px targets, logical
115 * sides.
116 */
117 export const voiceCss = /* css */ `
118 /* Over .card.bare's own border and overflow: a hairline on the start side, and a wide card scrolls in itself. */
119 .card.bare.talk-card { margin: 8px 0; max-width: 100%; overflow-x: auto; border-inline-start: 2px solid var(--border); padding-inline-start: 12px; }
120 .talk-card .row { min-height: 44px; padding-inline: 0; }
121 .talk-card .row-title, .talk-card .row-meta { white-space: normal; overflow-wrap: anywhere; }
122 .talk-card li[data-depth="1"] > .row { padding-inline-start: 16px; }
123 .talk-card li[data-depth="2"] > .row { padding-inline-start: 32px; }
124 .talk-card li[data-depth="3"] > .row { padding-inline-start: 48px; }
125 .talk-card-from { margin: 0; }
126 `;
test/data-browser.test.ts +3
@@ -32,6 +32,9 @@ const AUDITED_CLEAR: string[] = [
3232 "child_reach_ask.body_id",
3333 "child_reach_grant.body_id",
3434 "comment.body",
35 // The call a kept Talk result came from, in plain words (`stepOf` in core/talk_steps.ts, from a
36 // card-drawing read: "Issues"); never an argument's value.
37 "conversation_card.said",
3538 // A daily-proof line's evidence (`release/daily_proof.ts` plainEvidence): one plain line,
3639 // credential-shaped text removed before it is stored.
3740 "daily_proof_ask.evidence",
test/talk-shown.test.ts added +506
@@ -0,0 +1,506 @@
1 /**
2 * Shown results (docs/features/talk.md, Shown results): an MCP answer to a conversation's via token
3 * that has a card keeps the card for that conversation and hands the agent its handle outside the
4 * fence; a `::show c<n>` line in a reply draws the kept card on /talk, the forge's own data and
5 * never the model's; and another person's or conversation's handle draws nothing of it.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import {
14 CARD_CHARS_MAX,
15 CARDS_KEPT,
16 cardsOf,
17 plainVoice,
18 recordCard,
19 shownLine,
20 } from "../src/core/talk_voice.ts";
21 import {
22 appendTurn,
23 createConversation,
24 dropConversation,
25 type Conversation,
26 } from "../src/core/conversations.ts";
27 import { createIssue } from "../src/core/issues.ts";
28 import { createSession } from "../src/core/sessions.ts";
29 import { createToken } from "../src/core/tokens.ts";
30 import { createUser, type User } from "../src/core/users.ts";
31 import { mintViaToken } from "../src/core/via_token.ts";
32 import { serve, type Servers } from "../src/http/server.ts";
33 import { createForgeApp } from "../src/tui/forge.ts";
34 import { headlessTerminal } from "../src/tui/term/terminal.ts";
35 import { settleApp } from "./helpers/tui.ts";
36 import type { Card } from "../src/web/studio/cards.ts";
37 import { promote } from "./helpers/members.ts";
38 import { quietLogs } from "./helpers/globals.ts";
39 import { statements } from "./helpers/statements.ts";
40
41 quietLogs();
42
43 let dir: string;
44 let app: App;
45 let servers: Servers;
46 let alice: User;
47 let bob: User;
48 let rpcId = 1;
49
50 const HOSTILE = `<script>alert(1)</script> "quoted" & <img src=x onerror=alert(2)>`;
51
52 const cookie = (u: User) =>
53 `forge_session=${createSession(app.db, u.id).token}`;
54 const get = (path: string, u: User) =>
55 fetch(`${servers.url}${path}`, {
56 redirect: "manual",
57 headers: { cookie: cookie(u) },
58 });
59 async function call(
60 token: string,
61 name: string,
62 args: Record<string, unknown>,
63 ): Promise<any> {
64 const res = await fetch(`${servers.url}/mcp`, {
65 method: "POST",
66 headers: {
67 "content-type": "application/json",
68 accept: "application/json, text/event-stream",
69 authorization: `Bearer ${token}`,
70 },
71 body: JSON.stringify({
72 jsonrpc: "2.0",
73 id: rpcId++,
74 method: "tools/call",
75 params: { name, arguments: args },
76 }),
77 });
78 return ((await res.json()) as { result: any }).result;
79 }
80
81 const chat = (u: User): Conversation => {
82 const made = createConversation(app.db, u.id);
83 if (!made.ok) throw new Error(made.error);
84 return made.value;
85 };
86 const via = (c: Conversation) => `conversation:${c.id}`;
87 const viaToken = (u: User, c: Conversation, words = "list the issues") => {
88 const minted = mintViaToken(
89 app.db,
90 u.id,
91 via(c),
92 words,
93 new Date(Date.now() + 10 * 60_000).toISOString(),
94 );
95 if (!minted.ok) throw new Error(minted.error);
96 return minted.value.token;
97 };
98 const cardRows = (v: string) =>
99 app.db
100 .query("SELECT * FROM conversation_card WHERE via = ?1 ORDER BY n")
101 .all(v) as {
102 id: string;
103 n: number;
104 tool: string;
105 said: string;
106 card: string;
107 user_id: string;
108 }[];
109
110 /** A card of a kind and actions as `cardFor` would build them, kept for a conversation. */
111 function keep(
112 u: User,
113 c: Conversation,
114 card: Card,
115 now = Date.now(),
116 ): { n: number; id: string } {
117 const n = recordCard(
118 app.db,
119 via(c),
120 u.id,
121 "now",
122 "Now",
123 card,
124 servers.url,
125 now,
126 );
127 if (n === undefined) throw new Error("not kept");
128 return { n, id: cardRows(via(c)).find((r) => r.n === n)!.id };
129 }
130 const stopCard = (run = "01jabcdefghjkmnpqrstvwxyz0"): Card => ({
131 kind: "crew",
132 title: "Working now",
133 status: "1 going",
134 rows: [{ label: "smith on alice/w", value: "running" }],
135 actions: [
136 { label: "Stop smith", tool: "stop", args: { repo: "alice/w", run } },
137 ],
138 });
139
140 let repo = "";
141
142 beforeAll(async () => {
143 dir = await mkdtemp(join(tmpdir(), "forge-talk-shown-"));
144 app = createApp({ dataDir: dir, port: 0 });
145 servers = await serve(app);
146 const mk = async (username: string, first = false) => {
147 const u = await createUser(app.db, {
148 origin: "seed",
149 trusted: true,
150 username,
151 email: `${username}@forge.local`,
152 password: "a-good-passphrase",
153 adminIfFirst: first,
154 });
155 if (!u.ok) throw new Error(u.error);
156 promote(app.db, u.value);
157 return u.value;
158 };
159 alice = await mk("alice", true);
160 bob = await mk("bob");
161 const made = await createRepo(app, alice, {
162 name: "w",
163 visibility: "public",
164 });
165 if (!made.ok) throw new Error(String(made.error));
166 repo = "alice/w";
167 for (const [authorId, title] of [
168 [bob.id, HOSTILE],
169 [alice.id, "Ship the docs"],
170 ] as const) {
171 const i = createIssue(app.db, {
172 repoId: made.value.id,
173 authorId,
174 title,
175 body: "b",
176 });
177 if (!i.ok) throw new Error(i.error);
178 }
179 }, 30_000);
180
181 afterAll(async () => {
182 servers.stop();
183 app.close();
184 await rm(dir, { recursive: true, force: true });
185 });
186
187 describe("a via caller's answer keeps its card", () => {
188 test("the card is kept for the conversation and the agent reads its handle, outside the fence; the card is not sent", async () => {
189 const c = chat(alice);
190 const result = await call(viaToken(alice, c), "issues", { repo });
191 expect(result.isError).toBeUndefined();
192 expect(result.structuredContent).toBeUndefined();
193 expect(result.content).toHaveLength(2);
194 // The answer is fenced; the handle is the forge's own block after it.
195 expect(result.content[0].text).toContain("[[data ");
196 expect(result.content[1]).toEqual({ type: "text", text: shownLine(1) });
197 expect(result.content[1].text).toContain("::show c1");
198 const rows = cardRows(via(c));
199 expect(rows.map((r) => [r.n, r.tool, r.user_id])).toEqual([
200 [1, "issues", alice.id],
201 ]);
202 // Kept from the answer as the tool made it, not the fenced text, and its links made rooted.
203 const kept = JSON.parse(rows[0]!.card) as Card;
204 expect(kept.kind).toBe("issues");
205 expect(JSON.stringify(kept)).not.toContain("[[data");
206 expect(kept.rows.map((r) => r.label).join("\n")).toContain(
207 "<script>alert(1)</script>",
208 );
209 expect(
210 kept.rows.every(
211 (r) => r.link === undefined || r.link.startsWith("/alice/w/issues/"),
212 ),
213 ).toBe(true);
214 // A second answer is the next handle.
215 const again = await call(viaToken(alice, c), "issues", { repo });
216 expect(again.content[1].text).toBe(shownLine(2));
217 });
218
219 test("a card with no rows is not kept and carries no handle", async () => {
220 const c = chat(alice);
221 const result = await call(viaToken(alice, c), "runs", { repo });
222 expect(result.isError).toBeUndefined();
223 expect(result.content).toHaveLength(1);
224 expect(JSON.stringify(result.content)).not.toContain("Shown result");
225 expect(cardRows(via(c))).toEqual([]);
226 });
227
228 test("an answer with no card keeps nothing and carries no handle", async () => {
229 const c = chat(alice);
230 const result = await call(viaToken(alice, c), "whoami_can", {});
231 expect(result.content).toHaveLength(1);
232 expect(cardRows(via(c))).toEqual([]);
233 });
234
235 test("any other caller keeps nothing, and its answer is what it always was", async () => {
236 const before = (
237 app.db.query("SELECT COUNT(*) AS n FROM conversation_card").get() as {
238 n: number;
239 }
240 ).n;
241 const token = createToken(app.db, alice.id, "rw", "rw").token;
242 const result = await call(token, "issues", { repo });
243 expect(
244 (
245 app.db.query("SELECT COUNT(*) AS n FROM conversation_card").get() as {
246 n: number;
247 }
248 ).n,
249 ).toBe(before);
250 const value = JSON.parse(result.content[0].text);
251 // Exactly the text and the card beside it, nothing added.
252 expect(Object.keys(result).sort()).toEqual([
253 "content",
254 "structuredContent",
255 ]);
256 expect(result.content).toEqual([
257 { type: "text", text: JSON.stringify(value) },
258 ]);
259 expect(result.structuredContent.card.kind).toBe("issues");
260 expect(result.content[0].text).not.toContain("Shown result");
261 });
262
263 test("bounded: the newest are kept, and a card too big to keep is not kept", () => {
264 const c = chat(alice);
265 const small: Card = {
266 kind: "crew",
267 title: "t",
268 status: "",
269 rows: [],
270 actions: [],
271 };
272 for (let i = 0; i < CARDS_KEPT + 3; i++)
273 recordCard(app.db, via(c), alice.id, "now", "Now", small, "");
274 const ns = cardRows(via(c)).map((r) => r.n);
275 expect(ns.length).toBe(CARDS_KEPT);
276 expect(ns[0]).toBe(4);
277 const big: Card = {
278 ...small,
279 rows: [{ label: "x", value: "y".repeat(CARD_CHARS_MAX) }],
280 };
281 expect(
282 recordCard(app.db, via(c), alice.id, "now", "Now", big, ""),
283 ).toBeUndefined();
284 expect(cardRows(via(c)).length).toBe(CARDS_KEPT);
285 });
286 });
287
288 describe("what is kept", () => {
289 test("a kept card is what the page draws: its title, status and rows, never a button", () => {
290 const c = chat(alice);
291 const { n } = keep(alice, c, { ...stopCard(), rows: [{ label: "smith", value: "running", actions: [{ label: "Stop", tool: "stop", args: {} }] }] });
292 const text = cardRows(via(c)).find((r) => r.n === n)!.card;
293 expect(text).not.toContain("Stop");
294 const shown = cardsOf(app.db, alice.id, via(c), [n]).get(n)!;
295 expect(shown.card.actions).toEqual([]);
296 expect(shown.card.rows).toEqual([{ label: "smith", value: "running" }]);
297 });
298
299 test("a conversation's cards go when the conversation goes", () => {
300 const c = chat(alice);
301 keep(alice, c, stopCard());
302 const other = chat(alice);
303 keep(alice, other, stopCard());
304 dropConversation(app.db, alice.id, c.id);
305 expect(cardRows(via(c))).toEqual([]);
306 expect(cardRows(via(other))).toHaveLength(1);
307 });
308 });
309
310 describe("the terminal prints a placed card", () => {
311 test("as where it came from, its title and status, and a line per row; a missing handle as not found", () => {
312 const c = chat(alice);
313 const { n } = keep(alice, c, { kind: "crew", title: "Working now", status: "1 going", rows: [{ label: "smith on alice/w", value: "running" }, { label: "the docs", value: "", depth: 1 }], actions: [] });
314 const cards = cardsOf(app.db, alice.id, via(c), [n, 99]);
315 const printed = plainVoice(`Here it is.\n\n::show c${n}\n\n::show c99`, cards);
316 expect(printed).toMatch(/^Here it is\.\n+From the forge: Now, as of \d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC\nWorking now · 1 going\n smith on alice\/w: running\n the docs\nResult not found\.$/);
317 // A reply that places nothing prints as it was written.
318 expect(plainVoice("Just words, and `::show c1` in a sentence.", cards)).toBe("Just words, and `::show c1` in a sentence.");
319 });
320
321 test("the terminal's conversation screen prints a placed card's rows", async () => {
322 const c = chat(alice);
323 keep(alice, c, { kind: "crew", title: "Working now", status: "nothing running", rows: [{ label: "quiet row", value: "idle" }], actions: [] });
324 appendTurn(app.db, alice.id, c.id, { role: "agent", text: "Look:\n::show c1" });
325 const terminal = headlessTerminal(120, 40);
326 const { app: tui } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
327 tui.start();
328 await settleApp(tui);
329 for (const k of [":", "Conversations", "\r", "\r"]) {
330 terminal.feed(k);
331 await settleApp(tui);
332 }
333 const text = tui.screen.toText();
334 tui.stop?.();
335 expect(text).toContain("Working now · nothing running");
336 expect(text).toContain("quiet row: idle");
337 expect(text).not.toContain("::show c1");
338 });
339
340 test("forge talk reads the same printing from the turns API, as plain beside the raw text", async () => {
341 const c = chat(alice);
342 keep(alice, c, stopCard());
343 appendTurn(app.db, alice.id, c.id, { role: "agent", text: "Now:\n\n::show c1" });
344 appendTurn(app.db, alice.id, c.id, { role: "agent", text: "Nothing placed." });
345 const res = await fetch(`${servers.url}/api/v1/conversation/turns?conversation=${c.id}`, { headers: { authorization: `Bearer ${createToken(app.db, alice.id, "t", "ro").token}` } });
346 const turns = ((await res.json()) as { turns: { text: string; plain?: string }[] }).turns;
347 const placed = turns.find((t) => t.text.includes("::show c1"))!;
348 expect(placed.plain).toContain("Working now · 1 going\n smith on alice/w: running");
349 expect(turns.find((t) => t.text === "Nothing placed.")!.plain).toBeUndefined();
350 });
351 });
352
353 describe("::show draws the kept card", () => {
354 test("the card is drawn with where it came from, its hostile text inert", async () => {
355 const c = chat(alice);
356 await call(viaToken(alice, c), "issues", { repo });
357 appendTurn(app.db, alice.id, c.id, {
358 role: "person",
359 text: "what is open?",
360 });
361 appendTurn(app.db, alice.id, c.id, {
362 role: "agent",
363 text: "Two are open.\n\n::show c1\n\nThe first is from an outsider.",
364 });
365 const page = await (await get(`/talk/${c.id}`, alice)).text();
366 const id = cardRows(via(c))[0]!.id;
367 expect(page).toContain(`data-card="${id}"`);
368 expect(page).toContain('class="card bare talk-card"');
369 expect(page).toContain("From the forge: Issues · as of");
370 expect(page).toContain("<time");
371 expect(page).toContain("Ship the docs");
372 expect(page).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
373 expect(page).not.toContain("<script>alert(1)");
374 expect(page).not.toContain("<img src=x");
375 expect(page).not.toContain("::show c1");
376 // The words around the card are still the agent's Markdown.
377 expect(page).toContain("<p>Two are open.</p>");
378 });
379
380 test("a link is drawn only when it stays on this forge; anything else is text", async () => {
381 const c = chat(alice);
382 const links = [
383 "javascript:alert(1)",
384 "https://evil.example/x",
385 "//evil.example/x",
386 "/\\evil.example",
387 "/ok/path",
388 `${servers.url}/alice/w`,
389 "data:text/html,hi",
390 " /spaced",
391 ];
392 keep(alice, c, {
393 kind: "issues",
394 title: "Links",
395 status: "",
396 rows: links.map((link, i) => ({ label: `row ${i}`, value: "", link })),
397 actions: [],
398 });
399 appendTurn(app.db, alice.id, c.id, { role: "agent", text: "::show c1" });
400 const page = await (await get(`/talk/${c.id}`, alice)).text();
401 const hrefs = [
402 ...page.slice(page.indexOf("data-card=")).matchAll(/href="([^"]*)"/g),
403 ].map((m) => m[1]!);
404 expect(hrefs).toContain("/ok/path");
405 expect(hrefs).toContain("/alice/w");
406 for (const bad of ["javascript:", "evil.example", "data:"])
407 expect(hrefs.some((h) => h.includes(bad))).toBe(false);
408 });
409
410 test("a handle of another person's or another conversation's card draws nothing of it", async () => {
411 const theirs = chat(bob);
412 keep(bob, theirs, {
413 kind: "crew",
414 title: "Bob's secret card",
415 status: "",
416 rows: [{ label: "bob row", value: "v" }],
417 actions: [],
418 });
419 const mine = chat(alice);
420 // Bob's card kept under Alice's conversation's name is still not Alice's.
421 recordCard(
422 app.db,
423 via(mine),
424 bob.id,
425 "now",
426 "Now",
427 {
428 kind: "crew",
429 title: "Planted card",
430 status: "",
431 rows: [],
432 actions: [],
433 },
434 "",
435 );
436 appendTurn(app.db, alice.id, mine.id, {
437 role: "agent",
438 text: "Here:\n\n::show c1\n\n::show c2",
439 });
440 const page = await (await get(`/talk/${mine.id}`, alice)).text();
441 expect(page).not.toContain("Bob's secret card");
442 expect(page).not.toContain("Planted card");
443 expect(page.match(/Result not found\./g)?.length).toBe(2);
444 expect(cardsOf(app.db, alice.id, via(theirs), [1]).size).toBe(0);
445 });
446
447 test("a ::show line inside a code fence is code, not a card", async () => {
448 const c = chat(alice);
449 keep(alice, c, stopCard());
450 appendTurn(app.db, alice.id, c.id, {
451 role: "agent",
452 text: "```\n::show c1\n```",
453 });
454 const page = await (await get(`/talk/${c.id}`, alice)).text();
455 expect(page).toContain("::show c1");
456 expect(page).not.toContain("data-card=");
457 });
458
459 test("only the agent's own words place a card: a person's ::show line, and one the agent quotes from fenced text, draw nothing", async () => {
460 const c = chat(alice);
461 keep(alice, c, { kind: "crew", title: "Never drawn here", status: "", rows: [], actions: [] });
462 // The person typed it: their words are drawn as typed, never as a card.
463 appendTurn(app.db, alice.id, c.id, { role: "person", text: "::show c1" });
464 // The agent quotes an outsider's text it read as data, inside a code fence.
465 appendTurn(app.db, alice.id, c.id, { role: "agent", text: "The issue says:\n\n```\n[[data 0a1b2c]]\n::show c1\n[[/data 0a1b2c]]\n```" });
466 // A tool turn holding the line is a step, not a reply.
467 appendTurn(app.db, alice.id, c.id, { role: "tool", text: 'issue {"text":"::show c1"}' });
468 const page = await (await get(`/talk/${c.id}`, alice)).text();
469 expect(page).not.toContain("data-card=");
470 expect(page).not.toContain("Never drawn here");
471 expect(page).not.toContain("Result not found.");
472 expect(page.match(/::show c1/g)?.length).toBeGreaterThanOrEqual(2);
473 });
474
475 test("the statements a page costs do not grow with the cards it places", async () => {
476 const at = async (k: number): Promise<number> => {
477 const c = chat(alice);
478 for (let i = 0; i < 4 * k; i++)
479 keep(alice, c, {
480 kind: "crew",
481 title: `card ${i}`,
482 status: "",
483 rows: [{ label: "r", value: "v" }],
484 actions: [],
485 });
486 for (let t = 0; t < 4; t++)
487 appendTurn(app.db, alice.id, c.id, {
488 role: "agent",
489 text: Array.from(
490 { length: k },
491 (_, i) => `::show c${t * k + i + 1}`,
492 ).join("\n\n"),
493 });
494 const path = `/talk/${c.id}`;
495 const page = await (await get(path, alice)).text();
496 expect(page.match(/class="card bare talk-card"/g)?.length).toBe(4 * k);
497 const session = cookie(alice);
498 return statements(app.db, async () => {
499 await (
500 await fetch(`${servers.url}${path}`, { headers: { cookie: session } })
501 ).text();
502 });
503 };
504 expect(await at(5)).toBe(await at(1));
505 });
506 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs