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

A Talk turn that fails shows what failed and a Retry that resends the same words #16029

Merged opened this

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

Merged

torque/forge:torque/15996-a-talk-turn-that-fails-shows-what-failed → main 0 commits fork 5 threads · 5 unresolved

  • Merged. torque/15996-a-talk-turn-that-fails-shows-what-failed was merged into main as 0cd3ae5.

Review

Sign in to review this change.
6 files changed +89 −17
docs/features/talk.md +2 −2
@@ -52,9 +52,9 @@ Three actions on the last exchange, one door, `talkAgain()` in `src/actions/talk
5252 - **Edit** replaces your last message with new words and asks again. **Regenerate** asks the same message again for a new reply. **Retry** asks again after a failed turn.
5353 - What is replaced stays in the conversation, marked replaced (`replaced: true` in `GET /api/v1/conversation/turns`), dimmed on the page; the agent no longer reads it, and the new turn starts a fresh session from the turns that still stand.
5454 - A turn that could not answer (a failed run, a resting account) says what happened in plain words, never the raw error, and shows **Retry**.
55 - Refused while a turn runs (`running`, 409), or when there is nothing to act on (`nothing`, 409).
55 - Refused while a turn runs (`running`, 409), or when there is nothing to act on (`nothing`, 409). A retry names the failed turn it answers; without it the retry is refused (`unkeyed`, 409), and with a turn that is no longer the last (a double submit, a stale tab) it is refused as already retried (`retried`, 409), so one failure is retried once.
5656 - **Web:** Edit under your last message (opens the composer holding it, `/talk?edit=1`; Send resends), Regenerate under the last reply, Retry under a failed one. All are plain forms or links, so they work without the script, which only does them in place. They post to `POST /talk/again/edit|regenerate|retry`, from your own signed-in browser only.
57 - **Terminal:** `ssh <forge> talk-again edit <words>`, `ssh <forge> talk-again regenerate`, `ssh <forge> talk-again retry`.
57 - **Terminal:** `ssh <forge> talk-again edit <words>`, `ssh <forge> talk-again regenerate`, `ssh <forge> talk-again retry <turn>`. The turn is the failed turn's id: a bare `talk-again retry` exits 1 and prints the full command with the id of the open conversation's failed turn (the same id the page's Retry form posts as `turn`).
5858 - With several conversations they act on the one open: the forms post to `/talk/<id>/again/<how>` (`/talk/again/<how>` on the latest); the action takes the conversation as an optional argument.
5959 - There is no API or MCP door for these yet.
6060
src/actions/talk.ts +13 −4
@@ -8,7 +8,7 @@
88 import { NO_TALK_ACCOUNT } from "./blocked_words.ts";
99 import { storedText } from "../kernel/blocked.ts";
1010 import type { App } from "../app.ts";
11 import { getConversation } from "../core/conversations.ts";
11 import { getConversation, lastExchange, openConversation } from "../core/conversations.ts";
1212 import type { ConversationFile } from "../core/conversation_files.ts";
1313 import { RateLimiter } from "../core/ratelimit.ts";
1414 import type { User } from "../core/users.ts";
@@ -21,7 +21,7 @@ export const TALK_PER_MINUTE = 12;
2121 /** What an empty conversation offers to send in one tap: plain text, the one list. */
2222 export const STARTER_PROMPTS = ["What is waiting for me?", "What shipped this week?", "Start something new"] as const;
2323
24 export type TalkRefusal = SayRefusal | RedoRefusal | "off" | "rate_limited";
24 export type TalkRefusal = SayRefusal | RedoRefusal | "off" | "rate_limited" | "unkeyed" | "retried";
2525
2626 /** What each refusal says, with its status. */
2727 export const TALK_WORDS: Readonly<Record<TalkRefusal, readonly [number, string]>> = {
@@ -36,6 +36,8 @@ export const TALK_WORDS: Readonly<Record<TalkRefusal, readonly [number, string]>
3636 off: [503, "the forge's agent is not running here"],
3737 running: [409, "the forge is still answering; wait for it to finish"],
3838 nothing: [409, "there is nothing here to do that to"],
outdated

Changing the shared nothing message makes Regenerate and Edit refusals say the turn was already retried. Restore the old wording here and add a separate retried refusal for the stale retry key.

39 retried: [409, "That turn was already retried."],
40 unkeyed: [409, "Say which failed turn to retry."],
3941 file_taken: [409, "that file already waits in another message"],
4042 queue_full: [429, "five messages are already waiting; cancel one or wait for the answer"],
4143 rate_limited: [429, `at most ${TALK_PER_MINUTE} messages a minute`],
@@ -70,12 +72,19 @@ export function talk(app: App, user: User | undefined, text: string, files: read
7072
7173 /**
7274 * Edit the last message and resend it, regenerate the last reply, or retry a failed turn (#8817),
73 * in the named conversation or the latest.
75 * in the named conversation or the latest. A retry must name the failed turn it answers (`turn`):
76 * without the key it is refused, and with a key that is no longer the last turn (a double submit, a
77 * stale tab) it is refused as already retried, so one failure is retried once.
7478 */
75 export function talkAgain(app: App, user: User | undefined, how: RedoHow, text = "", conversationId?: string): Result<Said, TalkRefusal> {
79 export function talkAgain(app: App, user: User | undefined, how: RedoHow, text = "", conversationId?: string, turn?: string): Result<Said, TalkRefusal> {
7680 if (user === undefined) return err("unauthorized");
7781 const options = conversationOptions(app);
7882 if (options === undefined) return err("off");
83 if (how === "retry") {
84 if (turn === undefined || turn === "") return err("unkeyed");
85 const conversation = conversationId === undefined ? openConversation(app.db, user.id) : getConversation(app.db, user.id, conversationId);
86 if (conversation !== undefined && lastExchange(app.db, user.id, conversation.id).after.at(-1)?.id !== turn) return err("retried");
87 }
7988 if (!take(app, user)) return err("rate_limited");
8089 const said = redo(app, options, user.id, how, text, conversationId);
8190 if (said.ok) watch(app, said.value);
src/tui/ssh-talk.ts +8 −4
@@ -14,7 +14,7 @@
1414 * `talk /crew` prints the one line /talk shows above its box: the crew's
1515 * live work, or that it is idle (#13970).
1616 *
17 * `talk-again edit <words>`, `talk-again regenerate` and `talk-again retry`
17 * `talk-again edit <words>`, `talk-again regenerate` and `talk-again retry <turn>`

The terminal how-to in docs/features/talk.md:57 still shows bare talk-again retry, which now exits 1. Update it to match.

1818 * are the same three actions the page has (#8817), through `talkAgain`.
1919 *
2020 * `talk --about owner/repo[#N] [words]` first prints the same one line the
@@ -34,7 +34,7 @@ import { FILE_WORDS, IMAGE_MAX, pendingAmong, removePending, storeFile } from ".
3434 import { contextOf, contextText, conversationTotal, dollars, spendWords, totalText, turnSpend, type Spend } from "../core/conversation_cost.ts";
3535 import { liveCrewRows } from "../actions/crew_now.ts";
3636 import { crewLine } from "../web/crew_now.ts";
37 import { openConversation } from "../core/conversations.ts";
37 import { lastExchange, openConversation } from "../core/conversations.ts";
3838 import { aboutLine } from "../core/talk_about.ts";
3939 import type { App } from "../app.ts";
4040 import type { RedoHow } from "../crew/conversation.ts";
@@ -211,8 +211,12 @@ export function serveTalkAgain(app: App, session: SshSession, user: User | undef
211211 session.exit(1);
212212 };
213213 if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(words)) return refuse(CONTROL_WORDS);
214 const said = talkAgain(app, user, how, words);
215 if (!said.ok) return refuse(TALK_WORDS[said.error][1]);
214 // A retry names the failed turn it answers, as the page's Retry does: `talk-again retry <turn>`.
215 const said = how === "retry" ? talkAgain(app, user, how, "", undefined, words.trim()) : talkAgain(app, user, how, words);
216 if (!said.ok) {
217 const failed = said.error === "unkeyed" && user !== undefined ? lastExchange(app.db, user.id, openConversation(app.db, user.id).id).after.at(-1) : undefined;
218 return refuse(TALK_WORDS[said.error][1] + (failed?.failed === true ? `: talk-again retry ${failed.id}` : ""));
219 }
216220 session.write(`the forge's agent is answering again${CRLF}`);
217221 session.exit(0);
218222 }
src/web/pages/talk.ts +5 −4
@@ -177,8 +177,8 @@ const workHtml = (work: Work): Html =>
177177 html`<p class="talk-steps small muted">${work.steps.charAt(0).toUpperCase() + work.steps.slice(1)}</p>${work.links.length === 0 ? null : html`<p class="talk-links small">${work.links.map((l) => html`<a href="${l.href}">${l.label}</a>`)}</p>`}`;
178178
179179 /** Ask again as a form, so it works without the script; the script only enhances it. */
180 const againForm = (base: string, how: "regenerate" | "retry", label: string, words: string): Html =>
181 html`<form method="post" action="${base}/again/${how}" data-again="${how}">${btn(label, { icon: "sync", label: words })}</form>`;
180 const againForm = (base: string, how: "regenerate" | "retry", label: string, words: string, turn?: string): Html =>
181 html`<form method="post" action="${base}/again/${how}" data-again="${how}">${turn === undefined ? null : html`<input type="hidden" name="turn" value="${turn}">`}${btn(label, { icon: "sync", label: words })}</form>`;

