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

A Talk step says what the call did, not that it was made #16207

Merged opened this

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

Merged

talk/fix-steps-truth → main 0 commits

  • Merged. talk/fix-steps-truth was merged into main as 748a101.

Review

Sign in to review this change.
8 files changed +522 −19
docs/features/talk.md +4
@@ -38,6 +38,10 @@ The reply is drawn as it is written. The runner reports each piece of the block
3838 - **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`.
3939 - **Without the script**, or with a runner that reports no pieces, the page draws whole turns, as before.
4040
41 ## A step says what happened
42
43 A tool call is stored once its result is known (`src/crew/conversation_calls.ts`, for a runner that reports pieces): one that ended well reads as done ("Merged pull #2 and deployed"), one the forge held for your yes reads "Asked to merge pull #2" (its confirm and, once answered, the outcome line say the rest), and one that failed reads "Tried to merge pull #2: not done". The steps line under a reply and its links count only what was done, and say "asked your yes for 1 step" or "1 step not done" for the rest (`stepOf` in `src/core/talk_steps.ts`, `workOf` in `src/core/talk_work.ts`); `forge talk` prints the same line.
44
4145 ## The crew's line
4246
4347 `/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.
src/core/talk_steps.ts +35 −13
@@ -69,10 +69,11 @@ function filedStep(text: string): Step | undefined {
6969 return { label: cut(`${verb} ${object}${title === "" ? "" : ` ${title}`}`), details: [href] };
7070 }
7171
72 /** A step said done and said while it runs. */
72 /** A step said done, said while it runs, and said as asked for ("merge pull #2"). */
7373 export interface StepWords {
7474 readonly done: string;
7575 readonly running: string;
76 readonly ask: string;
7677 }
7778
7879 /**
@@ -81,35 +82,56 @@ export interface StepWords {
8182 */
8283 export function stepWords(tool: string, args: Record<string, unknown>): StepWords | undefined {
8384 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}`);
85 const both = (done: string, running: string, ask: string): StepWords => ({ done, running, ask });
86 if (tool === "read_file") return path === "" ? both("Read a file", "Reading a file", "read a file") : both(`Read ${path}`, `Reading ${path}`, `read ${path}`);
8687 if (tool === "write_file") {
8788 const content = args["content"];
8889 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 return path === "" ? both(`Edited a file${added}`, "Editing a file", "edit a file") : both(`Edited ${path}${added}`, `Editing ${path}`, `edit ${path}`);
9091 }
9192 const n = typeof args["number"] === "number" && Number.isInteger(args["number"]) && args["number"] > 0 ? `#${String(args["number"])}` : undefined;
9293 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}`);
94 if (tool === "issue") return both(`Opened issue ${n}`, `Opening issue ${n}`, `open issue ${n}`);
95 if (tool === "pull") return both(`Opened pull ${n}`, `Opening pull ${n}`, `open pull ${n}`);
96 if (tool === "merge") return args["dryRun"] === true ? both(`Checked that pull ${n} can merge`, `Checking that pull ${n} can merge`, `check that pull ${n} can merge`) : both(`Merged pull ${n} and deployed`, `Merging pull ${n}`, `merge pull ${n}`);
97 if (tool === "review") return both(`Reviewed pull ${n}`, `Reviewing pull ${n}`, `review pull ${n}`);
98 if (tool === "say") return both(`Commented on ${n}`, `Commenting on ${n}`, `comment on ${n}`);
99 if (tool === "close") return args["state"] === "open" ? both(`Reopened ${n}`, `Reopening ${n}`, `reopen ${n}`) : both(`Closed ${n}`, `Closing ${n}`, `close ${n}`);
100 if (tool === "keep_plan") return both(`Updated the plan on ${n}`, `Updating the plan on ${n}`, `update the plan on ${n}`);
99101 return undefined;
100102 }
101103
102 /** The step a call stands for. */
104 /**
105 * A call that did not end well, as stored (`crew/conversation_calls.ts`): the call and whether the
106 * forge held it for the person's yes or it failed; undefined for anything else.
107 */
108 export function callState(text: string): { readonly call: string; readonly state: "held" | "failed" } | undefined {
109 if (!text.startsWith('{"call"')) return undefined;
110 try {
111 const data = JSON.parse(text) as Record<string, unknown>;
112 const state = data["state"];
113 return typeof data["call"] === "string" && (state === "held" || state === "failed") ? { call: data["call"], state } : undefined;
114 } catch {
115 return undefined;
116 }
117 }
118
119 /** The step a call stands for: done as it was done, held as asked for, failed as not done. */
103120 export function stepOf(text: string): Step | undefined {
104121 const filed = filedStep(text);
105122 if (filed !== undefined) return filed;
106 const call = parseCall(text);
123 // Each stored text is parsed once: the envelope of a call that did not end well, then the call.
124 const ended = callState(text);
125 const call = parseCall(ended?.call ?? text);
107126 if (call === undefined) return undefined;
108127 const { tool, args } = call;
109128 const details = Object.entries(args)
110129 .slice(0, 8)
111130 .map(([k, v]) => `${k.slice(0, 40)}: ${cut(typeof v === "string" ? v : JSON.stringify(v) ?? "")}`);
112 return { label: cut(stepWords(tool, args)?.done ?? words(tool)), details };
131 const said = stepWords(tool, args);
132 if (ended === undefined) return { label: cut(said?.done ?? words(tool)), details };
133 const ask = said?.ask ?? `use ${tool.replaceAll("_", " ")}`;
134 return { label: cut(ended.state === "held" ? `Asked to ${ask}` : `Tried to ${ask}: not done`), details };
113135 }
114136
115137 /**
src/core/talk_work.ts +8 −1
@@ -11,6 +11,7 @@ import type { Database } from "bun:sqlite";
1111 import { getIssue } from "./issues.ts";
1212 import { listTurns } from "./conversations.ts";
1313 import { getRepo, type Repo } from "./repos.ts";
14 import { callState } from "./talk_steps.ts";
1415
1516 /** The part of a turn the reading needs: its role and its stored text. */
1617 export type Said = { readonly role: string; readonly text: string };
@@ -110,7 +111,11 @@ const plural = (n: number, one: string, many: string): string => `${String(n)} $
110111 /** The steps line and links for the tool turns that came before one reply; undefined when there were none. */
111112 export function workOf(turns: readonly Said[], look: Lookup = NOTHING): Work | undefined {
112113 const calls = turns.map(callOf).filter((c): c is Call => c !== undefined);
113 if (calls.length === 0) return undefined;
114 // A call held for the person's yes, or one that failed, changed nothing: said so, never linked.
115 const states = turns.map((t) => (t.role === "tool" ? callState(t.text)?.state : undefined));
116 const held = states.filter((s) => s === "held").length;
117 const failed = states.filter((s) => s === "failed").length;
118 if (calls.length === 0 && held === 0 && failed === 0) return undefined;
114119 const links = new Map<string, string>();
115120 const read = new Set<string>();
116121 const wrote = new Set<string>();
@@ -148,6 +153,8 @@ export function workOf(turns: readonly Said[], look: Lookup = NOTHING): Work | u
148153 if (wrote.size > 0) parts.push(`changed ${plural(wrote.size, "file", "files")}`);
149154 if (opened.size > 0) parts.push(`opened ${named(opened)}`);
150155 if (changed.size > 0) parts.push(`changed ${named(changed)}`);
156 if (held > 0) parts.push(`asked your yes for ${plural(held, "step", "steps")}`);
157 if (failed > 0) parts.push(`${plural(failed, "step", "steps")} not done`);
151158 const rest = [...other];
152159 // One kind of other call is named; several are counted.
153160 if (rest.length === 1) parts.push(`${rest[0]![0].replaceAll("_", " ")}${rest[0]![1] > 1 ? ` ×${String(rest[0]![1])}` : ""}`);
src/crew/agent_runner.ts +1 −1
@@ -74,7 +74,7 @@ export interface AgentRun {
7474 /** The session id, once the init record names it (a restart resumes it). */
7575 readonly onSession?: ((sessionId: string) => void) | undefined;
7676 /** What the agent said or called, as each assistant message arrives. */
77 readonly onSaid?: ((said: { readonly kind: "text" | "tool" | "thinking"; readonly text: string }) => void) | undefined;
77 readonly onSaid?: ((said: { readonly kind: "text" | "tool" | "thinking"; readonly text: string; readonly id?: string }) => void) | undefined;
7878 /**
7979 * What the agent is writing, before `onSaid` reports it whole: text (or thinking) appended to the
8080 * block being written, which may begin as empty text, and a tool call starting and ending, named
src/crew/claude.ts +6 −1
@@ -403,7 +403,12 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
403403 else if (b["type"] === "thinking" && typeof b["thinking"] === "string")
404404 input.onSaid({ kind: "thinking", text: b["thinking"] });
405405 else if (b["type"] === "tool_use" && typeof b["name"] === "string")
406 input.onSaid({ kind: "tool", text: `${b["name"]} ${JSON.stringify(b["input"] ?? {})}` });
406 input.onSaid({
407 kind: "tool",
408 text: `${b["name"]} ${JSON.stringify(b["input"] ?? {})}`,
409 // The id that pairs this call with its start and end (`onDelta`).
410 ...(typeof b["id"] === "string" ? { id: b["id"] } : {}),
411 });
407412 }
408413 }
409414 if (typeof message === "object" && message !== null) {
src/crew/conversation.ts +14 −3
@@ -44,6 +44,7 @@ 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";
4646 import { liveDelta, liveEnd, liveReset, liveSaid } from "./conversation_live.ts";
47 import { callBook } from "./conversation_calls.ts";
4748 import { isRateLimited, takeLimit, whenText } from "./limits.ts";
4849 import { turnBudget } from "./model_access.ts";
4950 import { credentialEnv, holdModelCredential, listenForSteer, steerRun } from "./runner.ts";
@@ -577,6 +578,9 @@ function begin(
577578 if (stored.ok && role === "agent") streamed.push({ id: stored.value.id, text });
578579 };
579580 let lastText = "";
581 // Each call is stored once its result is known, so its step says what it did
582 // (`conversation_calls.ts`).
583 const calls = callBook(app.db, userId, conversation.id, (text) => put("tool", text));
580584 // What the turn said as it went, by turn id, so a provider's refusal
581585 // printed as assistant text can be taken back.
582586 const streamed: { id: string; text: string }[] = [];
@@ -603,6 +607,7 @@ function begin(
603607 let named = false;
604608 liveReset(app.db, conversation.id);
605609 if (session !== undefined) appendRunLog(app.config.dataDir, runId, `resuming session ${session}`);
610 // Whatever the run does (ends, throws, is stopped), the calls it made are stored.
606611 outcome = await runAgent({
607612 binary: options.binary,
608613 cwd,
@@ -639,16 +644,22 @@ function begin(
639644 app.db.query("UPDATE conversation_run SET session_id = ?2 WHERE id = ?1").run(runId, sessionId);
640645 setClaudeSession(app.db, userId, conversation.id, sessionId);
641646 },
642 onDelta: (delta) => liveDelta(app.db, conversation.id, delta),
647 onDelta: (delta) => {
648 liveDelta(app.db, conversation.id, delta);
649 if (delta.kind === "tool") {
650 if (delta.state === "started") calls.started(delta.id, delta.name);
651 else calls.ended(delta.id, delta.name, delta.ok !== false);
652 }
653 },
643654 onSaid: (said) => {
644655 liveSaid(app.db, conversation.id, said.kind, said.text);
645656 if (said.kind === "text") lastText = said.text;
646657 if (said.text.trim() === "") return;
647658 // Thinking is kept as a tool turn of its own shape, so the page can fold it.
648659 if (said.kind === "thinking") put("tool", JSON.stringify({ thinking: said.text.slice(0, THINKING_CHARS) }));
649 else put(said.kind === "text" ? "agent" : "tool", said.text);
660 else if (said.kind !== "tool" || !calls.said(said.text, said.id)) put(said.kind === "text" ? "agent" : "tool", said.text);
650661 },
651 });
662 }).finally(() => calls.flush());
652663 const lost = !outcome.ok && lostSession(outcome.result);
653664 // Only the outcome and the version are kept, never the text or the session (#8795).
654665 if (session !== undefined && !options.signal.aborted)
src/crew/conversation_calls.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * A Talk turn's tool calls, stored once their result is known (#10262), so a step says what the
3 * call did, not that it was made. A runner that reports pieces (`onDelta`) says when a call starts
4 * and ends, and whether it ended well; the call reported whole (`onSaid`) waits here until then,
5 * paired with its start by the runner's id where it gives one. A call that ended well is stored
6 * as it always was (`<tool> <json args>`); one that did not is stored as `{ call, state }`:
7 * `held` when the forge kept that very call (its tool and arguments) for the person's yes during
8 * the call, `failed` otherwise. Each kept call is matched once, so of two same-name calls only
9 * the one that was kept reads as held. A runner that reports no pieces stores each call at once,
10 * as before; a call still waiting when the turn ends, however it ends, is stored as it was said.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import { heldIn } from "../core/fence.ts";
15 import { id as newId } from "../kernel/id.ts";
16 import { parseCall } from "../core/talk_steps.ts";
17
18 const PREFIX = /^mcp__[a-z0-9-]+(?:_[a-z0-9-]+)*__/;
19
20 interface Pending {
21 readonly id: string | undefined;
22 readonly name: string;
23 /**
24 * A mark made as the call began: every hold kept after it has a greater id (ids are monotonic).
25 */
26 readonly mark: string;
27 text?: string;
28 ok?: boolean;
29 }
30
31 export interface Calls {
32 /** A call began (`onDelta` started). */
33 started(id: string | undefined, name: string): void;
34 /**
35 * The call reported whole (`onSaid`), with the runner's id when it gives one: true when it
36 * waits here for its end, false to store it now.
37 */
38 said(text: string, id?: string): boolean;
39 /** The call ended (`onDelta` ended). */
40 ended(id: string | undefined, name: string, ok: boolean): void;
41 /** The turn is over: whatever still waits is stored as it was said. */
42 flush(): void;
43 }
44
45 /** A value with its keys in order, so two spellings of the same arguments compare equal. */
46 const canonical = (v: unknown): unknown =>
47 Array.isArray(v)
48 ? v.map(canonical)
49 : v !== null && typeof v === "object"
50 ? Object.fromEntries(
51 Object.keys(v)
52 .toSorted()
53 .map((k) => [k, canonical((v as Record<string, unknown>)[k])]),
54 )
55 : v;
56
57 const same = (a: unknown, b: unknown): boolean =>
58 JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
59
60 /** The book of one turn's calls; `store` keeps a tool turn's text. */
61 export function callBook(
62 db: Database,
63 userId: string,
64 conversationId: string,
65 store: (text: string) => void,
66 ): Calls {
67 const via = `conversation:${conversationId}`;
68 const pending: Pending[] = [];
69 /** The holds this turn's calls were matched to: each is one call's. */
70 const matched = new Set<string>();
71 /**
72 * Whether the forge kept this very call (its tool and arguments) since it began; the hold is then
73 * this call's.
74 */
75 const held = (p: Pending, text: string): boolean => {
76 const call = parseCall(text);
77 if (call === undefined) return false;
78 const tool = p.name.replace(PREFIX, "");
79 const hold = heldIn(db, via).find(
80 (h) =>
81 !matched.has(h.id) &&
82 h.userId === userId &&
83 h.tool === tool &&
84 h.id > p.mark &&
85 same(h.args, call.args),
86 );
87 if (hold === undefined) return false;
88 matched.add(hold.id);
89 return true;
90 };
91 const emit = (p: Pending): void => {
92 pending.splice(pending.indexOf(p), 1);
93 if (p.text === undefined) return;
94 if (p.ok !== false) return store(p.text);
95 store(
96 JSON.stringify({
97 call: p.text,
98 state: held(p, p.text) ? "held" : "failed",
99 }),
100 );
101 };
102 return {
103 started(id, name) {
104 pending.push({ id, name, mark: newId() });
105 },
106 said(text, id) {
107 const name = text.split(" ", 1)[0] ?? "";
108 const p =
109 id === undefined
110 ? pending.find((c) => c.name === name && c.text === undefined)
111 : pending.find((c) => c.id === id && c.text === undefined);
112 if (p === undefined) return false;
113 p.text = text;
114 if (p.ok !== undefined) emit(p);
115 return true;
116 },
117 ended(id, name, ok) {
118 const p =
119 id === undefined
120 ? pending.find((c) => c.name === name && c.ok === undefined)
121 : pending.find((c) => c.id === id);
122 if (p === undefined) return;
123 p.ok = ok;
124 if (p.text !== undefined) emit(p);
125 },
126 flush() {
127 for (const p of [...pending]) {
128 pending.splice(pending.indexOf(p), 1);
129 if (p.text !== undefined) store(p.text);
130 }
131 },
132 };
133 }
test/talk-steps-truth.test.ts added +321
@@ -0,0 +1,321 @@
1 /**
2 * A step says what the call did, not that it was made (#16207, under #10262). Seen with a real
3 * model: "Merged pull #2 and deployed" for a merge that was only held and then failed. A call is
4 * stored once its result is known: done as it was done, held as "Asked to …" (only the very call
5 * the forge kept, each hold matched once), failed as "Tried to …: not done", and the steps line
6 * and links under a reply count only what was done. The book is driven directly, with real holds
7 * in a real database; one stand-in agent shows a stopped turn still stores the call it was making.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { chmodSync, existsSync, writeFileSync } from "node:fs";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import {
16 appendTurn,
17 createConversation,
18 listTurns,
19 } from "../src/core/conversations.ts";
20 import { hold } from "../src/core/fence.ts";
21 import { createSession } from "../src/core/sessions.ts";
22 import { callState, stepOf } from "../src/core/talk_steps.ts";
23 import { workOf } from "../src/core/talk_work.ts";
24 import { createUser, type User } from "../src/core/users.ts";
25 import { say, stopTurn } from "../src/crew/conversation.ts";
26 import { callBook } from "../src/crew/conversation_calls.ts";
27 import { serve, type Servers } from "../src/http/server.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29 import { waitFor } from "./helpers/poll.ts";
30
31 quietLogs();
32
33 let dir: string;
34 let app: App;
35 let servers: Servers;
36 let alice: User;
37
38 const held = (call: string) => JSON.stringify({ call, state: "held" });
39 const failed = (call: string) => JSON.stringify({ call, state: "failed" });
40
41 /** A fresh conversation of alice's, and a book of its calls that stores into a list. */
42 function book() {
43 const c = createConversation(app.db, alice.id);
44 if (!c.ok) throw new Error(c.error);
45 const stored: string[] = [];
46 const via = `conversation:${c.value.id}`;
47 return {
48 id: c.value.id,
49 via,
50 stored,
51 calls: callBook(app.db, alice.id, c.value.id, (t) => stored.push(t)),
52 };
53 }
54
55 const labels = (texts: readonly string[]) => texts.map((t) => stepOf(t)?.label);
56
57 describe("the words of a step", () => {
58 test("done, held and failed each read as what happened", () => {
59 const merge = 'mcp__forge__merge {"repo":"a/b","number":2,"dryRun":false}';
60 expect(stepOf(merge)?.label).toBe("Merged pull #2 and deployed");
61 expect(stepOf(held(merge))?.label).toBe("Asked to merge pull #2");
62 expect(stepOf(failed(merge))?.label).toBe(
63 "Tried to merge pull #2: not done",
64 );
65 expect(stepOf(failed('mcp__forge__knobs {"knob":"autonomy"}'))?.label).toBe(
66 "Tried to use knobs: not done",
67 );
68 expect(stepOf(held(merge))?.details).toContain("number: 2");
69 expect(callState(merge)).toBeUndefined();
70 });
71
72 test("the steps line and links count only what was done", () => {
73 const tool = (text: string) => ({ role: "tool", text });
74 const work = workOf([
75 tool('mcp__forge__issue {"repo":"a/b","number":1}'),
76 tool(held('mcp__forge__merge {"repo":"a/b","number":2,"dryRun":false}')),
77 tool(failed('mcp__forge__close {"repo":"a/b","number":3}')),
78 ]);
79 expect(work?.steps).toBe(
80 "opened #1, asked your yes for 1 step, 1 step not done",
81 );
82 expect(work?.links.map((l) => l.label)).toEqual(["a/b #1"]);
83 });
84 });
85
86 beforeAll(async () => {
87 dir = await mkdtemp(join(tmpdir(), "forge-steps-truth-"));
88 app = createApp({ dataDir: dir, port: 0 });
89 servers = await serve(app);
90 const u = await createUser(app.db, {
91 origin: "seed",
92 trusted: true,
93 username: "alice",
94 email: "[email protected]",
95 password: "a-good-passphrase",
96 adminIfFirst: true,
97 });
98 if (!u.ok) throw new Error(u.error);
99 alice = u.value;
100 }, 30_000);
101
102 afterAll(async () => {
103 servers.stop();
104 app.close();
105 await rm(dir, { recursive: true, force: true });
106 });
107
108 describe("a turn's calls, stored once their result is known", () => {
109 const merge = (n: number) =>
110 `mcp__forge__merge {"repo":"alice/steps","number":${n},"dryRun":false}`;
111
112 test("of two merges in one turn, only the one the forge kept reads as held, whichever ends first", () => {
113 for (const order of [
114 ["t1", "t2"],
115 ["t2", "t1"],
116 ] as const) {
117 const b = book();
118 b.calls.started("t1", "mcp__forge__merge");
119 b.calls.started("t2", "mcp__forge__merge");
120 b.calls.said(merge(1), "t1");
121 b.calls.said(merge(2), "t2");
122 // The forge kept the first merge for the person's yes; the second was refused.
123 if (
124 hold(app.db, b.via, alice.id, "merge", {
125 repo: "alice/steps",
126 number: 1,
127 dryRun: false,
128 }) === null
129 )
130 throw new Error("hold");
131 for (const id of order) b.calls.ended(id, "mcp__forge__merge", false);
132 const byCall = Object.fromEntries(
133 b.stored.map((t) => [callState(t)!.call, callState(t)!.state]),
134 );
135 expect(byCall).toEqual({ [merge(1)]: "held", [merge(2)]: "failed" });
136 }
137 });
138
139 test("one hold is one call's: a second identical call that fails is not held by it", () => {
140 const b = book();
141 b.calls.started("a", "mcp__forge__merge");
142 b.calls.said(merge(1), "a");
143 if (
144 hold(app.db, b.via, alice.id, "merge", {
145 number: 1,
146 repo: "alice/steps",
147 dryRun: false,
148 }) === null
149 )
150 throw new Error("hold");
151 b.calls.ended("a", "mcp__forge__merge", false);
152 b.calls.started("b", "mcp__forge__merge");
153 b.calls.said(merge(1), "b");
154 b.calls.ended("b", "mcp__forge__merge", false);
155 expect(labels(b.stored)).toEqual([
156 "Asked to merge pull #1",
157 "Tried to merge pull #1: not done",
158 ]);
159 });
160
161 test("a hold made before the call began, or for other arguments, is not this call's", () => {
162 const b = book();
163 if (
164 hold(app.db, b.via, alice.id, "merge", {
165 repo: "alice/steps",
166 number: 1,
167 dryRun: false,
168 }) === null
169 )
170 throw new Error("hold");
171 b.calls.started("a", "mcp__forge__merge");
172 b.calls.said(merge(1), "a");
173 if (
174 hold(app.db, b.via, alice.id, "merge", {
175 repo: "alice/steps",
176 number: 9,
177 dryRun: false,
178 }) === null
179 )
180 throw new Error("hold");
181 b.calls.ended("a", "mcp__forge__merge", false);
182 expect(labels(b.stored)).toEqual(["Tried to merge pull #1: not done"]);
183 });
184
185 test("two same-name calls in flight keep their own words, paired by the runner's id", () => {
186 const b = book();
187 b.calls.started("x", "mcp__forge__merge");
188 b.calls.started("y", "mcp__forge__merge");
189 // The whole calls arrive in the other order from their starts.
190 b.calls.said(merge(2), "y");
191 b.calls.said(merge(1), "x");
192 b.calls.ended("x", "mcp__forge__merge", true);
193 b.calls.ended("y", "mcp__forge__merge", false);
194 expect(labels(b.stored)).toEqual([
195 "Merged pull #1 and deployed",
196 "Tried to merge pull #2: not done",
197 ]);
198 });
199
200 test("a call still waiting when the turn ends is stored as it was said", () => {
201 const b = book();
202 b.calls.started("z", "mcp__forge__merge");
203 expect(b.calls.said(merge(3), "z")).toBe(true);
204 expect(b.stored).toEqual([]);
205 b.calls.flush();
206 expect(b.stored).toEqual([merge(3)]);
207 });
208
209 test("the page draws a held call as asked and a failed one as not done, never as done", async () => {
210 const b = book();
211 appendTurn(app.db, alice.id, b.id, { role: "person", text: "tidy up" });
212 appendTurn(app.db, alice.id, b.id, {
213 role: "tool",
214 text: held('mcp__forge__archive {"repo":"alice/steps","archived":true}'),
215 });
216 appendTurn(app.db, alice.id, b.id, {
217 role: "tool",
218 text: failed('mcp__forge__close {"repo":"alice/steps","number":99}'),
219 });
220 appendTurn(app.db, alice.id, b.id, {
221 role: "agent",
222 text: "Done what I could.",
223 });
224 const page = await (
225 await fetch(`${servers.url}/talk/${b.id}`, {
226 headers: {
227 cookie: `forge_session=${createSession(app.db, alice.id).token}`,
228 },
229 })
230 ).text();
231 expect(page).toContain("Asked to use archive");
232 expect(page).toContain("Tried to close #99: not done");
233 expect(page).not.toContain("Closed #99");
234 });
235 });
236
237 describe("a stopped turn", () => {
238 test("still stores the call it was making when the person stopped it", async () => {
239 const sid = "s-stop";
240 const marker = join(dir, "calling");
241 const line = (o: unknown) => `printf '%s\\n' '${JSON.stringify(o)}'`;
242 const bin = join(dir, "agent-stop");
243 writeFileSync(
244 bin,
245 [
246 "#!/bin/sh",
247 'if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi',
248 "IFS= read -r first",
249 line({
250 type: "system",
251 subtype: "init",
252 session_id: sid,
253 model: "fake",
254 }),
255 line({
256 type: "stream_event",
257 session_id: sid,
258 event: {
259 type: "content_block_start",
260 index: 0,
261 content_block: {
262 type: "tool_use",
263 id: "t1",
264 name: "mcp__forge__merge",
265 input: {},
266 },
267 },
268 }),
269 line({
270 type: "assistant",
271 session_id: sid,
272 message: {
273 id: "m1",
274 content: [
275 {
276 type: "tool_use",
277 id: "t1",
278 name: "mcp__forge__merge",
279 input: { repo: "alice/steps", number: 4 },
280 },
281 ],
282 usage: { input_tokens: 1, output_tokens: 1 },
283 },
284 }),
285 `touch "${marker}"`,
286 "sleep 30",
287 "",
288 ].join("\n"),
289 );
290 chmodSync(bin, 0o755);
291 const c = createConversation(app.db, alice.id);
292 if (!c.ok) throw new Error(c.error);
293 const said = say(
294 app,
295 {
296 binary: bin,
297 localUrl: servers.url,
298 budgetUsd: 1,
299 timeoutMs: 30_000,
300 signal: new AbortController().signal,
301 liveMax: 100,
302 },
303 alice.id,
304 "merge 4",
305 [],
306 "inject",
307 c.value.id,
308 );
309 if (!said.ok || !("done" in said.value)) throw new Error("say");
310 expect(await waitFor(() => existsSync(marker))).toBe(true);
311 expect(stopTurn(app, alice.id)).toBe(true);
312 await said.value.done;
313 const turns = listTurns(app.db, alice.id, c.value.id, { limit: 50 });
314 const tools = (turns.ok ? turns.value : [])
315 .filter((t) => t.role === "tool")
316 .map((t) => t.text);
317 expect(tools).toContain(
318 'mcp__forge__merge {"repo":"alice/steps","number":4}',
319 );
320 });
321 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs