Skip to content

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

fix(cards): keep the typed-line note engine-only and close cards without a denial

luishron1239bae705c2677
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index ef305c1e43..9a70e58ce5 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -4544,6 +4544,22 @@ 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.ts
index 975c4e37ae..dc16ca48e8 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 !== "answer" : behavior === "answer") return false;
+ if (p.ask.kind === "question" ? behavior === "allow" : 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.ts
index 2c3e67f367..6abf5f4645 100644
--- a/server/host/ask-cards.test.ts
+++ b/server/host/ask-cards.test.ts
@@ -4,7 +4,7 @@ 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, createAskCards, type AskCardsDeps } from "./ask-cards.ts";
+import { askToolName, createAskCards, withoutTypedNote, 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?";
@@ -22,11 +22,13 @@ 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 };
@@ -42,7 +44,9 @@ 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?: "deny" }> = [];
+ const answers: Array<{ threadId: string; requestId: string; message?: string; engineMessage?: string; behavior?: "close" }> = [];
+ const live = new Set(options.live ?? []);
+ const written: unknown[] = [];
let refuse: { status: number; error: string } | null = null;
const deps: AskCardsDeps = {
store: store as unknown as AskCardsDeps["store"],
@@ -51,10 +55,12 @@ function world(options: { inboxThread?: string; live?: string[]; privateThreads?
notify: (notification) => { if (notification) notified.push(notification); },
copiedInto: (inboxThreadId) => inboxThreadId === options.inboxThread,
keptPrivate: (threadId) => (options.privateThreads ?? []).includes(threadId),
- live: (_threadId, requestId) => (options.live ?? []).includes(requestId),
+ 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 === "deny" ? { behavior: "deny" as const } : { message: input.message }) });
+ answers.push({ threadId: input.threadId, requestId: input.requestId, ...(input.behavior === "close" ? { behavior: "close" as const }
+ : { message: input.message, ...(input.engineMessage ? { engineMessage: input.engineMessage } : {}) }) });
+ live.delete(input.requestId);
return { ok: true as const };
}),
answeredIn: (threadId, requestId) => (threadId === "inbox" && requestId.startsWith("req") ? "work" : threadId),
@@ -77,7 +83,8 @@ 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, refuse: (value: typeof refuse) => { refuse = value; } };
+ return { cards, store, rows, notified, answers, answered, node, say, deps, written, open: (requestId: string) => live.add(requestId),
+ refuse: (value: typeof refuse) => { refuse = value; } };
}
describe("a teammate's NEEDS INPUT question", () => {
@@ -346,14 +353,29 @@ describe("a typed line answers a question card", () => {
expect(fixed.answers).toEqual([]);
});
- it("answers the card its turn waits on in the bot's own chat, telling the bot the words were typed, not picked", async () => {
+ const NOTE = "[The person typed this in the chat instead of picking an option. Reply to it, and ask again if you still need an answer.]";
+
+ it("answers the card its turn waits on in the bot's own chat, telling only the engine the words were typed, not picked", async () => {
const w = world({ live: ["req-1"] });
const asked = question(w, "chat");
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: "[The person typed this in the chat instead of picking an option. Reply to it, and ask again if you still need an answer.] What time is it?" }]);
- expect(w.rows("chat").find((row) => row.id === asked.id)?.card?.answeredText).toBe("What time is it?");
+ expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", message: "What time is it?", engineMessage: `${NOTE} What time is it?` }]);
expect(result).toMatchObject({ status: 202, message: { role: "user", text: "What time is it?", replyToId: asked.id, sendId: "send-3" } });
+ expect(JSON.stringify(w.written), "nothing the conversation writes carries the note").not.toContain("The person typed this");
+ expect(JSON.stringify(w.rows("chat"))).not.toContain("The person typed this");
+ });
+
+ it("files the note under a structured question's text for the engine, and the plain words for the card", async () => {
+ const w = world({ live: ["req-1"] });
+ question(w, "chat", { questionRequest: { version: 1, questions: [{ question: "Should I?", options: [{ label: "Yes" }, { label: "No" }] }] } });
+ 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",
+ engineMessage: `The user answered your questions.\n\nQ: Should I?\nA: ${NOTE} Not yet` }]);
+ });
+
+ it("keeps the note out of a tool's output that repeats the answer back", () => {
+ expect(withoutTypedNote(`The user answered your questions.\n\nQ: Should I?\nA: ${NOTE} Not yet`)).toBe("The user answered your questions.\n\nQ: Should I?\nA: Not yet");
+ expect(withoutTypedNote("ok")).toBe("ok");
});
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 () => {
@@ -361,11 +383,55 @@ describe("a typed line answers a question card", () => {
const w = world({ live: ["req-1"] });
question(w, "chat", card);
expect(await w.cards.typed(AUTH, "chat", "Something else first", undefined, {})).toBeNull();
- expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", behavior: "deny" }]);
+ expect(w.answers).toEqual([{ threadId: "chat", requestId: "req-1", behavior: "close" }]);
expect(w.rows("chat").filter((row) => row.role === "user")).toEqual([]);
}
});
+ it("leaves a card it could not close as it is, and the line to the usual send", 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]);
+ });
+
+ 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);
+ }
+ });
+
+ it("answers once when the same send arrives twice at the same time", async () => {
+ const w = world({ live: ["req-1"] });
+ question(w, "chat");
+ 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("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 });
+ 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([]);
+ }
+ });
+
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");
diff --git a/server/host/ask-cards.ts b/server/host/ask-cards.ts
index 0831c62be8..c5dc961307 100644
--- a/server/host/ask-cards.ts
+++ b/server/host/ask-cards.ts
@@ -26,6 +26,10 @@ const DAY_MS = 24 * 60 * 60_000;
const NEEDS_INPUT_LINE = /^needs input:/i;
const TYPED_IN_CHAT = "[The person typed this in the chat instead of picking an option. Reply to it, and ask again if you still need an answer.]";
const hasAttachment = (text: string): boolean => text.includes("<attached-image") || text.includes("<attached-file");
+/** Only the engine reads the typed-line note: a tool's output that repeats the answer back shows the person's words alone. */
+const CLOSED_BY_TYPING = "The person typed in the chat instead of picking an option; their line comes next.";
+export const withoutTypedNote = (text: string): string => text.replaceAll(`${TYPED_IN_CHAT} `, "");
+type Typed = { status: number; message?: Message; error?: string } | null;
export interface AskCardsDeps {
store: Pick<Store, "bot" | "messagesFor" | "activePath" | "appendMessage" | "patchMessage" | "taskByThread" | "patchTask" | "group"
@@ -43,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" | "deny"; message?: string }): Promise<{ ok: true } | { ok: false; status: number; error: string }>;
+ answerCard(input: { auth: RequestAuth; threadId: string; requestId: string; behavior: "answer" | "close"; message?: string; engineMessage?: 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;
@@ -302,35 +306,55 @@ 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 a card that takes no words closes instead, and the line goes on as the next message. Null
- * leaves the line to be sent (steered or queued) as usual. */
- async function typed(auth: RequestAuth, threadId: string, text: string, target: Message | undefined,
- line: { sendId?: string; sender?: Message["sender"] }): Promise<{ status: number; message?: Message; error?: string } | null> {
+ * 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. */
+ const typing = new Map<string, Promise<Typed>>();
+ function typed(auth: RequestAuth, threadId: string, text: string, target: Message | undefined,
+ line: { sendId?: string; sender?: Message["sender"] }): Promise<Typed> {
+ if (!line.sendId) return typedOnce(auth, threadId, text, target, line);
+ const key = `${threadId}:${line.sendId}`;
+ const run = (typing.get(key) ?? Promise.resolve(null)).catch(() => null).then(() => typedOnce(auth, threadId, text, target, line));
+ typing.set(key, run);
+ void run.catch(() => null).finally(() => { if (typing.get(key) === run) typing.delete(key); });
+ return run;
+ }
+
+ async function typedOnce(auth: RequestAuth, threadId: string, text: string, target: Message | undefined,
+ line: { sendId?: string; sender?: Message["sender"] }): Promise<Typed> {
if (store.groupByThread(threadId) || isStopCommand(text)) return null;
+ const thread = store.messagesFor(threadId);
+ // A send tried again touches no card: the same line that answered one is its receipt; anything else goes on to the
+ // usual send, which matches the line it wrote or refuses other words under the same id.
+ const again = line.sendId ? thread.find((message) => message.sendId === line.sendId) : undefined;
+ if (again) {
+ const answeredCard = again.text === text && (!target || target.id === again.replyToId)
+ && thread.some((message) => message.id === again.replyToId && message.card?.requestId);
+ return answeredCard ? { status: 202, message: again } : null;
+ }
const delegator = delegatorOf(threadId);
const handedOn = Boolean(delegator && delegator.threadId !== threadId);
- const waiting = store.messagesFor(threadId).findLast((message) => !message.inbox && liveCardKind(message.card) === "question"
- && deps.live(threadId, message.card!.requestId!));
- const ownChat = !handedOn && !hasAttachment(text) && Boolean(waiting) && (!target || target.id === waiting!.id);
- if (ownChat && !answerableInWords(waiting!.card)) {
- await deps.answerCard({ auth, threadId, requestId: waiting!.card!.requestId!, behavior: "deny" });
+ 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)) {
+ const closed = await deps.answerCard({ auth, threadId, requestId: only!.card!.requestId!, behavior: "close", engineMessage: CLOSED_BY_TYPING });
+ // Refused (the session ended, the person may not answer it, it is no longer open): the card stays as it is and the
+ // line is sent as before, steered into the waiting turn or queued behind it.
+ if (!closed.ok) return null;
return null;
}
const asked = target
? answerableInWords(target.card) ? target : undefined
- : ownChat ? waiting
- : handedOn ? store.messagesFor(threadId).findLast((message) => answerableInWords(message.card) && deps.live(threadId, message.card!.requestId!)) : undefined;
+ : ownChat ? only
+ : handedOn ? thread.findLast((message) => answerableInWords(message.card) && deps.live(threadId, message.card!.requestId!)) : undefined;
if (!asked?.card?.requestId) return null;
const requestId = asked.card.requestId;
const origin = deps.answeredIn(threadId, requestId);
if (origin === threadId && !((handedOn || ownChat) && deps.live(threadId, requestId))) return null;
- const again = line.sendId ? store.messagesFor(threadId).find((message) => message.sendId === line.sendId) : undefined;
- if (again) return { status: 202, message: again };
- const inChat = ownChat && origin === threadId;
- const answered = await deps.answerCard({ auth, threadId, requestId, behavior: "answer", message: typedAnswer(asked.card, inChat ? `${TYPED_IN_CHAT} ${text}` : text) });
+ const note = ownChat && origin === threadId ? { engineMessage: typedAnswer(asked.card, `${TYPED_IN_CHAT} ${text}`) } : {};
+ const answered = await deps.answerCard({ auth, threadId, requestId, behavior: "answer", message: typedAnswer(asked.card, text), ...note });
if (!answered.ok) return { status: answered.status, error: answered.error };
- const settled = inChat ? store.messagesFor(threadId).find((message) => message.id === asked.id)?.card : undefined;
- if (settled) store.patchMessage(threadId, asked.id, { card: { ...settled, answeredText: text } });
const posted = store.appendMessage(threadId, { role: "user", kind: "text", text, replyToId: asked.id,
...(line.sendId ? { sendId: line.sendId } : {}), ...(line.sender ? { sender: line.sender } : {}) });
return { status: 202, message: posted };
diff --git a/server/index.ts b/server/index.ts
index 1157980893..1f753eaebb 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, createAskCards } 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, withoutTypedNote } 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";
@@ -4743,11 +4743,11 @@ async function answerRequest(
threadId: string,
instanceId: string,
requestId: string,
- behavior: "allow" | "deny" | "answer",
+ behavior: "allow" | "deny" | "answer" | "close",
message?: string,
decidedFor?: { id: string; name: string },
always?: boolean,
- rememberCommand?: boolean,
+ rememberCommand?: boolean, engineMessage = message,
): Promise<RequestOutcome> {
// Snapshot the card BEFORE delivering: delivery synchronously consumes the askMessageByRequest entry.
const thread = store.messagesFor(threadId);
@@ -4757,13 +4757,14 @@ 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.
+ // The live turn owns this question, as it owns Stop and steer. A card closed without an answer says so before the engine's decline settles it, and records no denial.
const instance = runningTurnEngines.get(threadId) ?? registry.get(instanceId);
+ if (behavior === "close" && card) store.patchMessage(threadId, cardMessage!.id, { card: { ...card, answered: "unavailable", dismissed: true } });
let outcome: RequestOutcome = "unavailable";
if (instance) {
try {
// Only a card that offered "Allow for this session" can keep one: never a guest's turn, a sandbox widening or the person's own computer.
- outcome = await instance.adapter.respondToRequest(threadId, requestId, { behavior, message, always: always && behavior === "allow" && card?.allowSession === true });
+ outcome = await instance.adapter.respondToRequest(threadId, requestId, { behavior: behavior === "close" ? "deny" : behavior, message: engineMessage, always: always && behavior === "allow" && card?.allowSession === true });
} catch {
outcome = "unavailable";
}
@@ -4780,12 +4781,10 @@ async function answerRequest(
}
if (outcome === "answered" && behavior === "answer" && message && cardMessage) {
const settled = store.messagesFor(threadId).find((m) => m.id === cardMessage.id)?.card;
- if (settled) {
- store.patchMessage(threadId, cardMessage.id, { card: { ...settled, answeredText: message } });
- }
+ if (settled) store.patchMessage(threadId, cardMessage.id, { card: { ...settled, answeredText: message } });
}
// Record only verdicts that reached the engine; a question's answer is not a decision.
- if (outcome !== "unavailable" && behavior !== "answer") {
+ if (outcome !== "unavailable" && behavior !== "answer" && behavior !== "close") {
appendDecision(DATA_DIR, {
threadId,
requestId,
@@ -4823,17 +4822,18 @@ async function respondToCard(input: {
auth: RequestAuth;
threadId: string;
requestId: string;
- behavior: "allow" | "deny" | "answer";
+ behavior: "allow" | "deny" | "answer" | "close";
message?: string;
+ /** What the engine reads instead of `message`; the card and every copy of it keep `message`. */ engineMessage?: string;
callId?: string;
via?: DecisionVia;
}): Promise<CardRespondResult> {
- const { auth, requestId, behavior, message, callId, via } = input, threadId = automationReports.answeredIn(teamMessages.inbox.answeredIn(input.threadId, requestId), requestId);
+ const { auth, requestId, behavior, message, engineMessage, callId, via } = input, threadId = automationReports.answeredIn(teamMessages.inbox.answeredIn(input.threadId, requestId), requestId);
// A call outlives the request that started it: the session must still be valid.
if (auth.kind === "session" && !sessions.isLive(auth.session.id)) {
return { ok: false, status: 401, error: "The session that started this call has ended." };
}
- const refusal = cardAnswerRefusal(auth, input.threadId, requestId, behavior) ?? cardAnswerRefusal(auth, threadId, requestId, behavior);
+ const decline = behavior === "close" ? "deny" : behavior, refusal = cardAnswerRefusal(auth, input.threadId, requestId, decline) ?? cardAnswerRefusal(auth, threadId, requestId, decline);
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." };
@@ -4845,7 +4845,7 @@ async function respondToCard(input: {
await answeringCardAs(auth, threadId, requestId, async () => {
const outcome = await answerRequest(
threadId, botForThread(bot.id, threadId)?.modelSelection.instanceId ?? "", requestId, behavior, message,
- { id: bot.id, name: bot.name },
+ { id: bot.id, name: bot.name }, undefined, undefined, engineMessage,
);
if (outcome === "unavailable" && isPersistentQuestionCard(card) && behavior === "answer" && cardMessage) {
const answer = message?.trim() ?? "";
@@ -6409,7 +6409,7 @@ bus.subscribe((event: RuntimeEvent) => {
const existing = store.messagesFor(event.threadId).find((m) => m.id === messageId)?.tool;
toolName = existing?.name ?? "tool";
store.patchMessage(event.threadId, messageId, {
- tool: { ...existing, name: toolName, ok: event.ok, output: event.output === undefined ? undefined : scrubHeldSecrets(event.output), ...mcpToolProblem(toolName, event.ok, event.output, Object.keys(cfg.mcpServers ?? {}), threadLanguage(event.threadId)) },
+ tool: { ...existing, name: toolName, ok: event.ok, output: event.output === undefined ? undefined : scrubHeldSecrets(withoutTypedNote(event.output)), ...mcpToolProblem(toolName, event.ok, event.output, Object.keys(cfg.mcpServers ?? {}), threadLanguage(event.threadId)) },
}); void connectionHealth.toolStep({ threadId: event.threadId, generation: activeInternalGenerationByThread.get(event.threadId), tool: toolName, ok: event.ok, output: event.output }).catch(() => {});
toolMessageByItem.delete(itemKey);
}
diff --git a/server/question-card-typed-line.e2e.test.ts b/server/question-card-typed-line.e2e.test.ts
index fdeba153f2..832ce535ab 100644
--- a/server/question-card-typed-line.e2e.test.ts
+++ b/server/question-card-typed-line.e2e.test.ts
@@ -1,13 +1,23 @@
import { spawn, type ChildProcess } from "node:child_process";
import { randomUUID } from "node:crypto";
-import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from "node:fs";
+import { closeSync, existsSync, mkdtempSync, openSync, readdirSync, 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 { openSse } from "./testing/sse.ts";
const POLL = { timeout: 30_000, interval: 100 };
+const NOTE = "The person typed this in the chat";
+/** Every decision the server recorded: a card closed by a typed line is none. */
+/** 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 } };
@@ -23,30 +33,44 @@ function client(url: string) {
return { api, messages, openCard, control };
}
-it("in the bot's own chat, a line typed while its ask_user card waits answers the card and the turn goes on", async () => {
+it("in the bot's own chat, a line typed while its ask_user card waits answers the card, only the engine reads the note, and a retry changes nothing", async () => {
const fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });
- const { api, messages, openCard, control } = client(fixture.info.url);
+ const { url, dataDir } = fixture.info;
+ const { api, messages, openCard, control } = client(url);
+ const events = await openSse(`${url}/api/events`, { origin: url });
try {
const { bot } = await control("new-bot", "--name", "Asker");
const threadId = bot.activeTaskId as string;
writeFileSync(join(fixture.info.dataDir, "room-plan.json"), JSON.stringify({ [bot.id]: { script: [{
key: "Q", match: ["ASK-ME"], timeoutMs: 120_000,
steps: [{ server: "ogb", tool: "ask_user", arguments: { question: "Which color?", choices: ["Blue", "Green"] }, capture: { answer: "([\\s\\S]+)" } }],
- reply: "Q: got {{answer}}",
+ reply: "Q: answered",
}] } }));
await 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))!;
- const typed = await api("POST", `/api/bots/${bot.id}/messages`, { text: "what time is it?", threadId, sendId: randomUUID() });
+ 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);
expect(typed.body.steered).toBeUndefined();
expect(typed.body.message).toMatchObject({ role: "user", text: "what time is it?", replyToId: card.id });
- await expect.poll(async () => (await messages(threadId)).find((row) => row.role === "bot" && row.text?.startsWith("Q: got"))?.text, POLL)
- .toBe("Q: got [The person typed this in the chat instead of picking an option. Reply to it, and ask again if you still need an answer.] what time is it?");
+ await expect.poll(async () => (await messages(threadId)).some((row) => row.role === "bot" && row.text === "Q: answered"), POLL).toBe(true);
expect((await messages(threadId)).find((row) => row.id === card.id)?.card).toMatchObject({ answered: "answer", answeredText: "what time is it?" });
+ // The engine's side of the call, outside the transcript: the scripted turn's record of its ask_user step.
+ const asked = readFileSync(join(dataDir, "room-plan.json.evidence.jsonl"), "utf8");
+ expect(asked).toContain(`${NOTE} instead of picking an option. Reply to it, and ask again if you still need an answer.] what time is it?`);
+
+ const again = await api("POST", `/api/bots/${bot.id}/messages`, send);
+ expect(again).toMatchObject({ status: 202, body: { message: { id: typed.body.message.id } } });
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { ...send, text: "something else" })).status).toBe(409);
+ const rows = await messages(threadId);
+ expect(rows.filter((row) => row.role === "user" && row.text === "what time is it?")).toHaveLength(1);
+ expect(JSON.stringify(rows)).not.toContain(NOTE);
+ expect(JSON.stringify(events.frames), "no frame any client got carries the note").not.toContain(NOTE);
} finally {
+ events.close();
await fixture.close();
}
}, 120_000);
@@ -90,15 +114,60 @@ it("in the bot's own chat, a line typed while an ACP card of set options waits c
await expect.poll(async () => Boolean(await openCard(threadId)), POLL).toBe(true);
const card = (await openCard(threadId))!;
- const typed = await api("POST", `/api/bots/${bot.id}/messages`, { text: "what time is it?", threadId, sendId: randomUUID() });
+ 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");
const rows = await messages(threadId);
- expect(rows.find((row) => row.id === card.id)?.card?.answered).toBeTruthy();
+ 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);
+ 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 () => {
+ 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 });
+ const { api, messages, openCard, control } = client(fixture.info.url);
+ let socket: Socket | undefined;
+ try {
+ const { bot } = await control("new-bot", "--name", "Several");
+ const threadId = bot.activeTaskId as string;
+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Ask me two things");
+ await expect.poll(() => {
+ try { return JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8")).mcpConfig?.mcpServers?.ogb?.args[1]; } catch { return undefined; }
+ }, POLL).toEqual(expect.any(String));
+ // The turn's question broker, as Claude's own AskUserQuestion reaches it through the permission proxy.
+ socket = connect(JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8")).mcpConfig.mcpServers.ogb.args[1]);
+ socket.on("error", () => {});
+ await new Promise<void>((resolve, reject) => { socket!.once("connect", resolve); socket!.once("error", reject); });
+ let replies = "";
+ socket.on("data", (chunk) => { replies += chunk.toString(); });
+ const requestId = randomUUID();
+ socket.write(JSON.stringify({ t: "ask", kind: "question", id: requestId, tool: "AskUserQuestion", input: { questions: [
+ { question: "Which file?", options: [{ label: "README" }, { label: "Guide" }] },
+ { question: "Which tone?", options: [{ label: "Plain" }, { label: "Warm" }] },
+ ] } }) + "\n");
+ await expect.poll(async () => (await openCard(threadId))?.card?.requestId, POLL).toBe(requestId);
+ const card = (await openCard(threadId))!;
+
+ 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", message: expect.stringContaining("typed in the chat") });
+ 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([]);
+ } finally {
+ socket?.destroy();
+ await fixture.close();
+ rmSync(logs, { recursive: true, force: true });
+ }
+}, 120_000);
diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.ts
index a52db414c4..e7bc1b3025 100644
--- a/server/routes/bot-messages.ts
+++ b/server/routes/bot-messages.ts
@@ -285,7 +285,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
const target = resolveReplyTarget(threadId, press ? press.messageId : appSent ? appSent.messageId : body.replyToId);
if (relayed && target?.role !== "bot") return json(res, 400, { error: "a relayed reaction answers a bot's message" });
const passedBack = !guarded && !press && !appSent && !pointed && target ? deps.inboxReply?.(auth, threadId, target.id, text, { sendId, sender: messageSender(auth) }) : null;
- const typedAnswer = passedBack || guarded || press || appSent || pointed ? null : await deps.typedCardAnswer?.(auth, threadId, text, target, { sendId, sender: messageSender(auth) });
+ const queuedAgain = Boolean(sendId && queuedSteeredMessage(bot.id, threadId, sendId));
+ const typedAnswer = passedBack || guarded || press || appSent || pointed || queuedAgain ? null : await deps.typedCardAnswer?.(auth, threadId, text, target, { sendId, sender: messageSender(auth) });
const answeredBack = passedBack ?? typedAnswer;
if (answeredBack) return json(res, answeredBack.status, answeredBack.message ? { ok: true, threadId, message: answeredBack.message } : refusalText(answeredBack.error ?? ""));
// Only a real press or reaction, or an app's own words, marks the reply; a typed reply to the same row never does, whatever its words.
diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts
index 164ec277f1..412bf70e66 100755
--- a/server/testing/fake-claude-cli.ts
+++ b/server/testing/fake-claude-cli.ts
@@ -77,6 +77,7 @@
// claude.ai link and writes it from the pasted code (`alice-…` signs in [email protected], `bad-…` is refused),
// `auth logout` removes it
// FAKE_CLAUDE_AUTO_UNAVAILABLE_MODELS --model values where `--permission-mode auto` runs "default" (2.1.266)
+// FAKE_CLAUDE_STEER_LOG JSON-lines file every steered line's text is appended to
// FAKE_CLAUDE_LATE_STEER_GATE path: a late steer runs as the next native turn (2.1.282), replying once it exists
// FAKE_CLAUDE_LATE_STEER_INIT_GATE path: that late turn's `init` also waits for it
// FAKE_CLAUDE_LATE_STEER_SILENT 1: the late turn prints `init` and nothing else
@@ -1403,6 +1404,7 @@ process.stdin.on("data", (c) => {
steeredMessages.push(prompt);
}
if (process.env.FAKE_CLAUDE_STEER_RECEIVED) writeFileSync(process.env.FAKE_CLAUDE_STEER_RECEIVED, "received");
+ if (process.env.FAKE_CLAUDE_STEER_LOG) appendFileSync(process.env.FAKE_CLAUDE_STEER_LOG, `${JSON.stringify(steeredText(prompt))}\n`);
} else {
playTurn(prompt);
armSteerGate();