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

Talk: a new app's receipt reads its stored answer unfenced, so the pane opens #16344

Merged opened this

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

Merged

talk/live-pane-fix → main 0 commits 1 thread · 1 unresolved

  • Merged. talk/live-pane-fix was merged into main as 00cdd46.

Review

Sign in to review this change.
3 files changed +275 −2
src/core/conversation_writes.ts +4 −2
@@ -7,6 +7,7 @@
77 * with none. Plain data in and out; the door is `http/mcp.ts`.
88 */
99
10 import { unfenced } from "./fence.ts";

Nit: import order. Place this after the bun:sqlite type import, like the neighbouring imports.

1011 import type { Database } from "bun:sqlite";
1112 import { sha256 } from "../kernel/hash.ts";
1213 import { id } from "../kernel/id.ts";
@@ -110,8 +111,9 @@ export function toldIn(db: Database, via: string): { issue: number; page: string
110111 try {
111112 const data = JSON.parse(row.result) as Record<string, unknown> | null;
112113 const issue = data?.["issue"];
113 const page = data?.["page"];
114 const repo = data?.["repo"];
114 // The stored answer is the one the agent read, so its strings are fenced (#16339).
115 const page = typeof data?.["page"] === "string" ? unfenced(data["page"]) : undefined;
116 const repo = typeof data?.["repo"] === "string" ? unfenced(data["repo"]) : undefined;
115117 if (row.tool === "new_app") {
116118 // A new app's first build is on the issue it opened: the receipt follows that build.
117119 if (typeof issue === "number" && Number.isInteger(issue) && issue > 0 && typeof repo === "string" && /^[^/\s]+\/[^/\s]+$/.test(repo)) out.push({ issue, page: `/${repo}/issues/${String(issue)}`, app: repo });
src/core/fence.ts +9
@@ -91,6 +91,15 @@ export const fenceClose = (tag: string): string => `[[/data ${tag}]]`;
9191 export const fenced = (text: string, tag: string): string =>
9292 `${fenceOpen(tag)}\n${text}\n${fenceClose(tag)}`;
9393
94 /**
95 * The text inside one data block, or the text itself when it is not one: how
96 * the forge reads back an answer it stored fenced.
97 */
98 export function unfenced(text: string): string {
99 const m = /^\[\[data ([0-9a-f]+)\]\]\n([\s\S]*)\n\[\[\/data \1\]\]$/.exec(text);
100 return m?.[2] ?? text;
101 }
102
94103 /**
95104 * The answer with every non-empty string wrapped — in an object, an array or
96105 * the answer itself, and an object's key that is not a field name — except
test/talk-live-pane-fenced.test.ts added +262
@@ -0,0 +1,262 @@
1 /**
2 * Production's new_app and tell, read back (#16339): /mcp stores the answer the conversation's
3 * agent read, with every string an outsider could have chosen in a data block. The receipt, its
4 * live line and the pane come from that stored answer, so they are tested on it: the turns are the
5 * owner's unit-converter conversation on 0.7.645 (01m87nf01p2wj34p9fp9qgaq0t), word for word, and
6 * the stored answers are made by the real /mcp door, plus one copied in production's form with its
7 * tag.
8 */
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import {
15 completeWrite,
16 recordWrite,
17 toldIn,
18 } from "../src/core/conversation_writes.ts";
19 import { appendTurn, createConversation } from "../src/core/conversations.ts";
20 import { fenced, unfenced } from "../src/core/fence.ts";
21 import { createIssue, getIssue } from "../src/core/issues.ts";
22 import { getRepo } from "../src/core/repos.ts";
23 import { claimRun, createRun } from "../src/core/runs.ts";
24 import { createSession } from "../src/core/sessions.ts";
25 import { createUser, type User } from "../src/core/users.ts";
26 import { mintViaToken } from "../src/core/via_token.ts";
27 import { filedTurns } from "../src/crew/filed.ts";
28 import { serve, type Servers } from "../src/http/server.ts";
29 import { promote } from "./helpers/members.ts";
30
31 // The owner's conversation as production stored it, 2026-11-24 20:55 UTC.
32 const PERSON =
33 "build a tiny unit converter app: length, weight and temperature; works on a phone";
34 const CALL =
35 'mcp__forge__new_app {"name":"unit-converter","sentence":"A tiny unit converter app: length, weight and temperature; works well on a phone","description":"Build a tiny unit converter web app. Three categories: length (mm, cm, m, km, in, ft, yd, mi), weight (mg, g, kg, oz, lb), temperature (°C, °F, K). Pick a category, type a value, choose from/to units, see the result live, with a swap button. Mobile first: single column, large touch targets (44px+), numeric keypad on input (inputmode decimal), no horizontal scroll, viewport meta set. No dependencies; plain HTML/CSS/JS. Include tests for the conversion math (e.g. 0 °C = 32 °F, 1 mi = 1.609344 km, 1 lb = 453.59237 g).","visibility":"private"}';
36 const AGENT =
37 "I've started your unit converter. It has length, weight and temperature, a swap button and large touch targets for phones. I haven't opened it yet, so I can't say what it looks like.\n\nIt is private: only you and people you invite can open it. Anyone else gets a not-found page. You can open it up or invite someone from the repository's settings.\n\nThe app will be at https://unit-converter--forge-trevato-apps.open-platform.sh once it's built. The line under this receipt follows the build as it goes (waiting, working, pushed, landed).\n\n::show c1";
38 const ARGS = JSON.parse(CALL.slice(CALL.indexOf(" ") + 1)) as Record<
39 string,
40 unknown
41 >;
42
43 let dir: string;
44 let app: App;
45 let servers: Servers;
46 let owner: User;
47
48 beforeAll(async () => {
49 dir = await mkdtemp(join(tmpdir(), "forge-live-pane-fenced-"));
50 app = createApp({ dataDir: dir, port: 0 });
51 servers = await serve(app);
52 const made = await createUser(app.db, {
53 origin: "seed",
54 trusted: true,
55 username: "trevato",
56 email: "[email protected]",
57 password: "a-good-passphrase",
58 adminIfFirst: true,
59 });
60 if (!made.ok) throw new Error(made.error);
61 promote(app.db, made.value);
62 owner = made.value;
63 });
64 afterAll(async () => {
65 servers.stop();
66 app.close();
67 await rm(dir, { recursive: true, force: true });
68 });
69
70 /** One tool call through /mcp as the conversation's own agent, with the person's words heard. */
71 async function asAgent(
72 via: string,
73 words: string,
74 name: string,
75 args: Record<string, unknown>,
76 ): Promise<void> {
77 const minted = mintViaToken(
78 app.db,
79 owner.id,
80 via,
81 words,
82 new Date(Date.now() + 600_000).toISOString(),
83 );
84 if (!minted.ok) throw new Error(minted.error);
85 const res = await fetch(`${servers.url}/mcp`, {
86 method: "POST",
87 headers: {
88 "content-type": "application/json",
89 accept: "application/json, text/event-stream",
90 authorization: `Bearer ${minted.value.token}`,
91 },
92 body: JSON.stringify({
93 jsonrpc: "2.0",
94 id: 1,
95 method: "tools/call",
96 params: { name, arguments: args },
97 }),
98 });
99 const body = (await res.json()) as {
100 result?: { isError?: boolean; content?: { text: string }[] };
101 };
102 if (body.result?.isError === true)
103 throw new Error(body.result.content?.[0]?.text ?? "refused");
104 }
105
106 const stored = (via: string, tool: string): string =>
107 app.db
108 .query<
109 { result: string },
110 [string, string]
111 >("SELECT result FROM conversation_write WHERE via = ?1 AND tool = ?2")
112 .get(via, tool)?.result ?? "";
113
114 const page = async (id: string): Promise<string> =>
115 await (
116 await fetch(`${servers.url}/talk/${id}`, {
117 headers: {
118 cookie: `forge_session=${createSession(app.db, owner.id).token}`,
119 },
120 })
121 ).text();
122
123 test("a data block reads back as its text; anything else is itself", () => {
124 expect(unfenced(fenced("trevato/unit-converter", "e57b4adad142"))).toBe(
125 "trevato/unit-converter",
126 );
127 expect(unfenced("trevato/unit-converter")).toBe("trevato/unit-converter");
128 expect(unfenced(fenced("two\nlines", "ab12"))).toBe("two\nlines");
129 // A block whose closing tag is another's is not one block; nor is text around a block.
130 expect(unfenced("[[data aa]]\nx\n[[/data bb]]")).toBe(
131 "[[data aa]]\nx\n[[/data bb]]",
132 );
133 expect(unfenced(`say ${fenced("x", "aa")}`)).toBe(`say ${fenced("x", "aa")}`);
134 });
135
136 test("new_app's answer in production's stored form, with its tag, gives the app's receipt", () => {
137 const via = "conversation:stored0";
138 const wrote = recordWrite(app.db, via, "new_app", ARGS);
139 completeWrite(
140 app.db,
141 wrote,
142 '{"repo":"[[data 5c0e9a41d2f7]]\\ntrevato/unit-converter\\n[[/data 5c0e9a41d2f7]]","url":"https://unit-converter--forge-trevato-apps.open-platform.sh","issue":1,"agent":"[[data 5c0e9a41d2f7]]\\ncheffry-james\\n[[/data 5c0e9a41d2f7]]","run":"queued"}',
143 );
144 expect(toldIn(app.db, via)).toEqual([
145 {
146 issue: 1,
147 page: "/trevato/unit-converter/issues/1",
148 app: "trevato/unit-converter",
149 },
150 ]);
151 });
152
153 test("new_app through /mcp, the owner's turns stored: the pane opens on the queued build and the receipt's line walks to landed", async () => {
154 const chat = createConversation(app.db, owner.id);
155 if (!chat.ok) throw new Error(chat.error);
156 const via = `conversation:${chat.value.id}`;
157 await asAgent(via, PERSON, "new_app", ARGS);
158 // The shape production stores: the repository's name inside a data block.
159 expect(stored(via, "new_app")).toMatch(
160 /"repo":"\[\[data [0-9a-f]+\]\]\\ntrevato\/unit-converter\\n\[\[\/data [0-9a-f]+\]\]"/,
161 );
162
163 const filed = filedTurns(app.db, via, PERSON, true);
164 expect(filed.map((t) => JSON.parse(t))).toEqual([
165 {
166 filed: true,
167 done: true,
168 title: expect.any(String),
169 receipt: {
170 verb: "New app",
171 object: "trevato/unit-converter",
172 href: "/trevato/unit-converter/issues/1",
173 },
174 },
175 ]);
176 appendTurn(app.db, owner.id, chat.value.id, { role: "person", text: PERSON });
177 appendTurn(app.db, owner.id, chat.value.id, { role: "tool", text: CALL });
178 appendTurn(app.db, owner.id, chat.value.id, { role: "agent", text: AGENT });
179 const receipt = appendTurn(app.db, owner.id, chat.value.id, {
180 role: "tool",
181 text: filed[0]!,
182 });
183 if (!receipt.ok) throw new Error(String(receipt.error));
184
185 const repo = getRepo(app.db, "trevato", "unit-converter");
186 const issue = repo === undefined ? undefined : getIssue(app.db, repo.id, 1);
187 if (repo === undefined || issue === undefined)
188 throw new Error("the app and its first issue");
189 const line = (html: string): string =>
190 /id="w-[^"]+"[^>]*>([\s\S]*?)<\/p>/
191 .exec(html)?.[1]
192 ?.replace(/<[^>]+>/g, "")
193 .trim() ?? "";
194
195 const run = createRun(app.db, {
196 repoId: repo.id,
197 kind: "agent",
198 issueId: issue.id,
199 reason: "assigned",
200 branch: "crew/unit-converter",
201 });
202 const queued = await page(chat.value.id);
203 expect(line(queued)).toBe("Queued for the crew.");
204 expect(queued).toContain('data-live-repo="trevato/unit-converter"');
205 // The pane is open on the new app: the page splits and draws the crew's run in its stage.
206 expect(queued).toContain(" data-split");
207 expect(queued).toContain('class="talk-crew-now"');
208
209 claimRun(app.db, run.id);
210 expect(line(await page(chat.value.id))).toMatch(
211 /^The crew has been working on it( for \d+ min)?\.$/,
212 );
213
214 const pull = createIssue(app.db, {
215 repoId: repo.id,
216 authorId: owner.id,
217 title: "Unit converter",
218 body: "Closes #1",
219 kind: "pull",
220 });
221 if (!pull.ok) throw new Error("pull");
222 app.db.run(
223 "INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', 'crew/unit-converter', '', '')",
224 [pull.value.id],
225 );
226 expect(line(await page(chat.value.id))).toBe(
227 `The crew pushed #${String(pull.value.number)}: checks running.`,
228 );
229
230 app.db.run("UPDATE pull SET merged_at = ?1 WHERE issue_id = ?2", [
231 new Date().toISOString(),
232 pull.value.id,
233 ]);
234 app.db.run("UPDATE run SET state = 'ok' WHERE id = ?1", [run.id]);
235 expect(line(await page(chat.value.id))).toBe(
236 `The crew landed #${String(pull.value.number)}.`,
237 );
238 });
239
240 test("tell through /mcp: its stored page is in a data block, and it still gives the Filed #N receipt", async () => {
241 const chat = createConversation(app.db, owner.id);
242 if (!chat.ok) throw new Error(chat.error);
243 const via = `conversation:${chat.value.id}`;
244 const words = "make the swap button bigger";
245 await asAgent(via, words, "tell", {
246 repo: "trevato/unit-converter",
247 text: "Make the swap button bigger\nIt should be easy to tap on a phone.",
248 });
249 expect(stored(via, "tell")).toMatch(
250 /"page":"\[\[data [0-9a-f]+\]\]\\nhttp:\/\/[^"]+\/trevato\/unit-converter\/issues\/\d+\\n\[\[\/data [0-9a-f]+\]\]"/,
251 );
252 const [one] = filedTurns(app.db, via, words, true).map(
253 (t) =>
254 JSON.parse(t) as {
255 receipt?: { verb: string; object: string; href: string };
256 },
257 );
258 expect(one?.receipt).toMatchObject({
259 verb: "Filed",
260 href: expect.stringMatching(/^\/trevato\/unit-converter\/issues\/\d+$/),
261 });
262 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs