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

A Talk answer that fails says which call failed and why, in the pane #17900

opened this

Merged 21h ago, live in production

scout/forge:scout/17887-a-talk-answer-that-fails-says-which-call → main 0 commits fork

  • Merged. scout/17887-a-talk-answer-that-fails-says-which-call was merged into main as f29a578.

Review

Sign in to review this change.
7 files changed +128 −29
docs/features/talk.md +4
@@ -358,3 +358,7 @@ What the page says is someone else's text. It reaches the agent fenced, like an
358358 ## The context meter
359359
360360 The meter says how full the model that answered really is: its window comes from the run, else from the table in `src/crew/model_windows.ts`. A model that table does not know shows its token count and no percentage. The page and the terminal use the same words (`contextText`).
361
362 ## When an answer fails
363
364 A turn that could not answer says which call failed (the model and the account, `the default model` when none was chosen) and why (timed out, refused, rate limit, or an error class), then offers Retry. Each fact is said once: where the turn's own words already give the cause (a rest, a spent credit, a timeout) only the call is added; where they name the call but not the cause (a chosen model that did not answer) only the cause is. The words come from the same outcome the `talk model call` log line carries (`src/crew/call_line.ts`). They never show a key, the provider's message or a status body. The page and the terminal show the same stored turn.
src/crew/call_line.ts +36
@@ -42,3 +42,39 @@ export function callFields(end: CallEnd): LogFields {
4242 outcome: callOutcome(end),
4343 };
4444 }
45
46 /** What each class of ending says as a cause; an error's class is added to its words. */
47 const CAUSES: Readonly<Record<string, string>> = {
48 timed_out: "it ran out of time",
49 refused: "the provider refused it (its credit is spent)",
50 limit: "the account hit a rate limit",
51 };
52
53 /**
54 * The cause in plain words, from `callOutcome`'s own string; empty for a call that answered or was
55 * stopped on purpose.
56 */
57 function causeOf(outcome: string): string {
58 const known = CAUSES[outcome];
59 if (known !== undefined) return known;
60 return outcome.startsWith("error:") ? `the account or model returned an error (${outcome.slice(6)})` : "";
61 }
62
63 /**
64 * What of the call a pane line says: both, only which call (its text already has the cause), or
65 * only the cause (its text already names the call).
66 */
67 export type CallSays = "both" | "call" | "cause";
68
69 /**
70 * The pane's last line for a failed call (#17887), read from `callOutcome`'s own string so the log
71 * and the pane never classify twice. Never the provider's message, a key or a status body: the
72 * class only. Empty for a call that answered or was stopped on purpose.
73 */
74 export function causeWords(outcome: string, account: string, model: string, says: CallSays = "both"): string {
75 const cause = causeOf(outcome);
76 if (cause === "") return "";
77 const call = `${model === "default" ? "the default model" : model} on ${account}`;
78 if (says === "cause") return `Why: ${cause}.`;
79 return says === "call" ? `Which call failed: ${call}.` : `Which call failed: ${call}; ${cause}.`;
80 }
src/crew/conversation.ts +25 −21
@@ -65,7 +65,7 @@ import {
6565 type RunnerLimit,
6666 } from "./agent_runner.ts";
6767 import { runAccount } from "./runner_env.ts";
68 import { callFields } from "./call_line.ts";
68 import { callFields, callOutcome, causeWords, type CallEnd, type CallSays } from "./call_line.ts";
6969 import { CONVERSATION_BRIEF } from "./conversation_brief.ts";
7070 import { liveDelta, liveEnd, liveReset, liveSaid } from "./conversation_live.ts";
7171 import { callBook } from "./conversation_calls.ts";
@@ -939,18 +939,20 @@ function begin(
939939 let outcome: AgentOutcome | undefined;
940940 let unlisten = (): void => {};
941941 // One line per call to the runner, written as it ends or throws (#17825).
942 const logCall = (startedAt: number, result: AgentOutcome | undefined): void =>
943 app.log.info(
944 "talk model call",
945 callFields({
946 account: on !== undefined ? on.name : picked.kind === "ready" ? picked.subscription.name : PLATFORM,
947 model: (on !== undefined ? choice!.model : options.model) ?? "default",
948 ms: performance.now() - startedAt,
949 outcome: result,
950 refused: result?.ok === false && (creditSpent(result.result) || creditSpent(streamed.at(-1)?.text ?? "")),
951 stopped: stopper.signal.aborted || options.signal.aborted,
952 }),
953 );
942 const endOf = (startedAt: number, result: AgentOutcome | undefined): CallEnd => ({
943 account: on !== undefined ? on.name : picked.kind === "ready" ? picked.subscription.name : PLATFORM,
944 model: (on !== undefined ? choice!.model : options.model) ?? "default",
945 ms: performance.now() - startedAt,
946 outcome: result,
947 refused: result?.ok === false && (creditSpent(result.result) || creditSpent(streamed.at(-1)?.text ?? "")),
948 stopped: stopper.signal.aborted || options.signal.aborted,
949 });
950 // The last call's end, kept so the pane's failed line says what the log line says.
951 let lastEnd: CallEnd | undefined;
952 const logCall = (startedAt: number, result: AgentOutcome | undefined): void => {
953 lastEnd = endOf(startedAt, result);
954 app.log.info("talk model call", callFields(lastEnd));
955 };
954956 try {
955957 const cwd = turnDir(app.config.dataDir);
956958 const configDir = sessionsDir(app.config.dataDir, options.configDir);
@@ -1111,9 +1113,11 @@ function begin(
11111113 const answer = outcome?.result ?? "";
11121114 // A turn that could not answer says so in plain words, flagged so the page draws Retry;
11131115 // whatever the provider or process printed, streamed as text, is taken back first.
1114 const couldNot = (text: string, raw: (said: string) => boolean): void => {
1116 const couldNot = (text: string, raw: (said: string) => boolean, says?: CallSays): void => {
11151117 for (const turn of streamed) if (raw(turn.text)) removeTurn(app.db, userId, conversation.id, turn.id);
1116 appendTurn(app.db, userId, conversation.id, { role: "agent", text, failed: true });
1118 // What the text leaves unsaid of the call, said once (#17887): see `CallSays`.
1119 const why = says === undefined || lastEnd === undefined ? "" : causeWords(callOutcome(lastEnd), lastEnd.account, lastEnd.model, says);
1120 appendTurn(app.db, userId, conversation.id, { role: "agent", text: why === "" ? text : `${text}\n${why}`, failed: true });
11171121 };
11181122 // A chosen model that did not answer says so on this turn, with Retry and the picker: nothing
11191123 // else answers for it. Its connection's state is its own test's to say, never a turn's: one
@@ -1126,24 +1130,24 @@ function begin(
11261130 // the add form says it, with the hosts it reaches and the ask to allow this one.
11271131 const gated = new URL(on.base!).hostname;
11281132 const refusedByGate = (outcome?.result ?? "").includes(new GateRefusedError(gated).message);
1129 couldNot(refusedByGate ? blockedText(modelHostBlocked(app, person, gated)) : failedOnLine(on.name, choice!.model), (said) => said === outcome?.result);
1133 couldNot(refusedByGate ? blockedText(modelHostBlocked(app, person, gated)) : failedOnLine(on.name, choice!.model), (said) => said === outcome?.result, refusedByGate ? undefined : "cause");
11301134 } else if (toolless.signal.aborted) couldNot(NO_TOOLS_LINE, () => true);
1131 else if (outcome === undefined) couldNot(failureLine("error"), () => false);
1135 else if (outcome === undefined) couldNot(failureLine("error"), () => false, "both");
11321136 // The model door's own refusal (402: this forge's credit from its parent is spent): an error
11331137 // result whose words, or whose last streamed text, are the door's. One plain kept line
11341138 // instead, through the held path's words. An answer that only quotes them is an answer.
11351139 else if (!outcome.ok && (creditSpent(outcome.result) || creditSpent(streamed.at(-1)?.text ?? "")))
1136 couldNot(heldLine({ code: "credit_spent" }), (said) => said === outcome!.result || (said === streamed.at(-1)?.text && creditSpent(said)));
1140 couldNot(heldLine({ code: "credit_spent" }), (said) => said === outcome!.result || (said === streamed.at(-1)?.text && creditSpent(said)), "call");
11371141 else if (isRateLimited(outcome)) {
11381142 const first = outcome.result.split("\n").find((l) => l.trim() !== "")?.trim() ?? "";
1139 couldNot(limitLine(app, picked, outcome.limit), (said) => said === outcome!.result || (first !== "" && said.includes(first)));
1143 couldNot(limitLine(app, picked, outcome.limit), (said) => said === outcome!.result || (first !== "" && said.includes(first)), "call");
11401144 } else if (!outcome.ok && endedOnLimit(outcome.reason)) {
11411145 // Cut off by its own limit: said so plainly, flagged so the page draws Go on, not Retry.
11421146 for (const turn of streamed) if (turn.text === outcome.result) removeTurn(app.db, userId, conversation.id, turn.id);
11431147 appendTurn(app.db, userId, conversation.id, { role: "agent", text: LIMIT_LINE, failed: true, limited: true });
1144 } else if (!outcome.ok) couldNot(failureLine(outcome.reason), (said) => said === outcome!.result);
1148 } else if (!outcome.ok) couldNot(failureLine(outcome.reason), (said) => said === outcome!.result, outcome.reason === "timeout" ? "call" : "both");
11451149 else if (answer.trim() !== "" && answer !== lastText) put("agent", answer);
1146 else if (answer.trim() === "" && lastText === "") couldNot(failureLine("error"), () => false);
1150 else if (answer.trim() === "" && lastText === "") couldNot(failureLine("error"), () => false, "both");
11471151 // Where the line went (#13942): each issue a tell opened, on every outcome; the plain word
11481152 // that none was only when the turn answered.
11491153 for (const text of filedTurns(app.db, via, prompt, outcome?.ok === true && !toolless.signal.aborted)) put("tool", text);
test/conversation-turn.test.ts +3 −3
@@ -432,7 +432,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to
432432 expect(token.length).toBeGreaterThan(10);
433433 expect(verifyToken(app.db, token).ok).toBe(false);
434434 expect(viaTokens()).toBe(0);
435 expect(turns(alice).at(-1)).toBe("agent:I could not answer that just now.");
435 expect(turns(alice).at(-1)).toBe("agent:I could not answer that just now.\nWhich call failed: the default model on platform; the account or model returned an error (exit_1).");
436436 });
437437
438438 test("a binary that is not there fails the turn and revokes its token", async () => {
@@ -471,7 +471,7 @@ echo '{"type":"result","subtype":"success","is_error":true,"result":"You have hi
471471 expect(said.ok).toBe(true);
472472 if (said.ok) await said.value.done;
473473 const line = turns(alice).at(-1)!;
474 expect(line).toMatch(/^agent:home is resting until \d\d:\d\d UTC\.$/);
474 expect(line).toMatch(/^agent:home is resting until \d\d:\d\d UTC\.\nWhich call failed: the default model on home\.$/);
475475 expect(turns(alice).filter((t) => t.includes("session limit"))).toEqual([]);
476476 const rested = getSubscription(app.db, account.value.id)!;
477477 expect(rested.restingUntil).not.toBeNull();
@@ -497,7 +497,7 @@ echo '{"type":"result","subtype":"success","is_error":true,"result":"You have hi
497497 const said = say(app, options(limitedStub("platform-limited")), alice.id, "on the platform?");
498498 expect(said.ok).toBe(true);
499499 if (said.ok) await said.value.done;
500 expect(turns(alice).at(-1)).toMatch(/^agent:The forge's own model window is full until \d\d:\d\d UTC; try again then\.$/);
500 expect(turns(alice).at(-1)).toMatch(/^agent:The forge's own model window is full until \d\d:\d\d UTC; try again then\.\nWhich call failed: the default model on platform\.$/);
501501 expect(turns(alice).filter((t) => t.includes("session limit"))).toEqual([]);
502502 const noted = app.db.query<{ span: string }, [string]>("SELECT span FROM subscription_limit WHERE subscription_id = ?1").all(PLATFORM);
503503 expect(noted.map((r) => r.span)).toEqual(["5h"]);
test/talk-call-line.test.ts +57 −2
@@ -8,12 +8,13 @@ import { mkdtemp, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
11 import { createConversation, setClaudeSession } from "../src/core/conversations.ts";
11 import { createConversation, listTurns, setClaudeSession } from "../src/core/conversations.ts";
1212 import { saveConnection, removeConnection } from "../src/core/connections.ts";
1313 import { setChoice } from "../src/core/model_choice.ts";
14 import { createSession } from "../src/core/sessions.ts";
1415 import { createUser, type User } from "../src/core/users.ts";
1516 import { useRunner, type AgentOutcome } from "../src/crew/agent_runner.ts";
16 import { callOutcome } from "../src/crew/call_line.ts";
17 import { callOutcome, causeWords } from "../src/crew/call_line.ts";
1718 import { say, type ConversationOptions } from "../src/crew/conversation.ts";
1819 import { serve, type Servers } from "../src/http/server.ts";
1920 import { teeLines } from "../src/kernel/log.ts";
@@ -145,3 +146,57 @@ test("a call that answered stays answered even when a stop came after", () => {
145146 expect(callOutcome({ outcome: base, refused: false, stopped: true })).toBe("answered");
146147 expect(callOutcome({ outcome: { ...base, ok: false, reason: "cancelled" }, refused: false, stopped: true })).toBe("stopped");
147148 });
149
150 /** The last turn the pane shows after one call that ends as `end`. */
151 const lastTurn = async (end: Partial<AgentOutcome> | "throw") => {
152 next = end;
153 const conversation = createConversation(app.db, user.id);
154 if (!conversation.ok) throw new Error(conversation.error);
155 await sayIn(conversation.value.id);
156 const turns = listTurns(app.db, user.id, conversation.value.id);
157 if (!turns.ok) throw new Error(turns.error);
158 return { turn: turns.value.at(-1)!, conversationId: conversation.value.id };
159 };
160
161 test("a failed answer's last line names the call and the cause once, and the page draws Retry after it (#17887)", async () => {
162 const cases: [Partial<AgentOutcome> | "throw", string][] = [
163 [{ ok: false, reason: "timeout", result: "" }, "Which call failed: haiku on platform."],
164 [{ ok: false, reason: "error", result: "API Error: 402 credit" }, "Which call failed: haiku on platform."],
165 [{ ok: false, reason: "error", result: "x", limit: { said: "5 hour limit" } }, "Which call failed: haiku on platform."],
166 [{ ok: false, reason: "exit 1", result: "SECRET-STDERR" }, "Which call failed: haiku on platform; the account or model returned an error (exit_1)."],
167 ["throw", "Which call failed: haiku on platform; the account or model returned an error (threw)."],
168 ];
169 for (const [end, last] of cases) {
170 const { turn, conversationId } = await lastTurn(end);
171 expect(turn.failed).toBe(true);
172 expect(turn.text.split("\n").at(-1)).toBe(last);
173 // One way to say a thing: the cause is in the line above or in this one, never both.
174 const causes = turn.text.match(/rate limit|refused it|ran out of time|returned an error/g) ?? [];
175 expect(causes.length === 0 || causes.length === 1).toBe(true);
176 for (const secret of ["PRIVATE-PROMPT", "SECRET-STDERR", "SECRET-ERROR", "API Error"]) expect(turn.text).not.toContain(secret);
177 // The page draws the same stored turn, with Retry under it.
178 const page = await (await fetch(`${servers.url}/talk?conversation=${conversationId}`, { headers: { cookie: `forge_session=${createSession(app.db, user.id).token}` } })).text();
179 expect(page).toContain("Which call failed: haiku on platform");
180 expect(page).toContain('data-again="retry"');
181 expect(page.indexOf('data-again="retry"')).toBeGreaterThan(page.indexOf("Which call failed"));
182 }
183 });
184
185 test("a call that answered adds no cause line, and a stopped one is not a failed call", async () => {
186 const { turn } = await lastTurn({});
187 expect(turn.failed).toBe(false);
188 expect(turn.text).not.toContain("Which call failed");
189 expect(causeWords("stopped", "a", "m")).toBe("");
190 });
191
192 test("the pane's words are the log line's outcome, said in words", () => {
193 expect(causeWords("answered", "a", "m")).toBe("");
194 expect(causeWords("stopped", "a", "m")).toBe("");
195 expect(causeWords("limit", "work", "opus")).toBe("Which call failed: opus on work; the account hit a rate limit.");
196 expect(causeWords("timed_out", "work", "opus")).toBe("Which call failed: opus on work; it ran out of time.");
197 expect(causeWords("refused", "work", "opus")).toBe("Which call failed: opus on work; the provider refused it (its credit is spent).");
198 expect(causeWords("error:exit_1", "work", "opus")).toBe("Which call failed: opus on work; the account or model returned an error (exit_1).");
199 expect(causeWords("error:exit_1", "work", "opus", "call")).toBe("Which call failed: opus on work.");
200 expect(causeWords("error:exit_1", "work", "opus", "cause")).toBe("Why: the account or model returned an error (exit_1).");
201 expect(causeWords("timed_out", "platform", "default")).toBe("Which call failed: the default model on platform; it ran out of time.");
202 });
test/talk-model-choice.test.ts +2 −2
@@ -303,7 +303,7 @@ describe("a turn on a chosen model", () => {
303303 expect(setChoice(app.db, bob, c, `${spark().id} canned/small`).ok).toBe(true);
304304 answers = [() => new Response("upstream down", { status: 502 })];
305305 const turns = await turn(bob, c, "still there?");
306 expect(turns.at(-1)).toMatchObject({ role: "agent", text: failedOnLine("Spark", "canned/small"), failed: true });
306 expect(turns.at(-1)).toMatchObject({ role: "agent", text: `${failedOnLine("Spark", "canned/small")}\nWhy: the account or model returned an error (error).`, failed: true });
307307 expect(turns.filter((t) => t.role === "agent")).toHaveLength(1);
308308 expect(defaults).toHaveLength(0);
309309 // Nothing shared moved: Spark is working and offered, to keeper and to bob.
@@ -342,7 +342,7 @@ describe("a turn on a chosen model", () => {
342342 .run(own.value.id, `https://127.0.0.1:${String(canned.port)}/v1`);
343343 const turns = await turn(bob, c, "hi");
344344 expect(turns.at(-1)).toMatchObject({
345 text: failedOnLine("Bobs", "m1"),
345 text: `${failedOnLine("Bobs", "m1")}\nWhy: the account or model returned an error (error).`,
346346 failed: true,
347347 });
348348 expect(heard).toHaveLength(0);
test/ui-663-talk-and-merges.test.ts +1 −1
@@ -142,7 +142,7 @@ echo '{"type":"result","subtype":"success","is_error":true,"result":"API Error:
142142 : [];
143143 expect(shown.join("\n")).not.toContain("API Error");
144144 expect(shown.at(-1)).toBe(
145 "agent!:The model credit this forge's parent lends it is spent, so nothing could answer. Your message is kept for Retry. The parent forge's admin can raise it.",
145 "agent!:The model credit this forge's parent lends it is spent, so nothing could answer. Your message is kept for Retry. The parent forge's admin can raise it.\nWhich call failed: the default model on platform.",
146146 );
147147 expect(shown).toContain("person:what is happening on voxel?");
148148 });

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

Keyboard shortcuts

Docs