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

A Talk reply names its model, and a turn that reaches its limit says so and offers to go on #17842

opened this

Merged 34h 14m ago, live in production

mason/forge:mason/17827-a-talk-reply-names-its-model-and-a-turn → main 0 commits fork 3 threads · 3 unresolved

  • Merged. mason/17827-a-talk-reply-names-its-model-and-a-turn was merged into main as 01d8b2c.

Review

Sign in to review this change.
9 files changed +245 −13
docs/features/talk-stop.md +9
@@ -11,3 +11,12 @@ While an answer is being written on `/talk`, **Stop** ends it with one tap.
1111 - The spend is counted once: the run's row holds it and the turn list carries it a single time.
1212 - In the terminal, `ssh ... talk <words>` prints the same line (`Stopped: $X spent so far`) for the turn before, in place of `last turn $X`; one helper words both.
1313 - A turn cut before its result is priced from the usage it streamed, each component at its own rate: input $3, cache writes $3.75, cache reads $0.30 and output $15 per million tokens (an estimate; a result's own cost replaces it).
14
15 ## A turn that reached its limit (#17827)
16
17 A turn that ends on its own turn or token limit is not mistaken for a finished one: its reply says
18 "I stopped here because this turn reached its limit, so this is not finished", and a **Go on**
19 button under it sends "Go on." into the same conversation (`src/web/pages/talk.ts`, `goOnForm`;
20 the terminal's chat screen, `src/tui/screens/talk_chats.ts`, marks it and you send Go on). One press
21 starts one turn; nothing repeats by itself. Under each reply the small line names the model it ran
22 on when the run recorded one; older replies show none.
src/core/conversations.ts +16 −3
@@ -46,6 +46,11 @@ export interface Turn {
4646 readonly replaced: boolean;
4747 /** The line saying a run could not answer; the page draws Retry beside it. */
4848 readonly failed: boolean;
49 /**
50 * The reply that says the turn stopped at its own turn or token limit; the page draws Go on
51 * beside it.
52 */
53 readonly limited?: boolean;
4954 }
5055
5156 interface ConversationRow {
@@ -67,6 +72,7 @@ interface TurnRow {
6772 created_at: string;
6873 replaced_at: string | null;
6974 failed: number;
75 limited: number;
7076 }
7177
7278 const conversationOf = (r: ConversationRow): Conversation => ({
@@ -88,6 +94,7 @@ const turnOf = (r: TurnRow): Turn => ({
8894 createdAt: r.created_at,
8995 replaced: r.replaced_at !== null,
9096 failed: r.failed === 1,
97 limited: r.limited === 1,
9198 });
9299
93100 /** Most conversations a person holds, archived ones included; past it, New is refused. */
@@ -268,7 +275,12 @@ export function appendTurn(
268275 db: Database,
269276 userId: string,
270277 conversationId: string,
271 input: { readonly role: string; readonly text: string; readonly failed?: boolean },
278 input: {
279 readonly role: string;
280 readonly text: string;
281 readonly failed?: boolean;
282 readonly limited?: boolean;
283 },
272284 ): Result<Turn, "not_found" | "bad_role" | "empty_text" | "text_too_long"> {
273285 if (!owned(db, userId, conversationId)) return err("not_found");
274286 if (!(TURN_ROLES as readonly string[]).includes(input.role)) return err("bad_role");
@@ -283,10 +295,11 @@ export function appendTurn(
283295 created_at: now,
284296 replaced_at: null,
285297 failed: input.failed === true ? 1 : 0,
298 limited: input.limited === true ? 1 : 0,
286299 };
287300 db.query(
288 "INSERT INTO conversation_turn (id, conversation_id, role, text, created_at, failed) VALUES (?1,?2,?3,?4,?5,?6)",
289 ).run(row.id, row.conversation_id, row.role, row.text, row.created_at, row.failed);
301 "INSERT INTO conversation_turn (id, conversation_id, role, text, created_at, failed, limited) VALUES (?1,?2,?3,?4,?5,?6,?7)",
302 ).run(row.id, row.conversation_id, row.role, row.text, row.created_at, row.failed, row.limited);
290303 db.query("UPDATE conversation SET updated_at = ?2 WHERE id = ?1").run(conversationId, now);
291304 db.query(
292305 "DELETE FROM conversation_turn WHERE conversation_id = ?1 AND rowid < (SELECT rowid FROM conversation_turn WHERE conversation_id = ?1 ORDER BY rowid DESC LIMIT 1 OFFSET ?2)",
src/core/migration-pins/20261203040000-turn-limited.pin added +1
@@ -0,0 +1,1 @@
1 d3f15ec1136cc6ea5c3323b925a104471b67cfd73b19d287dc5c96640c5c505a
src/core/migrations/20261203040000-turn-limited.ts added +5
@@ -0,0 +1,5 @@
1 // A reply that ended on the turn's own turn or token limit says so and offers Go on (#17827): the
2 // turn carries the flag. Additive; every turn before this reads 0, so none is called cut off.
3 export default `
4 ALTER TABLE conversation_turn ADD COLUMN limited INTEGER NOT NULL DEFAULT 0;
5 `;
src/crew/conversation.ts +28 −3
@@ -55,7 +55,15 @@ import { running } from "../kernel/version.ts";
5555 import { err, ok, type Result } from "../kernel/result.ts";
5656 import { storedText } from "../kernel/blocked.ts";
5757 import { appendRunLog } from "../runs/log.ts";
58 import { currentRunner, runAgent, type AgentOutcome, type HistoryTurn, type RunnerLimit } from "./agent_runner.ts";
58 import {
59 BUDGET_REACHED,
60 TURNS_REACHED,
61 currentRunner,
62 runAgent,
63 type AgentOutcome,
64 type HistoryTurn,
65 type RunnerLimit,
66 } from "./agent_runner.ts";
5967 import { runAccount } from "./runner_env.ts";
6068 import { CONVERSATION_BRIEF } from "./conversation_brief.ts";
6169 import { liveDelta, liveEnd, liveReset, liveSaid } from "./conversation_live.ts";
@@ -806,6 +814,17 @@ function carryOn(app: App, options: ConversationOptions, conversation: Conversat
806814 if (started.ok) started.value.catch((error: unknown) => app.log.error("carried-on turn crashed", { error: String(error) }));
807815 }
808816
817 /**
818 * What a reply says when the turn stopped at its own turn or token limit: cut off, not finished.
819 */
820 export const LIMIT_LINE =
821 "I stopped here because this turn reached its limit, so this is not finished. " +
822 "Press Go on to continue in this conversation.";
823
824 /** Whether a run ended because it used every turn or all the budget it was given. */
825 export const endedOnLimit = (reason: string): boolean =>
826 reason === TURNS_REACHED || reason === "error_max_turns" || reason === BUDGET_REACHED;
827
809828 /** What a run that did not end well says to the person: what happened, never the raw error. */
810829 export function failureLine(reason: string): string {
811830 if (reason === "timeout") return "That took longer than a turn may, so I stopped.";
@@ -883,8 +902,10 @@ function begin(
883902 "INSERT INTO conversation_run (id, conversation_id, user_id, subscription_id, prompt, resumes, session_id, started_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
884903 )
885904 .run(runId, conversation.id, userId, subscriptionId, prompt, resumes, resumeSession ?? "", now.toISOString());
886 // The model the turn ran on, for the line under its reply.
887 if (on !== undefined) app.db.query("UPDATE conversation_run SET model = ?2 WHERE id = ?1").run(runId, choice!.model);
905 // The model the turn ran on, for the line under its reply: the chosen one, else the one the forge
906 // was set to run; none is stored when neither is named, never a guess.
907 const ranOn = on !== undefined ? choice!.model : (options.model ?? "");
908 if (ranOn !== "") app.db.query("UPDATE conversation_run SET model = ?2 WHERE id = ?1").run(runId, ranOn);
888909 live.set(conversation.id, runId);
889910 const stopper = new AbortController();
890911 stoppers.set(conversation.id, { runId, userId, stop: () => stopper.abort() });
@@ -1090,6 +1111,10 @@ function begin(
10901111 else if (isRateLimited(outcome)) {
10911112 const first = outcome.result.split("\n").find((l) => l.trim() !== "")?.trim() ?? "";
10921113 couldNot(limitLine(app, picked, outcome.limit), (said) => said === outcome!.result || (first !== "" && said.includes(first)));
1114 } else if (!outcome.ok && endedOnLimit(outcome.reason)) {
1115 // Cut off by its own limit: said so plainly, flagged so the page draws Go on, not Retry.
1116 for (const turn of streamed) if (turn.text === outcome.result) removeTurn(app.db, userId, conversation.id, turn.id);
1117 appendTurn(app.db, userId, conversation.id, { role: "agent", text: LIMIT_LINE, failed: true, limited: true });
10931118 } else if (!outcome.ok) couldNot(failureLine(outcome.reason), (said) => said === outcome!.result);
10941119 else if (answer.trim() !== "" && answer !== lastText) put("agent", answer);
10951120 else if (answer.trim() === "" && lastText === "") couldNot(failureLine("error"), () => false);
src/tui/screens/talk_chats.ts +4 −1
@@ -458,8 +458,11 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
458458 const said = t.role === "agent" ? pathRefs(forgeNames(plainVoice(t.text, cards)), refs) : t.text;
459459 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)));
460460 n += own.length + 2;
461 const state = t.limited === true
462 ? " · stopped at its limit: send Go on to continue"
463 : t.failed ? " · failed: Retry on the page, or talk-again retry" : "";
461464 return [
462 [{ text: `${t.id === around ? "▶ " : ""}${WHO[t.role] ?? t.role}${t.replaced ? " · replaced" : ""}${t.failed ? " · failed: Retry on the page, or talk-again retry" : ""} · ${ago(t.createdAt)}`, style: style(c.mutedFg, c.bg) }],
465 [{ text: `${t.id === around ? "▶ " : ""}${WHO[t.role] ?? t.role}${t.replaced ? " · replaced" : ""}${state} · ${ago(t.createdAt)}`, style: style(c.mutedFg, c.bg) }],
463466 ...own.map((l) => [{ text: l, style: style(c.fg, c.bg) }]),
464467 [],
465468 ];
src/web/pages/talk.ts +14 −1
@@ -336,6 +336,13 @@ const linksFold = (links: Work["links"]): Html => {
336336 const againForm = (base: string, how: "regenerate" | "retry", label: string, words: string, turn?: string): Html =>
337337 html`<form method="post" action="${base}/again/${how}" data-again="${how}">${turn === undefined ? null : html`<input type="hidden" name="turn" value="${turn}">`}${how === "retry" ? btn(label, { icon: "sync", label: words }) : iconBtn("sync", words, { variant: "ghost", extra: "talk-act" })}</form>`;
338338
339 /** What Go on sends: the continuation, one press, one turn, in the same conversation. */
340 export const GO_ON = "Go on.";
341
342 /** Go on as a form, so it works without the script: it sends `GO_ON` to the conversation once. */
343 const goOnForm = (conversationId: string): Html =>
344 html`<form method="post" action="${HERE}/${conversationId}" data-go-on><input type="hidden" name="text" value="${GO_ON}" />${btn("Go on", { icon: "play", label: "Go on: continue where the turn stopped" })}</form>`;
outdated

Go on uses the same sync icon as Retry, so the two controls look the same. Use a forward icon.

345
339346 /**
340347 * What the last exchange offers, by the turn it sits under: Edit under the
341348 * person's last message, and under the last turn Retry when it failed or
@@ -348,7 +355,8 @@ export function exchangeActs(db: Database, userId: string, conversationId: strin
348355 if (person === undefined) return acts;
349356 acts.set(person.id, html`<a class="btn btn-icon talk-act" data-variant="ghost" href="${base}?edit=1#compose" data-act="edit" aria-label="Edit your last message" title="Edit your last message">${icon("pencil")}</a>`);
350357 const last = after.at(-1);
351 if (last?.failed === true) acts.set(last.id, againForm(base, "retry", "Retry", "Retry the failed turn", last.id));
358 if (last?.limited === true) acts.set(last.id, goOnForm(conversationId));
359 else if (last?.failed === true) acts.set(last.id, againForm(base, "retry", "Retry", "Retry the failed turn", last.id));
352360 else if (last?.role === "agent") acts.set(last.id, againForm(base, "regenerate", "Regenerate", "Regenerate the last reply"));
353361 return acts;
354362 }
@@ -401,6 +409,11 @@ export function turnHtml(turn: Turn, waiting: ReadonlySet<string>, cost?: Spend,
401409 ${files.length === 0 ? null : html`<p class="talk-files">${files.map((f) => html`<a class="badge" href="/api/v1/conversation/files/${f.id}" download>${f.name}</a>`)}</p>`}
402410 ${label("You")}${acts}
403411 </li>`;
412 if (turn.role === "agent" && turn.limited === true)
413 return html`<li class="talk-turn talk-agent talk-limited${set}" id="${id}" data-limited>
414 <div class="talk-body">${turn.text}</div>
415 ${acts}
416 </li>`;
404417 if (turn.role === "agent" && turn.failed)
405418 return html`<li class="talk-turn talk-agent talk-failed${set}" id="${id}" role="alert">
406419 <div class="talk-body">${turn.text}</div>
test/talk-conversations.test.ts +12 −5
@@ -150,12 +150,20 @@ describe("the MCP", () => {
150150 });
151151 });
152152
153 /**
154 * A turn written straight to a database at an older schema, where appendTurn's newer columns do not
155 * exist.
156 */
157 function oldTurn(db: ReturnType<typeof openDb>, id: string, text: string): void {
158 db.query("INSERT INTO conversation_turn (id, conversation_id, role, text, created_at) VALUES (?1,'c1','person',?2,'t')").run(id, text);
159 }
160
153161 describe("the migration", () => {
154162 test("a person's one conversation, its turns and runs come through the table rebuild", () => {
155163 const db = openDb(join(dir, "before.db"), migrations.slice(0, -1));
156164 db.query("INSERT INTO user (id, username, email, password_hash) VALUES ('u1','u1','u1@x','x')").run();
157165 db.query("INSERT INTO conversation (id, user_id, claude_session_id, created_at, updated_at) VALUES ('c1','u1','s','t','t')").run();
158 for (const n of [1, 2, 3]) appendTurn(db, "u1", "c1", { role: "person", text: `t${n}` });
166 for (const n of [1, 2, 3]) oldTurn(db, `turn${n}`, `t${n}`);
159167 db.query("INSERT INTO conversation_run (id, conversation_id, user_id, prompt, started_at) VALUES ('r1','c1','u1','p','t')").run();
160168 db.close();
161169 const after = openDb(join(dir, "before.db"), migrations);
@@ -176,12 +184,11 @@ describe("the migration keeps attachments", () => {
176184 const db = openDb(path, migrationFiles.slice(0, at).map((m) => m.sql));
177185 db.query("INSERT INTO user (id, username, email, password_hash) VALUES ('u1','u1','u1@x','x')").run();
178186 db.query("INSERT INTO conversation (id, user_id, claude_session_id, created_at, updated_at) VALUES ('c1','u1','s','t','t')").run();
179 const turn = appendTurn(db, "u1", "c1", { role: "person", text: "see" });
180 if (!turn.ok) throw new Error("no turn");
181 db.query("INSERT INTO conversation_file (id, conversation_id, user_id, turn_id, name, type, size, created_at) VALUES ('f1','c1','u1',?1,'a.png','image/png',3,'t')").run(turn.value.id);
187 oldTurn(db, "turn1", "see");
188 db.query("INSERT INTO conversation_file (id, conversation_id, user_id, turn_id, name, type, size, created_at) VALUES ('f1','c1','u1',?1,'a.png','image/png',3,'t')").run("turn1");
182189 db.close();
183190 const after = openDb(path, migrations);
184 expect(after.query("SELECT conversation_id, turn_id, name FROM conversation_file").all()).toEqual([{ conversation_id: "c1", turn_id: turn.value.id, name: "a.png" }]);
191 expect(after.query("SELECT conversation_id, turn_id, name FROM conversation_file").all()).toEqual([{ conversation_id: "c1", turn_id: "turn1", name: "a.png" }]);
185192 after.close();
186193 });
187194 });
test/talk-limit.test.ts added +156
@@ -0,0 +1,156 @@
1 /**
2 * A turn that reached its limit says so and offers Go on; a normal one does not (#17827). Two
3 * replies from two models show two names; an older reply with none shows none.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { appendTurn, createConversation, listTurns, newConversation } from "../src/core/conversations.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { useRunner, type AgentOutcome } from "../src/crew/agent_runner.ts";
14 import { endedOnLimit, LIMIT_LINE, say, type ConversationOptions } from "../src/crew/conversation.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let app: App;
22 let servers: Servers;
23 let alice: User;
24
25 const page = async (id: string): Promise<string> =>
26 (await fetch(`${servers.url}/talk/${id}`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } })).text();
27
28 beforeAll(async () => {
29 dir = await mkdtemp(join(tmpdir(), "forge-talk-limit-"));
30 app = createApp({ dataDir: dir, port: 0 });
31 servers = await serve(app);
32 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
33 if (!u.ok) throw new Error("seed");
34 alice = u.value;
35 });
36 afterAll(async () => {
37 await servers.stop();
38 await rm(dir, { recursive: true, force: true });
39 });
40
41 describe("a turn that reached its limit", () => {
42 test("names the turn and token limits, and nothing else", () => {
43 expect(endedOnLimit("max_turns")).toBe(true);
44 expect(endedOnLimit("max_budget_reached")).toBe(true);
45 expect(endedOnLimit("timeout")).toBe(false);
46 expect(endedOnLimit("error")).toBe(false);
47 });
48
49 test("renders the line and one Go on form; a normal reply renders neither", async () => {
50 const cut = newConversation(app.db, alice.id);
51 appendTurn(app.db, alice.id, cut.id, { role: "person", text: "do the long thing" });
52 appendTurn(app.db, alice.id, cut.id, { role: "agent", text: LIMIT_LINE, failed: true, limited: true });
53 const html = await page(cut.id);
54 expect(html).toContain("reached its limit");
55 expect(html.match(/data-go-on/g)?.length).toBe(1);
56 expect(html).toContain('name="text" value="Go on."');
57 expect(html).not.toContain('data-again="retry"');
58
59 const fine = newConversation(app.db, alice.id);
60 appendTurn(app.db, alice.id, fine.id, { role: "person", text: "hi" });
61 appendTurn(app.db, alice.id, fine.id, { role: "agent", text: "hello" });
62 const normal = await page(fine.id);
63 expect(normal).not.toContain("reached its limit");
64 expect(normal).not.toContain("data-go-on");
65 });
66 });
67
68 describe("a reply names its model", () => {
69 test("two replies from two models show two names; an older one shows none", async () => {
70 const c = newConversation(app.db, alice.id);
71 const base = Date.now() - 60_000;
72 const reply = (n: number, model: string): void => {
73 const at = base + n * 10_000;
74 appendTurn(app.db, alice.id, c.id, { role: "person", text: `q${n}` });
75 const said = appendTurn(app.db, alice.id, c.id, { role: "agent", text: `answer ${n}` });
76 if (!said.ok) throw new Error(said.error);
77 app.db.query("UPDATE conversation_turn SET created_at = ?2 WHERE id = ?1").run(said.value.id, new Date(at).toISOString());
78 app.db
79 .query("INSERT INTO conversation_run (id, conversation_id, user_id, prompt, state, model, started_at, finished_at) VALUES (?1,?2,?3,'x','ok',?4,?5,?6)")
80 .run(`r${n}`, c.id, alice.id, model, new Date(at - 1000).toISOString(), new Date(at + 1000).toISOString());
81 };
82 reply(0, "");
83 reply(1, "model-alpha");
84 reply(2, "model-beta");
85 const html = await page(c.id);
86 expect(html).toContain("model-alpha");
87 expect(html).toContain("model-beta");
88 expect(html.match(/class="talk-cost /g)?.length).toBe(2);
89 });
90 });
91
92 describe("through a real turn", () => {
93 const options = (model?: string): ConversationOptions => ({
94 binary: "unused",
95 localUrl: servers.url,
96 budgetUsd: 1,
97 timeoutMs: 30_000,
98 signal: new AbortController().signal,
99 ...(model === undefined ? {} : { model }),
100 });
101 const outcome = (reason: string, ok: boolean, result: string): AgentOutcome => ({
102 ok, sessionId: "s1", result, costUsd: 0.01, turns: 3, tokensIn: 5, tokensOut: 5, contextTokens: 5, contextWindow: 0, reason,
103 });
104 /**
105 * One turn with a fake runner that streams `streamed`, then ends as `end`; the turns and the
106 * run's model.
107 */
108 const run = async (model: string | undefined, streamed: string, end: AgentOutcome) => {
109 useRunner({
110 run: async (input) => {
111 input.onSaid?.({ kind: "text", text: streamed });
112 return end;
113 },
114 detect: async () => ({ ok: true, version: "fake" }),
115 resumes: true,
116 });
117 const made = createConversation(app.db, alice.id);
118 if (!made.ok) throw new Error(made.error);
119 const said = say(app, options(model), alice.id, "do the long thing", [], "queue", made.value.id);
120 if (!said.ok) throw new Error(said.error);
121 if (said.value.how === "started") await said.value.done;
122 useRunner(undefined);
123 const turns = listTurns(app.db, alice.id, made.value.id, { limit: 50 });
124 if (!turns.ok) throw new Error("turns");
125 const ran = app.db.query("SELECT model FROM conversation_run WHERE conversation_id = ?1").get(made.value.id) as { model: string };
126 return { id: made.value.id, turns: turns.value, model: ran.model };
127 };
128
129 test.each(["max_turns", "max_budget_reached"])("a run ending on %s stores the limit line, flagged, and drops its partial text", async (reason) => {
130 const got = await run(undefined, "Half done so far", outcome(reason, false, "Half done so far"));
131 const agent = got.turns.filter((t) => t.role === "agent");
132 expect(agent.map((t) => t.text)).toEqual([LIMIT_LINE]);
133 expect(agent[0]?.limited).toBe(true);
134 expect(got.turns.some((t) => t.text === "Half done so far")).toBe(false);
135 expect(await page(got.id)).toContain("data-go-on");
136 });
137
138 test("another failure is not called a limit", async () => {
139 const got = await run(undefined, "x", outcome("error", false, "boom"));
140 const agent = got.turns.filter((t) => t.role === "agent");
141 expect(agent.some((t) => t.limited === true)).toBe(false);
142 expect(agent.at(-1)?.failed).toBe(true);
143 });
144
145 test("the run records the model the forge was set to run when none was picked, and nothing when none is named", async () => {
146 expect((await run("forge-default-model", "ok", outcome("completed", true, "ok"))).model).toBe("forge-default-model");
147 expect((await run(undefined, "ok", outcome("completed", true, "ok"))).model).toBe("");
148 });
149
150 test("a reply with no run row at all shows no model line", async () => {
151 const c = newConversation(app.db, alice.id);
152 appendTurn(app.db, alice.id, c.id, { role: "person", text: "hi" });
153 appendTurn(app.db, alice.id, c.id, { role: "agent", text: "hello" });
154 expect(await page(c.id)).not.toContain('class="talk-cost ');
155 });
156 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs