From 35aaeb7747e7c187546e11d8b7ddc2ef07109395 Mon Sep 17 00:00:00 2001 From: milind-soni Date: Mon, 31 Aug 2026 03:07:16 +0530 Subject: [PATCH] fix(comms): failure chips carry the provider's reason; timed-out asks convert to delegations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bare 'Delegated turn did not finish' chip threw away the turn.completed stopReason that would have explained every failure in the #583 user report — it now reads '… — auth_required' (etc.), on the channel chip, the delegation receipt, and ask_bot's reply when a failed turn produced no text. ask_bot's fixed 4-minute ceiling silently lost the reply of any peer doing legitimately slow work. A timed-out ask now converts into a delegation claim ticket: the existing watch mirrors the terminal state into the channel and the asker's thread when the turn settles, and check/wait_delegation read the receipt (status 'running' meanwhile). The asker's tool reply says what happened and what to do next turn; a 'still working — ask converted to a delegation' chip lands for the human. Ceiling configurable via OMB_ASK_BOT_TIMEOUT_MS (min 5s, default 4 minutes unchanged). Closes the visibility gap behind #583's user report (parts 1-2: #584, #585). Co-Authored-By: Claude Fable 5 --- server/comms.test.ts | 62 +++++++++++++++++++++++++- server/drivers/agents-proxy.test.ts | 14 +++++- server/drivers/agents-proxy.ts | 9 ++++ server/index.ts | 67 +++++++++++++++++++++++++---- 4 files changed, 141 insertions(+), 11 deletions(-) diff --git a/server/comms.test.ts b/server/comms.test.ts index 7cfb09362c6..137ced373e7 100644 --- a/server/comms.test.ts +++ b/server/comms.test.ts @@ -180,6 +180,9 @@ describe("comms e2e (fake ACP fleet)", () => { HOME: home, USERPROFILE: home, OMB_PORT: String(PORT), + // e2e-friendly ask ceiling: the timeout-conversion test needs the + // synchronous wait to end while the gated peer turn is still open + OMB_ASK_BOT_TIMEOUT_MS: "8000", }; if (process.env.PATH) env.PATH = process.env.PATH; // Without SystemRoot, winsock fails to initialize in the child. @@ -695,6 +698,63 @@ describe("comms e2e (fake ACP fleet)", () => { 90_000, ); + // ── ask_bot timeout conversion ────────────────────────────────────── + // A peer that is legitimately slow (rendering, long tool runs) used to + // hit ask_bot's fixed ceiling and the reply was simply lost — the other + // half of "the bots don't respond to each other" (#583's user report). + // Now the timed-out ask becomes a delegation claim ticket and the reply + // lands on the asker's thread when the peer's turn finally settles. + it( + "converts a timed-out ask into a delegation and delivers the late reply", + async () => { + rmSync(gateFile, { force: true }); + for (const existing of (await api("GET", "/api/bots")).body.bots) { + await api("PATCH", `/api/bots/${existing.id}`, { hidden: true }); + } + const helper = (await api("POST", "/api/bots")).body.bot; + await api("PATCH", `/api/bots/${helper.id}`, { + name: "SlowHelper", + modelSelection: { instanceId: "helperGate", model: "fake-model" }, + }); + const asker = (await api("POST", "/api/bots")).body.bot; + await api("PATCH", `/api/bots/${asker.id}`, { + name: "SlowAsker", + modelSelection: { instanceId: "grok", model: "fake-model" }, + }); + + // the ask starts the peer's gated turn, which stays open well past + // the 8s ceiling — the asker must get a claim ticket, not a drop + expect((await api("POST", `/api/bots/${asker.id}/messages`, { text: "ask @SlowHelper for the numbers" })).status).toBe(202); + let askerBot: any; + await waitUntil(async () => { + askerBot = (await api("GET", "/api/bots")).body.bots.find((b: any) => b.id === asker.id); + const reply = askerBot.messages.findLast((m: any) => m.kind === "text" && m.role === "bot"); + return Boolean(reply?.text?.includes("converted to a delegation") && !askerBot.busy); + }, 30_000, "asker never got the timeout-conversion reply"); + const conversionReply = askerBot.messages.findLast((m: any) => m.kind === "text" && m.role === "bot"); + expect(conversionReply.text).toContain("Task id:"); + expect(conversionReply.text).toContain("wait_delegation"); + expect(askerBot.messages.some( + (m: any) => m.kind === "activity" && m.tool?.name === "@SlowHelper is still working — ask converted to a delegation", + )).toBe(true); + + // free the peer: its held turn completes and the late reply lands on + // the asker's thread through the delegation watch — nothing is lost + writeFileSync(gateFile, "go"); + await waitUntil(async () => { + askerBot = (await api("GET", "/api/bots")).body.bots.find((b: any) => b.id === asker.id); + return askerBot.messages.some( + (m: any) => m.kind === "text" && m.role === "bot" + && m.text?.includes("replied to the delegated task") + && m.text?.includes("ping from fake"), + ); + }, 30_000, "late reply never landed on the asker's thread"); + const helperBot = (await api("GET", "/api/bots?messages=0")).body.bots.find((b: any) => b.id === helper.id); + expect(helperBot.busy).toBeFalsy(); + }, + 75_000, + ); + // ── delegation terminal-state mirroring ───────────────────────────── // A delegated turn is fire-and-forget. Its result is returned to the // initiating chat and mirrored into the A⇄B channel. These tests pin a @@ -847,7 +907,7 @@ describe("comms e2e (fake ACP fleet)", () => { ? state.groups.find((g: any) => g.id === note.comm.groupId) : undefined; const terminal = channel?.messages.some( - (m: any) => m.kind === "activity" && m.tool?.ok === false && m.tool?.name?.includes("did not finish"), + (m: any) => m.kind === "activity" && m.tool?.ok === false && /did not finish — .+/.test(m.tool?.name ?? ""), ); if (terminal) break; if (Date.now() > deadline) { diff --git a/server/drivers/agents-proxy.test.ts b/server/drivers/agents-proxy.test.ts index 986320e9db2..7ffa722cb23 100644 --- a/server/drivers/agents-proxy.test.ts +++ b/server/drivers/agents-proxy.test.ts @@ -18,7 +18,7 @@ let stubPort = 0; let lastAuth: string | undefined; let lastAskBody: any = null; /** What the stub harness returns from /api/internal/ask-bot. */ -type StubAskResponse = { botName?: string; text?: string; busy?: boolean; taskId?: string; toBotName?: string; error?: string }; +type StubAskResponse = { botName?: string; text?: string; busy?: boolean; timeout?: boolean; waitedMs?: number; taskId?: string; toBotName?: string; error?: string }; let askResponse: StubAskResponse = { botName: "Helper", text: "hi from helper" }; let lastDelegateBody: any = null; let lastDelegationUrl: string | null = null; @@ -256,6 +256,18 @@ describe("agents-proxy MCP surface", () => { expect(res.result.isError).toBeFalsy(); }); + it("renders a timeout conversion with the task id and guidance", async () => { + askResponse = { timeout: true, taskId: "task-42", toBotName: "Helper", waitedMs: 240_000 }; + const res = await callTool("ask_bot", { bot_id: "bot-helper", message: "ping" }); + const text = res.result.content[0].text; + expect(text).toContain("Helper is still working after 4 minutes"); + expect(text).toContain("converted to a delegation"); + expect(text).toContain("task-42"); + expect(text).toContain("check_delegation"); + expect(text).toContain("wait_delegation"); + expect(res.result.isError).toBeFalsy(); + }); + it("surfaces the harness's depth refusal as a tool error", async () => { askResponse = { error: "message chains are limited to one hop" }; const res = await callTool("ask_bot", { bot_id: "bot-helper", message: "ping" }); diff --git a/server/drivers/agents-proxy.ts b/server/drivers/agents-proxy.ts index 865e7a8a692..54730e6e22f 100644 --- a/server/drivers/agents-proxy.ts +++ b/server/drivers/agents-proxy.ts @@ -394,6 +394,15 @@ async function callTool(name: string, args: Json): Promise<{ text: string; isErr method: "POST", body: JSON.stringify({ fromBotId: BOT_ID, fromThreadId: THREAD_ID, toBotId, message, depth: DEPTH }), }); + if (r.timeout) { + // The peer's turn outlived the synchronous wait, so the harness + // converted the ask into a delegation — the reply is not lost. + const taskId = String(r.taskId ?? "").trim(); + const waitedMinutes = Math.max(1, Math.round((Number(r.waitedMs) || 0) / 60_000)); + return { + text: `${r.toBotName ?? "That bot"} is still working after ${waitedMinutes} minute${waitedMinutes === 1 ? "" : "s"} — the ask was converted to a delegation so the reply is not lost. Task id: ${taskId}. Finish your own turn; next turn read the outcome with check_delegation or block on it with wait_delegation.`, + }; + } if (r.busy) { // The harness queues the message as a delegation when it can; the // task id is the asker's claim ticket for the eventual reply. diff --git a/server/index.ts b/server/index.ts index df9c83edf85..a03ba7c8667 100644 --- a/server/index.ts +++ b/server/index.ts @@ -89,6 +89,7 @@ import { type ProviderInstance, type RequestOutcome, type RuntimeEvent, + newId, } from "./contracts.ts"; import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts"; @@ -587,14 +588,21 @@ function controlIntegration(botId: string) { /** Run a turn on `targetBotId` and resolve with its assistant text — the * synchronous half of ask_bot. Subscribes to the bus, folds assistant_text * for that thread, resolves on turn.completed (or a 4-min ceiling). */ -function askBotAndWait(targetBotId: string, message: string, depth: number, fromBotId?: string): Promise { +type AskBotOutcome = { + status: "reply" | "failed" | "timeout" | "error"; + text: string; + /** Provider's stop reason when the turn completed not-ok. */ + stopReason?: string | null; +}; + +function askBotAndWait(targetBotId: string, message: string, depth: number, fromBotId?: string): Promise { const target = store.bot(targetBotId); - if (!target) return Promise.resolve("(no such bot)"); + if (!target) return Promise.resolve({ status: "error", text: "(no such bot)" }); const threadId = target.threadId; return new Promise((resolve) => { let text = ""; let done = false; - const finish = (out: string) => { + const finish = (out: AskBotOutcome) => { if (done) return; done = true; clearTimeout(timer); @@ -610,16 +618,19 @@ function askBotAndWait(targetBotId: string, message: string, depth: number, from if (e.type === "item.completed" && e.itemType === "assistant_text") { text += (text ? "\n" : "") + e.text; } else if (e.type === "turn.completed") { - finish(text || "(the bot finished without a text reply)"); + if (e.ok) finish({ status: "reply", text: text || "(the bot finished without a text reply)" }); + else finish({ status: "failed", text, stopReason: e.stopReason ?? null }); } }); - const timer = setTimeout(() => finish(text || "(timed out waiting for the bot to reply)"), 4 * 60_000); + // Timing out does NOT stop the peer's turn — the caller decides whether + // the still-running work becomes a delegation claim ticket instead. + const timer = setTimeout(() => finish({ status: "timeout", text }), ASK_BOT_TIMEOUT_MS); startTurn(targetBotId, message, { commsDepth: depth + 1, unattended: isUnattended(fromBotId), - onDispatchError: (reason) => finish(`(couldn't start that bot: ${reason})`), + onDispatchError: (reason) => finish({ status: "error", text: `(couldn't start that bot: ${reason})` }), }).catch((err) => - finish(`(couldn't start that bot: ${err instanceof Error ? err.message : String(err)})`), + finish({ status: "error", text: `(couldn't start that bot: ${err instanceof Error ? err.message : String(err)})` }), ); }); } @@ -1167,6 +1178,9 @@ const repeats = new RepeatDetector({ thresholds: [5, 10, 20], maxKeysPerThread: // activity-based, so an hour-long turn that keeps streaming is never // touched, and turns parked on a human approval are exempt. const TURN_STALL_MS = Math.max(60_000, Number(process.env.OMB_TURN_STALL_MS) || 20 * 60_000); +/** How long ask_bot waits synchronously before the ask is converted into a + * delegation claim ticket (the peer's turn keeps running either way). */ +const ASK_BOT_TIMEOUT_MS = Math.max(5_000, Number(process.env.OMB_ASK_BOT_TIMEOUT_MS) || 4 * 60_000); const roomStallCompletions = new RoomTurnStallRegistry(); const watchdog = new TurnWatchdog({ stallMs: TURN_STALL_MS, @@ -1795,7 +1809,10 @@ bus.subscribe((event: RuntimeEvent) => { // the request was mirrored there when the delegation drained, and a // channel that only ever shows requests is half a record. Mirror the // reply on success; mirror a failed/stopped terminal chip otherwise. - finalizeDelegationWatch(event.threadId, event.ok, reply); + const delegationFailureName = !event.ok && event.stopReason?.trim() + ? `Delegated turn did not finish — ${event.stopReason.trim().slice(0, 120)}` + : undefined; + finalizeDelegationWatch(event.threadId, event.ok, reply, delegationFailureName); // group busy/unread settle in the group turn engine, which knows // whether more member turns are queued behind this one break; @@ -4262,7 +4279,39 @@ const server = createServer(async (req, res) => { const channel = getOrCreateChannel(store, currentFrom, currentTarget); mirrorExchange(commsBus, currentFrom, currentTarget, message, channel, fromThreadId); const prefixed = `[Message from @${currentFrom.name}, another bot in this OpenMausBot workspace. Reply to them.]\n\n${message}`; - const reply = await askBotAndWait(toBotId, prefixed, depth, fromBotId); + const outcome = await askBotAndWait(toBotId, prefixed, depth, fromBotId); + if (outcome.status === "timeout" && !delegationWatch.has(currentTarget.threadId)) { + // The peer's turn is still running — only the wait ended. Convert + // the ask into a delegation claim ticket: the watch mirrors the + // terminal state into the channel AND the asker's thread when the + // turn settles, and check/wait_delegation read the same receipt. + // Losing the reply was the old behavior, and it read as "the bots + // don't respond to each other". + const taskId = newId(); + delegationWatch.set(currentTarget.threadId, { + channelId: channel.id, + toBotId, + toBotName: currentTarget.name, + taskId, + sourceThreadId: fromThreadId, + }); + store.appendMessage(fromThreadId, { + role: "bot", + kind: "activity", + tool: { name: `@${currentTarget.name} is still working — ask converted to a delegation` }, + }); + return json(res, 200, { timeout: true, taskId, toBotName: currentTarget.name, waitedMs: ASK_BOT_TIMEOUT_MS }); + } + if (outcome.status === "failed" && !outcome.text.trim()) { + // No partial answer to hand back — mirror the failure where the + // exchange lives, with the provider's reason instead of silence. + const why = outcome.stopReason?.trim() ? ` — ${outcome.stopReason.trim().slice(0, 120)}` : ""; + mirrorActivity(commsBus, currentTarget, channel, `Turn failed${why}`, false); + return json(res, 200, { botName: currentTarget.name, text: `(the bot's turn failed${why})` }); + } + const reply = outcome.status === "timeout" + ? outcome.text || "(timed out waiting for the bot to reply)" + : outcome.text; mirrorReply(commsBus, currentTarget, reply, channel); return json(res, 200, { botName: currentTarget.name, text: reply }); }