Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(ask-cards): the close's own outcome says who settled a closed question

luishron12333e41374b6ac
diff --git a/server/host/ask-cards.test.ts b/server/host/ask-cards.test.ts
index b3c698146c..65962ba9a5 100644
--- a/server/host/ask-cards.test.ts
+++ b/server/host/ask-cards.test.ts
@@ -1,13 +1,11 @@
import { describe, expect, it, vi } from "vitest";
-import { shouldSettleRequestCard } from "../../shared/ask-question.ts";
-import type { OptionCardData } from "../../shared/wire.ts";
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, resolvedCard, type AskCardsDeps } from "./ask-cards.ts";
+import { askToolName, closeCard, createAskCards, settleRequestCard, type AskCardsDeps, type Closing } 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?";
@@ -569,90 +567,124 @@ 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" }>;
- /** The server's side: question cards by request, the live link of each, and what the engine settling one writes. */
+ /** Question cards in one chat, the live link of each, and an engine that takes a decline only once released. The
+ * request.resolved handler's own lookup of the link stays here: it finds the card and drops the link, then hands over. */
const server = () => {
- const cards = new Map<string, OptionCardData>(), live = new Map<string, string>(), closing = new Set<string>();
- const ask = (requestId: string) => { cards.set(requestId, { title: "Which?", subtitle: "Which?", requestId, requestType: "question", options: [], fixedOptions: true }); live.set(`chat:${requestId}`, requestId); };
- // As the request.resolved handler: a live request's card settles, and the request is no longer live.
- const settle = (requestId: string, behavior: Resolved["behavior"], source: Resolved["source"] = "user") => {
- if (!live.has(`chat:${requestId}`)) return;
- const card = cards.get(requestId)!;
- if (shouldSettleRequestCard(card, source)) cards.set(requestId, resolvedCard(card, { type: "request.resolved", threadId: "chat", requestId, behavior, source } as Resolved, closing));
+ const rows: Message[] = [], live = new Map<string, string>(), closing = new Map<string, Closing>(), 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, closing, { type: "request.resolved", eventId: `e-${requestId}`, provider: "claude", createdAt: "0", threadId: "chat", requestId, behavior, source }, messageId);
live.delete(`chat:${requestId}`);
};
- // As Stop or the turn ending: a question card stays for a late answer, and its request is no longer live.
- const turnEnds = () => live.clear();
let release!: () => void;
- const held = new Promise<void>((resolve) => { release = resolve; });
- const close = (requestId: string, decline: () => Promise<RequestOutcome>) => closeCard({ key: `chat:${requestId}`, live, closing, decline });
- // An engine that takes a decline only once released, and settles the request then unless something already did.
- const slowDecline = (requestId: string) => async (): Promise<RequestOutcome> => {
- await held;
- if (!live.has(`chat:${requestId}`)) return "unavailable";
- settle(requestId, "deny");
+ 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";
};
- return { cards, live, closing, ask, settle, turnEnds, release, close, slowDecline };
+ const close = (requestId: string, take: () => Promise<RequestOutcome>) =>
+ closeCard({ store, threadId: "chat", requestId, live, closing, decline: take });
+ return { live, closing, declines, ask, card, resolve, release, decline, close };
};
- it("reads closed without an answer once the engine took the decline, and records it as no answer", async () => {
- const s = server();
- s.ask("req-1");
- expect(await s.close("req-1", async () => { s.settle("req-1", "deny"); return "rejected"; })).toBe("rejected");
- expect(s.cards.get("req-1")).toMatchObject({ answered: "unavailable", dismissed: true });
- expect([...s.live.keys()]).toEqual([]);
- expect(s.closing.size).toBe(0);
+ 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("keeps a tap that wins while the decline is on its way, and leaves no dead request live for the next card", async () => {
+ 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 closing = s.close("req-1", s.slowDecline("req-1"));
- expect(s.live.has("chat:req-1"), "a tap still finds the card's request").toBe(true);
- s.settle("req-1", "answer");
+ const first = s.close("req-1", s.decline("req-1", { hold: true }));
+ const second = s.close("req-1", async () => "unavailable");
s.release();
- expect(await closing).toBe("unavailable");
- expect(s.cards.get("req-1")).toMatchObject({ answered: "answer", dismissed: false });
- expect([...s.live.keys()]).toEqual([]);
- s.ask("req-2");
- expect([...s.live.keys()], "the next card is the only one waiting").toEqual(["chat:req-2"]);
- expect(await s.close("req-2", async () => { s.settle("req-2", "deny"); return "rejected"; })).toBe("rejected");
- expect(s.cards.get("req-2")).toMatchObject({ answered: "unavailable", dismissed: true });
+ 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("leaves no dead request live when Stop or the turn ending beats the decline", async () => {
+ it("keeps an explicit refusal that wins while the decline is on its way", async () => {
const s = server();
s.ask("req-1");
- const closing = s.close("req-1", s.slowDecline("req-1"));
- s.turnEnds();
+ const closing = s.close("req-1", s.decline("req-1", { hold: true }));
+ await Promise.resolve();
+ s.resolve("req-1", "deny", "user");
s.release();
expect(await closing).toBe("unavailable");
- expect(s.cards.get("req-1")?.answered, "open for a late answer, as after any Stop").toBeUndefined();
- expect([...s.live.keys()]).toEqual([]);
- s.ask("req-2");
- expect([...s.live.keys()]).toEqual(["chat:req-2"]);
- s.settle("req-2", "deny", "system");
- expect(s.cards.get("req-2")?.answered, "a decline that is not a close's own settles as before").toBeUndefined();
+ 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 decline of [async () => "unavailable" as const, async (): Promise<"rejected"> => { throw new Error("broker gone"); }]) {
+ 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", decline)).toBe("unavailable");
- expect(s.cards.get("req-1")?.answered).toBeUndefined();
- expect(s.live.get("chat:req-1")).toBe("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.settle("req-1", "answer");
- expect(s.cards.get("req-1")).toMatchObject({ answered: "answer" });
+ 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 decline = vi.fn(async () => "rejected" as const);
- expect(await s.close("req-1", decline)).toBe("unavailable");
- expect(decline).not.toHaveBeenCalled();
+ const take = vi.fn(async () => "rejected" as const);
+ expect(await s.close("req-1", take)).toBe("unavailable");
+ expect(take).not.toHaveBeenCalled();
});
});
diff --git a/server/host/ask-cards.ts b/server/host/ask-cards.ts
index 025f9785e8..0175ff9f8e 100644
--- a/server/host/ask-cards.ts
+++ b/server/host/ask-cards.ts
@@ -4,7 +4,7 @@
// the person's inbox, which has the card itself. At Full access a teammate's question goes to its requester instead: its
// card says who decides and what was picked, and blocks nothing. A card whose work ended, or that a newer question
// replaced, closes, so nothing stale waits on the person.
-import { formatQuestionAnswers, isPersistentQuestionCard } from "../../shared/ask-question.ts";
+import { formatQuestionAnswers, isPersistentQuestionCard, shouldSettleRequestCard } from "../../shared/ask-question.ts";
import { liveCardKind } from "../../shared/live-approval.ts";
import { allowsTool, type ToolIdentity } from "../../shared/tool-scope.ts";
import type { PersonWait } from "../../shared/person-wait.ts";
@@ -71,27 +71,60 @@ const typedAnswer = (card: OptionCardData, text: string): string => {
return questions ? formatQuestionAnswers(questions, [[text]]) : text;
};
-/** Declines a question the person moved past without an answer. While the decline is on its way the request is marked
- * closing, so the engine settling it with that decline reads closed without an answer; a tap, Stop or the turn ending
- * first settles it as they always do. A decline that did not land leaves the card and the request as they were. */
-export async function closeCard(input: { key: string; live: ReadonlyMap<string, string>; closing: Set<string>;
- decline: () => Promise<RequestOutcome> }): Promise<RequestOutcome> {
- if (!input.live.has(input.key)) return "unavailable";
- input.closing.add(input.key);
- try {
- return await input.decline().catch((): RequestOutcome => "unavailable");
- } finally {
- input.closing.delete(input.key);
- }
-}
+type Resolved = Extract<RuntimeEvent, { type: "request.resolved" }>;
+type CardStore = Pick<Store, "messagesFor" | "patchMessage">;
+/** A close on its way to one request: the outcome every send closing it shares, and a decline the engine settled meanwhile. */
+export interface Closing { outcome: Promise<RequestOutcome>; deferred?: Resolved }
-/** The card a request settled into: closed without an answer when the decline was a close's own. */
-export function resolvedCard(card: OptionCardData, resolved: Extract<RuntimeEvent, { type: "request.resolved" }>, closing: ReadonlySet<string>): OptionCardData {
- if (resolved.behavior === "deny" && closing.has(`${resolved.threadId}:${resolved.requestId}`)) return { ...card, answered: "unavailable", dismissed: true };
+/** The card a request settled into. */
+export function resolvedCard(card: OptionCardData, resolved: Resolved): OptionCardData {
const persistent = isPersistentQuestionCard(card);
return { ...card, answered: resolved.behavior, dismissed: persistent ? false : resolved.source !== "user", ...(resolved.source === "timeout" && !persistent ? { expired: true } : {}) };
}
+function patchOpenCard(store: CardStore, threadId: string, messageId: string, next: (card: OptionCardData) => OptionCardData | null): void {
+ const card = store.messagesFor(threadId).find((message) => message.id === messageId)?.card;
+ const settled = card && !card.answered ? next(card) : null;
+ if (settled) store.patchMessage(threadId, messageId, { card: settled });
+}
+
+/** Settles a card as its request resolved. A decline that lands while a close is on its way waits for the close's own
+ * outcome, which alone tells whether that decline was the close's. */
+export function settleRequestCard(store: CardStore, closing: Map<string, Closing>, resolved: Resolved, messageId: string): void {
+ const inFlight = closing.get(`${resolved.threadId}:${resolved.requestId}`);
+ if (inFlight && resolved.behavior === "deny") inFlight.deferred = resolved;
+ else patchOpenCard(store, resolved.threadId, messageId, (card) => shouldSettleRequestCard(card, resolved.source) ? resolvedCard(card, resolved) : null);
+}
+
+/** 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: the card reads closed without an answer, whatever
+ * source the engine reported. Otherwise a tap, an explicit decline, Stop or the turn ending came first, and the card
+ * settles as that resolution would have settled it; 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, Closing>; decline: () => Promise<RequestOutcome> }): Promise<RequestOutcome> {
+ const key = `${input.threadId}:${input.requestId}`;
+ const running = input.closing.get(key);
+ if (running) return running.outcome;
+ 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);
+ }
+ if (outcome !== "unavailable") patchOpenCard(input.store, input.threadId, messageId, (card) => ({ ...card, answered: "unavailable", dismissed: true }));
+ else if (entry.deferred) settleRequestCard(input.store, input.closing, entry.deferred, messageId);
+ return outcome;
+ };
+ const entry: Closing = { outcome: Promise.resolve().then(close) };
+ input.closing.set(key, entry);
+ return entry.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/);
diff --git a/server/index.ts b/server/index.ts
index ae65989d3b..64fd804199 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, resolvedCard } 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, closeCard, createAskCards, settleRequestCard, type Closing } 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";
@@ -107,7 +107,7 @@ import { DataSheetRegistry } from "./data/sheet.ts";
import { DataFailure } from "./data/types.ts";
import { TeamComputers, teamComputerOwner, type TeamComputerRecord } from "./team-computers.ts";
import { isEffortLevel, type AuthPairResponse, type CardAnswerer, type LoopbackSessionResponse, type SignedInSessionResponse, type PairResponse, type ResolvedSender, type ServerFrame, type SignInRequestCardData, type WireBot, type WireGroup, type WireTask } from "../shared/wire.ts";
-import { isPersistentQuestionCard, shouldSettleRequestCard } from "../shared/ask-question.ts";
+import { isPersistentQuestionCard } from "../shared/ask-question.ts";
import { parseToolScope } from "../shared/tool-scope.ts";
import type { TeamComputersPayload } from "../shared/team-computer.ts";
import { boatCreateRecoverySnapshot } from "./boat-create-idempotency.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 Set<string>();
+const askMessageByRequest = new Map<string, string>(), closingRequests = new Map<string, Closing>();
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 }>();
@@ -4759,7 +4759,7 @@ async function answerRequest(
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.
const instance = runningTurnEngines.get(threadId) ?? registry.get(instanceId);
- if (behavior === "close") return closeCard({ key: `${threadId}:${requestId}`, live: askMessageByRequest, closing: closingRequests,
+ 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) {
@@ -6595,15 +6595,11 @@ bus.subscribe((event: RuntimeEvent) => {
const messageId = event.requestId ? askMessageByRequest.get(`${event.threadId}:${event.requestId}`) : null;
if (messageId) {
const existing = store.messagesFor(event.threadId).find((m) => m.id === messageId);
- if (existing?.card && !existing.card.answered) {
- if (existing.card.requestType === "permission") {
- if (event.source === "timeout") unansweredApprovals.record(event.threadId, event.turnId, existing.card.tool, existing.card.subtitle);
- else if (event.source !== "system" && event.source !== "unavailable") unansweredApprovals.answered(event.threadId, event.turnId, existing.card.tool, existing.card.subtitle);
- }
- if (shouldSettleRequestCard(existing.card, event.source)) {
- store.patchMessage(event.threadId, messageId, { card: resolvedCard(existing.card, event, closingRequests) });
- }
+ if (existing?.card && !existing.card.answered && existing.card.requestType === "permission") {
+ if (event.source === "timeout") unansweredApprovals.record(event.threadId, event.turnId, existing.card.tool, existing.card.subtitle);
+ else if (event.source !== "system" && event.source !== "unavailable") unansweredApprovals.answered(event.threadId, event.turnId, existing.card.tool, existing.card.subtitle);
}
+ settleRequestCard(store, closingRequests, event, messageId);
if (event.requestId) askMessageByRequest.delete(`${event.threadId}:${event.requestId}`);
}
break;
diff --git a/server/question-card-typed-line.e2e.test.ts b/server/question-card-typed-line.e2e.test.ts
index ec83648d54..ab4806afa2 100644
--- a/server/question-card-typed-line.e2e.test.ts
+++ b/server/question-card-typed-line.e2e.test.ts
@@ -70,7 +70,10 @@ it("in the bot's own chat, a line typed while its ask_user card waits answers th
}
}, 120_000);
-it("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", async () => {
+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);
@@ -86,7 +89,7 @@ it("in the bot's own chat, a line typed while an ACP card of set options waits c
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 },
+ 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);
@@ -114,8 +117,9 @@ it("in the bot's own chat, a line typed while an ACP card of set options waits c
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(rows.find((row) => row.id === card.id)?.card, "closed without an answer, not denied").toMatchObject({ answered: "unavailable", dismissed: true });
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);
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index 04da6d1394..feda913d44 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
+// | no-auth | auth-required | permission | question (FAKE_ACP_QUESTION_ONCE: only the first prompt asks; later ones answer)
// | 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)
@@ -128,6 +128,7 @@ 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`);
@@ -1861,7 +1862,8 @@ function handle(msg: any) {
})();
return;
}
- if (mode === "question") {
+ if (mode === "question" && !(process.env.FAKE_ACP_QUESTION_ONCE && askedQuestion)) {
+ askedQuestion = true;
pendingPermissionId = 9002;
onPermissionAnswered = () => {
// FAKE_ACP_HOLD_ON_CANCELLED: a cancelled question holds the prompt until session/cancel, as Antigravity does.