Public: anyone can read this; the crew can change it.
A Talk message never vanishes: kept, with why and when, and Retry (#16431) #16433
Check · Review · Land · Live done — Landed and live in production.
fix/talk-send-never-vanishes → main 0 commits
7 files
changed +361
−26
docs/features/talk-kept-message.md added +28
| @@ -0,0 +1,28 @@ | ||
| 1 | --- | |
| 2 | topic: Tell the crew | |
| 3 | row: A message that cannot start is kept, with why and when | |
| 4 | --- | |
| 5 | ||
| 6 | # A message that cannot start is kept (#16431) | |
| 7 | ||
| 8 | A message sent to Talk is never lost. When no turn can start for it right now, the message stays in | |
| 9 | the conversation and one line under it says why and when to try again, marked failed so the page | |
| 10 | draws **Retry**: | |
| 11 | ||
| 12 | - the account that answers you is resting: "The account that answers you is resting until 18:08 UTC. | |
| 13 | Your message is kept; Retry then." (the time is the account's own, or what it said); | |
| 14 | - the forge is answering as many people as it can: Retry in a minute; | |
| 15 | - pictures sent while an answer is under way: Retry when it has finished; | |
| 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. | |
| 18 | ||
| 19 | Messages queued behind one that cannot start are kept too, in the order they were sent. | |
| 20 | ||
| 21 | **Retry** sends the kept message again, once: the failed line is set aside and the same words start a | |
| 22 | new turn. The page says "Your message is kept. Tap Retry under it when you are ready." (`src/web/pages/talk.ts`). | |
| 23 | In the terminal's Talk (`src/tui/screens/talk_chats.ts`) the line shows with " · failed", and | |
| 24 | `ssh <forge> talk-again retry <turn>` retries it; the API keeps its codes (`resting` 429, `busy` | |
| 25 | 429, ...), and the kept turns are in `GET /api/v1/conversation/turns`. | |
| 26 | ||
| 27 | Code: `heldLine` and `isHeld` in `src/crew/conversation.ts`. Tests: `test/conversation-turn.test.ts`, | |
| 28 | `test/talk-kept-message.test.ts`. |
src/crew/conversation.ts +51 −12
| @@ -40,6 +40,7 @@ import { id } from "../kernel/id.ts"; | ||
| 40 | 40 | import { redactHeld, releaseValues } from "../kernel/log.ts"; |
| 41 | 41 | import { running } from "../kernel/version.ts"; |
| 42 | 42 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 43 | import { storedText } from "../kernel/blocked.ts"; | |
| 43 | 44 | import { appendRunLog } from "../runs/log.ts"; |
| 44 | 45 | import { currentRunner, runAgent, type AgentOutcome, type HistoryTurn, type RunnerLimit } from "./agent_runner.ts"; |
| 45 | 46 | import { runAccount } from "./runner_env.ts"; |
| @@ -392,8 +393,10 @@ function drain(app: App, options: ConversationOptions, conversation: Conversatio | ||
| 392 | 393 | return; |
| 393 | 394 | } |
| 394 | 395 | release(app.db, stored.value.id); |
| 396 | // The messages waiting behind it are kept too, in order, never dropped with the queue. | |
| 397 | for (const waiting of queues.get(current.id) ?? []) appendTurn(app.db, userId, current.id, { role: "person", text: waiting.text }); | |
| 395 | 398 | queues.delete(current.id); |
| 396 | appendTurn(app.db, userId, current.id, { role: "agent", text: failureLine("error"), failed: true }); | |
| 399 | appendTurn(app.db, userId, current.id, { role: "agent", text: heldLine(started.error), failed: true }); | |
| 397 | 400 | } |
| 398 | 401 | |
| 399 | 402 | /** |
| @@ -458,12 +461,13 @@ export function say( | ||
| 458 | 461 | const stored = appendTurn(app.db, userId, conversation.id, { role: "person", text }); |
| 459 | 462 | if (!stored.ok) return err("too_long"); |
| 460 | 463 | attach(app.db, files, stored.value.id); |
| 461 | // A message nobody will answer is not kept: the door says why instead, and its files wait for the | |
| 462 | // next try. | |
| 463 | const refuse = (why: SayRefusal): Result<Said, SayRefusal> => { | |
| 464 | // A message is never lost (#16431): one that cannot start now is kept, and the line under it says | |
| 465 | // why and when, flagged failed so the page draws Retry. Its files wait for the next try. | |
| 466 | const refuse = (why: HeldRefusal | NotStarted): Result<Said, SayRefusal> => { | |
| 467 | const reason = typeof why === "string" ? { code: why } : why; | |
| 464 | 468 | release(app.db, stored.value.id); |
| 465 | removeTurn(app.db, userId, conversation.id, stored.value.id); | |
| 466 | return err(why); | |
| 469 | appendTurn(app.db, userId, conversation.id, { role: "agent", text: heldLine(reason), failed: true }); | |
| 470 | return err(reason.code); | |
| 467 | 471 | }; |
| 468 | 472 | const delivery = deliver(app.config.dataDir, userId, files); |
| 469 | 473 | const running = live.get(conversation.id); |
| @@ -537,7 +541,7 @@ export function redo(app: App, options: ConversationOptions, userId: string, how | ||
| 537 | 541 | added = stored.value.id; |
| 538 | 542 | } |
| 539 | 543 | const started = begin(app, options, conversation, withHistory(app, conversation, words), 0, undefined); |
| 540 | if (!started.ok) return refuse(started.error, added); | |
| 544 | if (!started.ok) return refuse(started.error.code, added); | |
| 541 | 545 | return ok({ how: "started", done: started.value }); |
| 542 | 546 | } |
| 543 | 547 | |
| @@ -586,6 +590,41 @@ function limitLine(app: App, picked: Pick, limit: RunnerLimit): string { | ||
| 586 | 590 | : `${account.name} is resting until ${whenText(until)}.`; |
| 587 | 591 | } |
| 588 | 592 | |
| 593 | /** The refusals a message is kept through: it is a message, and it cannot start now. */ | |
| 594 | export type HeldRefusal = "resting" | "busy" | "answering" | "no_account" | "sandbox" | "unauthorized"; | |
| 595 | const HELD: ReadonlySet<string> = new Set<HeldRefusal>(["resting", "busy", "answering", "no_account", "sandbox", "unauthorized"]); | |
| 596 | ||
| 597 | /** Whether a refusal is one a message is kept through, with its line and Retry (#16431). */ | |
| 598 | export const isHeld = (code: string): code is HeldRefusal => HELD.has(code); | |
| 599 | ||
| 600 | /** Why a turn did not start: the refusal, and what the account said and until when, where known. */ | |
| 601 | export interface NotStarted { | |
| 602 | readonly code: "no_account" | "resting" | "unauthorized" | "sandbox"; | |
| 603 | readonly until?: string; | |
| 604 | readonly said?: string; | |
| 605 | } | |
| 606 | ||
| 607 | /** The line under a message that is kept but cannot start now: why, and when to Retry. */ | |
| 608 | export function heldLine(why: { readonly code: HeldRefusal; readonly until?: string; readonly said?: string }): string { | |
| 609 | switch (why.code) { | |
| 610 | case "resting": | |
| 611 | return why.until !== undefined | |
| 612 | ? `The account that answers you is resting until ${whenText(new Date(why.until))}. Your message is kept; Retry then.` | |
| 613 | : `The account that answers you is resting${why.said === undefined ? "" : `: ${why.said.replace(/\.$/, "")}`}. Your message is kept; Retry later.`; | |
| 614 | case "busy": | |
| 615 | return "The forge is answering as many people as it can at once. Your message is kept; Retry in a minute."; | |
| 616 | case "answering": | |
| 617 | return "Pictures cannot join an answer already under way. Your message is kept; Retry when it has finished."; | |
| 618 | case "no_account": | |
| 619 | // Who can grant one, through the one helper for such sentences (docs/features/blocked-by.md). | |
| 620 | return storedText("No account answers for you on this forge yet. Your message is kept for Retry.", "an admin of this forge", "grant one"); | |
| 621 | case "sandbox": | |
| 622 | return "This forge's agent cannot run here: it requires a sandbox that is unavailable. Your message is kept; an admin sees the cause at the foot of any page."; | |
| 623 | case "unauthorized": | |
| 624 | return "The forge could not open a turn for you just now. Your message is kept; Retry in a moment."; | |
| 625 | } | |
| 626 | } | |
| 627 | ||
| 589 | 628 | /** What a run that did not end well says to the person: what happened, never the raw error. */ |
| 590 | 629 | export function failureLine(reason: string): string { |
| 591 | 630 | if (reason === "timeout") return "That took longer than a turn may, so I stopped."; |
| @@ -607,10 +646,10 @@ function begin( | ||
| 607 | 646 | * answers. |
| 608 | 647 | */ |
| 609 | 648 | follow?: { readonly words: string }, |
| 610 | ): Result<Promise<void>, "no_account" | "resting" | "unauthorized" | "sandbox"> { | |
| 649 | ): Result<Promise<void>, NotStarted> { | |
| 611 | 650 | // A forge that requires the sandbox and cannot make one starts no agent process at all, a turn |
| 612 | 651 | // with no shell included (`sandbox_policy.ts`); any other forge is not asked. |
| 613 | if (sandboxRefusal(app) !== undefined) return err("sandbox"); | |
| 652 | if (sandboxRefusal(app) !== undefined) return err({ code: "sandbox" }); | |
| 614 | 653 | const userId = conversation.userId; |
| 615 | 654 | const runId = id(); |
| 616 | 655 | const now = new Date(); |
| @@ -619,9 +658,9 @@ function begin( | ||
| 619 | 658 | runId, |
| 620 | 659 | usd: options.budgetUsd, |
| 621 | 660 | }); |
| 622 | if (picked.kind === "resting") return err("resting"); | |
| 661 | if (picked.kind === "resting") return err({ code: "resting", until: picked.until }); | |
| 623 | 662 | const spend = turnBudget(app, picked, userId, options.budgetUsd, now); |
| 624 | if (!spend.ok) return err(spend.refusal); | |
| 663 | if (!spend.ok) return err({ code: spend.refusal, ...(spend.refusal === "resting" ? { said: spend.said } : {}) }); | |
| 625 | 664 | const budget = spend.budget; |
| 626 | 665 | const subscriptionId = picked.kind === "ready" ? picked.subscription.id : PLATFORM; |
| 627 | 666 | // A new turn's token replaces the last one's. |
| @@ -634,7 +673,7 @@ function begin( | ||
| 634 | 673 | // Answers to held actions since the last turn began, which the session never saw: told first. |
| 635 | 674 | const since = app.db.query<{ at: string | null }, [string]>("SELECT MAX(started_at) AS at FROM conversation_run WHERE conversation_id = ?1").get(conversation.id)?.at; |
| 636 | 675 | const told = follow !== undefined || since === null || since === undefined ? { text: "", fenced: false } : answeredNote(app.db, userId, conversation.id, since); |
| 637 | if (!minted.ok) return err("unauthorized"); | |
| 676 | if (!minted.ok) return err({ code: "unauthorized" }); | |
| 638 | 677 | if (told.fenced) readFenced(app.db, via); |
| 639 | 678 | // An attached file or picture is text that arrives without a read (#8820): the fence is raised |
| 640 | 679 | // before the agent sees it, on every path a message starts a turn by (send, queue, interrupt). |
src/tui/screens/talk_chats.ts +1 −1
| @@ -327,7 +327,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 327 | 327 | const own = (step === undefined ? said : [step.label, ...step.details.map((d) => ` ${d}`)].join("\n")).split("\n").flatMap((l) => wrap(l, Math.max(10, width - 2))); |
| 328 | 328 | n += own.length + 2; |
| 329 | 329 | return [ |
| 330 | [{ text: `${t.id === around ? "▶ " : ""}${WHO[t.role] ?? t.role}${t.replaced ? " · replaced" : ""} · ${ago(t.createdAt)}`, style: style(c.mutedFg, c.bg) }], | |
| 330 | [{ text: `${t.id === around ? "▶ " : ""}${WHO[t.role] ?? t.role}${t.replaced ? " · replaced" : ""}${t.failed ? " · failed: Retry on the page, or talk-again retry" : ""} · ${ago(t.createdAt)}`, style: style(c.mutedFg, c.bg) }], | |
| 331 | 331 | ...own.map((l) => [{ text: l, style: style(c.fg, c.bg) }]), |
| 332 | 332 | [], |
| 333 | 333 | ]; |
src/web/pages/talk.ts +8 −1
| @@ -50,7 +50,7 @@ import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.t | ||
| 50 | 50 | import { ASKING } from "../../crew/conversation_confirm.ts"; |
| 51 | 51 | import { INVERSES, readReceipt, type Receipt } from "../../crew/receipt.ts"; |
| 52 | 52 | import { pastTime } from "../../core/fence.ts"; |
| 53 | import { turnRunning, type RedoHow } from "../../crew/conversation.ts"; | |
| 53 | import { isHeld, turnRunning, type RedoHow } from "../../crew/conversation.ts"; | |
| 54 | 54 | import { liveBlock, subscribe } from "../../crew/conversation_live.ts"; |
| 55 | 55 | import { during } from "../../perf/jobs.ts"; |
| 56 | 56 | import type { Ctx } from "../../http/context.ts"; |
| @@ -719,10 +719,17 @@ export async function talkSend(ctx: Ctx): Promise<Response> { | ||
| 719 | 719 | const about = form.get("about"); |
| 720 | 720 | const said = talk(ctx.app, user, text, [], "queue", conversation.id, typeof about === "string" ? about : null); |
| 721 | 721 | if (!said.ok && said.error === "no_account") return flashTo(ctx, `${here}`, blockedFlash(noTalkAccountBlocked(ctx.app, user), "danger")); |
| 722 | // Kept: the line under the message says why it could not start and when to Retry. | |
| 723 | if (!said.ok && isHeld(said.error)) return flashTo(ctx, `${here}`, { tone: "attn", message: KEPT_FLASH }); | |
| 722 | 724 | if (!said.ok) return flashTo(ctx, `${here}`, { tone: "danger", message: TALK_WORDS[said.error][1] }); |
| 723 | 725 | return flashTo(ctx, `${here}`, { tone: "success", message: "Sent. Reload to see the answer." }); |
| 724 | 726 | } |
| 725 | 727 | |
| 728 | /** | |
| 729 | * What the page says when a message is kept but could not start: it is there, and Retry sends it. | |
| 730 | */ | |
| 731 | export const KEPT_FLASH = "Your message is kept. Tap Retry under it when you are ready."; | |
| 732 | ||
| 726 | 733 | // POST /talk/wall — the access wall answered from a receipt in Talk (`answerWall`, the pull page's |
| 727 | 734 | // merge or its request for changes): a same-origin form, so it works without the script. A pull |
| 728 | 735 | // the person may not read is answered as not found, never named. |
test/conversation-talk.test.ts +5 −3
| @@ -196,9 +196,11 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t | ||
| 196 | 196 | expect(over.status).toBe(429); |
| 197 | 197 | expect(over.headers.get("retry-after")).toBe("60"); |
| 198 | 198 | expect(((await over.json()) as { error: string }).error).toBe("rate_limited"); |
| 199 | // Nothing dana said was kept: no turn could answer it. | |
| 200 | const read = await fetch(`${servers.url}/api/v1/conversation/turns`, { headers: headers(dana) }); | |
| 201 | expect(((await read.json()) as { turns: unknown[] }).turns).toEqual([]); | |
| 199 | // Every message dana sent is kept with the line saying why; the one past the cap never arrived. | |
| 200 | const read = await fetch(`${servers.url}/api/v1/conversation/turns?limit=100`, { headers: headers(dana) }); | |
| 201 | const kept = ((await read.json()) as { turns: { role: string; failed?: boolean }[] }).turns; | |
| 202 | expect(kept.filter((t) => t.role === "person")).toHaveLength(TALK_PER_MINUTE); | |
| 203 | expect(kept.filter((t) => t.role === "agent" && t.failed === true)).toHaveLength(TALK_PER_MINUTE); | |
| 202 | 204 | }); |
| 203 | 205 | |
| 204 | 206 | test("a person whose only grant is a dollar grant can talk; with neither the refusal says to ask an admin", async () => { |
test/conversation-turn.test.ts +31 −9
| @@ -15,7 +15,7 @@ import { clearAccountCeiling, daySpent, setAccountCeiling } from "../src/core/ac | ||
| 15 | 15 | import { claimDone, completeWrite, recordWrite } from "../src/core/conversation_writes.ts"; |
| 16 | 16 | import { listTurns, newConversation, openConversation } from "../src/core/conversations.ts"; |
| 17 | 17 | import { monthSpent } from "../src/core/model_grant.ts"; |
| 18 | import { addSubscription, getSubscription, PLATFORM, setGrants, wakeSubscription } from "../src/core/subscriptions.ts"; | |
| 18 | import { addSubscription, getSubscription, PLATFORM, restSubscription, setGrants, wakeSubscription } from "../src/core/subscriptions.ts"; | |
| 19 | 19 | import { verifyToken } from "../src/core/tokens.ts"; |
| 20 | 20 | import { createUser, type User } from "../src/core/users.ts"; |
| 21 | 21 | import { createSession } from "../src/core/sessions.ts"; |
| @@ -351,19 +351,18 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to | ||
| 351 | 351 | expect(many).toContain("ask me after this answer and I will do them then."); |
| 352 | 352 | }); |
| 353 | 353 | |
| 354 | test("a person with no account and no admin is refused, and nothing is stored as a run", async () => { | |
| 354 | test("a person with no account and no admin is refused, the message kept with why, and nothing stored as a run", async () => { | |
| 355 | 355 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); |
| 356 | 356 | if (!b.ok) throw new Error("user"); |
| 357 | 357 | const said = say(app, options(stub("bobs", "s", "answer")), b.value.id, "hi"); |
| 358 | 358 | expect(!said.ok && said.error).toBe("no_account"); |
| 359 | 359 | expect(existsSync(join(dir, "bobs.argv"))).toBe(false); |
| 360 | // The words nobody will answer are not kept. | |
| 361 | expect(turns(b.value)).toEqual([]); | |
| 360 | // A message is never lost (#16431): kept, with the line saying why, flagged failed for Retry. | |
| 361 | 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."]); | |
| 362 | 362 | expect(app.db.query("SELECT 1 FROM conversation_run WHERE user_id = ?1").all(b.value.id)).toHaveLength(0); |
| 363 | 363 | }); |
| 364 | 364 | |
| 365 | test("a person at their daily ceiling rests, and the message is not kept", async () => { | |
| 366 | const before = turns(alice); | |
| 365 | test("a person at their daily ceiling rests: the message is kept, and the line says why", async () => { | |
| 367 | 366 | // Alice spent $0.50 a turn on the forge's own credential: her month counts each one. |
| 368 | 367 | const runs = app.db.query<{ n: number }, [string]>("SELECT SUM(cost_usd) AS n FROM conversation_run WHERE user_id = ?1").get(alice.id)?.n ?? 0; |
| 369 | 368 | expect(runs).toBeGreaterThan(0); |
| @@ -373,16 +372,18 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to | ||
| 373 | 372 | clearAccountCeiling(app.db, alice.id); |
| 374 | 373 | expect(!said.ok && said.error).toBe("resting"); |
| 375 | 374 | expect(existsSync(join(dir, "ceiling.argv"))).toBe(false); |
| 376 | expect(turns(alice)).toEqual(before); | |
| 375 | const added = turns(alice).slice(-2); | |
| 376 | expect(added[0]).toBe("person:over the day"); | |
| 377 | expect(added[1]).toMatch(/^agent:The account that answers you is resting.*Your message is kept; Retry later\.$/); | |
| 378 | expect(added).toHaveLength(2); | |
| 377 | 379 | }); |
| 378 | 380 | |
| 379 | 381 | test("past the live-turn cap a new turn is busy; a steer into a running one is not counted", async () => { |
| 380 | 382 | expect(TURNS_LIVE_MAX).toBe(4); |
| 381 | const before = turns(alice); | |
| 382 | 383 | const none = say(app, { ...options(stub("capped", "sess-a", "answer")), liveMax: 0 }, alice.id, "too many"); |
| 383 | 384 | expect(!none.ok && none.error).toBe("busy"); |
| 384 | 385 | expect(existsSync(join(dir, "capped.argv"))).toBe(false); |
| 385 | expect(turns(alice)).toEqual(before); | |
| 386 | 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."]); | |
| 386 | 387 | const bin = stub("one-live", "sess-a", "steer"); |
| 387 | 388 | const a = say(app, { ...options(bin), liveMax: 1 }, alice.id, "first"); |
| 388 | 389 | expect(a.ok && a.value.how).toBe("started"); |
| @@ -392,6 +393,27 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Back.","to | ||
| 392 | 393 | if (a.ok) await a.value.done; |
| 393 | 394 | }); |
| 394 | 395 | |
| 396 | test("an account resting until a time: the message is kept, the line names when, and Retry after it answers (#16431)", async () => { | |
| 397 | // What a cell saw at 18:08: its account still resting, the person's words gone without a line. | |
| 398 | const sub = addSubscription(app.db, dir, { name: "lent", token: "sk-ant-api-test-lent" }); | |
| 399 | if (!sub.ok) throw new Error("subscription"); | |
| 400 | setGrants(app.db, alice.id, "", [sub.value.id]); | |
| 401 | const until = new Date(Date.now() + 15 * 60_000).toISOString(); | |
| 402 | restSubscription(app.db, sub.value.id, until, "window full"); | |
| 403 | const said = say(app, options(stub("rested", "s", "answer")), alice.id, "what is happening on voxel?"); | |
| 404 | expect(!said.ok && said.error).toBe("resting"); | |
| 405 | expect(existsSync(join(dir, "rested.argv"))).toBe(false); | |
| 406 | const added = turns(alice).slice(-2); | |
| 407 | expect(added[0]).toBe("person:what is happening on voxel?"); | |
| 408 | expect(added[1]).toMatch(/^agent:The account that answers you is resting until .+\. Your message is kept; Retry then\.$/); | |
| 409 | // The kept line is the failed turn Retry answers. | |
| 410 | const conversation = openConversation(app.db, alice.id); | |
| 411 | const last = listTurns(app.db, alice.id, conversation.id); | |
| 412 | expect(last.ok && last.value.at(-1)?.failed).toBe(true); | |
| 413 | wakeSubscription(app.db, sub.value.id); | |
| 414 | setGrants(app.db, alice.id, "", []); | |
| 415 | }); | |
| 416 | ||
| 395 | 417 | const viaTokens = (): number => |
| 396 | 418 | app.db |
| 397 | 419 | .query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM via_token WHERE via = ?1") |
test/talk-kept-message.test.ts added +237
| @@ -0,0 +1,237 @@ | ||
| 1 | /** | |
| 2 | * A Talk message that cannot start is kept, with its line, on every door (#16431): the page's send | |
| 3 | * says so and names Retry, the terminal shows the line marked failed, Retry sends the kept words | |
| 4 | * once, and messages queued behind one whose turn cannot start are kept in order, as the person's. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { chmodSync, existsSync, writeFileSync } from "node:fs"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { talkAgain } from "../src/actions/talk.ts"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { listTurns, openConversation } from "../src/core/conversations.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { | |
| 17 | addSubscription, | |
| 18 | restSubscription, | |
| 19 | setGrants, | |
| 20 | wakeSubscription, | |
| 21 | } from "../src/core/subscriptions.ts"; | |
| 22 | import { createUser, type User } from "../src/core/users.ts"; | |
| 23 | import { | |
| 24 | configureConversation, | |
| 25 | say, | |
| 26 | type ConversationOptions, | |
| 27 | } from "../src/crew/conversation.ts"; | |
| 28 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 29 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 30 | import { talkChatsScreen } from "../src/tui/screens/talk_chats.ts"; | |
| 31 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 32 | import { KEPT_FLASH } from "../src/web/pages/talk.ts"; | |
| 33 | import { promote } from "./helpers/members.ts"; | |
| 34 | import { quietLogs } from "./helpers/globals.ts"; | |
| 35 | import { settleApp } from "./helpers/tui.ts"; | |
| 36 | import { waitFor } from "./helpers/poll.ts"; | |
| 37 | ||
| 38 | quietLogs(); | |
| 39 | ||
| 40 | let dir: string; | |
| 41 | let app: App; | |
| 42 | let servers: Servers; | |
| 43 | let alice: User; | |
| 44 | let answer = ""; | |
| 45 | let gated = ""; | |
| 46 | ||
| 47 | const options = ( | |
| 48 | extra: Partial<ConversationOptions> = {}, | |
| 49 | ): ConversationOptions => ({ | |
| 50 | binary: answer, | |
| 51 | localUrl: servers.url, | |
| 52 | budgetUsd: 1, | |
| 53 | timeoutMs: 30_000, | |
| 54 | signal: new AbortController().signal, | |
| 55 | ...extra, | |
| 56 | }); | |
| 57 | ||
| 58 | const said = (u: User) => { | |
| 59 | const r = listTurns(app.db, u.id, openConversation(app.db, u.id).id, { | |
| 60 | limit: 100, | |
| 61 | }); | |
| 62 | return r.ok | |
| 63 | ? r.value.map( | |
| 64 | (t) => | |
| 65 | `${t.role}${t.failed ? "!" : ""}${t.replaced ? "~" : ""}:${t.text}`, | |
| 66 | ) | |
| 67 | : []; | |
| 68 | }; | |
| 69 | ||
| 70 | const stub = (name: string, gate: boolean): string => { | |
| 71 | const path = join(dir, name); | |
| 72 | writeFileSync( | |
| 73 | path, | |
| 74 | `#!/bin/sh | |
| 75 | if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi | |
| 76 | IFS= read -r first | |
| 77 | echo '{"type":"system","subtype":"init","session_id":"s-${name}","model":"fake"}' | |
| 78 | ${gate ? `touch "${dir}/${name}.started"; while [ ! -f "${dir}/${name}.gate" ]; do sleep 0.05; done` : ""} | |
| 79 | echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","total_cost_usd":0.01,"num_turns":1,"session_id":"s-${name}","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}' | |
| 80 | `, | |
| 81 | ); | |
| 82 | chmodSync(path, 0o755); | |
| 83 | return path; | |
| 84 | }; | |
| 85 | ||
| 86 | beforeAll(async () => { | |
| 87 | dir = await mkdtemp(join(tmpdir(), "talk-kept-")); | |
| 88 | app = createApp({ dataDir: dir, port: 0 }); | |
| 89 | servers = await serve(app); | |
| 90 | const made = await createUser(app.db, { | |
| 91 | origin: "seed", | |
| 92 | trusted: true, | |
| 93 | username: "alice", | |
| 94 | email: "[email protected]", | |
| 95 | password: "a-good-passphrase", | |
| 96 | adminIfFirst: true, | |
| 97 | }); | |
| 98 | if (!made.ok) throw new Error(made.error); | |
| 99 | promote(app.db, made.value); | |
| 100 | alice = made.value; | |
| 101 | answer = stub("answer", false); | |
| 102 | gated = stub("gated", true); | |
| 103 | }); | |
| 104 | afterAll(async () => { | |
| 105 | servers.stop(); | |
| 106 | app.close(); | |
| 107 | await rm(dir, { recursive: true, force: true }); | |
| 108 | }); | |
| 109 | ||
| 110 | describe("a kept message on every door", () => { | |
| 111 | test("the page's send keeps it, names Retry, and the line is under it", async () => { | |
| 112 | // Past the live-turn cap: no turn can start for it now. | |
| 113 | configureConversation(app, options({ liveMax: 0 })); | |
| 114 | const cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 115 | const sent = await fetch(`${servers.url}/talk`, { | |
| 116 | method: "POST", | |
| 117 | headers: { cookie, origin: new URL(servers.url).origin }, | |
| 118 | body: new URLSearchParams({ text: "what is on voxel?" }), | |
| 119 | redirect: "manual", | |
| 120 | }); | |
| 121 | expect(sent.status).toBe(303); | |
| 122 | const flash = (sent.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 123 | const page = await ( | |
| 124 | await fetch(`${servers.url}${sent.headers.get("location")}`, { | |
| 125 | headers: { cookie: `${cookie}; ${flash}` }, | |
| 126 | }) | |
| 127 | ).text(); | |
| 128 | expect(page).toContain(KEPT_FLASH); | |
| 129 | expect(said(alice).slice(-2)).toEqual([ | |
| 130 | "person:what is on voxel?", | |
| 131 | "agent!:The forge is answering as many people as it can at once. Your message is kept; Retry in a minute.", | |
| 132 | ]); | |
| 133 | }); | |
| 134 | ||
| 135 | test("the terminal's Talk shows the kept line, marked failed", async () => { | |
| 136 | const { app: tui, session } = createForgeApp( | |
| 137 | app, | |
| 138 | { | |
| 139 | sshUsername: "alice", | |
| 140 | remoteAddress: "127.0.0.1", | |
| 141 | fingerprint: "SHA256:test", | |
| 142 | user: alice, | |
| 143 | }, | |
| 144 | { terminal: headlessTerminal(140, 40), exitHooks: false }, | |
| 145 | ); | |
| 146 | tui.start(); | |
| 147 | tui.ctx.push(talkChatsScreen(session, tui.ctx)); | |
| 148 | await settleApp(tui); | |
| 149 | tui.dispatch({ | |
| 150 | type: "key", | |
| 151 | key: "enter", | |
| 152 | ctrl: false, | |
| 153 | alt: false, | |
| 154 | shift: false, | |
| 155 | }); | |
| 156 | await settleApp(tui); | |
| 157 | const shown = tui.screen.toText().replace(/\s+/g, " "); | |
| 158 | expect(shown).toContain("what is on voxel?"); | |
| 159 | expect(shown).toContain( | |
| 160 | "The forge is answering as many people as it can at once.", | |
| 161 | ); | |
| 162 | expect(shown).toContain("· failed"); | |
| 163 | tui.stop?.(); | |
| 164 | }); | |
| 165 | ||
| 166 | test("Retry sends the kept words once: no second copy of the message", async () => { | |
| 167 | configureConversation(app, options()); | |
| 168 | const failed = listTurns( | |
| 169 | app.db, | |
| 170 | alice.id, | |
| 171 | openConversation(app.db, alice.id).id, | |
| 172 | { limit: 100 }, | |
| 173 | ); | |
| 174 | if (!failed.ok) throw new Error("turns"); | |
| 175 | const again = talkAgain( | |
| 176 | app, | |
| 177 | alice, | |
| 178 | "retry", | |
| 179 | "", | |
| 180 | openConversation(app.db, alice.id).id, | |
| 181 | failed.value.at(-1)!.id, | |
| 182 | ); | |
| 183 | expect(again.ok).toBe(true); | |
| 184 | if (again.ok) await again.value.done; | |
| 185 | const now = said(alice); | |
| 186 | expect(now.filter((t) => t === "person:what is on voxel?")).toHaveLength(1); | |
| 187 | expect(now.at(-1)).toBe("agent:Heard."); | |
| 188 | }); | |
| 189 | ||
| 190 | test("messages queued behind one whose turn cannot start are kept, in order, as the person's", async () => { | |
| 191 | const sub = addSubscription(app.db, dir, { | |
| 192 | name: "lent", | |
| 193 | token: "sk-ant-api-test-lent", | |
| 194 | }); | |
| 195 | if (!sub.ok) throw new Error("subscription"); | |
| 196 | setGrants(app.db, alice.id, "", [sub.value.id]); | |
| 197 | const other = await createUser(app.db, { | |
| 198 | origin: "seed", | |
| 199 | trusted: true, | |
| 200 | username: "bob", | |
| 201 | email: "[email protected]", | |
| 202 | password: "a-good-passphrase", | |
| 203 | }); | |
| 204 | if (!other.ok) throw new Error(other.error); | |
| 205 | try { | |
| 206 | const opts = options({ binary: gated }); | |
| 207 | const first = say(app, opts, alice.id, "first"); | |
| 208 | expect(first.ok && first.value.how).toBe("started"); | |
| 209 | expect(await waitFor(() => existsSync(join(dir, "gated.started")))).toBe(true); | |
| 210 | expect(say(app, opts, alice.id, "second", [], "queue").ok).toBe(true); | |
| 211 | expect(say(app, opts, alice.id, "third", [], "queue").ok).toBe(true); | |
| 212 | // The account rests before the next turn would start. | |
| 213 | restSubscription( | |
| 214 | app.db, | |
| 215 | sub.value.id, | |
| 216 | new Date(Date.now() + 15 * 60_000).toISOString(), | |
| 217 | "window full", | |
| 218 | ); | |
| 219 | writeFileSync(join(dir, "gated.gate"), ""); | |
| 220 | if (first.ok) await first.value.done; | |
| 221 | const tail = said(alice).slice(-5); | |
| 222 | expect(tail.slice(0, 4)).toEqual([ | |
| 223 | "person:first", | |
| 224 | "agent:Heard.", | |
| 225 | "person:second", | |
| 226 | "person:third", | |
| 227 | ]); | |
| 228 | expect(tail[4]).toMatch( | |
| 229 | /^agent!:The account that answers you is resting until .+\. Your message is kept; Retry then\.$/, | |
| 230 | ); | |
| 231 | expect(said(other.value)).toEqual([]); | |
| 232 | } finally { | |
| 233 | wakeSubscription(app.db, sub.value.id); | |
| 234 | setGrants(app.db, alice.id, "", []); | |
| 235 | } | |
| 236 | }); | |
| 237 | }); |
new above
offline