Public: anyone can read this; the crew can change it.
Talk on a starting forge keeps the message and says about how long (#16431) #16486
Check · Review · Land · Live done — Landed and live in production.
voice/wake → main 0 commits
8 files
changed +200
−10
docs/features/talk-kept-message.md +9 −3
| @@ -14,7 +14,12 @@ draws **Retry**: | ||
| 14 | 14 | - the forge is answering as many people as it can: Retry in a minute; |
| 15 | 15 | - pictures sent while an answer is under way: Retry when it has finished; |
| 16 | 16 | - no account answers for you yet: who can grant one, through the forge's own ask; |
| 17 | - the agent cannot run on this forge (no sandbox): an admin sees the cause. | |
| 17 | - the agent cannot run on this forge (no sandbox): an admin sees the cause; | |
| 18 | - the forge is starting (a woken cell waits for the forge it replaces before its agent runs, which | |
| 19 | 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. | |
| 18 | 23 | |
| 19 | 24 | Messages queued behind one that cannot start are kept too, in the order they were sent. |
| 20 | 25 | |
| @@ -24,5 +29,6 @@ In the terminal's Talk (`src/tui/screens/talk_chats.ts`) the line shows with " | ||
| 24 | 29 | `ssh <forge> talk-again retry <turn>` retries it; the API keeps its codes (`resting` 429, `busy` |
| 25 | 30 | 429, ...), and the kept turns are in `GET /api/v1/conversation/turns`. |
| 26 | 31 | |
| 27 | Code: `heldLine` and `isHeld` in `src/crew/conversation.ts`. Tests: `test/conversation-turn.test.ts`, | |
| 28 | `test/talk-kept-message.test.ts`. | |
| 32 | Code: `heldLine` and `isHeld` in `src/crew/conversation.ts`; the starting line is | |
| 33 | `src/crew/starting_line.ts`, kept by `keepWhileStarting`. Tests: `test/conversation-turn.test.ts`, | |
| 34 | `test/talk-kept-message.test.ts`, `test/talk-starting.test.ts`. |
src/actions/talk.ts +13 −4
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * and hands the words to `crew/conversation.ts`, which runs as that person. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { STARTING_LINE } from "../crew/starting_line.ts"; | |
| 8 | 9 | import { NO_TALK_ACCOUNT } from "./blocked_words.ts"; |
| 9 | 10 | import { storedText } from "../kernel/blocked.ts"; |
| 10 | 11 | import type { App } from "../app.ts"; |
| @@ -12,7 +13,7 @@ import { getConversation, lastExchange, openConversation } from "../core/convers | ||
| 12 | 13 | import type { ConversationFile } from "../core/conversation_files.ts"; |
| 13 | 14 | import { RateLimiter } from "../core/ratelimit.ts"; |
| 14 | 15 | import type { User } from "../core/users.ts"; |
| 15 | import { cancelQueued, queuedOf, conversationOptions, redo, say, stopTurn, type During, type RedoHow, type RedoRefusal, type SayRefusal, type Said } from "../crew/conversation.ts"; | |
| 16 | import { cancelQueued, queuedOf, conversationOptions, keepWhileStarting, redo, say, startingIn, stopTurn, type During, type RedoHow, type RedoRefusal, type SayRefusal, type Said } from "../crew/conversation.ts"; | |
| 16 | 17 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 17 | 18 | |
| 18 | 19 | /** Messages a person may send in a minute. */ |
| @@ -21,7 +22,7 @@ export const TALK_PER_MINUTE = 12; | ||
| 21 | 22 | /** What an empty conversation offers to send in one tap: plain text, the one list. */ |
| 22 | 23 | export const STARTER_PROMPTS = ["What is waiting for me?", "What shipped this week?", "Start something new"] as const; |
| 23 | 24 | |
| 24 | export type TalkRefusal = SayRefusal | RedoRefusal | "off" | "rate_limited" | "unkeyed" | "retried"; | |
| 25 | export type TalkRefusal = SayRefusal | RedoRefusal | "off" | "starting" | "rate_limited" | "unkeyed" | "retried"; | |
| 25 | 26 | |
| 26 | 27 | /** What each refusal says, with its status. */ |
| 27 | 28 | export const TALK_WORDS: Readonly<Record<TalkRefusal, readonly [number, string]>> = { |
| @@ -34,6 +35,7 @@ export const TALK_WORDS: Readonly<Record<TalkRefusal, readonly [number, string]> | ||
| 34 | 35 | answering: [409, "the forge is still answering; send pictures when it has finished"], |
| 35 | 36 | busy: [429, "the forge's agent is answering as many people as it can at once; try again in a minute"], |
| 36 | 37 | off: [503, "the forge's agent is not running here"], |
| 38 | starting: [503, STARTING_LINE], | |
| 37 | 39 | sandbox: [503, "this forge requires the agent sandbox and it is unavailable here, so its agent does not run; an admin sees the cause at the foot of any page"], |
| 38 | 40 | running: [409, "the forge is still answering; wait for it to finish"], |
| 39 | 41 | nothing: [409, "there is nothing here to do that to"], |
| @@ -64,7 +66,14 @@ export function talk(app: App, user: User | undefined, text: string, files: read | ||
| 64 | 66 | if (user === undefined) return err("unauthorized"); |
| 65 | 67 | if (conversationId !== undefined && getConversation(app.db, user.id, conversationId) === undefined) return err("not_found"); |
| 66 | 68 | const options = conversationOptions(app); |
| 67 | if (options === undefined) return err("off"); | |
| 69 | if (options === undefined) { | |
| 70 | // A woken forge configures its agent after it has waited for the one it replaces: the | |
| 71 | // message is kept meanwhile, and the person is told about when to Retry. | |
| 72 | if (startingIn(app) === undefined) return err("off"); | |
| 73 | if (!take(app, user)) return err("rate_limited"); | |
| 74 | const kept = keepWhileStarting(app, user.id, text, files, conversationId); | |
| 75 | return kept.ok ? err("starting") : kept; | |
| 76 | } | |
| 68 | 77 | if (!take(app, user)) return err("rate_limited"); |
| 69 | 78 | const said = say(app, options, user.id, text, files, during, conversationId, about); |
| 70 | 79 | if (said.ok) watch(app, said.value); |
| @@ -80,7 +89,7 @@ export function talk(app: App, user: User | undefined, text: string, files: read | ||
| 80 | 89 | export function talkAgain(app: App, user: User | undefined, how: RedoHow, text = "", conversationId?: string, turn?: string): Result<Said, TalkRefusal> { |
| 81 | 90 | if (user === undefined) return err("unauthorized"); |
| 82 | 91 | const options = conversationOptions(app); |
| 83 | if (options === undefined) return err("off"); | |
| 92 | if (options === undefined) return err(startingIn(app) === undefined ? "off" : "starting"); | |
| 84 | 93 | if (how === "retry") { |
| 85 | 94 | if (turn === undefined || turn === "") return err("unkeyed"); |
| 86 | 95 | const conversation = conversationId === undefined ? openConversation(app.db, user.id) : getConversation(app.db, user.id, conversationId); |
src/crew/conversation.ts +49
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | * what is done before doing anything. |
| 16 | 16 | */ |
| 17 | 17 | |
| 18 | import { STARTING_LINE } from "./starting_line.ts"; | |
| 18 | 19 | import { chmodSync, mkdirSync } from "node:fs"; |
| 19 | 20 | import { join } from "node:path"; |
| 20 | 21 | import type { App } from "../app.ts"; |
| @@ -85,8 +86,56 @@ const configured = new WeakMap<App, ConversationOptions>(); | ||
| 85 | 86 | /** The forge's conversation settings, set once at boot; the doors read them. */ |
| 86 | 87 | export const configureConversation = (app: App, options: ConversationOptions): void => { |
| 87 | 88 | configured.set(app, options); |
| 89 | starting.delete(app); | |
| 88 | 90 | }; |
| 89 | 91 | |
| 92 | /** | |
| 93 | * How long a boot may take before its agent answers: a woken cell waits for the forge it replaces | |
| 94 | * and probes its runner first (`main.ts`), which has taken up to about four minutes. | |
| 95 | */ | |
| 96 | export const STARTING_MS = 4 * 60_000; | |
| 97 | ||
| 98 | /** When this forge began a boot whose agent will answer, until it is configured. */ | |
| 99 | const starting = new WeakMap<App, number>(); | |
| 100 | ||
| 101 | /** The boot will configure the conversation: until it does, Talk says it is starting. */ | |
| 102 | export const expectConversation = (app: App, since: number = Date.now()): void => { | |
| 103 | if (!configured.has(app)) starting.set(app, since); | |
| 104 | }; | |
| 105 | ||
| 106 | /** The boot settled with no agent after all (the crew did not start): Talk says it is off. */ | |
| 107 | export const forgetConversation = (app: App): void => { | |
| 108 | starting.delete(app); | |
| 109 | }; | |
| 110 | ||
| 111 | /** | |
| 112 | * While the boot has yet to configure the conversation, about how many seconds are left: what is | |
| 113 | * left of `STARTING_MS`, at least ten. Undefined once it is configured, or when none is coming. | |
| 114 | */ | |
| 115 | export function startingIn(app: App, now: number = Date.now()): number | undefined { | |
| 116 | const since = starting.get(app); | |
| 117 | if (since === undefined || configured.has(app)) return undefined; | |
| 118 | return Math.max(10, Math.round((since + STARTING_MS - now) / 1000)); | |
| 119 | } | |
| 120 | ||
| 121 | /** | |
| 122 | * A message sent while the forge starts is kept, as any message that cannot start now is | |
| 123 | * (#16431): stored, its files released for the next try, and the line under it says the forge is | |
| 124 | * starting and when to Retry. | |
| 125 | */ | |
| 126 | export function keepWhileStarting(app: App, userId: string, text: string, files: readonly ConversationFile[], conversationId: string | undefined): Result<true, "not_found" | "too_long"> { | |
| 127 | const conversation = conversationId === undefined ? openConversation(app.db, userId) : getConversation(app.db, userId, conversationId); | |
| 128 | if (conversation === undefined) return err("not_found"); | |
| 129 | const stored = appendTurn(app.db, userId, conversation.id, { role: "person", text }); | |
| 130 | if (!stored.ok) return err("too_long"); | |
| 131 | attach(app.db, files, stored.value.id); | |
| 132 | release(app.db, stored.value.id); | |
| 133 | appendTurn(app.db, userId, conversation.id, { role: "agent", text: STARTING_LINE, failed: true }); | |
| 134 | return ok(true); | |
| 135 | } | |
| 136 | ||
| 137 | ||
| 138 | ||
| 90 | 139 | /** |
| 91 | 140 | * The person answered a held action on the page (`actions/conversation_confirms.ts`): the agent |
| 92 | 141 | * is told what became of it, so it never guesses. A turn still running hears it as a word between |
src/crew/starting_line.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | /** | |
| 2 | * The line under a message kept while the forge starts, and the API's message for it. No number: | |
| 3 | * the line stays in the conversation after the forge is up, and the seconds are the API's | |
| 4 | * Retry-After alone (`startingIn`, `crew/conversation.ts`). A leaf, so the refusal table in | |
| 5 | * `actions/talk.ts` and the conversation both read it without a cycle. | |
| 6 | */ | |
| 7 | export const STARTING_LINE = "This forge is starting; its agent answers within a few minutes. Your message is kept; Retry then."; |
src/http/api/conversation_talk.ts +4
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | * request is same-origin, and sending is throttled per person (`actions/talk.ts`). |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | import { startingIn } from "../../crew/conversation.ts"; | |
| 10 | 11 | import { limitRefusal } from "../../contract/page_query.ts"; |
| 11 | 12 | import { parseLimit } from "../../contract/page_query.ts"; |
| 12 | 13 | import { noTalkAccountBlocked } from "../../actions/blocked_words.ts"; |
| @@ -101,6 +102,9 @@ export function conversationTalkRoutes(router: Router<Handler>): void { | ||
| 101 | 102 | if (!said.ok) { |
| 102 | 103 | const [status, words] = TALK_WORDS[said.error]; |
| 103 | 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); | |
| 104 | 108 | return status === 429 || status === 503 ? tryAgain(said.error, status, words, talkWait(said.error)) : json({ error: said.error, message: words }, status); |
| 105 | 109 | } |
| 106 | 110 | return json(said.value.queued === undefined ? { how: said.value.how } : { how: said.value.how, queued: said.value.queued }, 202); |
src/main.ts +5 −2
| @@ -90,7 +90,7 @@ import { DRAIN_LINGER_MAX_S, drainLingerMs, startDraining } from "./http/health. | ||
| 90 | 90 | import { takePresence, warmBehind } from "./apps/presence.ts"; |
| 91 | 91 | import { STALE_AFTER_MS } from "./runs/lease.ts"; |
| 92 | 92 | import { runnerSettings, startCrew, sweepAssigned } from "./crew/dispatch.ts"; |
| 93 | import { configureConversation, resumeInterrupted } from "./crew/conversation.ts"; | |
| 93 | import { configureConversation, expectConversation, forgetConversation, resumeInterrupted } from "./crew/conversation.ts"; | |
| 94 | 94 | import { sandboxMode } from "./crew/sandbox_policy.ts"; |
| 95 | 95 | import { CREW_OFF_IN_PREVIEW, crewOffInPreview } from "./crew/preview.ts"; |
| 96 | 96 | import { typeSafeDecider } from "./crew/decide.ts"; |
| @@ -649,6 +649,9 @@ const leaveEarly = (): void => { | ||
| 649 | 649 | }; |
| 650 | 650 | const earlySignals = ["SIGINT", "SIGTERM", "SIGHUP"] as const; |
| 651 | 651 | for (const signal of earlySignals) process.once(signal, leaveEarly); |
| 652 | // Talk answers while this forge waits for the one it replaces and probes its runner: a message is | |
| 653 | // kept, and the person is told the forge is starting (crew/conversation.ts, `startingIn`). | |
| 654 | if (appsOn && !crewOffInPreview()) expectConversation(app); | |
| 652 | 655 | const peerWaitStarted = performance.now(); |
| 653 | 656 | await waitForPeer(app.db, app.log); |
| 654 | 657 | // How long this forge held its queue work for the old one (#7836): the keeper keeps it on the |
| @@ -792,7 +795,7 @@ if (crew !== undefined) { | ||
| 792 | 795 | startRoutines(app, conversationsStop.signal); |
| 793 | 796 | for (const turn of resumeInterrupted(app, conversation)) |
| 794 | 797 | turn.catch((error: unknown) => app.log.error("resumed conversation turn crashed", { error: String(error) })); |
| 795 | } | |
| 798 | } else forgetConversation(app); | |
| 796 | 799 | // Hosted children come back with their apps, awake before the first visit. |
| 797 | 800 | // The listener is up; the children open behind it, not in front of /healthz. |
| 798 | 801 | // A forge still inside this process is moved into a cell of its own first, where this host holds |
src/web/pages/talk.ts +1 −1
| @@ -726,7 +726,7 @@ export async function talkSend(ctx: Ctx): Promise<Response> { | ||
| 726 | 726 | const said = talk(ctx.app, user, text, [], "queue", conversation.id, typeof about === "string" ? about : null); |
| 727 | 727 | if (!said.ok && said.error === "no_account") return flashTo(ctx, `${here}`, blockedFlash(noTalkAccountBlocked(ctx.app, user), "danger")); |
| 728 | 728 | // Kept: the line under the message says why it could not start and when to Retry. |
| 729 | if (!said.ok && isHeld(said.error)) return flashTo(ctx, `${here}`, { tone: "attn", message: KEPT_FLASH }); | |
| 729 | if (!said.ok && (isHeld(said.error) || said.error === "starting")) return flashTo(ctx, `${here}`, { tone: "attn", message: KEPT_FLASH }); | |
| 730 | 730 | if (!said.ok) return flashTo(ctx, `${here}`, { tone: "danger", message: TALK_WORDS[said.error][1] }); |
| 731 | 731 | return flashTo(ctx, `${here}`, { tone: "success", message: "Sent. Reload to see the answer." }); |
| 732 | 732 | } |
test/talk-starting.test.ts added +112
| @@ -0,0 +1,112 @@ | ||
| 1 | /** | |
| 2 | * A woken forge configures its agent only after it has waited for the forge it replaces, which has | |
| 3 | * taken minutes on a hosted cell. Meanwhile Talk does not answer "off": a message is kept, the line | |
| 4 | * under it says the forge is starting and about when to Retry, and the API answers 503 with a | |
| 5 | * Retry-After of what is left. Once the agent is configured, Talk answers; a boot whose crew did | |
| 6 | * not start says off. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { talk, talkAgain } from "../src/actions/talk.ts"; | |
| 13 | import { STARTING_LINE } from "../src/crew/starting_line.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { listTurns, openConversation } from "../src/core/conversations.ts"; | |
| 16 | import { createSession } from "../src/core/sessions.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import { KEPT_FLASH } from "../src/web/pages/talk.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { configureConversation, expectConversation, forgetConversation, STARTING_MS, startingIn } from "../src/crew/conversation.ts"; | |
| 21 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | let dir: string, app: App, servers: Servers, alice: User, token: string; | |
| 26 | beforeAll(async () => { | |
| 27 | dir = await mkdtemp(join(tmpdir(), "forge-talk-starting-")); | |
| 28 | app = createApp({ dataDir: dir, port: 0 }); | |
| 29 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", isAdmin: true }); | |
| 30 | if (!made.ok) throw new Error(made.error); | |
| 31 | alice = made.value; | |
| 32 | token = createToken(app.db, alice.id, "t", "rw").token; | |
| 33 | servers = await serve(app); | |
| 34 | }); | |
| 35 | afterAll(async () => { | |
| 36 | await servers.stop(); | |
| 37 | app.close(); | |
| 38 | await rm(dir, { recursive: true, force: true }); | |
| 39 | }); | |
| 40 | ||
| 41 | const send = (text: string) => | |
| 42 | fetch(`${servers.url}/api/v1/conversation/messages`, { | |
| 43 | method: "POST", | |
| 44 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 45 | body: JSON.stringify({ text }), | |
| 46 | }); | |
| 47 | ||
| 48 | test("with no agent expected, Talk says off, as before", async () => { | |
| 49 | expect(startingIn(app)).toBeUndefined(); | |
| 50 | const res = await send("hello"); | |
| 51 | expect([res.status, ((await res.json()) as { error: string }).error]).toEqual([503, "off"]); | |
| 52 | }); | |
| 53 | ||
| 54 | test("while the boot has yet to configure the agent, a message is kept and the wait is said and sent", async () => { | |
| 55 | const now = Date.now(); | |
| 56 | expectConversation(app, now - 60_000); | |
| 57 | const left = startingIn(app, now)!; | |
| 58 | expect(left).toBe(Math.round((STARTING_MS - 60_000) / 1000)); | |
| 59 | const res = await send("what shipped today?"); | |
| 60 | expect(res.status).toBe(503); | |
| 61 | const wait = Number(res.headers.get("retry-after")); | |
| 62 | expect(wait).toBeGreaterThan(150); | |
| 63 | expect(wait).toBeLessThanOrEqual(180); | |
| 64 | const body = (await res.json()) as { error: string; message: string }; | |
| 65 | expect(body.error).toBe("starting"); | |
| 66 | // The line carries no number: the seconds are Retry-After's alone, read once. | |
| 67 | expect(body.message).toBe(STARTING_LINE); | |
| 68 | // Kept: the words, and the line under them flagged failed so the page draws Retry. | |
| 69 | const turns = listTurns(app.db, alice.id, openConversation(app.db, alice.id).id); | |
| 70 | if (!turns.ok) throw new Error(turns.error); | |
| 71 | const last = turns.value.slice(-2); | |
| 72 | // The stored line is the one the API answered, exactly. | |
| 73 | expect(last.map((t) => [t.role, t.text])).toEqual([ | |
| 74 | ["person", "what shipped today?"], | |
| 75 | ["agent", body.message], | |
| 76 | ]); | |
| 77 | expect(last[1]!.failed).toBe(true); | |
| 78 | // The page's plain form keeps it too, and says so rather than "not running". | |
| 79 | const session = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 80 | const posted = await fetch(`${servers.url}/talk`, { | |
| 81 | method: "POST", | |
| 82 | redirect: "manual", | |
| 83 | headers: { cookie: session, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, | |
| 84 | body: new URLSearchParams({ text: "and yesterday?" }), | |
| 85 | }); | |
| 86 | expect(posted.status).toBe(303); | |
| 87 | const flash = (posted.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 88 | const shown = await (await fetch(`${servers.url}${posted.headers.get("location")}`, { headers: { cookie: `${session}; ${flash}` } })).text(); | |
| 89 | expect(shown).toContain(KEPT_FLASH); | |
| 90 | expect(shown).not.toContain("not running here"); | |
| 91 | // Retry pressed before the agent is up: refused as starting, and nothing more is stored. | |
| 92 | const before = (listTurns(app.db, alice.id, openConversation(app.db, alice.id).id) as { ok: true; value: unknown[] }).value.length; | |
| 93 | expect(talkAgain(app, alice, "retry", "", undefined, last[1]!.id)).toEqual({ ok: false, error: "starting" }); | |
| 94 | expect((listTurns(app.db, alice.id, openConversation(app.db, alice.id).id) as { ok: true; value: unknown[] }).value.length).toBe(before); | |
| 95 | // Never less than ten seconds, however long the boot runs past its budget. | |
| 96 | expect(startingIn(app, now + STARTING_MS * 2)).toBe(10); | |
| 97 | }); | |
| 98 | ||
| 99 | test("once the agent is configured, it is no longer starting; a boot with no crew says off", () => { | |
| 100 | configureConversation(app, { binary: "/bin/false", localUrl: servers.url, budgetUsd: 1, timeoutMs: 1000, signal: new AbortController().signal }); | |
| 101 | expect(startingIn(app)).toBeUndefined(); | |
| 102 | const fresh = createApp({ dataDir: join(dir, "second"), port: 0 }); | |
| 103 | try { | |
| 104 | expectConversation(fresh); | |
| 105 | expect(startingIn(fresh)).toBeGreaterThan(200); | |
| 106 | forgetConversation(fresh); | |
| 107 | expect(startingIn(fresh)).toBeUndefined(); | |
| 108 | expect(talk(fresh, alice, "hi")).toEqual({ ok: false, error: "off" }); | |
| 109 | } finally { | |
| 110 | fresh.close(); | |
| 111 | } | |
| 112 | }); |
new above
offline