The hidden turn field is not in the data the script posts (talk_client.ts:490 builds an empty URLSearchParams), so the key is lost with JS on. Fix the client to send the form's fields.

182182
183183 /**
184184 * What the last exchange offers, by the turn it sits under: Edit under the
@@ -192,7 +192,7 @@ export function exchangeActs(db: Database, userId: string, conversationId: strin
192192 if (person === undefined) return acts;
193193 acts.set(person.id, html`<a class="btn talk-act" href="${base}?edit=1#compose" data-act="edit" aria-label="Edit your last message">Edit</a>`);
194194 const last = after.at(-1);
195 if (last?.failed === true) acts.set(last.id, againForm(base, "retry", "Retry", "Retry the failed turn"));
195 if (last?.failed === true) acts.set(last.id, againForm(base, "retry", "Retry", "Retry the failed turn", last.id));
196196 else if (last?.role === "agent") acts.set(last.id, againForm(base, "regenerate", "Regenerate", "Regenerate the last reply"));
197197 return acts;
198198 }
@@ -601,11 +601,12 @@ export async function talkAgainSend(ctx: Ctx): Promise<Response> {
601601 if (conversation === undefined) return notFoundPage(ctx);
602602 const here = ctx.params["id"] === undefined ? HERE : urlOf(conversation);
603603 const text = form.get("text");
604 const key = form.get("turn");
604605 const asJson = (ctx.request.headers.get("accept") ?? "").includes("application/json");
605606 let status = 422;
606607 let message = `Say something, up to ${WORDS_MAX} characters.`;
607608 if (how !== "edit" || (typeof text === "string" && text.trim() !== "" && text.length <= WORDS_MAX)) {
608 const said = talkAgain(ctx.app, user, how, typeof text === "string" ? text : "", conversation.id);
609 const said = talkAgain(ctx.app, user, how, typeof text === "string" ? text : "", conversation.id, typeof key === "string" ? key : undefined);
609610 if (said.ok) return asJson ? json({ ok: true }, 202) : flashTo(ctx, `${here}#end`, { tone: "success", message: "Asked again. Reload to see the answer." });
outdated

The check runs only when turn is present, so omitting the field skips it. Refuse a retry whenever the last turn is not failed, and use the key only to say which turn was meant. Principle 8: reword the 409 message in plain words.

610611 [status, message] = TALK_WORDS[said.error];
611612 }
src/web/pages/talk_client.ts +1 −1
@@ -487,7 +487,7 @@ ${dictateJs}
487487 });
488488 log.addEventListener("submit", async (e) => {
489489 const r = e.target.closest("form[data-again]");
490 if (r) { e.preventDefault(); again(r.dataset.again, new URLSearchParams()); return; }
490 if (r) { e.preventDefault(); again(r.dataset.again, new URLSearchParams(new FormData(r))); return; }
491491 const f = e.target.closest("form[data-confirm]");
492492 if (!f) return;
493493 e.preventDefault();
test/conversation-talk.test.ts +60 −2
@@ -24,7 +24,7 @@ import { forgeSshSession } from "../src/tui/ssh.ts";
2424 import { isStop, parseTalkAgain, parseTalkCommand } from "../src/tui/ssh-talk.ts";
2525 import { listTurns } from "../src/core/conversations.ts";
2626 import { createSession } from "../src/core/sessions.ts";
27 import { conversationOptions, redo, withHistory } from "../src/crew/conversation.ts";
27 import { conversationOptions, redo, say, withHistory } from "../src/crew/conversation.ts";
2828 import { exchangeActs, turnHtml } from "../src/web/pages/talk.ts";
2929 import { quietLogs } from "./helpers/globals.ts";
3030 import { waitFor } from "./helpers/poll.ts";
@@ -45,7 +45,8 @@ describe("talking to the forge's agent", () => {
4545 (await fetch(`${servers.url}/api/v1/conversation/turns`, { headers: headers(token) })).json() as never;
4646 const settle = async () => {
4747 for (let i = 0; i < 200; i++) {
48 if (!(await turns()).running) return;
48 const open = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM conversation_run WHERE state = 'running'").get()!.n;
49 if (!(await turns()).running && open === 0) return;
4950 await Bun.sleep(25);
5051 }
5152 throw new Error("the turn never finished");
@@ -487,6 +488,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
487488 await settle();
488489 expect((await standing()).slice(-2)).toEqual(["person:by terminal", "agent:By ssh again."]);
489490 expect((await exec("talk-again retry")).code).toBe(1);
491 expect((await exec("talk-again retry no-such-turn")).code).toBe(1);
490492 expect((await exec("talk-again edit bad\u0007words")).code).toBe(1);
491493 });
492494
@@ -609,4 +611,60 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
609611 expect(existsSync(join(dir, "conversation-files"))).toBe(true);
610612 });
611613 });
outdated

The test builds the post by hand with the key, so it never exercises the script's request. Add a no-key retry after the turn was retried, and a check that the client forwards the form fields.

614 let gus = "";
615 let conv = { id: "" };
616 const listOf = (id: string) => (listTurns(app.db, gus, id, { limit: 50 }) as { ok: true; value: { id: string; role: string; text: string; failed: boolean; replaced: boolean }[] }).value;
617 const lastOf = (id: string) => listOf(id).filter((t) => !t.replaced).at(-1)!;
618 const retryPost = (id: string, turn?: string) =>
619 fetch(`${servers.url}/talk/${id}/again/retry`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", cookie: `forge_session=${createSession(app.db, gus).token}` }, body: turn === undefined ? "" : `turn=${turn}` });
620 test("a failed turn is retried once per key: a double submit finds one person turn, never two", async () => {
621 // Its own person, so the minute's allowance the earlier tests spent is not in the way.
622 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "gus", email: "[email protected]", password: "a-good-passphrase" });
623 if (!made.ok) throw new Error(made.error);
624 gus = made.value.id;
625 setModelGrant(app.db, gus, 5, gus, new Date());
626 conv = newConversation(app.db, gus);
627 const fail = `echo '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"x","total_cost_usd":0,"num_turns":0,"session_id":"s4"}'\nexit 1`;
628 withBinary(fail);
629 await settled(say(app, conversationOptions(app)!, gus, "one question only", [], "inject", conv.id));
630 const first = lastOf(conv.id);
631 expect(first.failed).toBe(true);
632 const acts = exchangeActs(app.db, gus, conv.id, false).get(first.id)!;
633 expect(acts.text).toContain(`name="turn" value="${first.id}"`);
634 const sameWords = async () => listOf(conv.id).filter((t) => t.role === "person" && !t.replaced).length;
635 withBinary(fail);
636 expect((await retryPost(conv.id, first.id)).status).toBe(202);
637 await settle();
638 // The same form sent again, now the retry has itself failed: its key is stale.
639 const twice = await retryPost(conv.id, first.id);
640 expect(twice.status).toBe(409);
641 expect(await sameWords()).toBe(1);
642 expect(((await twice.json()) as { message: string }).message).toBe("That turn was already retried.");
643 // Regenerate on a failed turn has nothing to act on, and says so in its own words: the stale
644 // retry's refusal is its own, never shared with Regenerate and Edit.
645 const regen = await fetch(`${servers.url}/talk/${conv.id}/again/regenerate`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", cookie: `forge_session=${createSession(app.db, gus).token}` }, body: "" });
646 expect(regen.status).toBe(409);
647 expect(((await regen.json()) as { message: string }).message).toBe("there is nothing here to do that to");
648 // A retry with no key at all (a hand-built post) is refused too, though the last turn is
649 // failed.
650 withBinary(answers("Never."));
651 const bare = await retryPost(conv.id);
652 expect(bare.status).toBe(409);
653 expect(((await bare.json()) as { message: string }).message).toBe("Say which failed turn to retry.");
654 await settle();
655 expect(lastOf(conv.id).failed).toBe(true);
656 expect(await sameWords()).toBe(1);
657 // The new failure carries its own key, and that one retries.
658 const next = lastOf(conv.id);
659 expect(next.id).not.toBe(first.id);
660 withBinary(answers("Done."));
661 expect((await retryPost(conv.id, next.id)).status).toBe(202);
662 await settle();
663 expect(listOf(conv.id).filter((t) => !t.replaced).map((t) => `${t.role}:${t.text}`).slice(-2)).toEqual(["person:one question only", "agent:Done."]);
664 expect(await sameWords()).toBe(1);
665 });
666 test("the script's Retry posts the form's fields, so the turn key reaches the server", async () => {
667 const { talkJs } = await import("../src/web/pages/talk_client.ts");
668 expect(talkJs).toContain('again(r.dataset.again, new URLSearchParams(new FormData(r)))');
669 });
612670 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs