Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Ask cards: a typed line answers only a card that takes words and was already showing
milind-soni804af27529cd
diff --git a/docs/verification/question-cards.md b/docs/verification/question-cards.mdindex d945e37a2f..94c57892df 100644--- a/docs/verification/question-cards.md+++ b/docs/verification/question-cards.md@@ -89,27 +89,17 @@ One server of the person's own, no teammate handing work on, exactly one questio(`room-plan.json.evidence.jsonl`), as if they were typed in the card's own text field.- The same POST sent again (same `sendId`, same text) returns 202 with the first line and touches no card; the same`sendId` with other words is refused with 409, as a normal send is.-- With the fake ACP CLI on a question of set options (the shape Antigravity asks with, an engine that takes no message- mid-turn), the typed line closes the card without the "isn't one of the choices" note, the turn ends with- `session/cancel`, and the line is the next prompt in the same conversation, without waiting for the card to expire.- The card reads "Closed without an answer" (`answered: "unavailable"`, `dismissed: true`), not "Denied", and the- decision log under `decisions/` records no verdict for it.-- With the fake Claude CLI holding a turn, Claude's own `AskUserQuestion` of two questions waits; the typed line closes- it the same way, the waiting tool gets a plain decline, and the line is steered into the turn.--Two or more question cards live in the chat, Stop, a line with a file or image, a reply to another line, rooms and work-handed on keep their own paths. A card reads closed only when the engine took the close's own decline, which is what-the delivery returns, whatever source the engine reports for it: with the ACP fake set to ask only once-(`FAKE_ACP_QUESTION_ONCE=1`), the next turn answers without a new card and the first card still reads closed. If the-close is refused, or the engine did not take it, the card stays open and can still be tapped, and the line is sent as-before. Sends that close the same request share one decline. The card settles the moment its request resolves, the-close's own decline included, so for that instant it reads "Denied"; the close's outcome then turns it closed. In the-unit tests of `server/host/ask-cards.test.ts`, with the engine held mid-delivery: a tap, Stop or the turn ending that-wins settles the card as it always does, and an explicit decline that wins stays "Denied", even when a newer question-opens before the close returns, and takes no second answer. The default fakes settle a decline as soon as they take it,-so these races are not run end to end. Two tries of one send that arrive together close-or answer one card, even when another opens before the line is written. That holds for 60 seconds after the first try-took effect: a send whose line was never written, tried again after that, may close or answer the card open then.+- With the fake Claude CLI holding a turn, Claude's own `AskUserQuestion` of two questions waits. That card takes taps,+ not one line, so the typed line never touches it: the line is steered into the turn, the waiting tool gets no reply,+ and the card stays open to be tapped.++A card that only takes a tap (set options, or several questions) is never answered or closed by a typed line. A card+that opened less than 1.5 seconds before the line arrived opened while the person was typing, so the line goes on as+a message unless it replies to that card. Two or more question cards live in the chat, Stop, a line with a file or+image, a reply to another line, rooms and work handed on keep their own paths. If the card cannot take the line (a tap+or the timeout won, or the person may not answer it), the line is sent as usual instead of being refused. Two tries of+one send that arrive together answer one card, even when another opens before the line is written. That holds for 60+seconds after the first try took effect. These cases are unit tests in `server/host/ask-cards.test.ts`.Unit tests for the relay's rules (which thread, which sender, sign-ins, work handed out this turn, an engine that cannottake a message mid-turn) are in `server/host/question-routing.test.ts`.diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex 9a70e58ce5..ef305c1e43 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -4544,22 +4544,6 @@ describe("ClaudeDriver turns (fake CLI)", () => {conn.end();});- it("delivers a closed question's decline to the waiting tool, and never allows one", async () => {- await create("hang");- await instance.adapter.sendTurn({ threadId: "t-question-close", text: "go" });- await recorder.until((e) => e.type === "session.started");-- const conn = await connectSocket(permissionSocketPath("t-question-close"));- const reply = answerQueue(conn)();- conn.write(JSON.stringify({ t: "ask", kind: "question", id: "q-close", tool: "AskUserQuestion", input: { questions: [{ question: "Which?", options: [{ label: "A" }] }] } }) + "\n");- await recorder.until((e) => e.type === "request.opened" && e.requestId === "q-close");-- await expect(instance.adapter.respondToRequest("t-question-close", "q-close", { behavior: "allow" })).resolves.toBe("unavailable");- await expect(instance.adapter.respondToRequest("t-question-close", "q-close", { behavior: "deny", message: "typed instead" })).resolves.toBe("rejected");- await expect(reply).resolves.toMatchObject({ id: "q-close", behavior: "deny", message: "typed instead" });- conn.end();- });-it("drops a late question on an already-closed broker with an answer, not a deny (#211)", async () => {await create("hang");await instance.adapter.sendTurn({ threadId: "t-question-late", text: "go" });diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex dc16ca48e8..975c4e37ae 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -571,7 +571,7 @@ export async function createPermissionBroker(opts: {answer(askId: string, behavior: AskBehavior, message?: string, always?: boolean): boolean {const p = pending.get(askId);if (!p) return false;- if (p.ask.kind === "question" ? behavior === "allow" : behavior === "answer") return false;+ if (p.ask.kind === "question" ? behavior !== "answer" : behavior === "answer") return false;p.finish(behavior, message, "user", always && behavior === "allow");return true;},diff --git a/server/host/ask-cards.test.ts b/server/host/ask-cards.test.tsindex e04bfb4577..0a6fc559e0 100644--- a/server/host/ask-cards.test.ts+++ b/server/host/ask-cards.test.ts@@ -1,11 +1,10 @@import { describe, expect, it, vi } from "vitest";-import type { RequestOutcome, RuntimeEvent } from "../contracts.ts";import type { HandoffView } from "../coordinator.ts";import type { Notification } from "../notify.ts";import type { RequestAuth } from "../request-auth.ts";import type { BotRecord, Message } from "../store.ts";-import { askToolName, closeCard, createAskCards, settleRequestCard, type AskCardsDeps } from "./ask-cards.ts";+import { askToolName, CARD_SETTLE_MS, createAskCards, type AskCardsDeps } from "./ask-cards.ts";const AUTH = { kind: "session", scopes: ["client"], session: { id: "s", email: "[email protected]" } } as unknown as RequestAuth;const QUESTION = "What wording should the new footer text use?";@@ -23,13 +22,11 @@ function world(options: { inboxThread?: string; live?: string[]; privateThreads?messagesFor: rows,activePath: rows,appendMessage: (threadId: string, message: Omit<Message, "id" | "at">) => {- written.push(message);const full = { id: `m${++ids}`, at: 1_000 + ids, ...message } as Message;threads.set(threadId, [...rows(threadId), full]);return full;},patchMessage: (threadId: string, id: string, patch: Partial<Message>) => {- written.push(patch);const list = rows(threadId);const at = list.findIndex((message) => message.id === id);list[at] = { ...list[at]!, ...patch };@@ -45,11 +42,11 @@ function world(options: { inboxThread?: string; live?: string[]; privateThreads?const nodes = new Map<string, HandoffView>();const answered: Array<{ id: string; text: string }> = [];const notified: Notification[] = [];- const answers: Array<{ threadId: string; requestId: string; message?: string; behavior?: "close" }> = [];+ const answers: Array<{ threadId: string; requestId: string; message: string }> = [];const live = new Set(options.live ?? []);- const written: unknown[] = [];let refuse: { status: number; error: string } | null = null;let afterAnswer: (() => void) | null = null;+ let clock = 0;const deps: AskCardsDeps = {store: store as unknown as AskCardsDeps["store"],node: (id) => nodes.get(id),@@ -60,14 +57,13 @@ function world(options: { inboxThread?: string; live?: string[]; privateThreads?live: (_threadId, requestId) => live.has(requestId),answerCard: vi.fn(async (input) => {if (refuse) return { ok: false as const, ...refuse };- answers.push({ threadId: input.threadId, requestId: input.requestId, ...(input.behavior === "close" ? { behavior: "close" as const }- : { message: input.message }) });+ answers.push({ threadId: input.threadId, requestId: input.requestId, message: input.message });live.delete(input.requestId);afterAnswer?.();return { ok: true as const };}),answeredIn: (threadId, requestId) => (threadId === "inbox" && requestId.startsWith("req") ? "work" : threadId),- now: () => 0,+ now: () => clock,answerNode: (id, text) => {const parked = nodes.get(id);if (!parked || parked.status !== "waiting") return false;@@ -86,8 +82,10 @@ function world(options: { inboxThread?: string; live?: string[]; privateThreads?};nodes.set("root", { id: "root", rootId: "root", threadId: "inbox", botId: "scout" } as HandoffView);const say = (threadId: string, text: string) => store.appendMessage(threadId, { role: "bot", kind: "text", text });- return { cards, store, rows, notified, answers, answered, node, say, deps, written, open: (requestId: string) => live.add(requestId),- refuse: (value: typeof refuse) => { refuse = value; }, afterAnswer: (value: typeof afterAnswer) => { afterAnswer = value; } };+ return { cards, store, rows, notified, answers, answered, node, say, deps, open: (requestId: string) => live.add(requestId),+ refuse: (value: typeof refuse) => { refuse = value; }, afterAnswer: (value: typeof afterAnswer) => { afterAnswer = value; },+ /** Moves the clock past every card shown so far, as when the person reads a card before typing. */+ settle: () => { clock = Math.max(clock, ...[...threads.values()].flat().map((row) => row.at)) + CARD_SETTLE_MS; } };}describe("a teammate's NEEDS INPUT question", () => {@@ -359,6 +357,7 @@ describe("a typed line answers a question card", () => {it("answers the card its turn waits on in the bot's own chat with exactly the person's words", async () => {const w = world({ live: ["req-1"] });const asked = question(w, "chat");+ w.settle();const result = await w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-3" });expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", message: "What time is it?" }]);expect(result).toMatchObject({ status: 202, message: { role: "user", text: "What time is it?", replyToId: asked.id, sendId: "send-3" } });@@ -367,81 +366,80 @@ describe("a typed line answers a question card", () => {it("files a structured question's answer under its text, as an answer typed on the card would be", async () => {const w = world({ live: ["req-1"] });question(w, "chat", { questionRequest: { version: 1, questions: [{ question: "Should I?", options: [{ label: "Yes" }, { label: "No" }] }] } });+ w.settle();await w.cards.typed(AUTH, "chat", "Not yet", undefined, {});expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", message: "The user answered your questions.\n\nQ: Should I?\nA: Not yet" }]);});- it("closes a card that takes no words in the bot's own chat and leaves the line to be sent as the next message", async () => {- for (const card of [{ fixedOptions: true }, { questionRequest: { version: 1 as const, questions: [{ question: "A?", options: [{ label: "x" }] }, { question: "B?", options: [{ label: "y" }] }] } }]) {+ it("never touches a card in the bot's own chat that only takes a tap: the line goes on to the usual send", async () => {+ const several = { questionRequest: { version: 1 as const, questions: [{ question: "A?", options: [{ label: "x" }] }, { question: "B?", options: [{ label: "y" }] }] } };+ for (const card of [{ fixedOptions: true }, several]) {const w = world({ live: ["req-1"] });- question(w, "chat", card);+ const asked = question(w, "chat", card);+ w.settle();expect(await w.cards.typed(AUTH, "chat", "Something else first", undefined, {})).toBeNull();- expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", behavior: "close" }]);- expect(w.rows("chat").filter((row) => row.role === "user")).toEqual([]);+ expect(await w.cards.typed(AUTH, "chat", "Something else first", asked, {})).toBeNull();+ expect(w.deps.answerCard).not.toHaveBeenCalled();+ expect(w.rows("chat")).toEqual([asked]);}});- it("leaves a card it could not close as it is, and the line to the usual send", async () => {+ it("leaves a line to the usual send when its card opened as the person typed, unless the line replies to that card", async () => {const w = world({ live: ["req-1"] });- const asked = question(w, "chat", { fixedOptions: true });- w.refuse({ status: 403, error: "This question is Ben's to answer." });- expect(await w.cards.typed(AUTH, "chat", "Something else first", undefined, {})).toBeNull();- expect(w.deps.answerCard).toHaveBeenCalledWith(expect.objectContaining({ requestId: "req-1", behavior: "close" }));- expect(w.rows("chat")).toEqual([asked]);+ const asked = question(w, "chat");+ expect(await w.cards.typed(AUTH, "chat", "And the header too", undefined, { sendId: "send-8" })).toBeNull();+ expect(w.answers).toEqual([]);+ const replied = await w.cards.typed(AUTH, "chat", "The footer only", asked, { sendId: "send-10" });+ expect(replied).toMatchObject({ status: 202, message: { text: "The footer only", replyToId: asked.id } });+ expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", message: "The footer only" }]);});it("gives a send tried again the line it wrote, and touches no card it finds open then", async () => {- for (const next of [{ fixedOptions: true }, {}]) {- const w = world({ live: ["req-1"] });- question(w, "chat");- const first = await w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-4" });- question(w, "chat", { requestId: "req-2", ...next });- w.open("req-2");- const again = await w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-4" });- expect(again).toEqual({ status: 202, message: first!.message });- expect(w.answers.map((answer) => answer.requestId)).toEqual(["req-1"]);- expect(await w.cards.typed(AUTH, "chat", "Something else", undefined, { sendId: "send-4" }), "other words go on to be refused").toBeNull();- expect(w.answers).toHaveLength(1);- expect(w.rows("chat").filter((row) => row.role === "user")).toHaveLength(1);- }+ const w = world({ live: ["req-1"] });+ question(w, "chat");+ w.settle();+ const first = await w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-4" });+ question(w, "chat", { requestId: "req-2" });+ w.open("req-2");+ w.settle();+ const again = await w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-4" });+ expect(again).toEqual({ status: 202, message: first!.message });+ expect(w.answers.map((answer) => answer.requestId)).toEqual(["req-1"]);+ expect(await w.cards.typed(AUTH, "chat", "Something else", undefined, { sendId: "send-4" }), "other words go on to be refused").toBeNull();+ expect(w.answers).toHaveLength(1);+ expect(w.rows("chat").filter((row) => row.role === "user")).toHaveLength(1);});it("answers once when the same send arrives twice at the same time", async () => {const w = world({ live: ["req-1"] });question(w, "chat");+ w.settle();const [one, two] = await Promise.all([1, 2].map(() => w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-5" })));expect(two?.message?.id).toBe(one?.message?.id);expect(w.answers).toHaveLength(1);});- it("closes one card when the same send arrives twice at once and a new card opens before its line is written", async () => {+ it("answers one card when the same send arrives twice at once and a new card opens before its line is written", async () => {const w = world({ live: ["req-1"] });- question(w, "chat", { fixedOptions: true });+ question(w, "chat");+ w.settle();w.afterAnswer(() => {w.afterAnswer(null);- question(w, "chat", { requestId: "req-2", fixedOptions: true });+ question(w, "chat", { requestId: "req-2" });w.open("req-2");+ w.settle();});- const tries = await Promise.all([1, 2].map(() => w.cards.typed(AUTH, "chat", "Something else first", undefined, { sendId: "send-6" })));- expect(tries).toEqual([null, null]);+ const tries = await Promise.all([1, 2].map(() => w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-6" })));+ expect(tries[1]?.message?.id).toBe(tries[0]?.message?.id);expect(w.answers.map((answer) => answer.requestId)).toEqual(["req-1"]);});- it("lets a send whose close was refused try again", async () => {- const w = world({ live: ["req-1"] });- question(w, "chat", { fixedOptions: true });- w.refuse({ status: 409, error: "The request is no longer open." });- expect(await w.cards.typed(AUTH, "chat", "Something else first", undefined, { sendId: "send-7" })).toBeNull();- w.refuse(null);- expect(await w.cards.typed(AUTH, "chat", "Something else first", undefined, { sendId: "send-7" })).toBeNull();- expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", behavior: "close" }]);- });-it("leaves a line in the bot's own chat to the usual send while two question cards wait there", async () => {for (const second of [{}, { fixedOptions: true }]) {const w = world({ live: ["req-1", "req-2"] });const first = question(w, "chat");question(w, "chat", { requestId: "req-2", ...second });+ w.settle();expect(await w.cards.typed(AUTH, "chat", "What time is it?", undefined, {})).toBeNull();expect(await w.cards.typed(AUTH, "chat", "What time is it?", first, {})).toBeNull();expect(w.answers).toEqual([]);@@ -451,10 +449,12 @@ describe("a typed line answers a question card", () => {it("leaves a line in the bot's own chat to the usual send when no turn waits on its card, it is Stop, it replies to another line or carries a file", async () => {const idle = world();question(idle, "chat");+ idle.settle();expect(await idle.cards.typed(AUTH, "chat", "Take the second one", undefined, {})).toBeNull();const busy = world({ live: ["req-1"] });question(busy, "chat");const other = busy.say("chat", "I checked.");+ busy.settle();expect(await busy.cards.typed(AUTH, "chat", "stop", undefined, {})).toBeNull();expect(await busy.cards.typed(AUTH, "chat", "Thanks", other, {})).toBeNull();expect(await busy.cards.typed(AUTH, "chat", 'Look <attached-image path="a.png" />', undefined, {})).toBeNull();@@ -474,6 +474,7 @@ describe("a typed line answers a question card", () => {for (const refusal of [{ status: 403, error: "This question is Ben's to answer." }, { status: 409, error: "This card was already answered." }]) {const w = world({ live: ["req-1"] });const asked = question(w, "chat");+ w.settle();w.refuse(refusal);expect(await w.cards.typed(AUTH, "chat", "What time is it?", undefined, { sendId: "send-9" })).toBeNull();expect(w.deps.answerCard).toHaveBeenCalledWith(expect.objectContaining({ requestId: "req-1", behavior: "answer" }));@@ -576,151 +577,6 @@ describe("the chip in the conversation that handed the work on", () => {});});-describe("closing a card the person moved past", () => {- type Resolved = Extract<RuntimeEvent, { type: "request.resolved" }>;- /** Question cards in one chat, the live link of each, and an engine that takes a decline only once released. `resolve`- * stands in for the request.resolved handler: it settles the card through the link, then drops the link. */- const server = () => {- const rows: Message[] = [], live = new Map<string, string>(), closing = new Map<string, Promise<RequestOutcome>>(), pending = new Set<string>();- const store = {- messagesFor: () => rows,- patchMessage: (_threadId: string, id: string, patch: Partial<Message>) => {- const at = rows.findIndex((row) => row.id === id);- rows[at] = { ...rows[at]!, ...patch };- return rows[at]!;- },- } as unknown as Parameters<typeof closeCard>[0]["store"];- const ask = (requestId: string) => {- rows.push({ id: `m-${requestId}`, at: rows.length, role: "bot", kind: "options",- card: { title: "Which?", subtitle: "Which?", requestId, requestType: "question", options: [], fixedOptions: true } } as Message);- live.set(`chat:${requestId}`, `m-${requestId}`);- pending.add(requestId);- };- const card = (requestId: string) => rows.find((row) => row.id === `m-${requestId}`)!.card!;- const resolve = (requestId: string, behavior: Resolved["behavior"], source: Resolved["source"]) => {- pending.delete(requestId);- const messageId = live.get(`chat:${requestId}`);- if (!messageId) return;- settleRequestCard(store, { type: "request.resolved", eventId: `e-${requestId}`, provider: "claude", createdAt: "0", threadId: "chat", requestId, behavior, source }, messageId);- live.delete(`chat:${requestId}`);- };- let release!: () => void;- const held = new Promise<void>((done) => { release = done; });- const declines: string[] = [];- // `source` is what the engine reports for its own decline: the Claude broker says user, ACP of set options says system.- const decline = (requestId: string, options: { hold?: boolean; source?: Resolved["source"] } = {}) => async (): Promise<RequestOutcome> => {- if (options.hold) await held;- if (!pending.has(requestId)) return "unavailable";- declines.push(requestId);- resolve(requestId, "deny", options.source ?? "user");- return "rejected";- };- const close = (requestId: string, take: () => Promise<RequestOutcome>) =>- closeCard({ store, threadId: "chat", requestId, live, closing, decline: take });- // A newer question closes the older cards no turn waits on and nobody answered, as askedAgain does.- const askedAgain = (requestId: string) => {- for (const row of rows) {- if (row.card?.requestId && row.card.requestId !== requestId && !row.card.answered && !live.has(`chat:${row.card.requestId}`)) {- row.card = { ...row.card, answered: "unavailable", dismissed: true };- }- }- };- return { live, closing, declines, ask, askedAgain, card, resolve, release, decline, close };- };-- it("reads closed without an answer once the engine took the decline, whatever source the engine reported", async () => {- for (const source of ["user", "system"] as const) {- const s = server();- s.ask("req-1");- expect(await s.close("req-1", s.decline("req-1", { source }))).toBe("rejected");- expect(s.card("req-1"), source).toMatchObject({ answered: "unavailable", dismissed: true });- expect([...s.live.keys()]).toEqual([]);- expect(s.closing.size).toBe(0);- }- });-- it("delivers one decline for two sends that close the same request, and never reads as a refusal", async () => {- const s = server();- s.ask("req-1");- const first = s.close("req-1", s.decline("req-1", { hold: true }));- const second = s.close("req-1", async () => "unavailable");- s.release();- expect(await Promise.all([first, second])).toEqual(["rejected", "rejected"]);- expect(s.declines).toEqual(["req-1"]);- expect(s.card("req-1")).toMatchObject({ answered: "unavailable", dismissed: true });- expect(s.closing.size).toBe(0);- });-- it("keeps an explicit refusal that wins while the decline is on its way, even when a newer question opens meanwhile", async () => {- const s = server();- s.ask("req-1");- const closing = s.close("req-1", s.decline("req-1", { hold: true }));- await Promise.resolve();- s.resolve("req-1", "deny", "user");- s.ask("req-2");- s.askedAgain("req-2");- s.release();- expect(await closing).toBe("unavailable");- expect(s.card("req-1")).toMatchObject({ answered: "deny", dismissed: false });- });-- it("takes no second answer for a question refused while the decline is on its way", async () => {- const s = server();- s.ask("req-1");- const closing = s.close("req-1", s.decline("req-1", { hold: true }));- await Promise.resolve();- s.resolve("req-1", "deny", "user");- expect(s.card("req-1"), "settled before the close returns").toMatchObject({ answered: "deny", dismissed: false });- s.release();- expect(await closing).toBe("unavailable");- expect(s.card("req-1")).toMatchObject({ answered: "deny", dismissed: false });- });-- it("keeps a tap, Stop or the turn ending that wins while the decline is on its way, and the next card closes", async () => {- const wins: Record<string, (s: ReturnType<typeof server>) => void> = {- tap: (s) => s.resolve("req-1", "answer", "user"),- stop: (s) => { s.live.clear(); s.resolve("req-1", "deny", "system"); },- "turn end": (s) => s.resolve("req-1", "deny", "system"),- };- for (const [name, win] of Object.entries(wins)) {- const s = server();- s.ask("req-1");- const closing = s.close("req-1", s.decline("req-1", { hold: true }));- await Promise.resolve();- win(s);- s.release();- expect(await closing, name).toBe("unavailable");- if (name === "tap") expect(s.card("req-1")).toMatchObject({ answered: "answer", dismissed: false });- else expect(s.card("req-1").answered, `${name}: open for a late answer`).toBeUndefined();- expect([...s.live.keys()], name).toEqual([]);- s.ask("req-2");- expect([...s.live.keys()], `${name}: the next card is the only one waiting`).toEqual(["chat:req-2"]);- expect(await s.close("req-2", s.decline("req-2", { source: "system" }))).toBe("rejected");- expect(s.card("req-2"), name).toMatchObject({ answered: "unavailable", dismissed: true });- }- });-- it("stays open and live for a tap when the engine did not take the decline, or delivering it failed", async () => {- for (const take of [async () => "unavailable" as const, async (): Promise<"rejected"> => { throw new Error("broker gone"); }]) {- const s = server();- s.ask("req-1");- expect(await s.close("req-1", take)).toBe("unavailable");- expect(s.card("req-1").answered).toBeUndefined();- expect(s.live.get("chat:req-1")).toBe("m-req-1");- expect(s.closing.size).toBe(0);- s.resolve("req-1", "answer", "user");- expect(s.card("req-1")).toMatchObject({ answered: "answer" });- }- });-- it("delivers nothing for a card no turn waits on", async () => {- const s = server();- const take = vi.fn(async () => "rejected" as const);- expect(await s.close("req-1", take)).toBe("unavailable");- expect(take).not.toHaveBeenCalled();- });-});-describe("askToolName", () => {const bot = (toolScope?: BotRecord["toolScope"]) => ({ modelSelection: { instanceId: "claude", model: "m" }, toolScope }) as BotRecord;const claude = () => ({ kind: "mcp" as const, server: "ogb", name: "ask_user" });diff --git a/server/host/ask-cards.ts b/server/host/ask-cards.tsindex 6c168ab4e4..c13352e0ba 100644--- a/server/host/ask-cards.ts+++ b/server/host/ask-cards.ts@@ -10,7 +10,7 @@ import { allowsTool, type ToolIdentity } from "../../shared/tool-scope.ts";import type { PersonWait } from "../../shared/person-wait.ts";import type { OptionCardData } from "../../shared/wire.ts";import { noticeTool, type ChatNoticeKey } from "../chat-notices.ts";-import type { RequestOutcome, RuntimeEvent } from "../contracts.ts";+import type { RuntimeEvent } from "../contracts.ts";import type { HandoffView } from "../coordinator.ts";import { buildNotification, type Notification } from "../notify.ts";import type { RequestAuth } from "../request-auth.ts";@@ -25,8 +25,10 @@ const OPEN_QUESTION = "needs-input-";const DAY_MS = 24 * 60 * 60_000;const NEEDS_INPUT_LINE = /^needs input:/i;const hasAttachment = (text: string): boolean => text.includes("<attached-image") || text.includes("<attached-file");-/** How long a send that answered or closed a card keeps it from touching another, while its line is not yet written. */+/** How long a send that answered a card keeps it from touching another, while its line is not yet written. */const SPENT_SEND_MS = 60_000;+/** A card younger than this opened while the person was still typing: their line is not its answer. */+export const CARD_SETTLE_MS = 1_500;type Typed = { status: number; message?: Message; error?: string } | null;export interface AskCardsDeps {@@ -45,7 +47,7 @@ export interface AskCardsDeps {/** The parked node's next turn carries the person's answer. */answerNode(id: string, text: string): boolean;/** Answers a card as a tap on it would, with the same checks on who may answer, through an inbox copy too. */- answerCard(input: { auth: RequestAuth; threadId: string; requestId: string; behavior: "answer" | "close"; message?: string }): Promise<{ ok: true } | { ok: false; status: number; error: string }>;+ answerCard(input: { auth: RequestAuth; threadId: string; requestId: string; behavior: "answer"; message: string }): Promise<{ ok: true } | { ok: false; status: number; error: string }>;/** The conversation a card in `threadId` was asked in: an inbox copy's original. */answeredIn(threadId: string, requestId: string): string;now?: () => number;@@ -79,46 +81,12 @@ export function resolvedCard(card: OptionCardData, resolved: Resolved): OptionCareturn { ...card, answered: resolved.behavior, dismissed: persistent ? false : resolved.source !== "user", ...(resolved.source === "timeout" && !persistent ? { expired: true } : {}) };}-/** Settles a card as its request resolved, the moment it resolves: a decline a close sent included, which the close's- * own outcome then turns into closed without an answer. */+/** Settles a card as its request resolved, the moment it resolves. */export function settleRequestCard(store: CardStore, resolved: Resolved, messageId: string): void {const card = store.messagesFor(resolved.threadId).find((message) => message.id === messageId)?.card;if (card && !card.answered && shouldSettleRequestCard(card, resolved.source)) store.patchMessage(resolved.threadId, messageId, { card: resolvedCard(card, resolved) });}-/** Declines a question the person moved past without an answer, once per request however many sends close it. An- * outcome other than `unavailable` means the engine took this decline, so the refusal the card may already show was the- * close's: it reads closed without an answer, whatever source the engine reported. Otherwise a tap, an explicit decline,- * Stop or the turn ending came first and settled the card as usual; a decline that never landed leaves the card and the- * request alone. */-export function closeCard(input: { store: CardStore; threadId: string; requestId: string; live: ReadonlyMap<string, string>;- closing: Map<string, Promise<RequestOutcome>>; decline: () => Promise<RequestOutcome> }): Promise<RequestOutcome> {- const key = `${input.threadId}:${input.requestId}`;- const running = input.closing.get(key);- if (running) return running;- const messageId = input.live.get(key);- if (!messageId) return Promise.resolve("unavailable");- const close = async (): Promise<RequestOutcome> => {- let outcome: RequestOutcome;- try {- outcome = await input.decline();- } catch {- outcome = "unavailable";- } finally {- input.closing.delete(key);- }- const card = input.store.messagesFor(input.threadId).find((message) => message.id === messageId)?.card;- if (outcome !== "unavailable" && card && (!card.answered || card.answered === "deny")) {- const { answeredBy: _refuser, ...open } = card;- input.store.patchMessage(input.threadId, messageId, { card: { ...open, answered: "unavailable", dismissed: true } });- }- return outcome;- };- const outcome = Promise.resolve().then(close);- input.closing.set(key, outcome);- return outcome;-}-/** The reply up to its NEEDS INPUT line; empty when the line is the whole reply. */function beforeQuestion(text: string): string {const lines = text.split(/\r?\n/);@@ -352,9 +320,10 @@ export function createAskCards(deps: AskCardsDeps) {}/** A person's line answers an inbox copy it replies to, or the question card the bot's turn waits on, as a tap would.- * In the bot's own chat that is the one question card a turn waits on there, and one that takes no words closes- * instead, the line going on as the next message. Null leaves the line to be sent (steered or queued) as usual. Tries- * of one send run one after another, and one that answered or closed a card touches no other. */+ * In the bot's own chat that is the one question card a turn waits on there, when it takes words and was already+ * showing as the person typed. A card that only takes a tap is left to be tapped: the line never closes it. Null leaves+ * the line to be sent (steered or queued) as usual. Tries of one send run one after another, and one that answered a+ * card touches no other. */const typing = new Map<string, Promise<Typed>>();const spent = new Map<string, number>();function typed(auth: RequestAuth, threadId: string, text: string, target: Message | undefined,@@ -386,13 +355,9 @@ export function createAskCards(deps: AskCardsDeps) {const handedOn = Boolean(delegator && delegator.threadId !== threadId);const waiting = thread.filter((message) => !message.inbox && liveCardKind(message.card) === "question" && deps.live(threadId, message.card!.requestId!));const only = waiting.length === 1 ? waiting[0]! : undefined;- const ownChat = !handedOn && !hasAttachment(text) && Boolean(only) && (!target || target.id === only!.id);- if (ownChat && !answerableInWords(only!.card)) {- // Closed or not, the line goes on as the next message, steered into the waiting turn or queued behind it.- if (key) spent.set(key, now());- if (!(await deps.answerCard({ auth, threadId, requestId: only!.card!.requestId!, behavior: "close" })).ok) spent.delete(key);- return null;- }+ // A reply to the card means it whatever its age; otherwise a card that opened while the line was typed is not its question.+ const ownChat = !handedOn && !hasAttachment(text) && only !== undefined && answerableInWords(only.card)+ && (target ? target.id === only.id : now() - only.at >= CARD_SETTLE_MS);const asked = target? answerableInWords(target.card) ? target : undefined: ownChat ? onlydiff --git a/server/index.ts b/server/index.tsindex 93e5e62137..d7f83893b6 100644--- a/server/index.ts+++ b/server/index.ts@@ -26,7 +26,7 @@ import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";import { SharedComputerControl } from "./shared-computer-control.ts";import { STATUS_REPLY_TIMEOUT_MS } from "./runtime/status-reply.ts"; import { createCoordinator, type ComposedTurn, type CoordinateBotsCall, type Coordinator, type HandoffOpener, type HandoffOptions, type HandoffView, type HostTurnResult } from "./coordinator.ts";import { queuedBehindPersonText, turnWaitedOnPerson, UnansweredApprovals } from "./waiting-on-person.ts";-import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, closeCard, createAskCards, settleRequestCard } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { createConnectCardSettle } from "./host/connect-card-settle.ts";+import { createPersonWaits } from "./host/person-waits.ts"; import { askToolName, createAskCards, settleRequestCard } from "./host/ask-cards.ts"; import { createQuestionRouting } from "./host/question-routing.ts"; import { workThreadFor } from "./host/work-thread.ts"; import { leaveThreadPost, postToThread, threadWaitsOn, unreadThreadPosts } from "./host/thread-posts.ts"; import { anyCardLive, closedByStop, resumableCards as cardsWaitedOn } from "./host/resumable-cards.ts"; import { createMcpChat } from "./host/mcp-chat.ts"; import { isCardOwnerLive, isMcpSignInCard } from "./host/mcp-sign-in-cards.ts"; import { createConnectCardSettle } from "./host/connect-card-settle.ts";import { assertRequestTarget, guardedRequestPath, requestConflict, requestNeedsInput } from "./guarded-requests.ts";import { botAvatarUrlFromStoredPath } from "../shared/bot-avatar.ts";import { BOT_PROFILE_LIMITS } from "../shared/bot-profile.ts";@@ -4725,7 +4725,7 @@ onSteeredQueueChange(() => broadcast({ kind: "bot.queued", queues: publicBotQueu// Keyed by threadId: provider item and request ids are unique only within a thread.const toolMessageByItem = new Map<string, string>();-const askMessageByRequest = new Map<string, string>(), closingRequests = new Map<string, Promise<RequestOutcome>>();+const askMessageByRequest = new Map<string, string>();const unansweredApprovals = new UnansweredApprovals(); const approvalAsk = (botId: string | undefined, threadId: string, turnId: string | undefined): { approvalAsk?: string } => { const asked = botId ? unansweredApprovals.ask(threadId, turnId, store.bot(botId)?.name ?? "A teammate", threadLanguage(threadId)) : undefined; return asked ? { approvalAsk: asked } : {}; };// Only native, live permission metadata becomes a remembered grant, never an imported transcript or display summary.const pendingCommandRules = new Map<string, { botId: string; candidate: CommandAllowlistCandidate }>();@@ -4743,7 +4743,7 @@ async function answerRequest(threadId: string,instanceId: string,requestId: string,- behavior: "allow" | "deny" | "answer" | "close",+ behavior: "allow" | "deny" | "answer",message?: string,decidedFor?: { id: string; name: string },always?: boolean,@@ -4757,10 +4757,8 @@ async function answerRequest(: thread.find((m) => m.card?.requestId === requestId);const card = cardMessage?.card;const remembered = rememberCommand ? pendingCommandRules.get(`${threadId}:${requestId}`) : undefined;- // The live turn owns this question, as it owns Stop and steer. A card closed without an answer records no denial.+ // The live turn owns this question, as it owns Stop and steer.const instance = runningTurnEngines.get(threadId) ?? registry.get(instanceId);- if (behavior === "close") return closeCard({ store, threadId, requestId, live: askMessageByRequest, closing: closingRequests,- decline: async () => instance ? instance.adapter.respondToRequest(threadId, requestId, { behavior: "deny" }) : "unavailable" });let outcome: RequestOutcome = "unavailable";if (instance) {try {@@ -4823,7 +4821,7 @@ async function respondToCard(input: {auth: RequestAuth;threadId: string;requestId: string;- behavior: "allow" | "deny" | "answer" | "close";+ behavior: "allow" | "deny" | "answer";message?: string;callId?: string;via?: DecisionVia;@@ -4833,7 +4831,7 @@ async function respondToCard(input: {if (auth.kind === "session" && !sessions.isLive(auth.session.id)) {return { ok: false, status: 401, error: "The session that started this call has ended." };}- const decline = behavior === "close" ? "deny" : behavior, refusal = cardAnswerRefusal(auth, input.threadId, requestId, decline) ?? cardAnswerRefusal(auth, threadId, requestId, decline);+ const refusal = cardAnswerRefusal(auth, input.threadId, requestId, behavior) ?? cardAnswerRefusal(auth, threadId, requestId, behavior);if (refusal) return { ok: false, status: 403, error: refusal };const bot = store.botByThread(threadId);if (!bot) return { ok: false, status: 404, error: "The chat is gone." };diff --git a/server/question-card-typed-line.e2e.test.ts b/server/question-card-typed-line.e2e.test.tsindex ab4806afa2..bad88e60e0 100644--- a/server/question-card-typed-line.e2e.test.ts+++ b/server/question-card-typed-line.e2e.test.ts@@ -1,20 +1,13 @@-import { spawn, type ChildProcess } from "node:child_process";import { randomUUID } from "node:crypto";-import { closeSync, existsSync, mkdtempSync, openSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { connect, type Socket } from "node:net";import { tmpdir } from "node:os";import { join } from "node:path";-import { fileURLToPath } from "node:url";import { expect, it } from "vitest";-import { launchVerificationServer, runControlOmb, verificationServerEnvironment } from "../scripts/control-omb.ts";-import { waitForExit } from "./testing/cleanup.ts";+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";+import { CARD_SETTLE_MS } from "./host/ask-cards.ts";const POLL = { timeout: 30_000, interval: 100 };-/** The verdicts recorded for one request; showing its card is not one. */-const verdicts = (dataDir: string, requestId: string): string[] => (existsSync(join(dataDir, "decisions"))- ? readdirSync(join(dataDir, "decisions")).flatMap((file) => readFileSync(join(dataDir, "decisions", file), "utf8").split("\n").filter(Boolean)) : [])- .map((line) => JSON.parse(line) as { requestId?: string; decision?: string })- .filter((row) => row.requestId === requestId && row.decision !== "card-shown").map((row) => row.decision ?? "");type Row = { id: string; role: string; kind: string; text?: string; replyToId?: string;card?: { requestId?: string; answered?: string; answeredText?: string; dismissed?: boolean } };@@ -45,6 +38,8 @@ it("in the bot's own chat, a line typed while its ask_user card waits answers thawait control("send", "--bot", bot.id, "--task", threadId, "--text", "ASK-ME");await expect.poll(async () => Boolean(await openCard(threadId)), POLL).toBe(true);const card = (await openCard(threadId))!;+ // The person reads the card before typing: a card that opened as they typed leaves the line to the usual send.+ await new Promise((resolve) => setTimeout(resolve, CARD_SETTLE_MS + 100));const send = { text: "what time is it?", threadId, sendId: randomUUID() };const typed = await api("POST", `/api/bots/${bot.id}/messages`, send);@@ -70,67 +65,7 @@ it("in the bot's own chat, a line typed while its ask_user card waits answers th}}, 120_000);-it.each([- ["asks again", {}],- ["answers without asking", { FAKE_ACP_QUESTION_ONCE: "1" }],-])("in the bot's own chat, a line typed while an ACP card of set options waits closes it without an error, and runs as the next turn, which %s", async (_next, nextTurn) => {- const fixture = await launchVerificationServer();- const { dataDir, url, logPath } = fixture.info;- const { api, messages, openCard, control } = client(url);- const dump = join(dataDir, "acp-dump");- const rpcFile = join(dataDir, "rpc.jsonl");- let server: ChildProcess | undefined;- try {- // Only the repository's fake ACP CLI, added while the fixture is stopped; never the person's CLI or home.- await waitForExit(fixture.child, { signal: "SIGTERM" });- const configPath = join(dataDir, "config.json");- const config = JSON.parse(readFileSync(configPath, "utf8"));- config.instances.opencodeGo = {- driver: "opencodeGo", displayName: "Set options fixture",- config: { cli: fileURLToPath(new URL("./testing/fake-acp-cli.ts", import.meta.url)) },- environment: { FAKE_ACP_MODE: "question", FAKE_ACP_HOLD_ON_CANCELLED: "1", FAKE_ACP_MODELS: "fixture/question",- FAKE_ACP_DUMP: dump, FAKE_ACP_DUMP_PROMPT: "1", FAKE_ACP_RPC_APPEND_FILE: rpcFile, ...nextTurn },- };- writeFileSync(configPath, JSON.stringify(config));- const log = openSync(logPath, "a", 0o600);- server = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {- cwd: fileURLToPath(new URL("..", import.meta.url)),- env: verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), stdio: ["ignore", log, log],- });- closeSync(log);- await expect.poll(async () => {- try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }- }, { timeout: 20_000 }).toBe(true);-- const { bot } = await control("new-bot", "--name", "Picker");- const threadId = bot.activeTaskId as string;- await api("PATCH", `/api/bots/${bot.id}/tasks/${threadId}`, { modelSelection: { instanceId: "opencodeGo", model: "fixture/question" } });- const prompted = () => existsSync(`${dump}.prompt.json`) ? readFileSync(`${dump}.prompt.json`, "utf8") : "";- const calls = () => existsSync(rpcFile) ? readFileSync(rpcFile, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line).method as string) : [];-- await control("send", "--bot", bot.id, "--task", threadId, "--text", "pick a color");- await expect.poll(async () => Boolean(await openCard(threadId)), POLL).toBe(true);- const card = (await openCard(threadId))!;-- const send = { text: "what time is it?", threadId, sendId: randomUUID() };- const typed = await api("POST", `/api/bots/${bot.id}/messages`, send);- expect(typed.status).toBe(202);- await expect.poll(() => prompted().includes("what time is it?"), POLL).toBe(true);- expect(calls()).toContain("session/cancel");- await expect.poll(async () => (await messages(threadId)).find((row) => row.id === card.id)?.card, POLL)- .toMatchObject({ answered: "unavailable", dismissed: true });- const rows = await messages(threadId);- expect(JSON.stringify(rows)).not.toContain("isn't one of the choices");- expect(verdicts(dataDir, card.card!.requestId!)).toEqual([]);- expect((await api("POST", `/api/bots/${bot.id}/messages`, send)).status).toBe(202);- expect((await messages(threadId)).filter((row) => row.role === "user" && row.text === "what time is it?")).toHaveLength(1);- } finally {- if (server) await waitForExit(server, { signal: "SIGTERM" });- await fixture.close();- }-}, 120_000);--it("in the bot's own chat, a line typed while Claude's own question of several parts waits closes it, and is steered into the turn", async () => {+it("in the bot's own chat, a line typed while Claude's own question of several parts waits leaves the card open, and is steered into the turn", async () => {const logs = mkdtempSync(join(tmpdir(), "typed-line-"));const steerLog = join(logs, "steered.jsonl");const fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_MODE: "hang", FAKE_CLAUDE_STEER_LOG: steerLog });@@ -156,14 +91,16 @@ it("in the bot's own chat, a line typed while Claude's own question of several p] } }) + "\n");await expect.poll(async () => (await openCard(threadId))?.card?.requestId, POLL).toBe(requestId);const card = (await openCard(threadId))!;+ await new Promise((resolve) => setTimeout(resolve, CARD_SETTLE_MS + 100));+ // A card of several parts takes taps, not one line: the line is a message, and the card waits for its taps.const typed = await api("POST", `/api/bots/${bot.id}/messages`, { text: "what time is it?", threadId, sendId: randomUUID() });expect(typed).toMatchObject({ status: 202, body: { steered: true } });- await expect.poll(() => replies.split("\n").filter(Boolean).map((line) => JSON.parse(line)).find((reply) => reply.id === requestId), POLL)- .toMatchObject({ behavior: "deny" });await expect.poll(() => existsSync(steerLog) ? readFileSync(steerLog, "utf8") : "", POLL).toContain("what time is it?");- expect((await messages(threadId)).find((row) => row.id === card.id)?.card, "closed without an answer, not denied").toMatchObject({ answered: "unavailable", dismissed: true });- expect(verdicts(fixture.info.dataDir, requestId)).toEqual([]);+ expect(replies.split("\n").filter(Boolean).map((line) => JSON.parse(line)).find((reply) => reply.id === requestId)).toBeUndefined();+ const rows = await messages(threadId);+ expect(rows.find((row) => row.id === card.id)?.card).not.toHaveProperty("answered");+ expect(rows.find((row) => row.role === "user" && row.text === "what time is it?")?.replyToId).toBeUndefined();} finally {socket?.destroy();await fixture.close();diff --git a/server/steer-e2e.test.ts b/server/steer-e2e.test.tsindex 6ab5a21e2d..b8346bbf2d 100644--- a/server/steer-e2e.test.ts+++ b/server/steer-e2e.test.ts@@ -42,6 +42,15 @@ posixOnly("mid-turn steering e2e", () => {const askedAt = (botId: string, threadId: string) => (readRegistry(join(home, ".openmausbot")).bots as any[]).find((bot) => bot.id === botId).tasks.find((task: any) => task.threadId === threadId).askedAt;const PAIRED = { name: "Safari on Mac", id: expect.stringMatching(/^p_[\w-]{22}$/) };+ /** A codex turn's command started, so the turn is live with no card waiting. */+ const codexCommandRunning = (threadId: string) => {+ try {+ return readFileSync(join(home, ".openmausbot", "native", `${threadId}.ndjson`), "utf8").trim().split("\n")+ .some((line) => { const row = JSON.parse(line); return row.dir === "in" && row.msg?.method === "item/started"; });+ } catch {+ return false;+ }+ };const asPairedPerson = async () => {const opened = await api("POST", "/api/auth/pairing", {});expect(opened.status).toBe(200);@@ -119,13 +128,11 @@ posixOnly("mid-turn steering e2e", () => {},// codex parks its turn on an unanswered question; turn/steer folds new input into that live turn without ending it.codex: { driver: "codex", environment: { FAKE_CODEX_MODE: "question", FAKE_CODEX_ASK_HOLD: "1" }, config: { cli: FAKE_CODEX } },+ // A codex turn held mid-command, with no card: a question card waiting would take a typed line as its answer.+ codexHold: { driver: "codex", environment: { FAKE_CODEX_COMMAND_GATE: join(home, "codex-hold.never") }, config: { cli: FAKE_CODEX } },codexRace: {driver: "codex",- environment: {- FAKE_CODEX_MODE: "question",- FAKE_CODEX_ASK_HOLD: "1",- FAKE_CODEX_STEER_ERROR_FILE: codexSteerGate,- },+ environment: { FAKE_CODEX_COMMAND_GATE: join(home, "codex-hold.never"), FAKE_CODEX_STEER_ERROR_FILE: codexSteerGate },config: { cli: FAKE_CODEX },},},@@ -702,18 +709,15 @@ posixOnly("mid-turn steering e2e", () => {it("a codex message during a live turn is steered into it via turn/steer, and Stop never reports SIGTERM", async () => {const created = (await api("POST", "/api/bots")).body.bot;const instances = (await api("GET", "/api/instances")).body.instances;- const codexInstance = instances.find((i: any) => i.instanceId === "codex");+ const codexInstance = instances.find((i: any) => i.instanceId === "codexHold");expect(codexInstance.capabilities.queueing).toBe(true);await api("PATCH", `/api/bots/${created.id}`, {- modelSelection: { instanceId: "codex", model: codexInstance.models.default },+ modelSelection: { instanceId: "codexHold", model: codexInstance.models.default },});expect((await api("POST", `/api/bots/${created.id}/messages`, { text: "first codex turn" })).status).toBe(202);await waitFor(async () => (await getBot(created.id)).busy === true, "the codex turn to start");- await waitFor(- async () => (await getBot(created.id)).messages.some((m: any) => m.card),- "the codex question card",- );+ await waitFor(async () => codexCommandRunning(created.threadId), "the codex turn's held command");const second = await api("POST", `/api/bots/${created.id}/messages`, { text: "and also this" });expect(second.status).toBe(202);@@ -745,10 +749,7 @@ posixOnly("mid-turn steering e2e", () => {expect((await api("POST", `/api/bots/${created.id}/messages`, { text: "first gated turn" })).status).toBe(202);await waitFor(async () => (await getBot(created.id)).busy === true, "the gated turn to start");- await waitFor(- async () => (await getBot(created.id)).messages.some((m: any) => m.card),- "the gated question card",- );+ await waitFor(async () => codexCommandRunning(created.threadId), "the gated turn's held command");// the gate file makes the live steer lose: the words queue insteadconst person = await asPairedPerson();diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex 07b924aecd..7a68b62f5c 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -12,7 +12,7 @@// FAKE_ACP_MODE happy (default) | image | empty-reply | reasoning-only | exit-early | fail-after-text | crash-in-prompt// | abort-in-prompt (a sign-in link, then a TCMalloc CHECK line on stderr, then exit 134 as bubblewrap reports SIGABRT) | hang// | hang-initialize | unkeyed-tool | finished-tools (tool_call frames that arrive already completed or failed, one updated again)-// | no-auth | auth-required | permission | question (FAKE_ACP_QUESTION_ONCE: only the first prompt asks; later ones answer)+// | no-auth | auth-required | permission | question// | ask-question (a mid-prompt vendor question: FAKE_ACP_ASK_METHOD, default cursor/ask_question, params// FAKE_ACP_ASK_PARAMS; the client's reply is written to FAKE_ACP_ASK_ANSWER. FAKE_ACP_ASK_TIMING=with-result// settles the turn with the card open; after-result asks between turns)@@ -130,7 +130,6 @@ import { spawn } from "node:child_process";import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, writeSync } from "node:fs";const mode = process.env.FAKE_ACP_MODE ?? "happy";-let askedQuestion = false;if (process.env.FAKE_ACP_START_FAILURE) {writeSync(2, `${process.env.FAKE_ACP_START_FAILURE}\n`);@@ -1871,8 +1870,7 @@ function handle(msg: any) {})();return;}- if (mode === "question" && !(process.env.FAKE_ACP_QUESTION_ONCE && askedQuestion)) {- askedQuestion = true;+ if (mode === "question") {pendingPermissionId = 9002;onPermissionAnswered = () => {// FAKE_ACP_HOLD_ON_CANCELLED: a cancelled question holds the prompt until session/cancel, as Antigravity does.diff --git a/server/usage-attribution.e2e.test.ts b/server/usage-attribution.e2e.test.tsindex a9e7377fae..f331a56842 100644--- a/server/usage-attribution.e2e.test.ts+++ b/server/usage-attribution.e2e.test.ts@@ -98,7 +98,8 @@ posixOnly("usage attribution e2e", () => {acpHappy: { driver: "grokAgent", config: { cli: FAKE_ACP, fullAuto: true } },codexRace: {driver: "codex",- environment: { FAKE_CODEX_MODE: "question", FAKE_CODEX_ASK_HOLD: "1", FAKE_CODEX_STEER_ERROR_FILE: codexSteerGate },+ // held mid-command, with no card: a question card waiting would take a typed line as its answer+ environment: { FAKE_CODEX_COMMAND_GATE: join(home, "codex-hold.never"), FAKE_CODEX_STEER_ERROR_FILE: codexSteerGate },config: { cli: FAKE_CODEX },},},@@ -229,7 +230,13 @@ posixOnly("usage attribution e2e", () => {const model = (await api("GET", "/api/instances")).body.instances.find((i: any) => i.instanceId === "codexRace").models.default;const bot = await newBot("codexRace", model);expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "owner's codex turn" })).status).toBe(202);- await waitFor(async () => (await getBot(bot.id)).messages.some((m: any) => m.card), "the question card");+ await waitFor(() => {+ try {+ return readFileSync(join(home, ".openmausbot", "native", `${bot.threadId}.ndjson`), "utf8").includes('"method":"item/started"');+ } catch {+ return false;+ }+ }, "the held command");const asPaired = await asPerson();const queued = await asPaired("POST", `/api/bots/${bot.id}/messages`, { text: "steer these words" });expect(queued.body.queued).toBe(true);