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

Talk API: pin a conversation, answer a held action yes or no, and redo a turn #18012

opened this in answer to

Merged 13h 47m ago, live in production

scout/forge:scout/18003-talk-api-pin-a-conversation-answer-a-hel → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/18003-talk-api-pin-a-conversation-answer-a-hel was merged into main as 4513adb.

Review

Sign in to review this change.
16 files changed +286 −40
docs/features/talk.md +1
@@ -86,6 +86,7 @@ A turn can be ended mid-reply (`stopTalk` in `src/actions/talk.ts`, `stopTurn` i
8686
8787 - **Web:** the Stop button beside Send while an answer is running, and `Escape` in the composer. Send still posts the form without the script.
8888 - **API:** `POST /api/v1/conversation/stop` answers 200, or 409 when nothing runs; a read-only token is 403.
89 - **Pin, answer a held action, redo (#18003):** `PATCH /api/v1/conversations/:id` reads `pinned` (true or false; an archived conversation is 409 `archived`); `POST /api/v1/conversation-confirms/:id` reads `{answer: "yes"|"no"}` (no body is yes) from the person's session or own rw token, never the agent's; `POST /api/v1/conversation/again` reads `{how: "retry"|"regenerate"|"edit", text?, conversation?, turn?}` (a retry names the failed turn in `turn`) and answers 202 through `askAgain`, the code behind `/talk/again/:how`. The terminal has all three already: `src/tui/screens/talk_chats.ts` (pin), `src/tui/ssh-talk.ts` (again), `src/tui/screens/confirms.ts` (yes and no).
8990 - **MCP:** `stop` with no `repo` and no `run` stops the forge's agent; with both it stops that crew run; one without the other is an error. The agent's own token is refused.
9091 - **Terminal:** `ssh <forge> talk /stop` (or `--stop`) exits 0 when stopped, 1 with "no answer is running".
9192
src/actions/talk.ts +19
@@ -11,6 +11,7 @@ import { storedText } from "../kernel/blocked.ts";
1111 import type { App } from "../app.ts";
1212 import { getConversation, lastExchange, openConversation } from "../core/conversations.ts";
1313 import type { ConversationFile } from "../core/conversation_files.ts";
14 import { WORDS_MAX } from "../core/fence.ts";
1415 import { RateLimiter } from "../core/ratelimit.ts";
1516 import type { User } from "../core/users.ts";
1617 import { cancelQueued, queuedOf, conversationOptions, keepUnstarted, redo, say, stopTurn, type During, type RedoHow, type RedoRefusal, type SayRefusal, type Said } from "../crew/conversation.ts";
@@ -103,6 +104,24 @@ export function talkAgain(app: App, user: User | undefined, how: RedoHow, text =
103104 return said;
104105 }
105106
107 /** What a redo refused, in the words and status the page and the API both answer. */
108 export type Redone = { readonly ok: true } | { readonly ok: false; readonly error: string; readonly status: number; readonly message: string };
109
110 /**
111 * Edit and resend, regenerate or retry, as the page's `/talk/again/:how` and the API's
112 * `/api/v1/conversation/again` both do it: an edit needs words up to the cap, the others ignore
113 * them, and a retry names the failed turn it retries (`turn`).
114 */
115 export function askAgain(app: App, user: User, how: RedoHow, input: { readonly text?: unknown; readonly turn?: unknown }, conversationId: string): Redone {
116 const text = input.text;
117 if (how === "edit" && !(typeof text === "string" && text.trim() !== "" && text.length <= WORDS_MAX))
118 return { ok: false, error: "invalid_text", status: 422, message: `Say something, up to ${WORDS_MAX} characters.` };
119 const said = talkAgain(app, user, how, typeof text === "string" ? text : "", conversationId, typeof input.turn === "string" ? input.turn : undefined);
120 if (said.ok) return { ok: true };
121 const [status, message] = TALK_WORDS[said.error];
122 return { ok: false, error: said.error, status, message };
123 }
124
106125 /** Stop the person's running turn; `idle` when none runs. */
107126 export function stopTalk(app: App, user: User | undefined): Result<true, "unauthorized" | "off" | "idle"> {
108127 if (user === undefined) return err("unauthorized");
src/contract/openapi/routes/index.ts +1
@@ -368,6 +368,7 @@ export { route as postApiV1BrokerOrigins } from "./postApiV1BrokerOrigins.ts";
368368 export { route as postApiV1Builds } from "./postApiV1Builds.ts";
369369 export { route as postApiV1Codes } from "./postApiV1Codes.ts";
370370 export { route as postApiV1Contribute } from "./postApiV1Contribute.ts";
371 export { route as postApiV1ConversationAgain } from "./postApiV1ConversationAgain.ts";
371372 export { route as postApiV1ConversationConfirmsId } from "./postApiV1ConversationConfirmsId.ts";
372373 export { route as postApiV1ConversationFiles } from "./postApiV1ConversationFiles.ts";
373374 export { route as postApiV1ConversationMessages } from "./postApiV1ConversationMessages.ts";
src/contract/openapi/routes/patchApiV1ConversationsId.ts +4 −4
@@ -4,12 +4,12 @@ import type { Route } from "../shared.ts";
44 export const route: Route = {
55 method: "patch",
66 path: "/api/v1/conversations/{id}",
7 summary: "Rename a conversation or put it away and bring it back",
8 detail: "Rename a conversation (title) or put it away and bring it back (archived: true or false); another person's id is 404",
7 summary: "Rename, pin or put away a conversation, or bring it back",
8 detail: "Rename a conversation (title), pin it to the top of the list or let it go (pinned: true or false; an archived conversation is not pinned, 409), or put it away and bring it back (archived: true or false); another person's id is 404",
99 auth: true,
1010 role: "member",
11 body: { title: "string", archived: "boolean" },
12 refusals: { invalid_title: "title is over 80 characters or has a line break (422)", not_found: "no such conversation of yours (404)", forbidden: "the request is cross-origin, or the token is read-only" },
11 body: { title: "string", archived: "boolean", pinned: "boolean" },
12 refusals: { archived: "pinned: true on an archived conversation (409)", invalid_title: "title is over 80 characters or has a line break (422)", not_found: "no such conversation of yours (404)", forbidden: "the request is cross-origin, or the token is read-only" },
1313 response: ref("ConversationEnvelope"),
1414 request: ref("ConversationRequest"),
1515 refuses: [401, 404],
src/contract/openapi/routes/postApiV1ConversationAgain.ts added +27
@@ -0,0 +1,27 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/conversation/again",
6 summary: "Redo a turn: retry a failed one, regenerate the last reply, or edit and resend",
7 detail: "Redo a turn exactly as the page's Retry, Regenerate and Edit do, through the same code: `how` is retry (the failed last turn; name it with `turn`, its id from GET /api/v1/conversation/turns), regenerate (the last reply is asked again and replaced) or edit (`text`, 1 to 20000 characters, replaces the last message and is sent); `conversation` (optional) names one of the person's, else the open one; answers 202 at once, read the answer from the turns; shares the 12 a minute of sending a message",
8 auth: true,
9 role: "member",
10 status: 202,
11 body: { how: "string", text: "string", conversation: "string", turn: "string" },
12 reply: { ok: "boolean" },
13 refusals: {
14 invalid_how: "how is not retry, regenerate or edit (422)",
15 invalid_text: "an edit's text is not a string of 1 to 20000 characters (422)",
16 not_found: "conversation names none of the person's (404)",
17 nothing: "there is nothing there to redo (409)",
18 running: "the forge is still answering (409)",
19 unkeyed: "a retry names no failed turn (409)",
20 retried: "that turn was already retried (409)",
21 rate_limited: "more than 12 a minute (429)",
22 too_large: "the body is over 128000 bytes (413)",
23 forbidden: "the request is cross-origin, or the token may only read",
24 },
25 errorStatus: { 503: "This forge's agent is not running here" },
26 refuses: [401, 422],
27 };
src/contract/openapi/routes/postApiV1ConversationConfirmsId.ts +5 −3
@@ -3,11 +3,13 @@ import type { Route } from "../shared.ts";
33 export const route: Route = {
44 method: "post",
55 path: "/api/v1/conversation-confirms/{id}",
6 summary: "The person's yes to a confirm the forge's agent asked in their conversation",
7 detail: "The person's yes to a confirm the forge's agent asked in their conversation: does the stored call, with its stored arguments, exactly once, as the person by way of the agent; only the person's own browser session on the same origin says yes (a bearer token or password is 401); answers the result, the `tool` turn it wrote, with `undo` when the action has one",
8 auth: false,
6 summary: "The person's yes or no to a confirm the forge's agent asked in their conversation",
7 detail: "The person's yes or no (`answer`, no body is yes) to a confirm the forge's agent asked in their conversation: a no spends it and runs nothing; a yes does the stored call, with its stored arguments, exactly once, as the person by way of the agent; only the person says it: their own browser session on the same origin, or their own rw token (the forge's agent's token, a read-only token or a password is refused); answers the result, the `tool` turn it wrote, with `undo` when the action has one",
8 auth: true,
9 body: { answer: "string" },
910 role: "member",
1011 refusals: {
12 invalid_answer: "answer is not yes or no (422)",
1113 not_found: "no such confirm of the person's",
1214 answered: "the confirm was already answered (409)",
1315 expired: "the confirm is 10 minutes old or more (410)",
src/contract/openapi/schemas/conversation.ts +1 −1
@@ -98,7 +98,7 @@ const TURNS: Schema = obj(
9898 { running: bool, stoppedAt: orNull(str), conversation: str, totalUsd: orNull(num), queued: list(obj({ id: str, text: str })), turns: list(ref("ConversationTurn")) },
9999 );
100100
101 const CONVERSATION_REQUEST: Schema = obj({ title: str, archived: bool }, ["title", "archived"]);
101 const CONVERSATION_REQUEST: Schema = obj({ title: str, archived: bool, pinned: bool }, ["title", "archived", "pinned"]);
102102
103103 export const CONVERSATION_SCHEMAS: Readonly<Record<string, Schema>> = {
104104 MessageRequest: MESSAGE_REQUEST,
src/http/api/conversation_confirms.ts +29 −9
@@ -1,22 +1,42 @@
11 /**
2 * The person's yes over the API (#7650): `POST /api/v1/conversation-confirms/:id`.
3 * Only the person's own browser session on the same origin says yes — never
4 * a token, so never the agent. What a yes does is `actions/conversation_confirms.ts`;
5 * the answer is the `tool` turn it wrote, with the result as the person sees
6 * it once (a link or credential shown once is not kept in the turn).
2 * The person's yes or no over the API (#7650, #18003): `POST /api/v1/conversation-confirms/:id`
3 * with `{answer}` (no body is yes). Only the person says it: their own browser session on the same
4 * origin, or their own rw token — never the forge's agent. What a yes does is
5 * `actions/conversation_confirms.ts`; the answer is the `tool` turn it wrote, with the result as
6 * the person sees it once (a link or credential shown once is not kept in the turn).
77 */
88
9 import { REFUSED, sayYes } from "../../actions/conversation_confirms.ts";
9 import { scopeAllows } from "../../core/tokens.ts";
10 import { REFUSED, sayNo, sayYes } from "../../actions/conversation_confirms.ts";
1011 import { crossOrigin, type Handler } from "../context.ts";
11 import { apiError, forbidden, json, unauthorized } from "../respond.ts";
12 import { apiError, boundedBody, forbidden, json, unauthorized } from "../respond.ts";
1213 import type { Router } from "../router.ts";
1314
1415 export function conversationConfirmRoutes(router: Router<Handler>): void {
1516 router.add("POST", "/api/v1/conversation-confirms/:id", async (ctx) => {
1617 const user = ctx.auth.user;
17 if (ctx.auth.via !== "session" || user === undefined) return unauthorized();
18 if (user === undefined) return unauthorized();
19 // The person's own session, or their own rw token: never the forge's agent (a via token reaches
20 // /mcp alone) nor a run, contribute or app token.
21 const own = ctx.auth.via === "session" || (ctx.auth.via === "token" && ctx.auth.through === undefined && ctx.auth.run === undefined && ctx.auth.contribute === undefined && ctx.auth.appId === undefined);
22 if (!own) return unauthorized();
1823 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden();
19 const yes = await sayYes(ctx, user, ctx.params["id"] ?? "");
24 if (ctx.auth.via === "token" && !scopeAllows(ctx.auth.scope ?? "ro", "rw")) return forbidden();
25 // No body is a yes, as before; a body says `answer`: yes or no.
26 const input = await boundedBody(ctx.request, 1_000);
27 if (input === "too_large") return apiError("too_large", 413, "at most 1000 bytes");
28 const answer = input["answer"] ?? "yes";
29 if (answer !== "yes" && answer !== "no") return apiError("invalid_answer", 422, "answer is yes or no");
30 const id = ctx.params["id"] ?? "";
31 if (answer === "no") {
32 const no = sayNo(ctx, user, id);
33 if (!no.ok) {
34 const [status, words] = REFUSED[no.error];
35 return apiError(no.error, status, words);
36 }
37 return json(no.turn);
38 }
39 const yes = await sayYes(ctx, user, id);
2040 if (!yes.ok) {
2141 const [status, words] = REFUSED[yes.error];
2242 return apiError(yes.error, status, words);
src/http/api/conversation_talk.ts +29 −4
@@ -14,7 +14,7 @@ import { noTalkAccountBlocked } from "../../actions/blocked_words.ts";
1414 import { blockedFields } from "../../kernel/blocked.ts";
1515 import type { App } from "../../app.ts";
1616 import { RateLimiter } from "../../core/ratelimit.ts";
17 import { cancelTalk, stopTalk, TALK_WORDS, talk } from "../../actions/talk.ts";
17 import { askAgain, cancelTalk, stopTalk, TALK_WORDS, talk } from "../../actions/talk.ts";
1818 import { conversationTotal, turnCosts } from "../../core/conversation_cost.ts";
1919 import {
2020 archiveConversation,
@@ -25,6 +25,7 @@ import {
2525 listTurns,
2626 MAX_PAGE,
2727 openConversation,
28 pinConversation,
2829 renameConversation,
2930 TITLE_MAX,
3031 type Turn,
@@ -39,7 +40,7 @@ import type { User } from "../../core/users.ts";
3940 import { worksOf } from "../../core/talk_work.ts";
4041 import { cardsPlaced, plainVoice } from "../../core/talk_voice.ts";
4142 import { cardsOfReply } from "../../core/talk_cards.ts";
42 import { fileQueued, queuedOf, turnRunning } from "../../crew/conversation.ts";
43 import { fileQueued, queuedOf, turnRunning, type RedoHow } from "../../crew/conversation.ts";
4344 import { crossOrigin, type Handler } from "../context.ts";
4445 import { holds, weakEtag } from "../etag.ts";
4546 import { readBounded } from "../limits.ts";
@@ -144,6 +145,24 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
144145 return json(said.value.queued === undefined ? { how: said.value.how } : { how: said.value.how, queued: said.value.queued }, 202);
145146 });
146147
148 // The page's Retry, Regenerate and Edit (`/talk/again/:how`), through the same `askAgain`.
149 router.add("POST", "/api/v1/conversation/again", async (ctx) => {
150 const user = mayChange(ctx);
151 if (user instanceof Response) return user;
152 const input = await boundedBody(ctx.request, BODY_MAX);
153 if (input === "too_large") return apiError("too_large", 413, `at most ${BODY_MAX} bytes`);
154 const how = (["edit", "regenerate", "retry"] as const satisfies readonly RedoHow[]).find((h) => h === input["how"]);
155 if (how === undefined) return apiError("invalid_how", 422, "how is retry, regenerate or edit");
156 const named = input["conversation"];
157 if (named !== undefined && (typeof named !== "string" || !ID.test(named))) return apiError("not_found", 404, "no such conversation");
158 const conversation = named === undefined ? openConversation(ctx.app.db, user.id) : getConversation(ctx.app.db, user.id, named);
159 if (conversation === undefined) return apiError("not_found", 404, "no such conversation");
160 const done = askAgain(ctx.app, user, how, { text: input["text"], turn: input["turn"] }, conversation.id);
161 if (done.ok) return json({ ok: true }, 202);
162 const { status, message, error } = done;
outdated

const said = done; is a pointless alias, only there to narrow the type. Use if (done.ok) ...; const { status, message, error } = done; instead.

163 return status === 429 || status === 503 ? tryAgain(error, status, message, talkWait(error)) : json({ error, message }, status);
164 });
165
147166 router.add("DELETE", "/api/v1/conversation/queue/:id", (ctx) => {
148167 const user = ctx.auth.user;
149168 if (user === undefined) return unauthorized();
@@ -292,12 +311,18 @@ export function conversationTalkRoutes(router: Router<Handler>): void {
292311 if (!ID.test(id) || getConversation(ctx.app.db, user.id, id) === undefined) return apiError("not_found", 404, "no such conversation");
293312 const input = await boundedBody(ctx.request, 4_000);
294313 if (input === "too_large") return apiError("too_large", 413, "at most 4000 bytes");
295 const { title, archived } = input;
314 const { title, archived, pinned } = input;
296315 if (title !== undefined && typeof title !== "string") return apiError("invalid_title", 422, TITLE_WORDS);
297316 if (archived !== undefined && typeof archived !== "boolean") return apiError("invalid", 422, "archived is true or false");
298 if (title === undefined && archived === undefined) return apiError("invalid", 422, "send title or archived");
317 if (pinned !== undefined && typeof pinned !== "boolean") return apiError("invalid", 422, "pinned is true or false");
318 if (title === undefined && archived === undefined && pinned === undefined) return apiError("invalid", 422, "send title, archived or pinned");
319 // An archived conversation is not pinned (the page says Restore it first); unpinning always
320 // works. Decided before any write, so a refusal changes nothing: it is archived as the
321 // request leaves it, or already is.
322 if (pinned === true && (archived ?? getConversation(ctx.app.db, user.id, id)?.archivedAt != null)) return apiError("archived", 409, "an archived conversation is not pinned; restore it first");
299323 if (title !== undefined && !renameConversation(ctx.app.db, user.id, id, title).ok) return apiError("invalid_title", 422, TITLE_WORDS);
300324 if (archived !== undefined) archiveConversation(ctx.app.db, user.id, id, archived);
outdated

Not atomic: rename and archive above have already been written when this refuses with 409, so {archived:true,pinned:true} or {title,pinned:true} on an archived conversation changes state and then reports an error. Decide the pin result first (or validate that pinning is allowed after the archive flag is applied) and write nothing on refusal.

325 if (pinned !== undefined) pinConversation(ctx.app.db, user.id, id, pinned);
301326 return json({ conversation: getConversation(ctx.app.db, user.id, id) });
302327 });
303328 }
src/http/lazy_lists.ts +1
@@ -1469,6 +1469,7 @@ export const API_ROUTES = [
14691469 ["POST", "/api/v1/repos/:owner/:name/pulls/:number/take-back"],
14701470 ["POST", "/api/v1/conversation-confirms/:id"],
14711471 ["POST", "/api/v1/conversation/messages"],
1472 ["POST", "/api/v1/conversation/again"],
14721473 ["DELETE", "/api/v1/conversation/queue/:id"],
14731474 ["POST", "/api/v1/conversation/stop"],
14741475 ["POST", "/api/v1/conversation/files"],
src/web/pages/talk.ts +4 −8
@@ -19,7 +19,7 @@ import { lookupIdempotent, MAX_KEY_LENGTH, requestFingerprint, storeIdempotent }
1919 import { blockedFlash } from "../blocked.ts";
2020 import { noTalkAccountBlocked } from "../../actions/blocked_words.ts";
2121 import type { Database } from "bun:sqlite";
22 import { cancelTalk, queuedTalk, STARTER_PROMPTS, TALK_WORDS, talk, talkAgain } from "../../actions/talk.ts";
22 import { cancelTalk, queuedTalk, STARTER_PROMPTS, TALK_WORDS, talk, askAgain } from "../../actions/talk.ts";
2323 import { REFUSED, sayNo, sayYes, UNDO_REFUSED, undoReceipt, waitingConfirms, type Waiting } from "../../actions/conversation_confirms.ts";
2424 import { filesOfTalk, filesOfTurns, type ConversationFile } from "../../core/conversation_files.ts";
2525 import {
@@ -951,13 +951,9 @@ export async function talkAgainSend(ctx: Ctx): Promise<Response> {
951951 const text = form.get("text");
952952 const key = form.get("turn");
953953 const asJson = (ctx.request.headers.get("accept") ?? "").includes("application/json");
954 let status = 422;
955 let message = `Say something, up to ${WORDS_MAX} characters.`;
956 if (how !== "edit" || (typeof text === "string" && text.trim() !== "" && text.length <= WORDS_MAX)) {
957 const said = talkAgain(ctx.app, user, how, typeof text === "string" ? text : "", conversation.id, typeof key === "string" ? key : undefined);
958 if (said.ok) return asJson ? json({ ok: true }, 202) : flashTo(ctx, `${here}#end`, { tone: "success", message: "Asked again. Reload to see the answer." });
959 [status, message] = TALK_WORDS[said.error];
960 }
954 const said = askAgain(ctx.app, user, how, { text, turn: key }, conversation.id);
955 if (said.ok) return asJson ? json({ ok: true }, 202) : flashTo(ctx, `${here}#end`, { tone: "success", message: "Asked again. Reload to see the answer." });
956 const { status, message } = said;
961957 return asJson ? json({ ok: false, message }, status) : flashTo(ctx, `${here}#end`, { tone: "danger", message });
962958 }
963959
test/conversation-confirm.test.ts +65 −6
@@ -15,6 +15,9 @@ import { getRepoById } from "../src/core/repos.ts";
1515 import { createSession } from "../src/core/sessions.ts";
1616 import { createToken } from "../src/core/tokens.ts";
1717 import { createUser, type User } from "../src/core/users.ts";
18 import { conversationConfirmRoutes } from "../src/http/api/conversation_confirms.ts";
19 import type { Ctx, Handler } from "../src/http/context.ts";
20 import { Router } from "../src/http/router.ts";
1821 import { mintViaToken } from "../src/core/via_token.ts";
1922 import { argumentsShown, ASKING, asksFirst, tooBigToApprove, CONFIRM_TTL_MS } from "../src/crew/conversation_confirm.ts";
2023 import { confirmSentence } from "../src/crew/conversation_ask.ts";
@@ -253,15 +256,36 @@ describe("the agent asks, the person answers once", () => {
253256 expect((await yes(id, alice)).status).toBe(410);
254257 });
255258
259 test("the route's own gate: a run, contribute, app or via credential that reaches it is not a yes", async () => {
260 const w = await world(alice);
261 const id = JSON.parse((await call(w.token, "archive", { repo: w.repo, archived: true, dryRun: false })).text).needs_confirm;
262 const router = new Router<Handler>();
outdated

toBeGreaterThanOrEqual(401) accepts anything from 401 up, including a 500. Assert the exact status, and add a case that reaches the route's own own gate (a run or contribute token) so the new code is tested, not the via gate in front of it.

263 conversationConfirmRoutes(router);
264 const handler = router.handlerOf("POST", "/api/v1/conversation-confirms/:id")!;
265 const reach = (extra: Record<string, unknown>) => {
266 const url = new URL(`${servers.url}/api/v1/conversation-confirms/${id}`);
267 const auth = { user: alice, scope: "rw", via: "token", ...extra } as unknown as Ctx["auth"];
268 return handler({ app, request: new Request(url.href, { method: "POST" }), url, params: { id }, auth, theme: undefined });
269 };
270 for (const extra of [{ run: { repoId: w.repoId } }, { contribute: { repoId: w.repoId } }, { appId: "a1" }, { through: "conversation:c1" }]) {
271 expect((await reach(extra)).status).toBe(401);
272 }
273 expect(getRepoById(app.db, w.repoId)!.archivedAt).toBeNull();
274 // The same call as the person's own rw token is a yes: the gate is not what refused above.
275 expect((await reach({})).status).toBe(200);
276 expect(getRepoById(app.db, w.repoId)!.archivedAt).not.toBeNull();
277 });
278
256279 test("only the person's own session, same-origin, says yes", async () => {
257280 const w = await world(alice);
258281 const id = JSON.parse((await call(w.token, "archive", { repo: w.repo, archived: true, dryRun: false })).text).needs_confirm;
259 // The agent's own token, or any bearer token, is not a yes.
260 const bearer = await fetch(`${servers.url}/api/v1/conversation-confirms/${id}`, {
261 method: "POST",
262 headers: { authorization: `Bearer ${createToken(app.db, alice.id, "t", "admin").token}` },
263 });
264 expect(bearer.status).toBe(401);
282 // The agent's own token, a read-only token, or no credential is not a yes.
283 const url = `${servers.url}/api/v1/conversation-confirms/${id}`;
284 const as = (token: string) => fetch(url, { method: "POST", headers: { authorization: `Bearer ${token}` } });
285 expect((await as(w.token)).status).toBe(403); // the via gate turns it away before the route
286 expect(getRepoById(app.db, w.repoId)!.archivedAt).toBeNull();
287 expect((await as(createToken(app.db, alice.id, "ro", "ro").token)).status).toBe(403);
288 expect((await fetch(url, { method: "POST" })).status).toBe(401);
265289 expect((await yes(id, alice, { origin: "https://elsewhere.example" })).status).toBe(403);
266290 expect((await yes(id, bob)).status).toBe(404);
267291 expect(getRepoById(app.db, w.repoId)!.archivedAt).toBeNull();
@@ -270,6 +294,41 @@ describe("the agent asks, the person answers once", () => {
270294 });
271295 });
272296
297 describe("the answer over a bearer token", () => {
298 const answer = (id: string, token: string, body?: unknown) =>
299 fetch(`${servers.url}/api/v1/conversation-confirms/${id}`, {
300 method: "POST",
301 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
302 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
303 });
304 const held = async (w: Awaited<ReturnType<typeof world>>) => JSON.parse((await call(w.token, "archive", { repo: w.repo, archived: true, dryRun: false })).text).needs_confirm as string;
305
306 test("no body is yes, answer yes is yes, and the call runs once", async () => {
307 const w = await world(alice);
308 const rw = createToken(app.db, alice.id, "rw", "rw").token;
309 const first = await answer(await held(w), rw);
310 expect(first.status).toBe(200);
311 expect(getRepoById(app.db, w.repoId)!.archivedAt).not.toBeNull();
312 const w2 = await world(alice);
313 expect((await answer(await held(w2), rw, { answer: "yes" })).status).toBe(200);
314 expect(getRepoById(app.db, w2.repoId)!.archivedAt).not.toBeNull();
315 });
316
317 test("no spends the confirm and runs nothing; a second answer is 409; another word is 422", async () => {
318 const w = await world(alice);
319 const rw = createToken(app.db, alice.id, "rw", "rw").token;
320 const id = await held(w);
321 expect((await answer(id, rw, { answer: "maybe" })).status).toBe(422);
322 const no = await answer(id, rw, { answer: "no" });
323 expect(no.status).toBe(200);
324 expect(await no.json()).toMatchObject({ confirm: id, done: false, cancelled: true });
325 expect(getRepoById(app.db, w.repoId)!.archivedAt).toBeNull();
326 expect((await answer(id, rw, { answer: "yes" })).status).toBe(409);
327 expect((await answer(id, rw, { answer: "no" })).status).toBe(409);
328 expect(getRepoById(app.db, w.repoId)!.archivedAt).toBeNull();
329 });
330 });
331
273332 describe("admin-scope tools, deliberately", () => {
274333 test("an admin's agent with an rw token reaches repo_settings through a confirm", async () => {
275334 const w = await world(alice);
test/conversation-talk.test.ts +68 −4
@@ -42,12 +42,12 @@ describe("talking to the forge's agent", () => {
4242 let via: string;
4343 const headers = (t: string) => ({ "content-type": "application/json", authorization: `Bearer ${t}` });
4444
45 const turns = async (): Promise<{ running: boolean; turns: { id: string; role: string; text: string; replaced: boolean; failed: boolean }[] }> =>
46 (await fetch(`${servers.url}/api/v1/conversation/turns`, { headers: headers(token) })).json() as never;
47 const settle = async () => {
45 const turns = async (t = token): Promise<{ running: boolean; turns: { id: string; role: string; text: string; replaced: boolean; failed: boolean }[] }> =>
46 (await fetch(`${servers.url}/api/v1/conversation/turns`, { headers: headers(t) })).json() as Promise<{ running: boolean; turns: { id: string; role: string; text: string; replaced: boolean; failed: boolean }[] }>;
47 const settle = async (t = token) => {
4848 for (let i = 0; i < 200; i++) {
4949 const open = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM conversation_run WHERE state = 'running'").get()!.n;
50 if (!(await turns()).running && open === 0) return;
50 if (!(await turns(t)).running && open === 0) return;
5151 await Bun.sleep(25);
5252 }
5353 throw new Error("the turn never finished");
@@ -505,6 +505,70 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Heard.","t
505505 expect((await exec("talk-again edit bad\u0007words")).code).toBe(1);
506506 });
507507
508 test("POST /api/v1/conversation/again redoes a turn for a bearer token, through the same code", async () => {
509 withBinary(answers("Again."));
510 const api = (body: unknown, h: Record<string, string> = headers(token)) =>
511 fetch(`${servers.url}/api/v1/conversation/again`, { method: "POST", headers: h, body: JSON.stringify(body) });
512 expect((await api({ how: "regenerate" }, { "content-type": "application/json" })).status).toBe(401);
513 expect((await api({ how: "regenerate" }, { ...headers(token), origin: "https://elsewhere.example" })).status).toBe(403);
514 expect((await api({ how: "sideways" })).status).toBe(422);
515 expect((await api({ how: "regenerate", conversation: "nope" })).status).toBe(404);
516 for (const text of [undefined, "", "x".repeat(WORDS_MAX + 1)]) expect((await api({ how: "edit", text })).status).toBe(422);
517 expect((await api({ how: "retry" })).status).toBe(409);
518 });
outdated

This test is only green because of how many sends earlier tests in this file made against the shared 12 a minute limiter ("one redo is left"). Reordering or adding a test breaks it: a flaky test. Use a fresh user or reset the limiter, and also cover regenerate, retry with turn (and 409 retried) and the 429 branch.

519
520 test("the redo route: regenerate, edit, retry and its limit, for a person of their own (so earlier sends are not counted)", async () => {
521 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "rhea", email: "[email protected]", password: "a-good-passphrase" });
522 if (!made.ok) throw new Error(made.error);
523 setModelGrant(app.db, made.value.id, 5, made.value.id, new Date());
524 const mine = createToken(app.db, made.value.id, "personal", "rw").token;
525 const post = (path: string, body: unknown) => fetch(`${servers.url}/api/v1/conversation/${path}`, { method: "POST", headers: headers(mine), body: JSON.stringify(body) });
526 const read = () => turns(mine);
527 const quiet = () => settle(mine);
528 const lines = async () => (await read()).turns.filter((t) => !t.replaced).map((t) => `${t.role}:${t.text}`);
529 withBinary(answers("First."));
530 expect((await post("messages", { text: "hello" })).status).toBe(202); // 1 of the minute's twelve
531 await quiet();
532 withBinary(answers("Again."));
533 const regenerated = await post("again", { how: "regenerate" }); // 2
534 expect(regenerated.status).toBe(202);
535 expect(await regenerated.json()).toEqual({ ok: true });
536 await quiet();
537 expect((await lines()).slice(-2)).toEqual(["person:hello", "agent:Again."]);
538 expect((await post("again", { how: "edit", text: "edited" })).status).toBe(202); // 3
539 await quiet();
540 expect((await lines()).slice(-2)).toEqual(["person:edited", "agent:Again."]);
541 // Retry answers a failed turn, named by `turn`; it names none, or one that is not the last, and
542 // is refused.
543 withBinary(`echo '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"x","total_cost_usd":0,"num_turns":0,"session_id":"s9"}'\nexit 1`);
544 expect((await post("again", { how: "regenerate" })).status).toBe(202); // 4
545 await quiet();
546 const failed = (await read()).turns.at(-1)!;
547 expect(failed.failed).toBe(true);
548 expect(((await (await post("again", { how: "retry" })).json()) as { error: string }).error).toBe("unkeyed");
549 const stale = await post("again", { how: "retry", turn: "nope" });
550 expect(stale.status).toBe(409);
551 expect(((await stale.json()) as { error: string }).error).toBe("retried");
552 withBinary(answers("Fine now."));
553 expect((await post("again", { how: "retry", turn: failed.id })).status).toBe(202); // 5
554 await quiet();
555 expect((await lines()).slice(-2)).toEqual(["person:edited", "agent:Fine now."]);
556 // The same turn again is already retried (409), and spends nothing of the limit.
557 const twice = await post("again", { how: "retry", turn: failed.id });
558 expect(twice.status).toBe(409);
559 expect(((await twice.json()) as { error: string }).error).toBe("retried");
560 // Seven sends are left of twelve; the one after them is a 429 with a Retry-After.
561 for (let i = 5; i < TALK_PER_MINUTE; i++) {
562 expect((await post("again", { how: "edit", text: `more ${i}` })).status).toBe(202);
563 await quiet();
564 }
565 const limited = await post("again", { how: "edit", text: "one too many" });
566 expect(limited.status).toBe(429);
567 expect(limited.headers.get("retry-after")).not.toBeNull();
568 expect(((await limited.json()) as { error: string }).error).toBe("rate_limited");
569 expect((await lines()).some((l) => l.includes("one too many"))).toBe(false);
570 });
571
508572 test("a kept message is a success at every door: 202 kept, an MCP result, ssh exit 0, each with its line", async () => {
509573 // At the live-turn cap nothing can start; each message is kept with the line saying why.
510574 const busy = "The forge is answering as many people as it can at once. Your message is kept; Retry in a minute.";
test/openapi-drift.test.ts −1
@@ -102,7 +102,6 @@ const SESSION_ONLY: ReadonlySet<string> = new Set([
102102 "POST /api/v1/tokens",
103103 "DELETE /api/v1/tokens/{}",
104104 "POST /api/v1/conversation-tokens",
105 "POST /api/v1/conversation-confirms/{}",
106105 "POST /settings/account/close/options",
107106 ]);
108107
test/retry-after.test.ts +2
@@ -45,6 +45,8 @@ const EXEMPT: Record<string, string> = {
4545 "src/http/api/print.ts: daily_cap: 429,": "status table; printRefusal answers through tryAgain",
4646 "src/http/api/conversation_talk.ts: return status === 429 || status === 503 ? tryAgain(said.error, status, words, talkWait(said.error)) : json({ error: said.error, message: words }, status);":
4747 "the 429/503 branch is the tryAgain",
48 "src/http/api/conversation_talk.ts: return status === 429 || status === 503 ? tryAgain(error, status, message, talkWait(error)) : json({ error, message }, status);":
49 "the 429/503 branch is the tryAgain",
4850 "src/http/api/following.ts: ? 429": "the ceiling outcome is answered through tryAgain just below",
4951 "src/http/feed.ts: error.code === \"forbidden\" ? 403 : error.code === \"too_many\" ? 429 : error.code === \"already_undone\" || error.code === \"expired\" ? 409 : 422,":
5052 "a cap on one request's size, not a wait; json()'s 60 s floor answers it",
test/talk-conversations.test.ts +30
@@ -129,6 +129,36 @@ describe("the API", () => {
129129 expect((await api("GET", `/api/v1/conversation/turns?conversation=${conversation.id}`, alice)).status).toBe(200);
130130 expect((await api("POST", "/api/v1/conversation/messages", bob, { text: "hi", conversation: conversation.id })).status).toBe(404);
131131 });
132
133 test("pinned pins and unpins; an archived conversation is not pinned; the value is a boolean", async () => {
134 const made = (await (await api("POST", "/api/v1/conversations", alice, {})).json()) as { conversation: { id: string } };
135 const url = `/api/v1/conversations/${made.conversation.id}`;
136 const pin = async (body: unknown, who = alice) => api("PATCH", url, who, body);
137 const pinned = (await (await pin({ pinned: true })).json()) as { conversation: { pinnedAt: string | null } };
138 expect(pinned.conversation.pinnedAt).not.toBeNull();
139 expect(((await (await pin({ pinned: false })).json()) as { conversation: { pinnedAt: string | null } }).conversation.pinnedAt).toBeNull();
140 expect((await pin({ pinned: "yes" })).status).toBe(422);
141 expect((await pin({ pinned: true }, bob)).status).toBe(404);
142 await pin({ archived: true });
143 const refused = await pin({ pinned: true });
144 expect(refused.status).toBe(409);
145 expect(((await refused.json()) as { error: string }).error).toBe("archived");
146 expect((await pin({ pinned: false })).status).toBe(200);
147 });
148
149 test("a refused pin writes nothing: no rename, no archive", async () => {
150 const made = (await (await api("POST", "/api/v1/conversations", alice, { title: "Keep" })).json()) as { conversation: { id: string } };
151 const url = `/api/v1/conversations/${made.conversation.id}`;
152 const now = async () => ((await (await api("GET", "/api/v1/conversations", alice)).json()) as { conversations: { id: string; title: string; archivedAt: string | null }[] }).conversations.find((c) => c.id === made.conversation.id)!;
153 expect((await api("PATCH", url, alice, { archived: true, pinned: true })).status).toBe(409);
154 expect((await now()).archivedAt).toBeNull();
155 expect((await api("PATCH", url, alice, { archived: true })).status).toBe(200);
156 expect((await api("PATCH", url, alice, { title: "Lost", pinned: true })).status).toBe(409);
157 const list = ((await (await api("GET", "/api/v1/conversations?archived=1", alice)).json()) as { conversations: { id: string; title: string }[] }).conversations;
158 expect(list.find((c) => c.id === made.conversation.id)?.title).toBe("Keep");
159 // Restoring and pinning in one request is not a refusal.
160 expect((await api("PATCH", url, alice, { archived: false, pinned: true })).status).toBe(200);
161 });
132162 });
133163
134164 describe("the MCP", () => {

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs