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

A kept message is a successful send at every door: 202 kept, with why and when (#16471) #16593

Merged opened this

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

Merged

fix/talk-kept-is-202 → main 0 commits 3 threads · 3 unresolved

  • Merged. fix/talk-kept-is-202 was merged into main as f411bbe.

Review

Sign in to review this change.
21 files changed +263 −91
docs/features/talk-kept-message.md +30 −8
@@ -17,9 +17,9 @@ draws **Retry**:
1717 - the agent cannot run on this forge (no sandbox): an admin sees the cause;
1818 - the forge is starting (a woken cell waits for the forge it replaces before its agent runs, which
1919 has taken minutes): "This forge is starting; its agent answers within a few minutes. Your message
20 is kept; Retry then." The API answers `starting` (503) with that line and the seconds left of the
21 boot as `Retry-After`; a Retry pressed before the agent is up is refused as `starting` and stores
22 nothing more;
20 is kept; Retry then." The API answers it as a kept send (202, `why` `starting`) with the seconds left
21 of the boot as `Retry-After`; a Retry pressed before the agent is up is refused as `starting` and
22 stores nothing more;
2323 - the forge's agent is not running (off, with no agent coming): Retry once it runs;
2424 - a forge its parent lends model credit to has spent it (before the turn, or mid-answer): who can raise it (the parent forge's admin), never the raw "API Error: 402" (#16455).
2525
@@ -28,9 +28,31 @@ Messages queued behind one that cannot start are kept too, in the order they wer
2828 **Retry** sends the kept message again, once: the failed line is set aside and the same words start a
2929 new turn. The page says "Your message is kept. Tap Retry under it when you are ready." (`src/web/pages/talk.ts`).
3030 In the terminal's Talk (`src/tui/screens/talk_chats.ts`) the line shows with " · failed", and
31 `ssh <forge> talk-again retry <turn>` retries it; the API keeps its codes (`resting` 429, `busy`
32 429, ...), and the kept turns are in `GET /api/v1/conversation/turns`.
31 `ssh <forge> talk-again retry <turn>` retries it.
3332
34 Code: `heldLine` and `isHeld` in `src/crew/conversation.ts`; the starting line is
35 `src/crew/starting_line.ts`, kept by `keepUnstarted`, as an off one is. Tests: `test/conversation-turn.test.ts`,
36 `test/talk-kept-message.test.ts`, `test/talk-starting.test.ts`.
33 ## What a client gets
34
35 A kept message is a send that succeeded, so every door answers it as one:
36
37 - `POST /api/v1/conversation/messages` answers **202** with `{ "how": "kept", "why", "message",
38 "turn", "until" }`: `message` is the line, `turn` the kept message's own turn. `why` is
39 `resting` (a spent lent credit too), `busy`, `answering`, `no_account`, `sandbox`,
40 `unauthorized`, `off` or `starting`; `starting` adds `Retry-After`, the seconds left of the
41 boot. `until` is there only when the account said when it wakes. With `no_account` the body
42 also carries `says` and `ask`, the call that asks an admin for one.
43 - The MCP `say` tool returns a result (not an error) whose `says` is the line, with `kept: true`,
44 `why`, `turn` and `until`.
45 - `ssh <forge> talk <words>` prints `kept: <the line>` and exits 0.
46 - A build's first message (`POST /api/v1/builds`, MCP `say` with `action: "build"`) answers
47 `said`, `message` and `kept`.
48
49 A refusal that keeps nothing stays an error: an empty or overlong message, no such conversation,
50 more than 12 a minute, a full queue, a file already waiting, or no signed-in person.
51
52 **Retry, edit and regenerate** keep nothing new: one that cannot start puts the exchange back as it
53 was and is refused with why (the page's flash, `{ ok: false, message }` with its status, and
54 `ssh <forge> talk-again` exiting 1), never "Asked again" (#16593).
55
56 Code: `heldLine`, `Kept` and `keepUnstarted` in `src/crew/conversation.ts`; the starting line
57 is `src/crew/starting_line.ts`. Tests: `test/conversation-turn.test.ts`,
58 `test/talk-kept-message.test.ts`, `test/conversation-talk.test.ts`, `test/talk-starting.test.ts`.
src/actions/build.ts +17 −5
@@ -31,7 +31,7 @@ import { createBranch } from "./branches.ts";
3131 import { ensureBuildPull, type Version, versionsIn } from "./build_pull.ts";
3232 import { mergePull } from "./pulls.ts";
3333 import { deleteRepo } from "./repos.ts";
34 import { talk, type TalkRefusal } from "./talk.ts";
34 import { TALK_WORDS, talk } from "./talk.ts";
3535
3636 export { VERSIONS_MAX, type Version } from "./build_pull.ts";
3737
@@ -81,16 +81,27 @@ export const BUILD_WORDS: Readonly<Record<string, string>> = {
8181 /** A prompt as a one-line title. */
8282 const titleOf = (prompt: string): string => prompt.replace(/\s+/g, " ").trim().slice(0, TITLE_MAX);
8383
84 /** Why a build's first message did not start, and the words for it. */
85 export interface BuildSaid {
86 readonly why: string;
87 readonly message: string;
88 /** Kept with its line (Retry sends it), rather than refused. */
89 readonly kept: boolean;
90 }
91
92 /** The sentence a page or the terminal says after a build whose first message did not start. */
93 export const buildSaidWords = (said: BuildSaid): string => (said.kept ? `The app is made. ${said.message}` : `The app is made, but ${said.message}.`);
94
8495 /**
8596 * Make the repository from the template, start the chat on its branch and
86 * send the prompt. `said` is the refusal when the agent could not take the
87 * words (no account, resting): the build still exists and the person can send again.
97 * send the prompt. `said` is set when the agent did not start on it: kept with its line (resting,
98 * busy, no account…; Retry sends it), or refused (rate limited…). The build exists either way.
8899 */
89100 export async function startBuild(
90101 app: App,
91102 actor: User | undefined,
92103 input: { readonly prompt: string; readonly template?: string },
93 ): Promise<Result<{ build: ChatBuild; repo: Repo; said: TalkRefusal | undefined }, BuildError>> {
104 ): Promise<Result<{ build: ChatBuild; repo: Repo; said: BuildSaid | undefined }, BuildError>> {
94105 const user = requireUser(actor);
95106 if (!user.ok) return user;
96107 const template = input.template === undefined || input.template === "" ? undefined : input.template;
@@ -117,7 +128,8 @@ export async function startBuild(
117128 const build = startChatBuild(app.db, conversation.value.id, made.repo.id);
118129 renameConversation(app.db, user.value.id, conversation.value.id, titleOf(input.prompt));
119130 const said = talk(app, user.value, input.prompt, [], "queue", conversation.value.id);
120 return ok({ build, repo: made.repo, said: said.ok ? undefined : said.error });
131 const kept = said.ok ? said.value.kept : undefined;
132 return ok({ build, repo: made.repo, said: kept !== undefined ? { why: kept.why, message: kept.line, kept: true } : said.ok ? undefined : { why: said.error, message: TALK_WORDS[said.error][1], kept: false } });
121133 }
122134
123135 /** The build of one of the person's own conversations, with the repository it is in. */
src/actions/talk.ts +3 −3
@@ -32,7 +32,6 @@ export const TALK_WORDS: Readonly<Record<TalkRefusal, readonly [number, string]>
3232 too_long: [422, "the message is too long"],
3333 no_account: [403, storedText(NO_TALK_ACCOUNT, "an admin of this forge", "grant one")],
3434 resting: [429, "the account that serves you is resting or out of budget; try again later"],
35 answering: [409, "the forge is still answering; send pictures when it has finished"],
3635 busy: [429, "the forge's agent is answering as many people as it can at once; try again in a minute"],
3736 off: [503, "the forge's agent is not running here"],
3837 starting: [503, STARTING_LINE],
@@ -71,10 +70,11 @@ export function talk(app: App, user: User | undefined, text: string, files: read
7170 const options = conversationOptions(app);
7271 if (options === undefined) {
7372 // No agent yet: a woken forge configures it after waiting for the one it replaces (starting),
74 // or none is coming (off). Either way the message is kept with its line, never lost.
73 // or none is coming (off). Either way the message is kept with its line, never lost: a send
74 // that succeeded, as every kept one is.
7575 const why = startingIn(app) === undefined ? "off" : "starting";
7676 const kept = keepUnstarted(app, user.id, text, files, conversationId, why);
77 return kept.ok ? err(why) : kept;
77 return kept.ok ? ok({ how: "kept", kept: kept.value }) : kept;
7878 }
7979 const said = say(app, options, user.id, text, files, during, conversationId, about);
8080 if (said.ok) watch(app, said.value);
src/contract/openapi/routes/postApiV1ConversationMessages.ts +1 −4
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "post",
55 path: "/api/v1/conversation/messages",
66 summary: "Say something to the forge's own agent, as the signed-in person",
7 detail: "Say something to the forge's own agent, as the signed-in person: it answers through the forge's MCP with that person's permissions, resuming their conversation; a message sent while it answers is handed to the turn, or with `during` (optional) set to `queue` waits for it (at most 5), or set to `steer` stops it and goes at once; answers 202 at once, read the answer from the turns; at most 12 a minute per person",
7 detail: "Say something to the forge's own agent, as the signed-in person: it answers through the forge's MCP with that person's permissions, resuming their conversation; a message sent while it answers is handed to the turn, or with `during` (optional) set to `queue` waits for it (at most 5), or set to `steer` stops it and goes at once; answers 202 at once, read the answer from the turns; at most 12 a minute per person. A message that cannot start now (the account resting or out of credit, the forge busy, no model account, the agent not running) is kept with a line saying why and answers 202 too, as { how: \"kept\", why, message, turn, until? } (until: when the account wakes, where known; with no account the body also carries says and ask); a refusal that keeps nothing (an empty or overlong message, no such conversation, too many a minute) stays an error",
88 auth: true,
99 role: "member",
1010 status: 202,
@@ -17,10 +17,7 @@ export const route: Route = {
1717 file_taken: "an attached file already waits in a queued message (409)",
1818 queue_full: "five messages already wait (429)",
1919 too_large: "the body is over 128000 bytes (413)",
20 no_account: "no model account is granted to the person (403); the body carries `says` and `ask`, the call that asks an admin for one",
21 resting: "the account that serves the person is resting or out of budget (429)",
2220 rate_limited: "more than 12 messages in a minute (429)",
23 off: "the forge's agent is not running here (503)",
2421 forbidden: "the request is cross-origin",
2522 },
2623 refuses: [401, 422],
src/crew/conversation.ts +33 −13
@@ -337,20 +337,36 @@ export function mcpConfig(localUrl: string): string {
337337 });
338338 }
339339
340 export type SayRefusal = "not_found" | "unauthorized" | "empty" | "too_long" | "no_account" | "resting" | "busy" | "answering" | "queue_full" | "file_taken" | "sandbox";
340 /**
341 * What `say` refuses: only what keeps nothing. A message that cannot start now is kept (`Kept`).
342 */
343 export type SayRefusal = "not_found" | "unauthorized" | "empty" | "too_long" | "queue_full" | "file_taken";
341344
342345 export interface Said {
343346 /**
344347 * `started` a new turn, `steered` words into the one running, `queued` for after it, or
345348 * `interrupted` it to send these at once.
346349 */
347 readonly how: "started" | "steered" | "queued" | "interrupted" | "answered";
350 readonly how: "started" | "steered" | "queued" | "interrupted" | "answered" | "kept";
348351 /** Settles when the turn does; only a started turn has one. */
349352 readonly done?: Promise<void>;
350353 /** The queue id of a `queued` message, to cancel it by. */
351354 readonly queued?: string;
352355 /** The text of an `answered` message, so a door with no page (the terminal) prints it at once. */
353356 readonly answer?: string;
357 /** A `kept` message: why no turn started, the line under it, its turn, and until when. */
358 readonly kept?: Kept;
359 }
360
361 /**
362 * A message kept with its line because no turn could start now (#16431): the send succeeded, the
363 * answer waits on Retry. `why` is the door's code; `until` when the account wakes, where known.
364 */
365 export interface Kept {
366 readonly why: HeldRefusal | "off" | "starting";
367 readonly line: string;
368 readonly turn: string;
369 readonly until?: string;
354370 }
355371
356372 /**
@@ -507,9 +523,12 @@ export function say(
507523 const refuse = (why: HeldRefusal | NotStarted): Result<Said, SayRefusal> => {
508524 const reason = typeof why === "string" ? { code: why } : why;
509525 release(app.db, stored.value.id);
510 appendTurn(app.db, userId, conversation.id, { role: "agent", text: heldLine(reason), failed: true });
511 // The doors keep their codes: a spent lent credit is a resting account to them.
512 return err(reason.code === "credit_spent" ? "resting" : reason.code);
526 const line = heldLine(reason);
527 appendTurn(app.db, userId, conversation.id, { role: "agent", text: line, failed: true });
528 // Kept is a success of the send: the doors answer it as such, with why (a spent lent credit is
outdated

refuse is shared by redo, so every caller of redo now gets ok for a kept message. Each one must be taught to read kept, or redo must keep returning the refusal for a retry. A test must pin whichever you choose.

529 // a resting account to them), the line, the turn and, where known, until when.
530 const until = "until" in reason && typeof reason.until === "string" ? { until: reason.until } : {};
531 return ok({ how: "kept", kept: { why: reason.code === "credit_spent" ? "resting" : reason.code, line, turn: stored.value.id, ...until } });
513532 };
514533 const delivery = deliver(app.config.dataDir, userId, files);
515534 const running = live.get(conversation.id);
@@ -541,7 +560,11 @@ export const CONTEXT_FULL = 0.85;
541560 export const CONTEXT_RENEWED_LINE = "This thread's context was nearly full, so I continue in a fresh session from its record and your standing rules.";
542561
543562 export type RedoHow = "edit" | "regenerate" | "retry";
544 export type RedoRefusal = SayRefusal | "running" | "nothing";
563 /**
564 * What `redo` refuses. A Retry, edit or regenerate that cannot start puts the exchange back as it
565 * was and says why (#16593): nothing new is kept, so it is never answered as a success.
566 */
567 export type RedoRefusal = SayRefusal | "running" | "nothing" | "busy" | Exclude<NotStarted["code"], "credit_spent">;
545568
546569 /**
547570 * Ask again, in place of the last exchange (#8817). `edit` replaces the
@@ -637,10 +660,6 @@ export type HeldRefusal = "resting" | "busy" | "answering" | "no_account" | "san
637660
638661 /** The model door answered 402, as Claude Code prints it: the credit a parent lends is spent. */
639662 const creditSpent = (text: string): boolean => /\bAPI Error: 402\b/.test(text);
640 const HELD: ReadonlySet<string> = new Set<HeldRefusal>(["resting", "busy", "answering", "no_account", "sandbox", "unauthorized"]);
641
642 /** Whether a refusal is one a message is kept through, with its line and Retry (#16431). */
643 export const isHeld = (code: string): code is HeldRefusal => HELD.has(code);
644663
645664 /**
646665 * A message the forge cannot hand to its agent at all right now is kept, as any message that cannot
@@ -648,7 +667,7 @@ export const isHeld = (code: string): code is HeldRefusal => HELD.has(code);
648667 * why and when to Retry. `starting`: a woken forge has yet to configure its agent (#16486);
649668 * `off`: no agent is coming (#16455). Nothing is kept for an empty or overlong message.
650669 */
651 export function keepUnstarted(app: App, userId: string, text: string, files: readonly ConversationFile[], conversationId: string | undefined, why: "starting" | "off"): Result<true, "empty" | "too_long" | "not_found"> {
670 export function keepUnstarted(app: App, userId: string, text: string, files: readonly ConversationFile[], conversationId: string | undefined, why: "starting" | "off"): Result<Kept, "empty" | "too_long" | "not_found"> {
652671 if (text.trim() === "") return err("empty");
653672 if (text.length > WORDS_MAX) return err("too_long");
654673 const conversation = conversationId === undefined ? openConversation(app.db, userId) : getConversation(app.db, userId, conversationId);
@@ -657,8 +676,9 @@ export function keepUnstarted(app: App, userId: string, text: string, files: rea
657676 if (!stored.ok) return err("too_long");
658677 attach(app.db, files, stored.value.id);
659678 release(app.db, stored.value.id);
660 appendTurn(app.db, userId, conversation.id, { role: "agent", text: why === "starting" ? STARTING_LINE : heldLine({ code: "off" }), failed: true });
661 return ok(true);
679 const line = why === "starting" ? STARTING_LINE : heldLine({ code: "off" });
680 appendTurn(app.db, userId, conversation.id, { role: "agent", text: line, failed: true });
681 return ok({ why, line, turn: stored.value.id });
662682 }
663683
664684 /** Why a turn did not start: the refusal, and what the account said and until when, where known. */
src/http/api/conversation_build.ts +1 −2
@@ -8,7 +8,6 @@
88
99 import { BUILD_WORDS, buildState, publishBuild, restoreVersion, startBuild, versionDiff, type BuildError } from "../../actions/build.ts";
1010 import { BUILD_ID as ID, promptRefusal, templateRefusal, versionRefusal } from "../../actions/build_input.ts";
11 import { TALK_WORDS } from "../../actions/talk.ts";
1211 import { apiError, boundedBody, json, tryAgain, unauthorized } from "../respond.ts";
1312 import type { Router } from "../router.ts";
1413 import type { Handler } from "../context.ts";
@@ -38,7 +37,7 @@ export function conversationBuildRoutes(router: Router<Handler>): void {
3837 const started = await startBuild(ctx.app, user, { prompt, ...(template === undefined ? {} : { template }) });
3938 if (!started.ok) return fail(started.error);
4039 const { build, repo, said } = started.value;
41 return json({ conversation: build.conversationId, repo: `${repo.ownerName}/${repo.name}`, branch: build.branch, ...(said === undefined ? {} : { said, message: TALK_WORDS[said][1] }) }, 201);
40 return json({ conversation: build.conversationId, repo: `${repo.ownerName}/${repo.name}`, branch: build.branch, ...(said === undefined ? {} : { said: said.why, message: said.message, kept: said.kept }) }, 201);
4241 });
4342
4443 const named = (id: string | undefined): string | undefined => (id !== undefined && ID.test(id) ? id : undefined);
src/http/api/conversation_talk.ts +17 −4
@@ -101,12 +101,25 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
101101 const said = talk(ctx.app, user, text, files.value, during === "queue" ? "queue" : during === "steer" ? "interrupt" : "inject", named, typeof input["about"] === "string" ? input["about"] : null);
102102 if (!said.ok) {
103103 const [status, words] = TALK_WORDS[said.error];
104 if (said.error === "no_account") return json({ error: said.error, message: words, ...blockedFields(noTalkAccountBlocked(ctx.app, user)) }, status);
105 // While the forge starts, the line is the kept one and the wait is what is left of its boot,
106 // read once, as Retry-After alone.
107 if (said.error === "starting") return tryAgain(said.error, 503, words, startingIn(ctx.app) ?? 10);
108104 return status === 429 || status === 503 ? tryAgain(said.error, status, words, talkWait(said.error)) : json({ error: said.error, message: words }, status);
109105 }
106 // Kept is a success: the message is in the conversation; the body says why it did not start,
107 // the line under it, its turn and until when, so a client never reads it as lost.
108 const kept = said.value.kept;
109 if (kept !== undefined)
110 return json(
111 {
112 how: "kept",
113 why: kept.why,
114 message: kept.line,
115 turn: kept.turn,
116 ...(kept.until === undefined ? {} : { until: kept.until }),
117 ...(kept.why === "no_account" ? blockedFields(noTalkAccountBlocked(ctx.app, user)) : {}),
118 },
119 202,
120 // While the forge starts, about when to Retry: what is left of its boot, read once.
121 kept.why === "starting" ? { "retry-after": String(startingIn(ctx.app) ?? 10) } : {},
122 );
110123 return json(said.value.queued === undefined ? { how: said.value.how } : { how: said.value.how, queued: said.value.queued }, 202);
111124 });
112125
src/http/mcp/tools/say.ts +4 −4
@@ -1,6 +1,4 @@
11 import { mayView } from "../../../core/sealed.ts";
2 import { badBlocked } from "../shared.ts";
3 import { noTalkAccountBlocked } from "../../../actions/blocked_words.ts";
42 import { addCommentThrough } from "../../../actions/issues.ts";
53 import { getIssue } from "../../../core/issues.ts";
64 import { archiveConversation, createConversation, findConversations, getConversation, listConversations, renameConversation, TOO_MANY_WORDS } from "../../../core/conversations.ts";
@@ -67,7 +65,7 @@ export const tool: Tool = {
6765 const started = await startBuild(ctx.app, user, { prompt, ...(template === undefined ? {} : { template }) });
6866 if (!started.ok) return buildBad(started.error);
6967 const { build, repo, said } = started.value;
70 return good({ conversation: build.conversationId, repo: `${repo.ownerName}/${repo.name}`, branch: build.branch, ...(said === undefined ? {} : { said, message: TALK_WORDS[said][1] }) });
68 return good({ conversation: build.conversationId, repo: `${repo.ownerName}/${repo.name}`, branch: build.branch, ...(said === undefined ? {} : { said: said.why, message: said.message, kept: said.kept }) });
7169 }
7270 const id = str(args["conversation"]);
7371 if (!BUILD_ID.test(id)) return buildBad("not_found");
@@ -123,8 +121,10 @@ export const tool: Tool = {
123121 if (text.trim() === "" || text.length > WORDS_MAX) return bad("invalid_text", `text is 1 to ${WORDS_MAX} characters`);
124122 const named = args["conversation"] === undefined ? undefined : str(args["conversation"]);
125123 const talked = talk(ctx.app, user, text, [], "inject", named);
126 if (!talked.ok && talked.error === "no_account") return badBlocked("no_account", noTalkAccountBlocked(ctx.app, user));
127124 if (!talked.ok) return bad(talked.error, TALK_WORDS[talked.error][1]);
125 // Kept: the message is in the conversation, and its line says why it did not start.
126 const kept = talked.value.kept;
127 if (kept !== undefined) return good({ says: kept.line, kept: true, why: kept.why, turn: kept.turn, ...(kept.until === undefined ? {} : { until: kept.until }) });
128128 return good({ says: talked.value.how === "steered" ? "Said to the forge's agent, mid-answer." : "The forge's agent is answering; read it in GET /api/v1/conversation/turns." });
129129 }
130130 const repo = repoArg(ctx, user, args);
src/tui/screens/talk_build.ts +2 −3
@@ -6,8 +6,7 @@
66 * read shows: Restore announces its push and Publish merges the pull.
77 */
88
9 import { buildState, BUILD_WORDS, publishBuild, restoreVersion, startBuild, versionDiff, type BuildState } from "../../actions/build.ts";
10 import { TALK_WORDS } from "../../actions/talk.ts";
9 import { buildSaidWords, buildState, BUILD_WORDS, publishBuild, restoreVersion, startBuild, versionDiff, type BuildState } from "../../actions/build.ts";
1110 import { offeredTemplates } from "../../core/app_templates.ts";
1211 import { buildsOf } from "../../core/chat_build.ts";
1312 import { getRepoById } from "../../core/repos.ts";
@@ -192,7 +191,7 @@ export function talkBuildScreen(f: Session, ctx: Ctx): Screen {
192191 if (prompt.trim() === "") return "Say what to build.";
193192 runAsync(ctx, async () => {
194193 const started = await startBuild(f.app, user, { prompt, ...(template === "" ? {} : { template }) });
195 note = started.ok ? (started.value.said === undefined ? "Started; Enter opens it." : `The app is made, but ${TALK_WORDS[started.value.said][1]}.`) : words(started.error);
194 note = started.ok ? (started.value.said === undefined ? "Started; Enter opens it." : buildSaidWords(started.value.said)) : words(started.error);
196195 ctx.invalidate();
197196 });
198197 return undefined;
src/tui/screens/talk_chats.ts +2 −2
@@ -524,7 +524,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
524524 const starter = turns.length === 0 && !pane && around === undefined ? STARTER_PROMPTS[Number(e.key) - 1] : undefined;
525525 if (starter !== undefined && /^[1-9]$/.test(e.key)) {
526526 const said = talk(f.app, user, starter, [], "inject", chat.id);
527 note = said.ok ? `Sent "${starter}"; r reloads to see the answer.` : TALK_WORDS[said.error][1];
527 note = said.ok ? (said.value.kept?.line ?? `Sent "${starter}"; r reloads to see the answer.`) : TALK_WORDS[said.error][1];
528528 ctx.invalidate();
529529 return true;
530530 }
@@ -628,7 +628,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
628628 onSubmit: (words) => {
629629 const said = talk(f.app, user, words, [], "inject", chat.id);
630630 if (!said.ok) return TALK_WORDS[said.error][1];
631 note = "Sent; r reloads to see the answer.";
631 note = said.value.kept?.line ?? "Sent; r reloads to see the answer.";
632632 ctx.invalidate();
633633 return undefined;
634634 },
src/tui/ssh-talk.ts +5
@@ -162,6 +162,11 @@ export function serveTalk(app: App, session: SshSession, user: User | undefined,
162162 }
163163 const finish = (said: ReturnType<typeof talk>): void => {
164164 if (!said.ok) return refuse(TALK_WORDS[said.error][1]);
165 // Kept: the message is in the conversation; the line says why it did not start, and Retry.

talk prints the kept line, but talk-again (line ~225) still prints 'the forge's agent is answering again' and exits 0 when the retry itself was kept. Print the kept line there too.

166 if (said.value.kept !== undefined) {
167 session.write(`kept: ${said.value.kept.line}${CRLF}`);
168 return session.exit(0);
169 }
165170 if (said.value.how === "answered") {
166171 session.write(terminalAnswer(said.value.answer ?? ""));
167172 return session.exit(0);
src/web/pages/talk.ts +5 −4
@@ -51,7 +51,7 @@ import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.t
5151 import { ASKING } from "../../crew/conversation_confirm.ts";
5252 import { INVERSES, readReceipt, type Receipt } from "../../crew/receipt.ts";
5353 import { pastTime } from "../../core/fence.ts";
54 import { isHeld, turnRunning, type RedoHow } from "../../crew/conversation.ts";
54 import { turnRunning, type RedoHow } from "../../crew/conversation.ts";
5555 import { liveBlock, subscribe } from "../../crew/conversation_live.ts";
5656 import { during } from "../../perf/jobs.ts";
5757 import type { Ctx } from "../../http/context.ts";
@@ -730,9 +730,10 @@ export async function talkSend(ctx: Ctx): Promise<Response> {
730730 return flashTo(ctx, `${here}#end`, { tone: "danger", message: `Say something, up to ${WORDS_MAX} characters.` });
731731 const about = form.get("about");
732732 const said = talk(ctx.app, user, text, [], "queue", conversation.id, typeof about === "string" ? about : null);
733 if (!said.ok && said.error === "no_account") return flashTo(ctx, `${here}#end`, blockedFlash(noTalkAccountBlocked(ctx.app, user), "danger"));
734 // Kept: the line under the message says why it could not start and when to Retry.
735 if (!said.ok && (isHeld(said.error) || said.error === "starting" || said.error === "off")) return flashTo(ctx, `${here}#end`, { tone: "attn", message: KEPT_FLASH });
733 // Kept: the line under the message says why it could not start and when to Retry; with no
outdated

This kept path covers only talkSend. talkRedo (Retry, edit, regenerate) still treats any ok result as success, so a kept retry says 'Asked again. Reload to see the answer.' Handle said.value.kept there with the same attn flash.

734 // account, the ask for one beside it.
735 if (said.ok && said.value.kept?.why === "no_account") return flashTo(ctx, `${here}#end`, blockedFlash(noTalkAccountBlocked(ctx.app, user), "attn"));
736 if (said.ok && said.value.kept !== undefined) return flashTo(ctx, `${here}#end`, { tone: "attn", message: KEPT_FLASH });
736737 if (!said.ok) return flashTo(ctx, `${here}#end`, { tone: "danger", message: TALK_WORDS[said.error][1] });
737738 return flashTo(ctx, `${here}#end`, { tone: "success", message: "Sent. Reload to see the answer." });
738739 }
src/web/talk_build.ts +2 −3
@@ -6,8 +6,7 @@
66 * ships no script.
77 */
88
9 import { buildState, BUILD_WORDS, publishBuild, restoreVersion, startBuild, versionDiff, type BuildState } from "../actions/build.ts";
10 import { TALK_WORDS } from "../actions/talk.ts";
9 import { buildSaidWords, buildState, BUILD_WORDS, publishBuild, restoreVersion, startBuild, versionDiff, type BuildState } from "../actions/build.ts";
1110 import { offeredTemplates } from "../core/app_templates.ts";
1211 import { WORDS_MAX } from "../core/fence.ts";
1312 import { getConversation } from "../core/conversations.ts";
@@ -111,7 +110,7 @@ export async function talkBuild(ctx: Ctx): Promise<Response> {
111110 const started = await startBuild(ctx.app, user, { prompt, ...(from === undefined ? {} : { template: from }) });
112111 if (!started.ok) return flashTo(ctx, "/talk", { tone: "danger", message: BUILD_WORDS[started.error] ?? "Not started." });
113112 const to = `/talk/${started.value.build.conversationId}`;
114 return started.value.said === undefined ? redirect(to) : flashTo(ctx, to, { tone: "danger", message: `The app is made, but ${TALK_WORDS[started.value.said][1]}.` });
113 return started.value.said === undefined ? redirect(to) : flashTo(ctx, to, { tone: started.value.said.kept ? "attn" : "danger", message: buildSaidWords(started.value.said) });
115114 }
116115
117116 /** The conversation a build request names, when it is the person's. */
test/conversation-files.test.ts +2 −2
@@ -89,8 +89,8 @@ describe("attachments", () => {
8989 const png = storeFile(app.db, dir, alice.id, "a.png", PNG);
9090 if (!png.ok) throw new Error(png.error);
9191 const refused = say(app, options, alice.id, "look", [png.value]);
92 expect(refused.ok).toBe(false);
93 expect(!refused.ok && refused.error).toBe("answering");
92 expect(refused.ok && refused.value.how).toBe("kept");
93 expect(refused.ok && refused.value.kept?.why).toBe("answering");
9494 // Not attached to anything: it can go with the next message.
9595 expect(pendingAmong(app.db, alice.id, [png.value.id]).ok).toBe(true);
9696 const note = text("n.md", "steer me");
test/conversation-talk.test.ts +58 −10
@@ -32,6 +32,7 @@ import { waitFor } from "./helpers/poll.ts";
3232 quietLogs();
3333
3434 const KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB2S7bF0R4NmuTUvVJXPPjdI1AF8XHXeYSNfr8DJ5eDo alice";
35 const KIT_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHRugSiAU1FLP6WOEA7pZQJ4a/kFVu+eOyKjsd6yZALb kit";
3536
3637 describe("talking to the forge's agent", () => {
3738 let dir: string;
@@ -63,15 +64,15 @@ describe("talking to the forge's agent", () => {
6364 return { error: body.result.isError === true, text: body.result.content[0]!.text };
6465 };
6566
66 const exec = async (command: string) => {
67 const parsed = parseAuthorizedKey(KEY);
67 const exec = async (command: string, key = KEY) => {
68 const parsed = parseAuthorizedKey(key);
6869 if (!parsed.ok) throw new Error("key");
6970 let out = "";
7071 let err = "";
7172 let code: number | undefined;
7273 await new Promise<void>((resolve) => {
7374 const session = {
74 key: { fingerprint: fingerprint(parsed.value.blob), line: KEY },
75 key: { fingerprint: fingerprint(parsed.value.blob), line: key },
7576 username: "whoever",
7677 remoteAddress: "203.0.113.9",
7778 kind: "exec" as const,
@@ -188,9 +189,14 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
188189 const send = () =>
189190 fetch(`${servers.url}/api/v1/conversation/messages`, { method: "POST", headers: headers(dana), body: JSON.stringify({ text: "hi" }) });
190191 for (let i = 0; i < TALK_PER_MINUTE; i++) {
192 // Kept, so the send succeeded: 202 with why, the line, its turn and the ask for an account.
191193 const res = await send();
192 expect(res.status).toBe(403);
193 expect(((await res.json()) as { error: string }).error).toBe("no_account");
194 expect(res.status).toBe(202);
195 const body = (await res.json()) as { how: string; why: string; message: string; turn: string; ask?: unknown };
196 expect([body.how, body.why]).toEqual(["kept", "no_account"]);
197 expect(body.message).toContain("Your message is kept for Retry");
198 expect(body.turn).toMatch(/\S/);
199 expect(body.ask).toBeDefined();
194200 }
195201 const over = await send();
196202 expect(over.status).toBe(429);
@@ -209,7 +215,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
209215 const erin = createToken(app.db, made.value.id, "personal", "rw").token;
210216 const send = () => fetch(`${servers.url}/api/v1/conversation/messages`, { method: "POST", headers: headers(erin), body: JSON.stringify({ text: "hi" }) });
211217 const refused = await send();
212 expect(refused.status).toBe(403);
218 expect(refused.status).toBe(202);
213219 expect(JSON.stringify(await refused.json())).toContain("An admin of this forge can grant one");
214220 expect(setModelGrant(app.db, made.value.id, 5, made.value.id, new Date())).toBe(true);
215221 const ok = await send();
@@ -219,18 +225,23 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
219225 expect(JSON.stringify(await read.json())).toContain('"hi"');
220226 });
221227
222 test("a spent dollar grant is resting (429), and the host's lent credit alone lets a turn through", async () => {
228 test("a spent dollar grant is resting (kept, 202), and the host's lent credit alone lets a turn through", async () => {
223229 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "finn", email: "[email protected]", password: "a-good-passphrase" });
224230 if (!made.ok) throw new Error(made.error);
225231 const finn = createToken(app.db, made.value.id, "personal", "rw").token;
226232 const send = () => fetch(`${servers.url}/api/v1/conversation/messages`, { method: "POST", headers: headers(finn), body: JSON.stringify({ text: "hi" }) });
227233 expect(setModelGrant(app.db, made.value.id, 0.1, made.value.id, new Date())).toBe(true);
228 expect((await send()).status).toBe(429);
234 const how = async (): Promise<[number, string]> => {
235 const res = await send();
236 const body = (await res.json()) as { how: string; why?: string };
237 return [res.status, body.why === undefined ? body.how : `${body.how} ${body.why}`];
238 };
239 expect(await how()).toEqual([202, "kept resting"]);
229240 setModelGrant(app.db, made.value.id, null, made.value.id, new Date());
230 expect((await send()).status).toBe(403);
241 expect(await how()).toEqual([202, "kept no_account"]);
231242 writeFileSync(join(dir, "parent.json"), JSON.stringify({ credit: { token: "bearer-token-1", capUsd: 5, spentUsd: 1 } }));
232243 try {
233 expect((await send()).status).toBe(202);
244 expect((await how())[1]).not.toStartWith("kept");
234245 } finally {
235246 rmSync(join(dir, "parent.json"));
236247 }
@@ -494,6 +505,43 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
494505 expect((await exec("talk-again edit bad\u0007words")).code).toBe(1);
495506 });
496507
508 test("a kept message is a success at every door: 202 kept, an MCP result, ssh exit 0, each with its line", async () => {
509 // At the live-turn cap nothing can start; each message is kept with the line saying why.
510 const busy = "The forge is answering as many people as it can at once. Your message is kept; Retry in a minute.";
511 // Kit, a person of their own, so the per-minute count of earlier tests is not theirs.
512 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "kit", email: "[email protected]", password: "a-good-passphrase" });
513 if (!made.ok) throw new Error(made.error);
514 setModelGrant(app.db, made.value.id, 5, made.value.id, new Date());
515 const parsed = parseAuthorizedKey(KIT_KEY);
516 if (!parsed.ok) throw new Error("key");
517 addKey(app.db, made.value.id, "laptop", parsed.value);
518 const kit = createToken(app.db, made.value.id, "personal", "rw").token;
519 const standing = async () => {
520 const read = (await (await fetch(`${servers.url}/api/v1/conversation/turns`, { headers: headers(kit) })).json()) as { turns: { id: string; role: string; text: string }[] };
521 return read.turns;
522 };
523 configureConversation(app, { binary: join(dir, "never-runs"), localUrl: servers.url, budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal, liveMax: 0 });
524 try {
525 const res = await fetch(`${servers.url}/api/v1/conversation/messages`, { method: "POST", headers: headers(kit), body: JSON.stringify({ text: "kept by api" }) });
526 expect(res.status).toBe(202);
527 const body = (await res.json()) as { how: string; why: string; message: string; turn: string };
528 expect({ how: body.how, why: body.why, message: body.message }).toEqual({ how: "kept", why: "busy", message: busy });
529 // `turn` is the kept message's own turn, the one Retry answers after.
530 expect((await standing()).find((t) => t.id === body.turn)?.text).toBe("kept by api");
531 const said = await mcp(kit, { text: "kept by mcp" });
532 expect(said).toEqual({ error: false, text: expect.stringContaining(busy) });
533 const r = await exec("talk kept by ssh", KIT_KEY);
534 expect(r.code).toBe(0);
535 expect(r.out).toContain(`kept: ${busy}`);
536 expect((await standing()).map((t) => `${t.role}:${t.text}`).slice(-6)).toEqual(["person:kept by api", `agent:${busy}`, "person:kept by mcp", `agent:${busy}`, "person:kept by ssh", `agent:${busy}`]);
537 // A message that keeps nothing is still an error at each door.
538 expect((await fetch(`${servers.url}/api/v1/conversation/messages`, { method: "POST", headers: headers(kit), body: JSON.stringify({ text: " " }) })).status).toBe(422);
539 expect((await exec("talk ", KIT_KEY)).code).toBe(1);
540 } finally {
541 withBinary(answers("Back."));
542 }
543 });
544
497545 test("ssh talk /stop stops instead of speaking; with nothing running it says so (#8818)", async () => {
498546 expect(isStop("/stop")).toBe(true);
499547 expect(isStop(" --stop ")).toBe(true);
test/conversation-turn.test.ts +9 −5
@@ -355,7 +355,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to
355355 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
356356 if (!b.ok) throw new Error("user");
357357 const said = say(app, options(stub("bobs", "s", "answer")), b.value.id, "hi");
358 expect(!said.ok && said.error).toBe("no_account");
358 expect(said.ok && said.value.kept?.why).toBe("no_account");
359359 expect(existsSync(join(dir, "bobs.argv"))).toBe(false);
360360 // A message is never lost (#16431): kept, with the line saying why, flagged failed for Retry.
361361 expect(turns(b.value)).toEqual(["person:hi", "agent:No account answers for you on this forge yet. Your message is kept for Retry. An admin of this forge can grant one."]);
@@ -370,7 +370,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to
370370 expect(setAccountCeiling(app.db, alice.id, 0.5, 0.5, alice.id, new Date())).toBe(true);
371371 const said = say(app, options(stub("ceiling", "s", "answer")), alice.id, "over the day");
372372 clearAccountCeiling(app.db, alice.id);
373 expect(!said.ok && said.error).toBe("resting");
373 expect(said.ok && said.value.kept?.why).toBe("resting");
374374 expect(existsSync(join(dir, "ceiling.argv"))).toBe(false);
375375 const added = turns(alice).slice(-2);
376376 expect(added[0]).toBe("person:over the day");
@@ -381,7 +381,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to
381381 test("past the live-turn cap a new turn is busy; a steer into a running one is not counted", async () => {
382382 expect(TURNS_LIVE_MAX).toBe(4);
383383 const none = say(app, { ...options(stub("capped", "sess-a", "answer")), liveMax: 0 }, alice.id, "too many");
384 expect(!none.ok && none.error).toBe("busy");
384 expect(none.ok && none.value.kept?.why).toBe("busy");
385385 expect(existsSync(join(dir, "capped.argv"))).toBe(false);
386386 expect(turns(alice).slice(-2)).toEqual(["person:too many", "agent:The forge is answering as many people as it can at once. Your message is kept; Retry in a minute."]);
387387 const bin = stub("one-live", "sess-a", "steer");
@@ -401,7 +401,11 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to
401401 const until = new Date(Date.now() + 15 * 60_000).toISOString();
402402 restSubscription(app.db, sub.value.id, until, "window full");
403403 const said = say(app, options(stub("rested", "s", "answer")), alice.id, "what is happening on voxel?");
404 expect(!said.ok && said.error).toBe("resting");
404 expect(said.ok && said.value.kept?.why).toBe("resting");
405 // The send succeeded: what a client gets back names why, the line, the message's turn and when.
406 expect(said.ok && said.value.kept?.until).toBe(until);
407 expect(said.ok && said.value.kept?.line).toMatch(/^The account that answers you is resting until /);
408 expect(said.ok && said.value.done).toBeUndefined();
405409 expect(existsSync(join(dir, "rested.argv"))).toBe(false);
406410 const added = turns(alice).slice(-2);
407411 expect(added[0]).toBe("person:what is happening on voxel?");
@@ -474,7 +478,7 @@ echo '{"type":"result","subtype":"success","is_error":true,"result":"You have hi
474478
475479 const before = turns(alice).length;
476480 const refused = say(app, options(stub("while-resting", "s", "answer")), alice.id, "again?");
477 expect(refused.ok ? "started" : refused.error).toBe("resting");
481 expect(refused.ok ? (refused.value.kept?.why ?? "started") : refused.error).toBe("resting");
478482 expect(turns(alice)).toHaveLength(before);
479483
480484 wakeSubscription(app.db, account.value.id);
test/crew-sandbox-required.test.ts +8 −6
@@ -153,7 +153,7 @@ describe("required and unavailable: nothing of the agent runs, a turn and a one-
153153 try {
154154 const runs = () => (app.db.query("SELECT count(*) AS n FROM conversation_run").get() as { n: number }).n;
155155 const before = runs();
156 expect(say(app, options, userId, "hello")).toEqual({ ok: false, error: "sandbox" });
156 expect(say(app, options, userId, "hello")).toEqual({ ok: true, value: { how: "kept", kept: { why: "sandbox", line: expect.any(String), turn: expect.any(String) } } });
157157 expect(await oneShot(app, userId, "s", "p")).toEqual({ ok: false, error: "sandbox" });
158158 expect(runs()).toBe(before);
159159 } finally {
@@ -185,7 +185,7 @@ describe("required and unavailable: nothing of the agent runs, a turn and a one-
185185 const runs = () => (app.db.query("SELECT count(*) AS n FROM conversation_run").get() as { n: number }).n;
186186 const spends = () => (app.db.query("SELECT count(*) AS n FROM one_shot_spend").get() as { n: number }).n;
187187 const [r, s] = [runs(), spends()];
188 expect(say(app, options, userId, "hello again")).toEqual({ ok: false, error: "sandbox" });
188 expect(say(app, options, userId, "hello again")).toEqual({ ok: true, value: { how: "kept", kept: { why: "sandbox", line: expect.any(String), turn: expect.any(String) } } });
189189 expect(await oneShot(app, userId, "s", "p")).toEqual({ ok: false, error: "sandbox" });
190190 expect(runs()).toBe(r);
191191 expect(spends()).toBe(s);
@@ -264,7 +264,7 @@ describe("the probe is taken again, at most once a minute and one at a time", ()
264264 });
265265
266266 describe("Talk's doors answer a refused turn in the forge's own words", () => {
267 test("the API says 503 with the sentence, and nothing is started or kept", async () => {
267 test("the API keeps the message with the sentence (202 kept), and nothing is started", async () => {
268268 const dir = await mkdtemp(join(tmpdir(), "forge-sandbox-door-"));
269269 const door = createApp({ dataDir: dir, port: 0, host: "forge.test" });
270270 const servers = await serve(door);
@@ -275,9 +275,11 @@ describe("Talk's doors answer a refused turn in the forge's own words", () => {
275275 configureConversation(door, { binary: "/nonexistent-agent", localUrl: servers.url, budgetUsd: 1, timeoutMs: 60_000, signal: new AbortController().signal });
276276 noteSandbox(door, true, { ok: false, reason: "bwrap is not installed" }, () => {});
277277 const res = await fetch(`${servers.url}/api/v1/conversation/messages`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify({ text: "hello" }) });
278 expect(res.status).toBe(503);
279 expect(await res.text()).toContain("requires the agent sandbox");
280 expect(talk(door, made.value, "hello")).toEqual({ ok: false, error: "sandbox" });
278 expect(res.status).toBe(202);
279 const body = (await res.json()) as { how: string; why: string; message: string };
280 expect([body.how, body.why]).toEqual(["kept", "sandbox"]);
281 expect(body.message).toContain("it requires a sandbox that is unavailable. Your message is kept");
282 expect(talk(door, made.value, "hello")).toEqual({ ok: true, value: { how: "kept", kept: { why: "sandbox", line: expect.any(String), turn: expect.any(String) } } });
281283 expect((door.db.query("SELECT count(*) AS n FROM conversation_run").get() as { n: number }).n).toBe(0);
282284 } finally {
283285 await servers.stop();
test/talk-kept-message.test.ts +43 −1
@@ -9,7 +9,9 @@ import { chmodSync, existsSync, writeFileSync } from "node:fs";
99 import { mkdtemp, rm } from "node:fs/promises";
1010 import { tmpdir } from "node:os";
1111 import { join } from "node:path";
12 import { talkAgain } from "../src/actions/talk.ts";
12 import { TALK_WORDS, talkAgain } from "../src/actions/talk.ts";
13 import { serveTalkAgain } from "../src/tui/ssh-talk.ts";
14 import type { SshSession } from "../src/ssh/server.ts";
1315 import { createApp, type App } from "../src/app.ts";
1416 import { listTurns, openConversation } from "../src/core/conversations.ts";
1517 import { createSession } from "../src/core/sessions.ts";
@@ -163,6 +165,46 @@ describe("a kept message on every door", () => {
163165 tui.stop?.();
164166 });
165167
168 test("a Retry that cannot start yet says why on the page, in JSON and in the terminal, never 'Asked again' (#16593)", async () => {
169 configureConversation(app, options({ liveMax: 0 }));
170 const conversation = openConversation(app.db, alice.id);
171 const before = said(alice);
172 const failed = listTurns(app.db, alice.id, conversation.id, { limit: 100 });
173 if (!failed.ok) throw new Error("turns");
174 const turn = failed.value.at(-1)!.id;
175 const busy = TALK_WORDS.busy[1];
176 const cookie = `forge_session=${createSession(app.db, alice.id).token}`;
177 const post = (accept?: string) =>
178 fetch(`${servers.url}/talk/again/retry`, {
179 method: "POST",
180 headers: { cookie, origin: new URL(servers.url).origin, ...(accept === undefined ? {} : { accept }) },
181 body: new URLSearchParams({ turn }),
182 redirect: "manual",
183 });
184 const page = await post();
185 expect(page.status).toBe(303);
186 const flash = (page.headers.get("set-cookie") ?? "").split(";")[0]!;
187 const shown = await (await fetch(`${servers.url}${page.headers.get("location")}`, { headers: { cookie: `${cookie}; ${flash}` } })).text();
188 expect(shown).toContain("as many people as it can at once; try again in a minute");
189 expect(shown).not.toContain("Asked again");
190 const asJson = await post("application/json");
191 expect(asJson.status).toBe(429);
192 expect(await asJson.json()).toMatchObject({ ok: false, message: busy });
193 // The terminal's talk-again: the refusal, exit 1, nothing said of an answer.
194 let out = "", errOut = "", code: number | undefined;
195 const session: SshSession = {
196 key: { algo: "ssh-ed25519", blob: new Uint8Array(), fingerprint: "", line: "" }, username: "alice", remoteAddress: "203.0.113.9", kind: "exec", command: "talk-again retry", term: undefined, env: {},
197 cols: 0, rows: 0, widthPx: 0, heightPx: 0, ended: false, pending: 0,
198 write: (d: Uint8Array | string) => void (out += typeof d === "string" ? d : Buffer.from(d).toString()),
199 writeStderr: (d: string) => void (errOut += d), onData() {}, onResize() {}, onEof() {}, onClose() {}, exit: (c: number) => void (code = c), drain: async () => {},
200 };
201 serveTalkAgain(app, session, alice, "retry", turn);
202 expect([code, out]).toEqual([1, ""]);
203 expect(errOut).toContain(busy);
204 // And the exchange is as it was: the kept line is still there to Retry.
205 expect(said(alice)).toEqual(before);
206 });
207
166208 test("Retry sends the kept words once: no second copy of the message", async () => {
167209 configureConversation(app, options());
168210 const failed = listTurns(
test/talk-starting.test.ts +11 −6
@@ -45,10 +45,12 @@ const send = (text: string) =>
4545 body: JSON.stringify({ text }),
4646 });
4747
48 test("with no agent expected, Talk says off, as before", async () => {
48 test("with no agent expected, Talk keeps the message as off (202 kept)", async () => {
4949 expect(startingIn(app)).toBeUndefined();
5050 const res = await send("hello");
51 expect([res.status, ((await res.json()) as { error: string }).error]).toEqual([503, "off"]);
51 const body = (await res.json()) as { how: string; why: string };
52 expect([res.status, body.how, body.why]).toEqual([202, "kept", "off"]);
53 expect(res.headers.get("retry-after")).toBeNull();
5254 });
5355
5456 test("while the boot has yet to configure the agent, a message is kept and the wait is said and sent", async () => {
@@ -57,12 +59,13 @@ test("while the boot has yet to configure the agent, a message is kept and the w
5759 const left = startingIn(app, now)!;
5860 expect(left).toBe(Math.round((STARTING_MS - 60_000) / 1000));
5961 const res = await send("what shipped today?");
60 expect(res.status).toBe(503);
62 // Kept, so the send succeeded: 202 kept, why starting, and the wait left of the boot.
63 expect(res.status).toBe(202);
6164 const wait = Number(res.headers.get("retry-after"));
6265 expect(wait).toBeGreaterThan(150);
6366 expect(wait).toBeLessThanOrEqual(180);
64 const body = (await res.json()) as { error: string; message: string };
65 expect(body.error).toBe("starting");
67 const body = (await res.json()) as { how: string; why: string; message: string; turn: string };
68 expect([body.how, body.why]).toEqual(["kept", "starting"]);
6669 // The line carries no number: the seconds are Retry-After's alone, read once.
6770 expect(body.message).toBe(STARTING_LINE);
6871 // Kept: the words, and the line under them flagged failed so the page draws Retry.
@@ -75,6 +78,7 @@ test("while the boot has yet to configure the agent, a message is kept and the w
7578 ["agent", body.message],
7679 ]);
7780 expect(last[1]!.failed).toBe(true);
81 expect(body.turn).toBe(last[0]!.id);
7882 // The page's plain form keeps it too, and says so rather than "not running".
7983 const session = `forge_session=${createSession(app.db, alice.id).token}`;
8084 const posted = await fetch(`${servers.url}/talk`, {
@@ -108,7 +112,8 @@ test("once the agent is configured, it is no longer starting; a boot with no cre
108112 // Off, the message is kept too, with its own line (#16455).
109113 const bea = await createUser(fresh.db, { origin: "seed", trusted: true, username: "bea", email: "[email protected]", password: "a-good-passphrase" });
110114 if (!bea.ok) throw new Error(bea.error);
111 expect(talk(fresh, bea.value, "hi")).toEqual({ ok: false, error: "off" });
115 const off = talk(fresh, bea.value, "hi");
116 expect(off.ok && off.value.kept?.why).toBe("off");
112117 const kept = listTurns(fresh.db, bea.value.id, openConversation(fresh.db, bea.value.id).id, { limit: 10 });
113118 expect(kept.ok && kept.value.map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`)).toEqual(["person:hi", "agent!:This forge's agent is not running right now. Your message is kept; Retry once it runs."]);
114119 } finally {
test/tui-talk-chats.test.ts +2 −2
@@ -118,7 +118,7 @@ describe("the terminal's conversations screen", () => {
118118 // The crew is off in this app: the prompt says why, and the message is kept with its line
119119 // (#16455).
120120 const said = await drive(bob, [...open, "\r", "s", "hello", "\r"]);
121 expect(said).toContain("not running here");
121 expect(said).toContain("This forge's agent is not running right now. Your message is kept; Retry once it runs.");
122122 const turns = listTurns(app.db, bob.id, made.value.id, { limit: 50 });
123123 expect(turns.ok && turns.value.slice(2).map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`)).toEqual(["person:hello", "agent!:This forge's agent is not running right now. Your message is kept; Retry once it runs."]);
124124 });
@@ -148,7 +148,7 @@ describe("the terminal's conversations screen", () => {
148148 STARTER_PROMPTS.forEach((p, i) => expect(text).toContain(`${String(i + 1)} ${p}`));
149149 // The crew is off in this app: the header says why, and the starter is kept with its line.
150150 const sent = await drive(carol.value, [...open, "\r", "2"]);
151 expect(sent).toContain("not running here");
151 expect(sent).toContain("This forge's agent is not running right now. Your message is kept; Retry once it runs.");
152152 const turns = listTurns(app.db, carol.value.id, made.value.id, { limit: 50 });
153153 expect(turns.ok && turns.value.map((t) => `${t.role}${t.failed ? "!" : ""}`)).toEqual(["person", "agent!"]);
154154 expect(turns.ok && turns.value[0]?.text).toBe(STARTER_PROMPTS[1]);
test/ui-663-talk-and-merges.test.ts +8 −4
@@ -181,7 +181,7 @@ describe("a cell whose lent credit is spent, and a forge whose agent is starting
181181 chmodSync(bin, 0o755);
182182 try {
183183 const res = say(app, { binary: bin, localUrl: servers.url, budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal }, alice.id, "quick check: can you answer now?");
184 expect(!res.ok && res.error).toBe("resting");
184 expect(res.ok && res.value.kept?.why).toBe("resting");
185185 const turns = listTurns(app.db, alice.id, openConversation(app.db, alice.id).id, { limit: 50 });
186186 const shown = turns.ok ? turns.value.map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`) : [];
187187 expect(shown.slice(-2)).toEqual([
@@ -197,7 +197,7 @@ describe("a cell whose lent credit is spent, and a forge whose agent is starting
197197 // Before the crew is up, `conversationOptions` is undefined: `talk` answered "off" and kept
198198 // nothing.
199199 const sent = talk(app, alice, "capped send: are you there?");
200 expect(!sent.ok && sent.error).toBe("off");
200 expect(sent.ok && sent.value.kept?.why).toBe("off");
201201 const turns = listTurns(app.db, alice.id, openConversation(app.db, alice.id).id, { limit: 50 });
202202 const shown = turns.ok ? turns.value.map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`) : [];
203203 expect(shown.slice(-2)).toEqual([
@@ -209,7 +209,10 @@ describe("a cell whose lent credit is spent, and a forge whose agent is starting
209209 test("while the agent is off, the per-minute cap holds: past it nothing more is kept", async () => {
210210 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "flood", email: "[email protected]", password: "a-good-passphrase" });
211211 if (!made.ok) throw new Error(made.error);
212 for (let i = 0; i < TALK_PER_MINUTE; i++) expect(talk(app, made.value, `kept ${String(i)}`)).toEqual({ ok: false, error: "off" });
212 for (let i = 0; i < TALK_PER_MINUTE; i++) {
213 const sent = talk(app, made.value, `kept ${String(i)}`);
214 expect(sent.ok && sent.value.kept?.why).toBe("off");
215 }
213216 expect(talk(app, made.value, "one too many")).toEqual({ ok: false, error: "rate_limited" });
214217 const turns = listTurns(app.db, made.value.id, openConversation(app.db, made.value.id).id, { limit: 100 });
215218 expect(turns.ok && turns.value.length).toBe(TALK_PER_MINUTE * 2);
@@ -221,7 +224,8 @@ describe("a cell whose lent credit is spent, and a forge whose agent is starting
221224 if (!made.ok) throw new Error(made.error);
222225 promote(app.db, made.value);
223226 setModelGrant(app.db, made.value.id, 5, alice.id, new Date());
224 expect(talk(app, made.value, "build me a clock")).toEqual({ ok: false, error: "off" });
227 const sent = talk(app, made.value, "build me a clock");
228 expect(sent.ok && sent.value.kept?.why).toBe("off");
225229 const conversation = openConversation(app.db, made.value.id);
226230 const before = listTurns(app.db, made.value.id, conversation.id, { limit: 10 });
227231 const kept = before.ok ? before.value.at(-1) : undefined;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs