Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
fix(chat): make stream settlement idempotent
IgnoreMeBut94d89414987b
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex 25a47196..18d1c85a 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -3564,6 +3564,29 @@ const streamHandlers: Record<string, StreamHandler> = {interface StreamState { cancelled: boolean; controller: AbortController; sender: WebContents }const activeStreams = new Map<string, StreamState>();+interface SettledStreamState { sender: WebContents; settledAt: number }+const recentlySettledStreams = new Map<string, SettledStreamState>();+const SETTLED_STREAM_TTL_MS = 60_000;+const SETTLED_STREAM_MAX = 512;++function pruneSettledStreams(now = Date.now()): void {+ for (const [requestId, state] of recentlySettledStreams) {+ if (now - state.settledAt <= SETTLED_STREAM_TTL_MS) break;+ recentlySettledStreams.delete(requestId);+ }+ while (recentlySettledStreams.size > SETTLED_STREAM_MAX) {+ const oldest = recentlySettledStreams.keys().next().value;+ if (typeof oldest !== 'string') break;+ recentlySettledStreams.delete(oldest);+ }+}++function rememberSettledStream(requestId: string, sender: WebContents): void {+ const settledAt = Date.now();+ recentlySettledStreams.delete(requestId);+ recentlySettledStreams.set(requestId, { sender, settledAt });+ pruneSettledStreams(settledAt);+}/*** Resolve the current user context for an IPC request. `user.init` must be@@ -3724,6 +3747,7 @@ export function register(): void {out({ type: 'error', text: (err as Error).message || String(err) });} finally {activeStreams.delete(requestId);+ rememberSettledStream(requestId, event.sender);log.info(`streamDone channel=${channel} requestId=${requestId} cancelled=${state.cancelled}`);out({ type: 'done' });}@@ -3735,6 +3759,19 @@ export function register(): void {if (!requestId) return;const state = activeStreams.get(requestId);if (!state) {+ pruneSettledStreams();+ const settled = recentlySettledStreams.get(requestId);+ if (settled?.sender === event.sender) {+ // Renderer cleanup may race the terminal `done` delivery by a few+ // milliseconds. Cancellation is idempotent: a request that this same+ // renderer already completed has nothing left to abort.+ log.debug(`streamCancel: already settled requestId=${requestId}`);+ return;+ }+ if (settled) {+ log.warn(`streamCancel: sender mismatch requestId=${requestId}`);+ return;+ }log.warn(`streamCancel: unknown requestId=${requestId}`);return;}diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.jsindex 7e4f33a9..d7ee55e8 100644--- a/src/renderer/modules/conversation.js+++ b/src/renderer/modules/conversation.js@@ -3417,6 +3417,11 @@ function _renderMessageQueueForRuntimeState(cid) {const _runtimeRecoveryTimers = new Map(); // cid → timeout idconst _lastGroupWorkEventAt = new Map(); // cid → ms timestamp of process/artifact/assistant messageconst _groupObserverCtrls = new Map(); // cid → recovery observer controller+// Reserve an observer before its asynchronous IPC stream is connected. The+// lifecycle controller map is populated only after activity is observed, which+// left a pre-activity window where two recovery triggers could subscribe to the+// same bus and replay every event twice.+const _groupObserverReservations = new Map(); // cid → observer controllerconst _conversationInfoFileRefreshTimers = new Map(); // cid → timeout idconst _offViewGroupProcessEvents = new Map(); // cid → bounded non-delta process eventsconst _MAX_OFF_VIEW_GROUP_PROCESS_EVENTS = 300;@@ -3643,9 +3648,9 @@ async function _syncPendingActorsFromRuntime(cid, opts = {}) {}if (hasLiveController) {// Re-arm the bus observer if this snapshot found a live run without one.- // The observer is the conversation's only event source (the send stream- // carries lifecycle only) and is idempotent per cid, so re-arming is safe- // and losing it would silently stop the live rail.+ // The primary send stream and this observer are redundant delivery paths;+ // the observer keeps terminal recovery alive if the primary renderer path+ // disconnects. Its reservation makes re-arming idempotent per cid._observeConversationRunFromPlanAction(cid, {attachExisting: true,allowWithController: true,@@ -10261,12 +10266,11 @@ function _makeConvChatController(cid, options = {}) {_lastGroupWorkEventAt.set(id, Date.now());_updateConvSendUI(id);_updateConvSidebarBadge(id, true);- // The send stream carries lifecycle only (see ipc `conversations.sendStream`),- // so the bus observer must be attached here — it is the only source of- // process/delta/message events for this turn. Attaching at send time- // rather than waiting for a `state_changed` also removes the old- // bootstrap dependency: that event used to arrive over the send stream,- // which no longer relays anything.+ // Keep a recovery observer beside the primary `conversations.sendStream`.+ // The primary owns append-semantics process events; the observer keeps+ // idempotent terminal/state delivery alive if the primary renderer path+ // disconnects. Attach at send time so neither path depends on first+ // observing `state_changed` before it can recover the turn._observeConversationRunFromPlanAction(id, {attachExisting: true,allowWithController: true,@@ -10563,7 +10567,7 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {const attachExisting = !!opts.attachExisting;const allowWithController = !!opts.allowWithController;if (_convChatCtrls.has(cid) && !allowWithController) return null;- if (allowWithController && _groupObserverCtrls.has(cid)) return null;+ if (_groupObserverReservations.has(cid)) return null;if (!attachExisting && (pendingConvs.has(cid) || isGroupConversationBusy(cid))) return null;const controller = new AbortController();@@ -10571,12 +10575,20 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {let sawActivity = attachExisting;let settled = false;let activated = false;+ // Capture ownership at subscription time. A paired observer must keep+ // ignoring append-semantics process events even after the primary controller+ // settles, because its IPC buffer can drain a few milliseconds later.+ const pairedWithPrimary = allowWithController && _convChatCtrls.has(cid);const ctrl = {abort: () => {+ if (_groupObserverReservations.get(cid) === ctrl) {+ _groupObserverReservations.delete(cid);+ }try { controller.abort(); } catch (_) {}},};+ _groupObserverReservations.set(cid, ctrl);if (allowWithController) _groupObserverCtrls.set(cid, ctrl);const activate = () => {@@ -10653,8 +10665,11 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {if (st.status === 'running' || inFlight.length > 0 || activeTurns.length > 0) sawActivity = true;}if (sawActivity) activate();- // The primary send stream owns the process rail while it is alive.- if (allowWithController && _convChatCtrls.has(cid) && _isPrimaryOwnedLiveEvent(evData)) {+ // A paired primary send stream owns the process rail for this entire+ // observer subscription. Checking the live-controller map here was+ // racy: main could finish the primary first while this observer still+ // had duplicate terminal process events buffered.+ if (pairedWithPrimary && _isPrimaryOwnedLiveEvent(evData)) {continue;}_handleGroupBusEvent(cid, msgEl, evData, { archive: true });@@ -10675,7 +10690,9 @@ function _observeConversationRunFromPlanAction(cid, opts = {}) {// Whether this observer is still the conversation's current one. A newer// send registers its own observer, and once that happens every global// teardown below belongs to that newer run, not to this finishing one.- const supersededByNewerRun = allowWithController && _groupObserverCtrls.get(cid) !== ctrl;+ const currentReservation = _groupObserverReservations.get(cid);+ const supersededByNewerRun = !!currentReservation && currentReservation !== ctrl;+ if (currentReservation === ctrl) _groupObserverReservations.delete(cid);if (allowWithController) {if (_groupObserverCtrls.get(cid) === ctrl) _groupObserverCtrls.delete(cid);} else if (_convChatCtrls.get(cid) === ctrl) {@@ -13252,6 +13269,20 @@ function _reportUnclaimedKeyedRecord(cid, gm, renderKey) {} catch (_) { /* diagnostics must never break rendering */ }}+/** A second event stream can deliver the same persisted terminal record after+ * its first delivery already finalized the row. Treat that as an idempotent+ * replay only when the durable message id matches; a finalized silent row with+ * no message id still has to be replaced if a real record arrives later. */+function _isFinalizedGroupMessageReplay(cid, gm) {+ if (!gm || !gm.id) return false;+ const container = document.getElementById('chat-history');+ const existing = _findRenderedGroupMessage(container, gm);+ if (!existing || existing.dataset.finalized !== '1') return false;+ if (String(existing.dataset.msgId || '') !== String(gm.id)) return false;+ _syncRenderedGroupMessageIdentity(existing, gm);+ return true;+}+// Transform a streaming placeholder bubble into its finalized form:// freeze the process rail (keep visible + collapsed by default),// render markdown into [data-role="final"], append produced-files chip /@@ -13522,6 +13553,11 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {const isCommanderSegment = !isTurnEnd&& gm.seg !== undefined && String(gm.from || '') === 'commander';if (isTurnEnd || isCommanderSegment) {+ // `conversations.sendStream` and its recovery observer both carry+ // persisted messages. Whichever reaches the DOM first owns finalization;+ // the second is a replay, not a missing-row failure and not another+ // auto-recipient trigger.+ if (_isFinalizedGroupMessageReplay(cid, gm)) return;// Finalize THIS actor's placeholder in place — preserves the process// rail (tool calls, progress lines) accumulated during the turn so// it stays readable after the reply settles. If we don't have a@@ -13619,6 +13655,12 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {cid, actor, streamingMsg, turnId, undefined, undefined, evData.seg,);if (!target) {+ // Terminal content is authoritative. A process event buffered by a+ // redundant stream can arrive after that row is finalized; dropping it+ // preserves the final text and makes terminal-late delivery idempotent.+ const renderKey = turnId ? _segmentRenderKey(turnId, evData.seg) : _pendingRenderKey(actor);+ const settledTarget = renderKey ? _findRenderNode(cid, renderKey) : null;+ if (settledTarget?.dataset?.finalized === '1') return;_convLog.warn('group process target missing', {cid,actor,diff --git a/test/main/ipc/conversations-send-stream.test.ts b/test/main/ipc/conversations-send-stream.test.tsindex 5bf918b5..1b9a641e 100644--- a/test/main/ipc/conversations-send-stream.test.ts+++ b/test/main/ipc/conversations-send-stream.test.ts@@ -4,6 +4,18 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';+const loggerMocks = vi.hoisted(() => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+}));++vi.mock('../../../src/main/logger', () => ({+ createLogger: () => loggerMocks,+ logFromRenderer: vi.fn(),+}));+type StreamStartFn = (event: { sender: { getURL: () => string; isDestroyed: () => boolean; send: (channel: string, payload: unknown) => void } },req: { requestId: string; channel: string; payload?: unknown },@@ -87,6 +99,10 @@ beforeEach(async () => {groupChatMock.releaseSend = null;groupChatMock.sendCalls.length = 0;groupChatMock.retryCalls.length = 0;+ loggerMocks.debug.mockReset();+ loggerMocks.info.mockReset();+ loggerMocks.warn.mockReset();+ loggerMocks.error.mockReset();groupChatMock.sendStarted = new Promise<void>((resolve) => { groupChatMock.resolveSendStarted = resolve; });groupChatMock.sendFinished = new Promise<void>((resolve) => { groupChatMock.resolveSendFinished = resolve; });vi.resetModules();@@ -288,6 +304,28 @@ describe('ipc › conversations.sendStream', () => {groupChatMock.releaseSend?.();});+ it('treats a late cancel from the completed stream owner as idempotent cleanup', async () => {+ if (!streamStartHandler || !streamCancelHandler) throw new Error('stream handlers not registered');+ const sender = trustedIpcSender({ isDestroyed: () => false, send: vi.fn() });++ await streamStartHandler(+ { sender },+ {+ requestId: 'already-settled',+ channel: 'groupChat.events',+ payload: { cid: 'c123abc' },+ },+ );+ loggerMocks.warn.mockClear();++ streamCancelHandler({ sender }, 'already-settled');++ expect(loggerMocks.warn).not.toHaveBeenCalled();+ expect(loggerMocks.debug).toHaveBeenCalledWith(+ 'streamCancel: already settled requestId=already-settled',+ );+ });+it('rejects a duplicate request id without replacing the original owner', async () => {if (!streamStartHandler || !streamCancelHandler) throw new Error('stream handlers not registered');const first = trustedIpcSender({ isDestroyed: () => false, send: vi.fn() });diff --git a/test/renderer/conversation-sidebar.test.ts b/test/renderer/conversation-sidebar.test.tsindex c509a6fd..0f01fd70 100644--- a/test/renderer/conversation-sidebar.test.ts+++ b/test/renderer/conversation-sidebar.test.ts@@ -1878,6 +1878,101 @@ describe('conversation sticky scroll', () => {});});+describe('conversation stream lifecycle idempotency', () => {+ it('reserves a recovery observer before activity so concurrent triggers cannot double-subscribe', async () => {+ const context = loadConversationRenderer();+ context.AbortController = AbortController;+ let streamStarts = 0;+ context.apiFetch = (_url: string, options: any) => {+ streamStarts += 1;+ return new Promise((_resolve, reject) => {+ options.signal.addEventListener('abort', () => {+ reject(Object.assign(new Error('cancelled'), { name: 'AbortError' }));+ }, { once: true });+ });+ };++ const first = context._observeConversationRunFromPlanAction('c1');+ const duplicate = context._observeConversationRunFromPlanAction('c1');++ expect(first).not.toBeNull();+ expect(duplicate).toBeNull();+ expect(streamStarts).toBe(1);++ first.cancel();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(vm.runInContext('_groupObserverReservations.size', context)).toBe(0);+ });++ it('treats a duplicate terminal message as an idempotent replay of its finalized row', () => {+ const context = loadConversationRenderer();+ context.currentCid = 'c1';+ context.__existing = {+ dataset: {+ finalized: '1',+ msgId: 'message-1',+ renderKey: 's:turn-1:0',+ },+ };+ context.__syncCalls = 0;+ context.__autoRecipientCalls = 0;+ context.document.getElementById = () => ({});+ vm.runInContext(`+ _findRenderedGroupMessage = function() { return __existing; };+ _syncRenderedGroupMessageIdentity = function() { __syncCalls += 1; };+ _claimRenderNodeForMessage = function() { throw new Error('replay claimed the row again'); };+ appendChatMessage = function() { throw new Error('replay appended a duplicate row'); };+ _evaluateAutoRecipient = function() { __autoRecipientCalls += 1; };+ _scheduleConversationInfoFileRefresh = function() {};+ `, context);++ context._handleGroupBusEvent('c1', null, {+ type: 'message',+ turn_id: 'turn-1',+ turn_end: true,+ msg: {+ id: 'message-1',+ from: 'commander',+ to: ['user'],+ turn_id: 'turn-1',+ seg: 0,+ text: 'Canonical final answer',+ ts: '2026-08-27T22:40:16.745Z',+ },+ });++ expect(context.__syncCalls).toBe(1);+ expect(context.__autoRecipientCalls).toBe(0);+ });++ it('drops a terminal-late process event instead of reopening or warning on the finalized row', () => {+ const context = loadConversationRenderer();+ context.currentCid = 'c1';+ context.groupBusyConvs.set('c1', true);+ context.__settledRow = { dataset: { finalized: '1' } };+ context.__warnCalls = 0;+ vm.runInContext(`+ _ensureActorPlaceholder = function() { return null; };+ _findRenderNode = function() { return __settledRow; };+ _convLog.warn = function() { __warnCalls += 1; };+ `, context);++ context._handleGroupBusEvent('c1', null, {+ type: 'process',+ actor: 'commander',+ turn_id: 'turn-1',+ seg: 0,+ data: {+ type: 'event',+ event: { stream: 'tool', data: { phase: 'end', id: 'tool-1' } },+ },+ });++ expect(context.__warnCalls).toBe(0);+ expect(context.__settledRow.dataset).toEqual({ finalized: '1' });+ });+});+describe('conversation history reconcile', () => {// Matching used to fall back to a sender+second-timestamp+text-hash// signature, which two genuinely different replies can share. Identity is now@@ -6156,9 +6251,9 @@ describe('conversation controller settlement', () => {context._updateConvSidebarBadge = () => {};context.startPolling = () => {};context._startRuntimeActorRecovery = () => {};- // Sending now attaches the bus observer (the turn's only event source);- // this case is about controller settlement, so stub it like the other- // onAssistantStart side effects above.+ // Sending now attaches the recovery bus observer beside the primary send+ // stream; this case is about controller settlement, so stub it like the+ // other onAssistantStart side effects above.context._observeConversationRunFromPlanAction = () => {};const ctrl = context._makeConvChatController('c1');