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

Talk at a spent credit says so plainly; older merged pulls show their diff (#16455) #16457

opened this

Check · Review · Land · Live — It conflicts with its base. Next: builder, it conflicts with its base.

Conflicts with main

fix/talk-credit-and-old-merges → main 1 commit 3 threads · 3 unresolved

Review

Sign in to review this change.
8 files changed +339 −21
docs/features/talk-kept-message.md +3 −1
@@ -14,7 +14,9 @@ draws **Retry**:
1414 - the forge is answering as many people as it can: Retry in a minute;
1515 - pictures sent while an answer is under way: Retry when it has finished;
1616 - 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's agent is not running (off, or starting after a restart): Retry in a moment;
19 - 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).
1820
1921 Messages queued behind one that cannot start are kept too, in the order they were sent.
2022
src/actions/talk.ts +10 −3
@@ -12,7 +12,7 @@ import { getConversation, lastExchange, openConversation } from "../core/convers
1212 import type { ConversationFile } from "../core/conversation_files.ts";
1313 import { RateLimiter } from "../core/ratelimit.ts";
1414 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";
15 import { cancelQueued, keepUnstarted, queuedOf, conversationOptions, redo, say, stopTurn, type During, type RedoHow, type RedoRefusal, type SayRefusal, type Said } from "../crew/conversation.ts";
1616 import { err, ok, type Result } from "../kernel/result.ts";
1717
1818 /** Messages a person may send in a minute. */
@@ -63,9 +63,16 @@ const watch = (app: App, said: Said): void => {
6363 export function talk(app: App, user: User | undefined, text: string, files: readonly ConversationFile[] = [], during: During = "inject", conversationId?: string, about?: string | null): Result<Said, TalkRefusal> {
6464 if (user === undefined) return err("unauthorized");
6565 if (conversationId !== undefined && getConversation(app.db, user.id, conversationId) === undefined) return err("not_found");
66 const options = conversationOptions(app);
67 if (options === undefined) return err("off");
66 // The cap counts every message, a kept one too: while the agent is off nobody may write turns
67 // past it.
6868 if (!take(app, user)) return err("rate_limited");
69 const options = conversationOptions(app);
70 if (options === undefined) {
71 // Not running (off, or starting after a restart): the message is kept with its line, never
outdated

keepUnstarted appends turns before take() is checked, so this path has no rate limit. Apply the limiter before keeping the message.

72 // lost.
73 keepUnstarted(app, user.id, text, conversationId);
74 return err("off");
75 }
6976 const said = say(app, options, user.id, text, files, during, conversationId, about);
7077 if (said.ok) watch(app, said.value);
7178 return said;
src/core/pulls.ts +25 −5
@@ -6,6 +6,7 @@
66 * Forgejo left open (#30972).
77 */
88
9 import { commitParents } from "../git/revert.ts";
910 import { getRepoById } from "./repos.ts";
1011 import { repoDir } from "../git/repos.ts";
1112 import { clearLanding, recordLanding } from "./landing.ts";
@@ -920,6 +921,22 @@ export function reviewGate(
920921 };
921922 }
922923
924 /**
outdated

This is pullStatus's doc comment, now stacked above landedWith's. Move it back onto pullStatus.

925 * The base and head a merged pull landed with: the ones recorded at the merge, when they still make
926 * a change (the base does not already hold the head); else the merge commit's own parents, for a
927 * merge recorded before they were kept (#16422) or with a base read after it landed: an ordinary
928 * merge's two parents, or a squash's parent and itself. Undefined when neither is known.
929 */
930 async function landedWith(dir: string, pull: Pull): Promise<{ base: string; head: string } | undefined> {
931 if (pull.baseOid !== "" && pull.headOid !== "" && (await mergeBase(dir, pull.baseOid, pull.headOid)) !== pull.headOid)
932 return { base: pull.baseOid, head: pull.headOid };
933 if (pull.mergedOid === null || pull.mergedOid === "") return undefined;
934 const parents = await commitParents(dir, pull.mergedOid);
935 const first = parents?.[0];
936 if (first === undefined) return undefined;
937 return { base: first, head: parents?.[1] ?? pull.mergedOid };
938 }
939
923940 /** Recompute mergeability against the live base. The head is the live branch
924941 * for a same-repo PR, or the snapshot in refs/pull/N/head for a cross-repo one
925942 * (the fork's tip lives in another repo; we compare against what we fetched). */
@@ -928,11 +945,14 @@ export async function pullStatus(
928945 pull: Pull,
929946 gate?: ReviewGate,
930947 ): Promise<PullStatus> {
931 // A merged pull is history: its change is the one it landed with, read from the base and head
932 // recorded at the merge. Against the live base, which now holds the head, it would be empty.
933 if (typeof pull.mergedAt === "string" && pull.baseOid !== "" && pull.headOid !== "") {
934 const reviews = gate === undefined ? null : reviewGate(gate, pull, pull.headOid, pull.baseOid);
935 return { baseOid: pull.baseOid, headOid: pull.headOid, ahead: 0, mergeable: false, conflicts: [], reviews };
948 // A merged pull is history: its change is the one it landed with (`landedWith`). Against the
949 // live base, which now holds the head, it would be empty.
950 if (typeof pull.mergedAt === "string") {
951 const landed = await landedWith(dir, pull);
952 if (landed !== undefined) {
953 const reviews = gate === undefined ? null : reviewGate(gate, pull, landed.head, landed.base);
954 return { baseOid: landed.base, headOid: landed.head, ahead: 0, mergeable: false, conflicts: [], reviews };
955 }
936956 }
937957 const headRef = pull.crossRepo
938958 ? `refs/pull/${pull.number}/head`
src/crew/conversation.ts +41 −5
@@ -15,6 +15,7 @@
1515 * what is done before doing anything.
1616 */
1717
18 import { lentCreditLeft } from "../spawn/funding.ts";
1819 import { chmodSync, mkdirSync } from "node:fs";
1920 import { join } from "node:path";
2021 import type { App } from "../app.ts";
@@ -467,7 +468,8 @@ export function say(
467468 const reason = typeof why === "string" ? { code: why } : why;
468469 release(app.db, stored.value.id);
469470 appendTurn(app.db, userId, conversation.id, { role: "agent", text: heldLine(reason), failed: true });
470 return err(reason.code);
471 // The doors keep their codes: a spent lent credit is a resting account to them.
472 return err(reason.code === "credit_spent" ? "resting" : reason.code);
471473 };
472474 const delivery = deliver(app.config.dataDir, userId, files);
473475 const running = live.get(conversation.id);
@@ -541,7 +543,7 @@ export function redo(app: App, options: ConversationOptions, userId: string, how
541543 added = stored.value.id;
542544 }
543545 const started = begin(app, options, conversation, withHistory(app, conversation, words), 0, undefined);
544 if (!started.ok) return refuse(started.error.code, added);
546 if (!started.ok) return refuse(started.error.code === "credit_spent" ? "resting" : started.error.code, added);
545547 return ok({ how: "started", done: started.value });
546548 }
547549
@@ -592,20 +594,37 @@ function limitLine(app: App, picked: Pick, limit: RunnerLimit): string {
592594
593595 /** The refusals a message is kept through: it is a message, and it cannot start now. */
594596 export type HeldRefusal = "resting" | "busy" | "answering" | "no_account" | "sandbox" | "unauthorized";
597
598 /** The model door answered 402, as Claude Code prints it: the credit a parent lends is spent. */

The regex matches any text containing "API Error: 402", including a normal answer that quotes it. Require the turn to have failed (is_error result) before treating it as spent credit.

599 const creditSpent = (text: string): boolean => /\bAPI Error: 402\b/.test(text);
595600 const HELD: ReadonlySet<string> = new Set<HeldRefusal>(["resting", "busy", "answering", "no_account", "sandbox", "unauthorized"]);
596601
597602 /** Whether a refusal is one a message is kept through, with its line and Retry (#16431). */
598603 export const isHeld = (code: string): code is HeldRefusal => HELD.has(code);
599604
605 /**
606 * A message the forge cannot hand to its agent at all right now (its agent is not running: off, or
607 * starting after a restart): kept, with the line saying so and Retry, never dropped at the door.
608 * False when it is not a message to keep (empty, too long, a conversation not theirs).
609 */
610 export function keepUnstarted(app: App, userId: string, text: string, conversationId?: string): boolean {
611 if (text.trim() === "" || text.length > WORDS_MAX) return false;
612 const conversation = conversationId === undefined ? openConversation(app.db, userId) : getConversation(app.db, userId, conversationId);
613 if (conversation === undefined) return false;
614 if (!appendTurn(app.db, userId, conversation.id, { role: "person", text }).ok) return false;
615 appendTurn(app.db, userId, conversation.id, { role: "agent", text: heldLine({ code: "off" }), failed: true });
616 return true;
617 }
618
600619 /** Why a turn did not start: the refusal, and what the account said and until when, where known. */
601620 export interface NotStarted {
602 readonly code: "no_account" | "resting" | "unauthorized" | "sandbox";
621 readonly code: "no_account" | "resting" | "unauthorized" | "sandbox" | "credit_spent";
603622 readonly until?: string;
604623 readonly said?: string;
605624 }
606625
607626 /** 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 {
627 export function heldLine(why: { readonly code: HeldRefusal | "credit_spent" | "off"; readonly until?: string; readonly said?: string }): string {
609628 switch (why.code) {
610629 case "resting":
611630 return why.until !== undefined
@@ -622,6 +641,11 @@ export function heldLine(why: { readonly code: HeldRefusal; readonly until?: str
622641 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.";
623642 case "unauthorized":
624643 return "The forge could not open a turn for you just now. Your message is kept; Retry in a moment.";
644 case "off":
645 return "This forge's agent is not running right now; it may be starting. Your message is kept; Retry in a moment.";
646 case "credit_spent":
647 // Who can raise it, through the one helper for such sentences (docs/features/blocked-by.md).
648 return storedText("The model credit this forge's parent lends it is spent, so nothing could answer. Your message is kept for Retry.", "the parent forge's admin", "raise it");
625649 }
626650 }
627651
@@ -660,7 +684,12 @@ function begin(
660684 });
661685 if (picked.kind === "resting") return err({ code: "resting", until: picked.until });
662686 const spend = turnBudget(app, picked, userId, options.budgetUsd, now);
663 if (!spend.ok) return err({ code: spend.refusal, ...(spend.refusal === "resting" ? { said: spend.said } : {}) });
687 if (!spend.ok) {
688 // A forge whose model credit its parent lends is spent says that, and who can raise it.
689 const lentSpent = spend.refusal === "resting" && (picked.kind === "none" || picked.kind === "env") && lentCreditLeft(true, app.config.dataDir) === 0;
690 if (lentSpent) return err({ code: "credit_spent" });
691 return err({ code: spend.refusal, ...(spend.refusal === "resting" ? { said: spend.said } : {}) });
692 }
664693 const budget = spend.budget;
665694 const subscriptionId = picked.kind === "ready" ? picked.subscription.id : PLATFORM;
666695 // A new turn's token replaces the last one's.
@@ -853,6 +882,13 @@ function begin(
853882 };
854883 if (toolless.signal.aborted) couldNot(NO_TOOLS_LINE, () => true);
855884 else if (outcome === undefined) couldNot(failureLine("error"), () => false);
885 // The model door's own refusal (402: this forge's credit from its parent is spent): an error
886 // result whose words, or whose last streamed text, are the door's. One plain kept line
887 // instead, through the held path's words. An answer that only quotes them is an answer.
888 else if (!outcome.ok && (creditSpent(outcome.result) || creditSpent(streamed.at(-1)?.text ?? ""))) {
889 const door = streamed.at(-1);
890 couldNot(heldLine({ code: "credit_spent" }), (said) => said === outcome!.result || (door !== undefined && said === door.text && creditSpent(said)));
891 }
856892 else if (isRateLimited(outcome)) {
857893 const first = outcome.result.split("\n").find((l) => l.trim() !== "")?.trim() ?? "";
858894 couldNot(limitLine(app, picked, outcome.limit), (said) => said === outcome!.result || (first !== "" && said.includes(first)));
src/web/pages/talk.ts +1 −1
@@ -726,7 +726,7 @@ export async function talkSend(ctx: Ctx): Promise<Response> {
726726 const said = talk(ctx.app, user, text, [], "queue", conversation.id, typeof about === "string" ? about : null);
727727 if (!said.ok && said.error === "no_account") return flashTo(ctx, `${here}#end`, blockedFlash(noTalkAccountBlocked(ctx.app, user), "danger"));
728728 // 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}#end`, { tone: "attn", message: KEPT_FLASH });
729 if (!said.ok && (isHeld(said.error) || said.error === "off")) return flashTo(ctx, `${here}#end`, { tone: "attn", message: KEPT_FLASH });
730730 if (!said.ok) return flashTo(ctx, `${here}#end`, { tone: "danger", message: TALK_WORDS[said.error][1] });
731731 return flashTo(ctx, `${here}#end`, { tone: "success", message: "Sent. Reload to see the answer." });
732732 }
test/talk-page.test.ts +3 −2
@@ -193,11 +193,12 @@ describe("the page", () => {
193193 expect(bobs).toContain("What should we work on?");
194194 });
195195
196 test("a message with no agent running says so and is not kept", async () => {
196 test("a message with no agent running is kept, its line saying so", async () => {
197197 const res = await post("/talk", bob, { text: "do a thing" });
198198 expect(res.status).toBe(303);
199199 const after = await (await get("/talk", bob)).text();
200 expect(after).not.toContain("do a thing");
200 expect(after).toContain("do a thing");
201 expect(after).toContain("is not running right now");
201202 expect((await post("/talk", bob, { text: "x" }, { origin: "https://elsewhere.example" })).status).toBe(403);
202203 expect((await post("/talk", bob, { text: " " })).status).toBe(303);
203204 });
test/tui-talk-chats.test.ts +6 −4
@@ -115,11 +115,12 @@ describe("the terminal's conversations screen", () => {
115115 expect(text).toContain("how is the forge");
116116 expect(text).toContain("all green today");
117117 expect(text).toContain(`/talk/${made.value.id}`);
118 // The crew is off in this app: talk() refuses, the prompt says why, and nothing is stored.
118 // The crew is off in this app: the prompt says why, and the message is kept with its line
119 // (#16455).
119120 const said = await drive(bob, [...open, "\r", "s", "hello", "\r"]);
120121 expect(said).toContain("not running here");
121122 const turns = listTurns(app.db, bob.id, made.value.id, { limit: 50 });
122 expect(turns.ok && turns.value.length).toBe(2);
123 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; it may be starting. Your message is kept; Retry in a moment."]);
123124 });
124125
125126 test("an answer's cited number prints its path when readable and nothing when not (#13405)", async () => {
@@ -145,11 +146,12 @@ describe("the terminal's conversations screen", () => {
145146 if (!made.ok) throw new Error(made.error);
146147 const text = await drive(carol.value, [...open, "\r"]);
147148 STARTER_PROMPTS.forEach((p, i) => expect(text).toContain(`${String(i + 1)} ${p}`));
148 // The crew is off in this app: talk() refuses, the header says why, and nothing is stored.
149 // The crew is off in this app: the header says why, and the starter is kept with its line.
149150 const sent = await drive(carol.value, [...open, "\r", "2"]);
150151 expect(sent).toContain("not running here");
151152 const turns = listTurns(app.db, carol.value.id, made.value.id, { limit: 50 });
152 expect(turns.ok && turns.value.length).toBe(0);
153 expect(turns.ok && turns.value.map((t) => `${t.role}${t.failed ? "!" : ""}`)).toEqual(["person", "agent!"]);
154 expect(turns.ok && turns.value[0]?.text).toBe(STARTER_PROMPTS[1]);
153155 // Once something is said the list is gone, and a number is not a send.
154156 appendTurn(app.db, carol.value.id, made.value.id, { role: "person", text: "hello" });
155157 const later = await drive(carol.value, [...open, "\r", "1"]);
test/ui-663-talk-and-merges.test.ts added +250
@@ -0,0 +1,250 @@
1 /**
2 * Two faults from the UI check on 0.7.663 (#16455): a merged pull recorded before its base and head
3 * were kept showed "0 commits" and an empty Files tab, and a cell's Talk at its credit cap answered
4 * with the raw "API Error: 402 …" as its words.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { chmodSync, readFileSync, 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 { mergePull, openPull } from "../src/actions/pulls.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { listTurns, openConversation } from "../src/core/conversations.ts";
16 import { getPull, pullDiff, pullDir } from "../src/core/pulls.ts";
17 import { getRepo } from "../src/core/repos.ts";
18 import { setModelGrant } from "../src/core/model_grant.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { configureConversation, say } from "../src/crew/conversation.ts";
21 import { TALK_PER_MINUTE, talk, talkAgain } from "../src/actions/talk.ts";
22 import { resolveOid } from "../src/git/merge.ts";
23 import { repoDir } from "../src/git/repos.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26 import { promote } from "./helpers/members.ts";
27
28 quietLogs();
29
30 let dir: string;
31 let app: App;
32 let servers: Servers;
33 let alice: User;
34
35 beforeAll(async () => {
36 dir = await mkdtemp(join(tmpdir(), "ui-663-"));
37 app = createApp({ dataDir: dir, port: 0 });
38 servers = await serve(app);
39 const made = await createUser(app.db, {
40 origin: "seed",
41 trusted: true,
42 username: "alice",
43 email: "[email protected]",
44 password: "a-good-passphrase",
45 adminIfFirst: true,
46 });
47 if (!made.ok) throw new Error(made.error);
48 promote(app.db, made.value);
49 alice = made.value;
50 });
51 afterAll(async () => {
52 servers.stop();
53 app.close();
54 await rm(dir, { recursive: true, force: true });
55 });
56
57 describe("a merged pull recorded before its base and head were kept", () => {
58 for (const strategy of ["merge", "squash"] as const)
59 test(`shows the change it landed with, read from the merge commit (${strategy})`, async () => {
60 const name = `old-${strategy}`;
61 const made = await createRepo(app, alice, { name, visibility: "public" });
62 if (!made.ok) throw new Error("repo");
63 await commitToBranch(app, alice, made.value, {
64 message: "first",
65 files: [{ path: "README.md", content: "# x\n" }],
66 });
67 await commitToBranch(app, alice, made.value, {
68 branch: "change",
69 base: "main",
70 message: "change",
71 files: [{ path: "valid.ts", content: "export const V = 1;\n" }],
72 });
73 const opened = await openPull(app, alice, made.value, {
74 title: "change",
75 baseBranch: "main",
76 headBranch: "change",
77 });
78 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
79 const merged = await mergePull(
80 app,
81 alice,
82 made.value,
83 opened.value,
84 strategy,
85 );
86 if (!merged.ok) throw new Error(JSON.stringify(merged.error));
87 // As an older merge left it: the base recorded is the base after the merge, which holds the
88 // head.
89 const repo = getRepo(app.db, "alice", name)!;
90 const tip = (await resolveOid(
91 repoDir(app.reposRoot, "alice", name),
92 "refs/heads/main",
93 ))!;
94 app.db
95 .query("UPDATE pull SET base_oid = ?1 WHERE issue_id = ?2")
96 .run(tip, opened.value.id);
97 const pull = getPull(app.db, repo.id, opened.value.number)!;
98 const { diff } = await pullDiff(
99 await pullDir(app.db, app.reposRoot, repo, pull),
100 pull,
101 );
102 expect(diff.files.map((f) => f.path)).toEqual(["valid.ts"]);
103 });
104 });
105
106 describe("Talk at its parent's credit cap", () => {
107 test("says one plain kept line with who can raise it, never the raw API error", async () => {
108 const bin = join(dir, "spent");
109 writeFileSync(
110 bin,
111 `#!/bin/sh
112 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
113 IFS= read -r first
114 echo '{"type":"system","subtype":"init","session_id":"s-spent","model":"fake"}'
115 echo '{"type":"assistant","session_id":"s-spent","message":{"id":"m1","content":[{"type":"text","text":"API Error: 402 {\\"type\\":\\"error\\",\\"error\\":{\\"type\\":\\"credit\\",\\"message\\":\\"f2f-reader 1 from its parent is spent\\"}}"}],"usage":{"input_tokens":1,"output_tokens":1}}}'
116 echo '{"type":"result","subtype":"success","is_error":true,"result":"API Error: 402 f2f-reader 1 from its parent is spent","total_cost_usd":0,"num_turns":1,"session_id":"s-spent","usage":{"input_tokens":1,"output_tokens":1}}'
117 `,
118 );
119 chmodSync(bin, 0o755);
120 const said = say(
121 app,
122 {
123 binary: bin,
124 localUrl: servers.url,
125 budgetUsd: 1,
126 timeoutMs: 30_000,
127 signal: new AbortController().signal,
128 },
129 alice.id,
130 "what is happening on voxel?",
131 );
132 expect(said.ok).toBe(true);
133 if (said.ok) await said.value.done;
134 const turns = listTurns(
135 app.db,
136 alice.id,
137 openConversation(app.db, alice.id).id,
138 { limit: 50 },
139 );
140 const shown = turns.ok
141 ? turns.value.map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`)
142 : [];
143 expect(shown.join("\n")).not.toContain("API Error");
144 expect(shown.at(-1)).toBe(
145 "agent!:The model credit this forge's parent lends it is spent, so nothing could answer. Your message is kept for Retry. The parent forge's admin can raise it.",
146 );
147 expect(shown).toContain("person:what is happening on voxel?");
148 });
149 });
150
151 describe("an answer that quotes the 402 words", () => {
152 test("is the answer, never replaced by the credit line", async () => {
153 const quote = "The fault you asked about printed API Error: 402 when the credit ran out.";
154 const bin = join(dir, "quotes");
155 writeFileSync(
156 bin,
157 `#!/bin/sh
158 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
159 IFS= read -r first
160 echo '{"type":"system","subtype":"init","session_id":"s-quote","model":"fake"}'
161 echo '{"type":"assistant","session_id":"s-quote","message":{"id":"m1","content":[{"type":"text","text":"${quote}"}],"usage":{"input_tokens":1,"output_tokens":1}}}'
162 echo '{"type":"result","subtype":"success","is_error":false,"result":"${quote}","total_cost_usd":0.01,"num_turns":1,"session_id":"s-quote","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}'
163 `,
164 );
165 chmodSync(bin, 0o755);
166 const said = say(app, { binary: bin, localUrl: servers.url, budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal }, alice.id, "what does a 402 from the model look like?");
167 expect(said.ok).toBe(true);
168 if (said.ok) await said.value.done;
169 const turns = listTurns(app.db, alice.id, openConversation(app.db, alice.id).id, { limit: 50 });
170 const shown = turns.ok ? turns.value.map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`) : [];
171 expect(shown.slice(-2)).toEqual(["person:what does a 402 from the model look like?", `agent:${quote}`]);
172 });
173 });
174
175 describe("a cell whose lent credit is spent, and a forge whose agent is starting", () => {
176 test("a message sent after the cell's credit is spent is kept, with the credit and who can raise it", async () => {
177 // A cell's parent lent it $1 and it has spent $1.03, as f2f-reader had.
178 writeFileSync(join(dir, "parent.json"), JSON.stringify({ credit: { token: "lent-bearer-token-0001", capUsd: 1, spentUsd: 1.03 } }));
179 const bin = join(dir, "never");
180 writeFileSync(bin, "#!/bin/sh\nexit 1\n");
181 chmodSync(bin, 0o755);
182 try {
183 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");
185 const turns = listTurns(app.db, alice.id, openConversation(app.db, alice.id).id, { limit: 50 });
186 const shown = turns.ok ? turns.value.map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`) : [];
187 expect(shown.slice(-2)).toEqual([
188 "person:quick check: can you answer now?",
189 "agent!:The model credit this forge's parent lends it is spent, so nothing could answer. Your message is kept for Retry. The parent forge's admin can raise it.",
190 ]);
191 } finally {
192 writeFileSync(join(dir, "parent.json"), "{}");
193 }
194 });
195
196 test("a message sent while the agent is not running (a restart) is kept with its line, not dropped at the door", async () => {
197 // Before the crew is up, `conversationOptions` is undefined: `talk` answered "off" and kept
198 // nothing.
199 const sent = talk(app, alice, "capped send: are you there?");
200 expect(!sent.ok && sent.error).toBe("off");
201 const turns = listTurns(app.db, alice.id, openConversation(app.db, alice.id).id, { limit: 50 });
202 const shown = turns.ok ? turns.value.map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`) : [];
203 expect(shown.slice(-2)).toEqual([
204 "person:capped send: are you there?",
205 "agent!:This forge's agent is not running right now; it may be starting. Your message is kept; Retry in a moment.",
206 ]);
207 });
208
209 test("while the agent is off, the per-minute cap holds: past it nothing more is kept", async () => {
210 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "flood", email: "[email protected]", password: "a-good-passphrase" });
211 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" });
213 expect(talk(app, made.value, "one too many")).toEqual({ ok: false, error: "rate_limited" });
214 const turns = listTurns(app.db, made.value.id, openConversation(app.db, made.value.id).id, { limit: 100 });
215 expect(turns.ok && turns.value.length).toBe(TALK_PER_MINUTE * 2);
216 expect(turns.ok && turns.value.some((t) => t.text === "one too many")).toBe(false);
217 });
218
219 test("Retry on a kept 'off' line starts a turn once the agent is up, with the kept words", async () => {
220 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "later", email: "[email protected]", password: "a-good-passphrase" });
221 if (!made.ok) throw new Error(made.error);
222 promote(app.db, made.value);
223 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" });
225 const conversation = openConversation(app.db, made.value.id);
226 const before = listTurns(app.db, made.value.id, conversation.id, { limit: 10 });
227 const kept = before.ok ? before.value.at(-1) : undefined;
228 expect(kept?.failed).toBe(true);
229 const bin = join(dir, "up");
230 writeFileSync(
231 bin,
232 `#!/bin/sh
233 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
234 IFS= read -r first
235 printf '%s' "$first" > "${dir}/up.first"
236 echo '{"type":"system","subtype":"init","session_id":"s-up","model":"fake"}'
237 echo '{"type":"result","subtype":"success","is_error":false,"result":"Here is your clock.","total_cost_usd":0.01,"num_turns":1,"session_id":"s-up","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}'
238 `,
239 );
240 chmodSync(bin, 0o755);
241 configureConversation(app, { binary: bin, localUrl: servers.url, budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal });
242 const again = talkAgain(app, made.value, "retry", "", conversation.id, kept?.id);
243 expect(again.ok ? again.value.how : again.error).toBe("started");
244 if (again.ok) await again.value.done;
245 expect(readFileSync(join(dir, "up.first"), "utf8")).toContain("build me a clock");
246 const after = listTurns(app.db, made.value.id, conversation.id, { limit: 10 });
247 const shown = after.ok ? after.value.filter((t) => !t.replaced).map((t) => `${t.role}${t.failed ? "!" : ""}:${t.text}`) : [];
248 expect(shown.slice(-2)).toEqual(["person:build me a clock", "agent:Here is your clock."]);
249 });
250 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs