From 52ba0285a03083b218e460d1b79a9fd7d2316a00 Mon Sep 17 00:00:00 2001 From: Roman Pavlovskyi <634881+rpavlovs@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:06:12 +0100 Subject: [PATCH] Let a turn finish quietly past a question an earlier turn left open An open question in a conversation refused bloks quiet for every later turn there, so a turn nobody waits on had to reply just because an older question was still on screen. Each open request now records the lane turn it was asked in, and each lane the turn its current work began in. A quiet finish passes only a question asked before that work began; an approval, a question of the turn's own work, or a request whose turn is not known still refuses. A retry, the backup or a pickup may go on with work older than the conversation's latest turn, so it records no start, and every open request still holds it. The earlier question stays open, waiting and answerable, and a quiet finish that passed one gives back the unread dot the turn took on starting, unless the person opened the conversation meanwhile. --- docs/ARCHITECTURE.md | 9 +- server/index.ts | 46 +++++++- server/quiet-finish.ts | 19 ++++ test/codex-async-questions.test.ts | 171 ++++++++++++++++++++++++++++- test/quiet-finish-unit.test.ts | 15 ++- 5 files changed, 246 insertions(+), 14 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 42e91adf..c2caf47d 100755 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -3019,7 +3019,14 @@ from the turn's own credential (`seq`, the lane's turn count when it was minted), only for a check-in or a turn nobody waits on (`unaskedTurn`), and only while nothing of the turn has reached the person: no text previewed or saved, no card, file or open question, none of their words -in it or on their way in (`SteerHolds`). A refusal is a 409 with a +in it or on their way in (`SteerHolds`). A question an earlier turn left +open is not this turn's (`heldByRequest`, by the lane turn it was asked +in): it stays open, on its card and waiting, and a turn finished quietly +past it gives back the conversation's dot it took on starting, unless the +person has opened it since. An approval, a question asked since the work +began, one nobody knows the turn of, or any question in a retry, the +backup or a pickup (whose work may be older than the conversation's +latest turn) still refuses. A refusal is a 409 with a reason, and tells the agent to answer substantively. Once accepted (`QuietGate` in `server/quiet-finish.ts`), what the turn says is saved `quiet` and not previewed; a card, a file, a team proposal or a question diff --git a/server/index.ts b/server/index.ts index 07838f9a..db797fe2 100755 --- a/server/index.ts +++ b/server/index.ts @@ -49,7 +49,7 @@ import { ENGINE_PACKAGES, engineUpdates } from "./engine-updates.ts"; import { FEATURES } from "./features.ts"; import { ReplyNotifications, settledFrame, settledReply } from "./reply-notifications.ts"; import { TextPreview } from "./text-preview.ts"; -import { belongs, QUIET_ACCEPTED, quietKind, quietRefused, SteerHolds, writer, type QuietGate, type QuietRefusal } from "./quiet-finish.ts"; +import { belongs, heldByRequest, QUIET_ACCEPTED, quietKind, quietRefused, SteerHolds, writer, type OpenAsk, type QuietGate, type QuietRefusal } from "./quiet-finish.ts"; import { LaneTurns, buildTrace, emptyTrace, readTurn, turnAt, turnCovers, type LiveTraces, type Trace } from "./trace.ts"; import { AnswerReady, answerDue, answersAllowed, attentionFrom, Viewing, viewingReport, type Attention } from "./answer-ready.ts"; import { Presence, presenceReport, quietWake } from "./presence.ts"; @@ -3470,6 +3470,9 @@ function fitTranscripts(lists: Message[][], tail = RELAY_TAIL): Array<{ messages * one it judged (judgeGoal), so a judge that took a minute never starts a * turn behind the person's back, or on a reply no longer the latest. */ const laneTurns = new Map(); +/** The lane turn each lane's current work began in: the turn itself, or + * for a retry, the backup or a pickup, the one it goes on from. */ +const workSince = new Map(); /** Lanes whose goal is being judged right now, for the chip to say so. */ const goalJudging = new Set(); /** The active choice survives client reloads, never transcript/history storage. */ @@ -5184,6 +5187,7 @@ function forgetAsk(requestId: string) { askMessageByRequest.delete(requestId); askCardThread.delete(requestId); askThreadByRequest.delete(requestId); + askedIn.delete(requestId); askEngineByRequest.delete(requestId); asyncAskOrigin.delete(requestId); withdrawing.delete(requestId); @@ -6023,6 +6027,8 @@ async function onRuntimeEvent(event: RuntimeEvent) { } // answers must reach the lane that asked, not the active one askThreadByRequest.set(event.requestId, event.threadId); + // and in which of its turns: asked again, it is the later one's + askedIn.set(event.requestId, { seq: laneTurns.get(event.threadId) ?? 0, question: asking }); // and are read against the questions it asked (/respond) if (questions) askQuestions.set(event.requestId, questions); if (event.providerInstanceId) askEngineByRequest.set(event.requestId, event.providerInstanceId); @@ -6524,7 +6530,7 @@ async function onRuntimeEvent(event: RuntimeEvent) { const quietGate = quietGates.get(event.threadId)?.turnId === event.turnId ? quietGates.get(event.threadId) : undefined; const quietAction = quietGate?.state === "accepted" && !inRoom && event.ok !== false && !handedOver && event.stopReason !== "interrupted" && !pickingUp && !refolding && - !turnsForYou.has(event.threadId) && ![...askThreadByRequest.values()].includes(event.threadId); + !turnsForYou.has(event.threadId) && !requestHolds(event.threadId, quietGate.since); if (quietGate && !quietAction) cancelQuiet(event.threadId, quietGate); if (quietGate) quietGates.delete(event.threadId); // Restored words take the same notification path as ordinary ones, @@ -6594,7 +6600,9 @@ async function onRuntimeEvent(event: RuntimeEvent) { spokeInTurn.delete(event.threadId); if (origin?.turnId === event.turnId) codexOrigins.delete(event.threadId); if (quietAgentTurn || quietRun || quietEnd) { - // nothing new here + // nothing new here, and an earlier question still waiting keeps + // the dot its reply had, unless the person has opened it since + if (quietAction && quietGate.passed && dotTaken.get(event.threadId) === quietGate.since) store.markLane(bot.id, event.threadId, true); } else if (bot.tasks.some((t) => t.id === event.threadId)) store.markLane(bot.id, event.threadId, true); else store.patchBot(bot.id, { unread: true }); broadcast({ kind: "bot", bot: clientBot(store.bot(bot.id)) }); @@ -7246,6 +7254,12 @@ function callConflict(token?: string): { device: string; targetId: string } | nu /** Which lane raised a live ask, so the answer lands in the right one. */ const askThreadByRequest = new Map(); +/** And in which of its turns, and whether it only asks (requestHolds). */ +const askedIn = new Map(); +/** The lane turn whose work took an unread lane's dot as it started, until + * the person opens the lane: a turn finished quietly past an earlier + * question gives it back (the reply's dot is that question's attention). */ +const dotTaken = new Map(); /** * When each running turn began. * @@ -8824,6 +8838,11 @@ async function startClaimedTurn( if (opts.serviceMessages?.length || !(opts.fallback || opts.retry || opts.carriedOn) || !answerAsked.has(task.id)) answerAsked.set(task.id, askedForAnswer); // a goal judged before this turn began is not judging this one laneTurns.set(task.id, (laneTurns.get(task.id) ?? 0) + 1); + // A retry, the backup or a pickup goes on with work that need not be + // the lane's latest (an incident is tried again after other turns), so + // when its work began is not known, and every open request holds it. + if (goesOn) workSince.delete(task.id); + else workSince.set(task.id, laneTurns.get(task.id)!); // the busy flag holds the lane from here if (claimedLanes.get(task.id) === claim) claimedLanes.delete(task.id); codexDispatches.delete(task.id); @@ -8852,6 +8871,10 @@ async function startClaimedTurn( // hour would otherwise read the lane for the person each time, and a // reply they have not seen yet would lose its dot to a run that, being // quiet, puts none back. + // The dot new work takes is given back only if it finishes quietly past + // an earlier question, which a retry, the backup or a pickup never does. + if (!goesOn && !checkIn && store.taskByThread(task.id)?.task.unread) dotTaken.set(task.id, laneTurns.get(task.id)!); + else dotTaken.delete(task.id); if (!checkIn) store.markLane(bot.id, task.id, false); artifactTurns.begin(task.id, bot.id); turnTokens.delete(task.id); @@ -13907,6 +13930,7 @@ function readOn(threadId: string, personId: string, through: unknown, visible: ( * opening it still finds the line where it was. */ function readByOpening(threadId: string, body: { keepsPlace?: unknown } | null | undefined) { + dotTaken.delete(threadId); if (body?.keepsPlace === true) return; lastRead.readToEnd(threadId, "owner", placeOrder(threadId, () => true).map((m) => m.id)); } @@ -16377,6 +16401,15 @@ function foldFinished(laneId: string, gate: QuietGate): boolean { return true; } +/** Whether a request still open in the lane keeps its turn, whose work + * began at lane turn `since`, from finishing quietly (heldByRequest). */ +function requestHolds(laneId: string, since: number | undefined): boolean { + for (const [requestId, lane] of askThreadByRequest) { + if (lane === laneId && heldByRequest(askedIn.get(requestId), since)) return true; + } + return false; +} + /** `POST /api/bots/:me/tasks/:id/quiet`: checked and taken in one step, * with nothing awaited, so a steer or an event cannot fall in between. */ function acceptQuiet(credential: { seq?: number }, laneId: string): { status: number; body: Record } { @@ -16395,7 +16428,10 @@ function acceptQuiet(credential: { seq?: number }, laneId: string): { status: nu if (turnsForYou.has(laneId)) return refuse("person_in_turn"); const checkIn = checkInTurns.has(laneId); if (!checkIn && !unaskedTurn(laneId)) return refuse("not_eligible"); - if ([...askThreadByRequest.values()].includes(laneId)) return refuse("open_request"); + const since = workSince.get(laneId); + if (requestHolds(laneId, since)) return refuse("open_request"); + // what is still open here is an earlier turn's question + const passed = [...askThreadByRequest.values()].includes(laneId); if (shownInTurn.get(laneId) === seq || spokeInTurn.has(laneId)) return refuse("already_shown"); // the turn so far: after the words it started on const said = store.messagesFor(laneId).filter((m) => !m.queued && !m.unsent); @@ -16410,7 +16446,7 @@ function acceptQuiet(credential: { seq?: number }, laneId: string): { status: nu const quietAsk = (prompt?.via === "routine" && prompt.routine?.quiet) || (prompt?.via === "incident" && prompt.incident?.kind === "note"); if (checkIn && (!prompt || prompt.deleted || !quietAsk)) return refuse("not_eligible"); quietGates.set(laneId, { - seq, turnId, state: "accepted", + seq, turnId, since, passed, state: "accepted", ...(checkIn && prompt ? { promptId: prompt.id } : {}), checked: checkIn ? turn.map((m) => m.id) : [], rows: [], hidden: [], diff --git a/server/quiet-finish.ts b/server/quiet-finish.ts index ff4a7e25..fbce7f37 100644 --- a/server/quiet-finish.ts +++ b/server/quiet-finish.ts @@ -31,6 +31,12 @@ export interface QuietGate { /** The lane turn it was accepted in (laneTurns) and its runtime turn. */ seq: number; turnId: string; + /** The lane turn its work began in (heldByRequest). Not known for a + * retry, the backup or a pickup, whose work may be older than the + * lane's latest. */ + since?: number; + /** An earlier turn's question was open when it was accepted. */ + passed?: boolean; /** superseded: something for the person came after, so the turn ends * as usual, and a later call is refused. */ state: "accepted" | "superseded"; @@ -52,6 +58,19 @@ export function belongs(gate: QuietGate, laneId: string, m: Message, w: Writer | return w.turnId !== undefined ? w.turnId === gate.turnId : w.seq !== undefined && w.seq === gate.seq; } +/** An open request, by the lane turn it was asked in (laneTurns) and + * whether it only asks, as a question does, rather than wanting a yes. */ +export type OpenAsk = { seq: number; question: boolean }; + +/** Whether an open request keeps a turn whose work began at lane turn + * `since` from finishing quietly. A question asked before then stays + * open, on its card and waiting, for the person to answer when they + * choose, and does not hold it. An approval, a question of the turn's own + * work, or a request whose turn is not known always does. */ +export function heldByRequest(asked: OpenAsk | undefined, since: number | undefined): boolean { + return !asked || !asked.question || since === undefined || asked.seq >= since; +} + /** Words on their way into a lane's running turn (steerOne), counted per * lane turn, so a quiet finish cannot pass words the engine may already * have. A settle from an earlier turn changes nothing of a later one. */ diff --git a/test/codex-async-questions.test.ts b/test/codex-async-questions.test.ts index 9bf1340b..3003d14a 100644 --- a/test/codex-async-questions.test.ts +++ b/test/codex-async-questions.test.ts @@ -24,7 +24,7 @@ import { asyncQuestion, CodexDriver } from "../server/drivers/codex.ts"; import { JoinClient } from "../server/join-client.ts"; import { startHarness } from "./helpers/server.ts"; import { teamPlan } from "./helpers/team-plan.ts"; -import { waitFor } from "./helpers/turns.ts"; +import { idle, waitFor } from "./helpers/turns.ts"; async function setup(t: TestContext, fullAuto = false) { const peers: ReturnType[] = []; @@ -300,7 +300,11 @@ test("only an async item with something to ask is read as a question", () => { * it ran, which is whose authority it had; WHICH-SANDBOX says only that. * BLOCKED asks a question its turn waits on and an approval, and waits. * CLI[tag|args] runs the agent's command line and says what it answered, - * as CLI-tag. Each turn notes its words and credential in turns.jsonl. */ + * as CLI-tag; with ASK-FIRST it asks a question of its own a second + * before, and with SLOW it says so a second and a half after. FAIL-word + * fails its first n tries, the first asking a question without waiting + * before it fails, and the try after them goes on as the rest of its words + * say. Each turn notes its words and credential in turns.jsonl. */ function codexHome(extra: Record = {}): string { const home = mkdtempSync(join(tmpdir(), "bloks-async-questions-")); mkdirSync(join(home, ".bloks"), { recursive: true }); @@ -310,7 +314,7 @@ function codexHome(extra: Record = {}): string { `#!${process.execPath} import { createInterface } from "node:readline"; import { execFile } from "node:child_process"; -import { appendFileSync } from "node:fs"; +import { appendFileSync, readFileSync } from "node:fs"; if (process.argv[2] === "--version") { console.log("codex-cli 0.164.0"); process.exit(0); } if (process.argv[2] === "login") { console.log("Logged in using ChatGPT"); process.exit(0); } process.stdin.on("end", () => process.exit(0)); @@ -351,7 +355,18 @@ createInterface({ input: process.stdin }).on("line", (line) => { out({ id: "blocking", method: "item/tool/requestUserInput", params: { threadId: thread, turnId: turn, questions: [{ id: "date", question: "When should it ship?", options: [{ label: "Friday" }] }] } }); return out({ id: "approval", method: "item/commandExecution/requestApproval", params: { threadId: thread, turnId: turn, itemId: "c1", command: "rm -rf build" } }); } + const failing = text.match(/FAIL(\\d)-\\w+/); + const tries = failing ? readFileSync(${JSON.stringify(join(home, "turns.jsonl"))}, "utf8").split("\\n").filter((l) => l.includes(failing[0])).length : 0; + if (failing && tries <= Number(failing[1])) { + if (tries === 1) ask("q-" + failing[0], [{ title: "Which ledger should I use?", options: ["Main", "Archive"] }]); + return out({ method: "turn/completed", params: { threadId: thread, turn: { id: turn, status: "failed", error: { message: "the example engine is having a moment" } } } }); + } const cli = text.match(/CLI\\[(\\w+)\\|([^\\]]+)\\]/); + if (cli && text.includes("ASK-FIRST")) { + ask("q-first", [{ title: "Which day works?", options: ["Monday", "Tuesday"] }]); + return setTimeout(() => execFile(process.execPath, [process.env.BLOKS_CLI, ...cli[2].trim().split(/\\s+/)], (_error, stdout) => finish("CLI-" + cli[1] + " " + stdout.trim())), 1000); + } + if (cli && text.includes("SLOW")) return execFile(process.execPath, [process.env.BLOKS_CLI, ...cli[2].trim().split(/\\s+/)], (_error, stdout) => setTimeout(() => finish("CLI-" + cli[1] + " " + stdout.trim()), 1500)); if (cli) return execFile(process.execPath, [process.env.BLOKS_CLI, ...cli[2].trim().split(/\\s+/)], (_error, stdout) => finish("CLI-" + cli[1] + " " + stdout.trim())); if (text.includes("ASYNC-ENDS")) { ask("q-name", [{ title: "What should the release be called?" }]); return finish("Carried on without it."); } if (text.includes("Replying to")) return finish("GOT " + JSON.stringify({ text, sandbox })); @@ -364,9 +379,9 @@ createInterface({ input: process.stdin }).on("line", (line) => { return home; } -async function fixture(t: TestContext) { +async function fixture(t: TestContext, env: Record = {}) { const home = codexHome(); - let h = await startHarness({ HOME: home }); + let h = await startHarness({ HOME: home, ...env }); t.after(async () => { await h.stop(); rmSync(home, { recursive: true, force: true }); @@ -421,11 +436,48 @@ async function fixture(t: TestContext) { /** Gone with no chance to tidy up, then started again on the same data. */ async reboot() { await h.crash(); - h = await startHarness({ HOME: home }); + h = await startHarness({ HOME: home, ...env }); }, }; } +/** What Kat's command line answered, said as CLI-tag. */ +async function cliSaid(f: Awaited>, tag: string) { + const row = await waitFor(async () => (await f.messages()).findLast((m) => m.role === "bot" && m.kind === "text" && (m.text ?? "").startsWith(`CLI-${tag} `))); + assert.ok(row, `the agent never said CLI-${tag}`); + return { row, answer: JSON.parse(String(row.text).slice(`CLI-${tag} `.length)) }; +} + +/** Kat's lane once the latest turn whose words include `words` is over. + * The lane reads "needs-you" all along while a card is open, so it is + * asked with that turn's own credential: a quiet call made again changes + * nothing, and the step that ends the turn and settles the lane's dot also + * spends the credential (or the call is refused as not running). */ +async function turnEnded(f: Awaited>, words: string) { + const token = await f.token(words); + const over = await waitFor(async () => { + const res = await f.as(token, "POST", `/api/bots/${f.bot.id}/tasks/${f.bot.threadId}/quiet`); + const body = await res.json().catch(() => ({})); + return res.status === 401 || body.reason === "not_running" ? true : null; + }); + assert.ok(over, `the turn that began with "${words}" never ended`); + return f.lane(); +} + +/** Another agent, Lee, whose turn is kept running so its credential can + * write to Kat as `bloks say` does: what it asks is a turn nobody waits + * on. */ +async function anotherAgent(f: Awaited>) { + const { bot: sender } = await f.h.json("/api/bots", { method: "POST", body: JSON.stringify({ name: "Lee" }) }); + await f.h.fetch(`/api/bots/${sender.id}`, { method: "PATCH", body: JSON.stringify({ modelSelection: { instanceId: "codex", model: "gpt-6.1-sol" } }) }); + await f.h.json(`/api/bots/${sender.id}/messages`, { method: "POST", body: JSON.stringify({ text: "ASYNC-WORKING on the example handover", taskId: sender.threadId }) }); + const senderToken = await f.token("ASYNC-WORKING on the example handover"); + return async (text: string) => { + const res = await f.h.fetch(`/api/bots/${f.bot.id}/messages`, { method: "POST", headers: { authorization: `Bearer ${senderToken}` }, body: JSON.stringify({ text }) }); + assert.ok(res.ok, await res.text()); + }; +} + test("an answer to a question asked mid-turn goes into that turn, quoting the question", async (t) => { const f = await fixture(t); await f.say("ASYNC-WORKING on the outage"); @@ -477,6 +529,113 @@ test("an answer given after the turn ended starts the next turn, and is said onc assert.equal(after.filter((m) => m.kind === "text" && (m.text ?? "").startsWith("GOT ")).length, 1); }); +// An earlier turn's question waits for the person, on its card, for as +// long as they like. A later turn nobody waits on, here another agent's +// `bloks say`, may still finish quietly: the question is not its own, and +// stays open, waiting and answerable. A question of its own, or the +// person's own words, keep it from finishing quietly as before. +test("a question an earlier turn left open does not keep a later turn from finishing quietly, and stays open to answer", async (t) => { + const f = await fixture(t); + const ended = (words: string) => turnEnded(f, words); + const said = (tag: string) => cliSaid(f, tag); + await f.say("ASYNC-ENDS the release notes"); + const asked = await f.card(); + const before = await ended("ASYNC-ENDS the release notes"); + assert.equal(before.state, "needs-you"); + assert.equal(before.unread, true, "the reply left a dot"); + + const sayAs = await anotherAgent(f); + + await sayAs("CLI[quiet|quiet] check the example inventory"); + const quiet = await said("quiet"); + assert.equal(quiet.answer.quiet, "accepted", JSON.stringify(quiet.answer)); + const after = await ended("CLI[quiet|quiet] check the example inventory"); + assert.equal((await said("quiet")).row.quiet, true, "what it wrote after the finish is kept quiet"); + assert.equal(after.state, "needs-you", "the lane still waits on the person"); + assert.equal(after.unread, true, "the quiet turn gave back the dot it took"); + const card = (await f.messages()).find((m) => m.id === asked.id); + assert.ok(!card.card.answered && !card.card.closed && !card.card.withdrawn && !card.quiet, JSON.stringify(card.card)); + + // opened while the turn runs, the person has seen it: no dot comes back + await sayAs("SLOW CLI[seen|quiet] check the example inventory once more"); + await f.token("SLOW CLI[seen|quiet] check the example inventory once more"); + await f.h.fetch(`/api/bots/${f.bot.id}/tasks/${f.bot.threadId}/activate`, { method: "POST", body: "{}" }); + assert.equal((await said("seen")).answer.quiet, "accepted"); + const seen = await ended("SLOW CLI[seen|quiet] check the example inventory once more"); + assert.equal((await said("seen")).row.quiet, true); + assert.equal(seen.unread, false, "the person opened it during the turn"); + assert.equal(seen.state, "needs-you"); + + // read before the turn, it stays read: the dot given back is the one found + await sayAs("CLI[again|quiet] check the example inventory again"); + assert.equal((await said("again")).answer.quiet, "accepted"); + const read = await ended("CLI[again|quiet] check the example inventory again"); + assert.equal((await said("again")).row.quiet, true); + assert.equal(read.unread, false, "no dot for what the person had seen"); + assert.equal(read.state, "needs-you"); + + // a question of its own still keeps it from finishing quietly + await sayAs("ASK-FIRST CLI[own|quiet] check the example calendar"); + const own = await said("own"); + assert.match(own.answer.error, /will not finish quietly \(open_request\)/, JSON.stringify(own.answer)); + await ended("ASK-FIRST CLI[own|quiet] check the example calendar"); + assert.notEqual((await said("own")).row.quiet, true, "its report is delivered"); + + // and so do the person's own words, whatever is still open + await f.say("CLI[person|quiet] anything new?"); + const person = await said("person"); + assert.match(person.answer.error, /will not finish quietly/, JSON.stringify(person.answer)); + await ended("CLI[person|quiet] anything new?"); + assert.notEqual((await said("person")).row.quiet, true); + + // the earlier question is answered as it would have been + assert.equal((await f.respond(asked.card.requestId, { behavior: "answer", message: "Lighthouse" })).outcome, "delivered"); + const got = (await f.heard("GOT")).text; + assert.match(got, /What should the release be called\?/); + assert.match(got, /Lighthouse$/); +}); + +test("a retry goes on with the work that failed: the question its failed try left still keeps it from finishing quietly", async (t) => { + const f = await fixture(t, { BLOKS_RETRY_WAIT_MS: "200" }); + const sayAs = await anotherAgent(f); + await sayAs("FAIL1-backlog CLI[retry|quiet] check the example backlog"); + const asked = await f.card(); + const retry = await cliSaid(f, "retry"); + assert.match(retry.answer.error, /will not finish quietly \(open_request\)/, JSON.stringify(retry.answer)); + await turnEnded(f, "FAIL1-backlog"); + assert.ok((await f.messages()).some((m) => m.kind === "notice" && /Trying again/.test(m.text ?? "")), "it was not a retry"); + assert.notEqual((await cliSaid(f, "retry")).row.quiet, true, "its report is delivered"); + const card = (await f.messages()).find((m) => m.id === asked.id); + assert.ok(!card.card.answered && !card.card.closed && !card.card.withdrawn, JSON.stringify(card.card)); +}); + +test("a failed turn tried again from its incident after other work is still that work: its question holds it", async (t) => { + const f = await fixture(t, { BLOKS_RETRY_WAIT_MS: "200" }); + assert.equal((await f.h.fetch("/api/config", { method: "PUT", body: JSON.stringify({ incidents: { enabled: true, lead: "person" } }) })).status, 200); + const sayAs = await anotherAgent(f); + await sayAs("FAIL2-ledger CLI[desk|quiet] check the example ledger"); + const asked = await f.card(); + const incident = await waitFor(async () => ((await f.h.json("/api/incidents")).incidents as any[]).find((i) => i.open && i.where.laneId === f.bot.threadId && i.state === "needs-you"), 30_000); + assert.ok(incident, "the failed turn never became an incident"); + await turnEnded(f, "FAIL2-ledger"); + + // other work in between, new, finishes quietly past the question + await sayAs("CLI[between|quiet] check the example inventory"); + assert.equal((await cliSaid(f, "between")).answer.quiet, "accepted"); + await turnEnded(f, "CLI[between|quiet] check the example inventory"); + assert.equal((await cliSaid(f, "between")).row.quiet, true); + + // tried again, it goes on with its own work, which asked the question + await idle(f.h, f.bot); + assert.equal((await f.h.fetch(`/api/incidents/${incident.id}/retry`, { method: "POST" })).status, 202); + const desk = await cliSaid(f, "desk"); + assert.match(desk.answer.error, /will not finish quietly \(open_request\)/, JSON.stringify(desk.answer)); + await turnEnded(f, "FAIL2-ledger"); + assert.notEqual((await cliSaid(f, "desk")).row.quiet, true, "its report is delivered"); + const card = (await f.messages()).find((m) => m.id === asked.id); + assert.ok(!card.card.answered && !card.card.closed && !card.card.withdrawn, JSON.stringify(card.card)); +}); + test("a collaborator's answer arrives as their own words, with their authority and never the owner's", async (t) => { // An answer said as the owner's would carry the owner's authority into // the turn it starts: on an agent in full access, Codex unsandboxed. diff --git a/test/quiet-finish-unit.test.ts b/test/quiet-finish-unit.test.ts index fdc90eaa..424a1545 100644 --- a/test/quiet-finish-unit.test.ts +++ b/test/quiet-finish-unit.test.ts @@ -1,10 +1,11 @@ // The parts of `bloks quiet` that need no server (server/quiet-finish.ts, // TextPreview.close): which writes belong to the finished turn, whose words -// are still on their way into it, and what the preview shows after it. +// are still on their way into it, which open requests hold it, and what +// the preview shows after it. import assert from "node:assert/strict"; import { test } from "node:test"; import type { RuntimeEvent } from "../server/contracts.ts"; -import { belongs, SteerHolds, writer, type QuietGate } from "../server/quiet-finish.ts"; +import { belongs, heldByRequest, SteerHolds, writer, type QuietGate } from "../server/quiet-finish.ts"; import type { Message } from "../server/store.ts"; import { TextPreview } from "../server/text-preview.ts"; @@ -23,6 +24,16 @@ test("a write belongs to the finished turn only by its runtime turn or its turn' assert.equal(belongs(gate, "lane", row({ queued: true }), { lane: "lane", seq: 3 }), false, "words waiting for a later turn"); }); +test("only a question asked before the turn's work began leaves it free to finish quietly", () => { + assert.equal(heldByRequest({ seq: 3, question: true }, 4), false, "an earlier turn's question"); + assert.equal(heldByRequest({ seq: 4, question: true }, 4), true, "a question of this turn"); + assert.equal(heldByRequest({ seq: 5, question: true }, 4), true, "a question asked after the work began"); + assert.equal(heldByRequest({ seq: 3, question: false }, 4), true, "an earlier turn's approval"); + assert.equal(heldByRequest({ seq: 4, question: false }, 4), true, "this turn's approval"); + assert.equal(heldByRequest(undefined, 4), true, "a request nobody knows the turn of"); + assert.equal(heldByRequest({ seq: 3, question: true }, undefined), true, "a retry, the backup or a pickup, whose work start is not known"); +}); + test("each request or event is its own writer, and none outlives its callback", async () => { assert.equal(writer.getStore(), undefined); // Each callback says what it saw under its own name. The timers only