From 8cc9f88e1f0195a24790265419806c6cf594a1fd Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:02:50 -0600 Subject: [PATCH] Fix dropped replies on remote-host iMessage channels When an iMessage channel on a Mac is bound to a primary agent on a remote paired host, any single transient TEAMWORK_OFFLINE error (profile service 429, relay blip, or peer timeout) during hosts(), channel.submit, or channel.status caused remote-bridge.mjs to abandon polling immediately. The remote agent still finished its turn in its local chat, but the reply was never fetched or sent back to iMessage. Changes: - desktop/desktop/channels/remote-bridge.mjs: retry TEAMWORK_OFFLINE errors with bounded exponential backoff across host resolution, idempotent channel.submit (reusing the same turn UUID), and channel.status polling, matching remote-teamwork.mjs. Ease default poll cadence from 350ms..1000ms to 1000ms..2500ms to avoid hammering findHost/relay/profile. - desktop/desktop/channels/index.mjs: pass clientMessageId=payload.id to workspace.submit and correlate finished runs in handleTurnFinished by clientMessageId so joined/steered multi-message turns resolve once without hanging and manual UI messages or cancelled stops cannot steal queued remote turns. - desktop/desktop/channels/adapters/imessage.mjs: add TEAMWORK_OFFLINE retry/backoff to createNodeChannelBridge and ease default imsg_node poll interval (1500ms -> 4000ms) and job poll (150ms -> 500ms) to stay well within profile.botkins.app IP rate limits. - desktop/test/channels-imessage.test.mjs: add regression tests for transient TEAMWORK_OFFLINE recovery, fail-fast on non-offline errors, and clientMessageId correlation with manual turns and joined runs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../desktop/channels/adapters/imessage.mjs | 58 +++- desktop/desktop/channels/index.mjs | 75 +++++- desktop/desktop/channels/remote-bridge.mjs | 97 +++++-- desktop/test/channels-imessage.test.mjs | 248 ++++++++++++++++++ 4 files changed, 437 insertions(+), 41 deletions(-) diff --git a/desktop/desktop/channels/adapters/imessage.mjs b/desktop/desktop/channels/adapters/imessage.mjs index 100df925..80bceec5 100644 --- a/desktop/desktop/channels/adapters/imessage.mjs +++ b/desktop/desktop/channels/adapters/imessage.mjs @@ -314,7 +314,7 @@ export function createIMessageAdapter(deps = {}) { const launch = deps.launch ?? launchProgram; const spawnProcess = deps.spawnProcess ?? spawn; const sendTimeoutMs = deps.sendTimeoutMs ?? 15000; - const pollIntervalMs = deps.pollIntervalMs ?? 1500; + const pollIntervalMs = deps.pollIntervalMs ?? 4000; const reconnectBaseMs = deps.reconnectBaseMs ?? 1000; const reconnectMaxMs = deps.reconnectMaxMs ?? 30000; @@ -618,18 +618,31 @@ export function createIMessageAdapter(deps = {}) { * Builds a node-host bridge over the workspace's encrypted same-owner `teamwork-peers` transport * so iMessage channels can run `channel.imessage.watch` and `channel.imessage.send` on a bound Mac node. */ -export function createNodeChannelBridge(workspace, { pollMs = 150, timeoutMs = 30000 } = {}) { - const resolvePeer = async (nodeHostId) => { +export function createNodeChannelBridge( + workspace, + { pollMs = 500, retryBaseMs = 1000, maxRetryMs = 5000, timeoutMs = 30000 } = {}, +) { + const resolvePeer = async (nodeHostId, deadline) => { const peers = workspace?.teamworkPeers; if (!peers) throw new Error("Teamwork peers transport is unavailable on this host."); - const hosts = await peers.hosts(true); - const host = hosts.find((item) => item.serverId === nodeHostId); - if (!host) throw new Error(`Mac node host "${nodeHostId}" is not linked to this account.`); - return { peers, host }; + let retryDelay = 0; + while (true) { + try { + const hosts = await peers.hosts(true); + const host = hosts.find((item) => item.serverId === nodeHostId); + if (!host) throw new Error(`Mac node host "${nodeHostId}" is not linked to this account.`); + return { peers, host }; + } catch (err) { + if (err?.code !== "TEAMWORK_OFFLINE" || !deadline || Date.now() >= deadline) throw err; + retryDelay = Math.min(maxRetryMs, Math.max(retryBaseMs, retryDelay * 2)); + await new Promise((r) => setTimeout(r, Math.min(retryDelay, Math.max(0, deadline - Date.now())))); + } + } }; const runJob = async (nodeHostId, operation, { botId = "", params = {} } = {}) => { - const { peers, host } = await resolvePeer(nodeHostId); + const deadline = Date.now() + timeoutMs; + const { peers, host } = await resolvePeer(nodeHostId, deadline); const bot = botId ? workspace.bot?.(botId) : null; const jobId = randomUUID(); const submit = { @@ -642,15 +655,34 @@ export function createNodeChannelBridge(workspace, { pollMs = 150, timeoutMs = 3 params, createdAt: Date.now(), }; - const deadline = Date.now() + timeoutMs; - let res = await peers.call(host.serverId, "job.submit", submit, host.pin); - while (res && (res.status === "pending" || res.status === "working")) { + let op = "job.submit"; + let retryDelay = 0; + let res = null; + while (true) { if (Date.now() > deadline) { await peers.call(host.serverId, "job.cancel", { id: jobId }, host.pin).catch(() => {}); throw new Error(`Timed out waiting for ${operation} on node ${host.name || host.serverId}.`); } - await new Promise((r) => setTimeout(r, pollMs)); - res = await peers.call(host.serverId, "job.status", { id: jobId }, host.pin); + try { + res = await peers.call(host.serverId, op, op === "job.submit" ? submit : { id: jobId }, host.pin); + retryDelay = 0; + } catch (err) { + if (err?.code !== "TEAMWORK_OFFLINE") throw err; + retryDelay = Math.min(maxRetryMs, Math.max(retryBaseMs, retryDelay * 2)); + const remaining = deadline - Date.now(); + if (remaining <= 0) { + await peers.call(host.serverId, "job.cancel", { id: jobId }, host.pin).catch(() => {}); + throw new Error(`Timed out waiting for ${operation} on node ${host.name || host.serverId}.`); + } + await new Promise((r) => setTimeout(r, Math.min(retryDelay, remaining))); + continue; + } + if (res && (res.status === "pending" || res.status === "working")) { + op = "job.status"; + await new Promise((r) => setTimeout(r, pollMs)); + continue; + } + break; } if (!res || res.status !== "completed") { throw new Error(res?.error || `Node ${host.name || host.serverId} did not complete ${operation}.`); diff --git a/desktop/desktop/channels/index.mjs b/desktop/desktop/channels/index.mjs index 5a5d9478..6fe0deed 100644 --- a/desktop/desktop/channels/index.mjs +++ b/desktop/desktop/channels/index.mjs @@ -1506,6 +1506,7 @@ export class ChannelManager { id: payload.id, hostHash, fingerprint, + framedText: framed, chatId: chat.id, status: "working", reply: "", @@ -1535,6 +1536,7 @@ export class ChannelManager { try { const submitPromise = this.workspace.submit(chat.id, framed, { title: `${label}: ${senderDisplay}`.slice(0, 100), + clientMessageId: payload.id, }); if (submitPromise && typeof submitPromise.catch === "function") { submitPromise.catch(failRow); @@ -1558,23 +1560,72 @@ export class ChannelManager { if (chat.channel.remoteHostId) { const queue = this.remoteTurnQueue.get(chat.id); if (!queue?.length) return; - const row = queue.shift(); + + const runUserMessages = (chat.messages ?? []).filter( + (m) => m.role === "user" && (m.runId === run.id || m.steeredRunId === run.id), + ); + const taggedIds = new Set( + runUserMessages + .map((m) => (typeof m.clientMessageId === "string" ? m.clientMessageId : "")) + .filter(Boolean), + ); + + let matched = []; + if (taggedIds.size > 0) { + matched = queue.filter((r) => taggedIds.has(r.id)); + } else if (runUserMessages.length > 0) { + const textMatches = queue.filter((r) => + runUserMessages.some((m) => typeof m.text === "string" && m.text === r.framedText), + ); + if (textMatches.length > 0) { + matched = [textMatches[0]]; + } else if (runUserMessages.some((m) => typeof m.text === "string" && m.text.startsWith("[UNTRUSTED_CHANNEL_MESSAGE "))) { + matched = [queue[0]]; + } + } else { + matched = [queue[0]]; + } + + if (!matched.length) return; + for (const item of matched) { + const idx = queue.indexOf(item); + if (idx >= 0) queue.splice(idx, 1); + } if (queue.length === 0) this.remoteTurnQueue.delete(chat.id); - if (!row || (row.status !== "pending" && row.status !== "working")) return; - row.turnId = run.id || ""; - row.updatedAt = this.now(); + + const activeMatched = matched.filter((r) => r && (r.status === "pending" || r.status === "working")); + if (!activeMatched.length) return; + + const now = this.now(); + const primary = activeMatched[activeMatched.length - 1]; + for (const item of activeMatched.slice(0, -1)) { + item.turnId = run.id || ""; + item.updatedAt = now; + if (run.status === "Stopped") { + item.status = "cancelled"; + } else if (run.status === "Error" || run.error) { + item.status = "failed"; + item.error = scrubSecrets(run.error || run.detail || "Remote agent turn failed.", this.allSecretValues()); + } else { + item.status = "done"; + item.silent = true; + } + } + + primary.turnId = run.id || ""; + primary.updatedAt = now; if (run.status === "Stopped") { - row.status = "cancelled"; + primary.status = "cancelled"; return; } if (run.status === "Error" || run.error) { - row.status = "failed"; - row.error = scrubSecrets(run.error || run.detail || "Remote agent turn failed.", this.allSecretValues()); + primary.status = "failed"; + primary.error = scrubSecrets(run.error || run.detail || "Remote agent turn failed.", this.allSecretValues()); return; } if (run.silent || run.noOutput) { - row.status = "done"; - row.silent = true; + primary.status = "done"; + primary.silent = true; return; } const replies = (chat.messages ?? []).filter( @@ -1582,9 +1633,9 @@ export class ChannelManager { ); const rawText = replies.map((m) => m.text.trim()).join("\n\n").trim(); const safeText = scrubSecrets(rawText, this.allSecretValues()); - row.status = "done"; - row.reply = safeText; - row.silent = !safeText; + primary.status = "done"; + primary.reply = safeText; + primary.silent = !safeText; return; } diff --git a/desktop/desktop/channels/remote-bridge.mjs b/desktop/desktop/channels/remote-bridge.mjs index 986df823..48b3c118 100644 --- a/desktop/desktop/channels/remote-bridge.mjs +++ b/desktop/desktop/channels/remote-bridge.mjs @@ -4,8 +4,10 @@ import { randomUUID } from "node:crypto"; -const DEFAULT_POLL_MS = 350; -const MAX_POLL_MS = 1_000; +const DEFAULT_POLL_MS = 1_000; +const MAX_POLL_MS = 2_500; +const DEFAULT_RETRY_BASE_MS = 1_500; +const MAX_RETRY_MS = 15_000; const DEFAULT_TIMEOUT_MS = 10 * 60_000; function sleep(ms, signal) { @@ -75,7 +77,16 @@ async function fetchBotsFromHost(peers, host) { /** * Builds the remote-turn bridge over `workspace.teamworkPeers`. */ -export function createRemoteTurnBridge(workspace, { pollMs = DEFAULT_POLL_MS, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) { +export function createRemoteTurnBridge( + workspace, + { + pollMs = DEFAULT_POLL_MS, + maxPollMs = pollMs === DEFAULT_POLL_MS ? MAX_POLL_MS : Math.max(pollMs, Math.min(MAX_POLL_MS, pollMs * 3)), + retryBaseMs = DEFAULT_RETRY_BASE_MS, + maxRetryMs = MAX_RETRY_MS, + timeoutMs = DEFAULT_TIMEOUT_MS, + } = {}, +) { const getPeers = () => workspace?.teamworkPeers ?? null; return { @@ -133,29 +144,83 @@ export function createRemoteTurnBridge(workspace, { pollMs = DEFAULT_POLL_MS, ti if (!peers?.available?.()) { throw new Error("Remote host teamwork transport is unavailable on this computer."); } - const hosts = await peers.hosts(true); - const host = hosts.find((h) => h.serverId === hostId); - if (!host) { - throw new Error(`Remote computer "${hostId}" is not linked to this account.`); - } + const id = randomUUID(); - let state = await peers.call(host.serverId, "channel.submit", { id, ...payload }, host.pin); const startedAt = Date.now(); const deadline = startedAt + timeoutMs; + let host = null; + let submitted = false; + let operation = "channel.submit"; + let retryDelay = 0; + + const cancelBestEffort = async () => { + if (!host || !submitted) return; + await peers.call(host.serverId, "channel.cancel", { id }, host.pin).catch(() => {}); + }; + + const sleepOrCancel = async (ms) => { + const remaining = deadline - Date.now(); + if (remaining <= 0) { + await cancelBestEffort(); + throw new Error(`Remote agent on ${host?.name || hostId} timed out before replying.`); + } + try { + await sleep(Math.min(ms, remaining), signal); + } catch (err) { + await cancelBestEffort(); + throw err; + } + }; + + while (!host) { + if (Date.now() >= deadline) { + throw new Error(`Remote agent on ${hostId} timed out before replying.`); + } + try { + const hosts = await peers.hosts(true); + host = hosts.find((h) => h.serverId === hostId) ?? null; + if (!host) { + throw new Error(`Remote computer "${hostId}" is not linked to this account.`); + } + retryDelay = 0; + } catch (err) { + if (err?.code !== "TEAMWORK_OFFLINE") throw err; + retryDelay = Math.min(maxRetryMs, Math.max(retryBaseMs, retryDelay * 2)); + await sleepOrCancel(retryDelay); + } + } - while (state?.status === "pending" || state?.status === "working") { + let state = null; + while (true) { if (Date.now() >= deadline) { - await peers.call(host.serverId, "channel.cancel", { id }, host.pin).catch(() => {}); + await cancelBestEffort(); throw new Error(`Remote agent on ${host.name || hostId} timed out before replying.`); } - const waitMs = Date.now() - startedAt > 5_000 ? MAX_POLL_MS : pollMs; try { - await sleep(waitMs, signal); + if (operation === "channel.submit") { + submitted = true; + state = await peers.call(host.serverId, "channel.submit", { id, ...payload }, host.pin); + } else { + state = await peers.call(host.serverId, "channel.status", { id }, host.pin); + } + retryDelay = 0; } catch (err) { - await peers.call(host.serverId, "channel.cancel", { id }, host.pin).catch(() => {}); - throw err; + if (err?.code !== "TEAMWORK_OFFLINE") throw err; + // Retry transient relay/profile/network blips with bounded backoff, matching remote-teamwork.mjs. + // Retrying channel.submit with the same id is idempotent on the receiver. + retryDelay = Math.min(maxRetryMs, Math.max(retryBaseMs, retryDelay * 2)); + await sleepOrCancel(retryDelay); + continue; } - state = await peers.call(host.serverId, "channel.status", { id }, host.pin); + + if (state?.status === "pending" || state?.status === "working") { + operation = "channel.status"; + const waitMs = Date.now() - startedAt > 5_000 ? maxPollMs : pollMs; + await sleepOrCancel(waitMs); + continue; + } + + break; } if (state?.status === "failed") { diff --git a/desktop/test/channels-imessage.test.mjs b/desktop/test/channels-imessage.test.mjs index 758a53e4..ec5fe82d 100644 --- a/desktop/test/channels-imessage.test.mjs +++ b/desktop/test/channels-imessage.test.mjs @@ -765,4 +765,252 @@ describe("iMessage remote primary agent across paired hosts", () => { await vpsManager.stopAll(); } }); + + it("retries transient TEAMWORK_OFFLINE errors during hosts, submit (idempotently), and status polling and still delivers the iMessage reply", async () => { + const offlineErr = () => + Object.assign(new Error("The computer or profile service is temporarily unreachable."), { + code: "TEAMWORK_OFFLINE", + }); + + const events = new EventEmitter(); + const chats = new Map(); + let runSeq = 0; + const submitted = []; + const vpsWs = { + events, + state: { bots: [{ id: "bot-gordie", name: "Gordie" }], chats: [], channels: [] }, + save: () => {}, + notify: () => {}, + bot: (id) => (id === "bot-gordie" ? { id: "bot-gordie", name: "Gordie" } : null), + chat: (id) => chats.get(id) ?? null, + createChat: (botId, title) => { + const id = `chat-vps-${chats.size + 1}`; + const chatObj = { id, botId, title, messages: [] }; + chats.set(id, chatObj); + vpsWs.state.chats.push(chatObj); + return id; + }, + submit: async (chatId, text, options = {}) => { + const c = chats.get(chatId); + const run = { id: `run-vps-${++runSeq}`, status: "Done" }; + submitted.push({ chatId, text, clientMessageId: options.clientMessageId }); + c.messages.push({ role: "user", text, runId: run.id, clientMessageId: options.clientMessageId }); + // Simulate a slower turn (e.g. waiting on tool approval) so several status polls hit TEAMWORK_OFFLINE first. + setTimeout(() => { + c.messages.push({ role: "assistant", text: "Yep! Running on the Linux Hostinger VM.", runId: run.id }); + events.emit("turn", { chat: c, run }); + }, 90); + }, + stop: () => {}, + }; + const vpsManager = new ChannelManager({ workspace: vpsWs, vault: makeFakeVault() }); + + const peerFromMac = { + profileId: "profile-colt", + serverId: "mac-host-1", + serverKey: "pub-key-mac", + targetId: "vps-host-1", + targetKey: "pub-key-vps", + targetName: "Hostinger VPS", + }; + + let hostsAttempts = 0; + let submitAttempts = 0; + let statusAttempts = 0; + const macWs = makeHostWorkspace({ + hostId: "mac-host-1", + hostName: "Mac Studio", + bots: [{ id: "bot-local", name: "Local" }], + }); + macWs.teamworkPeers = { + available: () => true, + selfId: () => "mac-host-1", + hosts: async () => { + hostsAttempts += 1; + // First hosts() lookup during runTurn fails with TEAMWORK_OFFLINE (after bind/test calls) + if (hostsAttempts === 2) throw offlineErr(); + return [{ serverId: "vps-host-1", name: "Hostinger VPS", pin: "pin-vps" }]; + }, + call: async (hostId, operation, payload) => { + assert.equal(hostId, "vps-host-1"); + if (operation === "channel.submit") { + submitAttempts += 1; + if (submitAttempts === 1) { + // Simulate response lost AFTER the remote host already accepted the turn + await vpsManager.receiveRemoteTurn(peerFromMac, operation, payload); + throw offlineErr(); + } + } + if (operation === "channel.status") { + statusAttempts += 1; + // Simulate two transient offline/429 blips while waiting for the turn to complete + if (statusAttempts <= 2) throw offlineErr(); + } + return vpsManager.receiveRemoteTurn(peerFromMac, operation, payload); + }, + }; + + let pushInbound = null; + const sentReplies = []; + const macManager = new ChannelManager({ + workspace: macWs, + vault: makeFakeVault(), + remoteTurnBridge: createRemoteTurnBridge(macWs, { + pollMs: 15, + maxPollMs: 30, + retryBaseMs: 15, + maxRetryMs: 40, + timeoutMs: 5000, + }), + }); + macManager.registerAdapter("imessage", () => ({ + start: async ({ onMessage }) => { + pushInbound = onMessage; + }, + stop: async () => {}, + test: async () => ({ ok: true, detail: "imsg ready" }), + send: async (msg) => { + sentReplies.push(msg); + }, + })); + + try { + const conn = await macManager.add({ + kind: "imessage", + label: "Colt iMessage", + botId: "bot-gordie", + botHostId: "vps-host-1", + policy: { dm: "open", toolProfile: "standard" }, + }); + + await macManager.startConnection(conn.id); + await pushInbound({ + sender: { id: "+15551234567", display: "Colt" }, + conversationId: "3", + isDirect: true, + text: "Is this Gordie on the Hostinger VM??", + attachments: [], + }); + + const deadline = Date.now() + 2500; + while (sentReplies.length === 0 && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 20)); + } + + // Remote submit was retried with the same UUID, so the VPS ran Gordie ONLY ONCE + assert.equal(submitted.length, 1); + assert.ok(submitAttempts >= 2, `expected idempotent channel.submit retry, got ${submitAttempts}`); + assert.ok(statusAttempts >= 3, `expected channel.status retry after offline blips, got ${statusAttempts}`); + assert.equal(sentReplies.length, 1); + assert.equal(sentReplies[0].conversationId, "3"); + assert.equal(sentReplies[0].text, "Yep! Running on the Linux Hostinger VM."); + + // Non-TEAMWORK_OFFLINE errors still fail immediately without retrying + let hardFailCalls = 0; + const failBridge = createRemoteTurnBridge( + { + teamworkPeers: { + available: () => true, + hosts: async () => [{ serverId: "vps-host-1", name: "Hostinger VPS", pin: "pin-vps" }], + call: async () => { + hardFailCalls += 1; + throw new Error("These computers must both belong to the same Botkins profile."); + }, + }, + }, + { pollMs: 10, retryBaseMs: 10, maxRetryMs: 20, timeoutMs: 2000 }, + ); + await assert.rejects( + failBridge.runTurn("vps-host-1", { kind: "imessage" }), + /same Botkins profile/i, + ); + assert.equal(hardFailCalls, 1); + } finally { + await macManager.stopAll(); + await vpsManager.stopAll(); + } + }); + + it("correlates remote turns by clientMessageId so manual host turns do not steal replies and joined messages resolve once", async () => { + const events = new EventEmitter(); + const chats = new Map(); + const queuedCalls = []; + const vpsWs = { + events, + state: { bots: [{ id: "bot-gordie", name: "Gordie" }], chats: [], channels: [] }, + save: () => {}, + notify: () => {}, + bot: (id) => (id === "bot-gordie" ? { id: "bot-gordie", name: "Gordie" } : null), + chat: (id) => chats.get(id) ?? null, + createChat: (botId, title) => { + const id = `chat-vps-${chats.size + 1}`; + const chatObj = { id, botId, title, messages: [] }; + chats.set(id, chatObj); + vpsWs.state.chats.push(chatObj); + return id; + }, + submit: async (chatId, text, options = {}) => { + queuedCalls.push({ chatId, text, clientMessageId: options.clientMessageId }); + }, + stop: () => {}, + }; + const vpsManager = new ChannelManager({ workspace: vpsWs, vault: makeFakeVault() }); + const peer = { + profileId: "profile-colt", + serverId: "mac-host-1", + serverKey: "pub-key-mac", + targetId: "vps-host-1", + targetKey: "pub-key-vps", + targetName: "Hostinger VPS", + }; + + const id1 = "11111111-1111-4111-8111-111111111111"; + const id2 = "22222222-2222-4222-8222-222222222222"; + const basePayload = { + connectionId: "ch-1", + kind: "imessage", + label: "Colt iMessage", + botId: "bot-gordie", + conversationId: "3", + sender: { id: "+15551234567", display: "Colt" }, + isDirect: true, + mentionsBot: false, + toolProfile: "standard", + }; + + await vpsManager.receiveRemoteTurn(peer, "channel.submit", { ...basePayload, id: id1, text: "First question" }); + await vpsManager.receiveRemoteTurn(peer, "channel.submit", { ...basePayload, id: id2, text: "Second question" }); + assert.equal(queuedCalls.length, 2); + assert.equal(queuedCalls[0].clientMessageId, id1); + assert.equal(queuedCalls[1].clientMessageId, id2); + + const chat = vpsWs.state.chats[0]; + + // An unrelated manual turn typed directly in the VPS chat must NOT resolve id1 or id2 + const manualRun = { id: "run-manual", status: "Done" }; + chat.messages.push({ role: "user", text: "Manual UI message", runId: manualRun.id }); + chat.messages.push({ role: "assistant", text: "Manual UI reply", runId: manualRun.id }); + events.emit("turn", { chat, run: manualRun }); + + const s1Before = await vpsManager.receiveRemoteTurn(peer, "channel.status", { id: id1 }); + const s2Before = await vpsManager.receiveRemoteTurn(peer, "channel.status", { id: id2 }); + assert.equal(s1Before.status, "working"); + assert.equal(s2Before.status, "working"); + + // Now a single joined run processes both id1 (runId) and id2 (steeredRunId) + const joinedRun = { id: "run-joined", status: "Done" }; + chat.messages.push({ role: "user", text: queuedCalls[0].text, runId: joinedRun.id, clientMessageId: id1 }); + chat.messages.push({ role: "user", text: queuedCalls[1].text, steeredRunId: joinedRun.id, joined: true, clientMessageId: id2 }); + chat.messages.push({ role: "assistant", text: "Combined answer to both!", runId: joinedRun.id }); + events.emit("turn", { chat, run: joinedRun }); + + const s1After = await vpsManager.receiveRemoteTurn(peer, "channel.status", { id: id1 }); + const s2After = await vpsManager.receiveRemoteTurn(peer, "channel.status", { id: id2 }); + assert.equal(s1After.status, "done"); + assert.equal(s1After.silent, true); + assert.equal(s2After.status, "done"); + assert.equal(s2After.reply, "Combined answer to both!"); + + await vpsManager.stopAll(); + }); });