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): prevent stale handoff loading rows
CloudTianTian5806eb005f2c
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.jsindex fd01f6b7..a398c606 100644--- a/src/renderer/modules/conversation.js+++ b/src/renderer/modules/conversation.js@@ -3662,15 +3662,13 @@ async function _syncPendingActorsFromRuntime(cid, opts = {}) {if (hasActiveTurnsField) {const activeCommander = activeTurns.some((t) => t.actor === 'commander');if (!activeCommander) _removeEmptyActorPlaceholder(cid, 'commander');- for (const turn of activeTurns) {- _ensureActorPlaceholder(cid, turn.actor, loadingEl, turn.turn_id, turn.msg_id, turn.started_at_ms);- }} else {if (!inFlight.includes('commander')) _removeEmptyActorPlaceholder(cid, 'commander');- for (const actorId of inFlight) {- _ensureActorPlaceholder(cid, actorId, loadingEl);- }}+ const primary = _ensureRuntimeActorPlaceholders(+ cid, loadingEl, activeTurns, inFlight, hasActiveTurnsField,+ );+ if (primary && pendingConvs.get(cid) === state) state.loadingEl = primary;return true;}@@ -6687,6 +6685,66 @@ function _ensureCreateAgentInlineObserver() {_ensureConvCreateAgentInline();}+/**+ * A pending controller outlives whichever actor first adopted its loading row.+ * History recovery may only reattach that row when it is still a live target+ * for the runtime snapshot. Persisted/finalized rows are owned by canonical+ * history, and actor/turn mismatches belong to an earlier orchestration step.+ */+function _canReattachPendingLoadingEl(+ loadingEl,+ activeTurns = [],+ inFlightActors = [],+ hasActiveTurnsField = false,+) {+ if (!loadingEl) return false;+ const data = loadingEl.dataset || {};+ if (data.finalized === '1' || data.msgId) return false;++ const actorId = String(data.fromActor || '');+ const turnId = _normaliseTurnId(data.turnId);+ const renderKey = String(data.renderKey || '');+ // The controller's untouched hidden row is actor-neutral and safe to adopt+ // after the snapshot identifies the current worker.+ if (!actorId && !turnId && !renderKey) return true;++ if (hasActiveTurnsField) {+ return activeTurns.some((turn) => {+ if (String(turn?.actor || '') !== actorId) return false;+ const activeTurnId = _normaliseTurnId(turn?.turn_id);+ return !turnId || !activeTurnId || turnId === activeTurnId;+ });+ }+ if (inFlightActors.length && actorId) return inFlightActors.includes(actorId);+ // Legacy/stale snapshots without actor identity cannot disprove ownership.+ // Keep the live row so the controller closure does not lose direct deltas.+ return true;+}++function _ensureRuntimeActorPlaceholders(+ cid,+ fallbackPh,+ activeTurns,+ inFlightActors,+ hasActiveTurnsField,+) {+ let primary = null;+ if (hasActiveTurnsField) {+ for (const turn of activeTurns) {+ const ph = _ensureActorPlaceholder(+ cid, turn.actor, fallbackPh, turn.turn_id, turn.msg_id, turn.started_at_ms,+ );+ if (!primary && ph) primary = ph;+ }+ } else {+ for (const actorId of inFlightActors) {+ const ph = _ensureActorPlaceholder(cid, actorId, fallbackPh);+ if (!primary && ph) primary = ph;+ }+ }+ return primary;+}+async function loadConversationHistory(cid, opts = {}) {const perfStartedAt = performance.now();const container = document.getElementById('chat-history');@@ -6889,15 +6947,11 @@ async function loadConversationHistory(cid, opts = {}) {needsIndicator: false,startedAtMs: Math.max(0, new Date(convMeta.processing_since).getTime() || 0),});- if (hasActiveTurnsField) {- for (const turn of activeTurns) {- _ensureActorPlaceholder(cid, turn.actor, loadingEl, turn.turn_id, turn.msg_id, turn.started_at_ms);- }- } else {- for (const actorId of inFlightActors) {- _ensureActorPlaceholder(cid, actorId, loadingEl);- }- }+ const recoveredState = pendingConvs.get(cid);+ const primary = _ensureRuntimeActorPlaceholders(+ cid, loadingEl, activeTurns, inFlightActors, hasActiveTurnsField,+ );+ if (primary && recoveredState) recoveredState.loadingEl = primary;// Opening/reloading into an already-running plan still needs the// group event stream; runtime polling can recover placeholders, but// it cannot replay live text deltas.@@ -6905,36 +6959,34 @@ async function loadConversationHistory(cid, opts = {}) {_startRuntimeActorRecovery(cid);_updateConvSendUI(cid);} else if (isConvPending(cid)) {- // User navigated away and back during an in-flight request. The stream- // reader loop in createChatController.send() holds the original msgEl- // in closure and keeps dispatching deltas/final to that *specific* node- // — so we must re-attach the original node, not mint a fresh bubble.- // Minting a new one here (as before) stranded the stream: events kept- // landing on the orphaned node and the new bubble stayed at "thinking…"- // until stream end / polling rescue.+ // User navigated away and back during an in-flight request. Preserve a+ // still-live controller row, but never revive a row already finalized by+ // history or owned by an earlier actor/turn. A terminal Commander hand-+ // off keeps the whole conversation pending while the Agent runs; blindly+ // reattaching the original Commander row creates the duplicate loading+ // bubble beside its canonical history record.let state = pendingConvs.get(cid);if (!state) {state = { loadingEl: null, needsIndicator: false, controller: null, aborted: false };pendingConvs.set(cid, state);}pollMsgCounts.set(cid, String(lastMsg?._msg_id || ''));- if (state.loadingEl) {+ const reusableLoadingEl = _canReattachPendingLoadingEl(+ state.loadingEl, activeTurns, inFlightActors, hasActiveTurnsField,+ ) ? state.loadingEl : null;+ if (reusableLoadingEl) {const emptyEl = container.querySelector('.empty');if (emptyEl) emptyEl.remove();- _appendBeforeSpacer(container, state.loadingEl);+ _appendBeforeSpacer(container, reusableLoadingEl);+ state.loadingEl = reusableLoadingEl;} else {const loadingEl = _createStreamingAssistantMessage(container, { hiddenUntilActor: true });state.loadingEl = loadingEl;}- if (hasActiveTurnsField) {- for (const turn of activeTurns) {- _ensureActorPlaceholder(cid, turn.actor, state.loadingEl, turn.turn_id, turn.msg_id, turn.started_at_ms);- }- } else {- for (const actorId of inFlightActors) {- _ensureActorPlaceholder(cid, actorId, state.loadingEl);- }- }+ const primary = _ensureRuntimeActorPlaceholders(+ cid, state.loadingEl, activeTurns, inFlightActors, hasActiveTurnsField,+ );+ if (primary) state.loadingEl = primary;if (!state.controller) {// Same recovery path for a detached pending state: reconnect to the// live group event stream so the bubble streams instead of waiting@@ -13476,16 +13528,11 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {// handed-off agent's reply._serverFloorByCid.set(cid, typeof st.active_recipient === 'string' ? st.active_recipient : '');setGroupConversationBusy(cid, st.status === 'running' || inFlight.length > 0 || activeTurns.length > 0);- if (hasActiveTurnsField) {- for (const turn of activeTurns) {- _ensureActorPlaceholder(cid, turn.actor, streamingMsg, turn.turn_id, turn.msg_id, turn.started_at_ms);- }- } else if (inFlight.length) {- for (const actorId of inFlight) {- if (!actorId) continue;- _ensureActorPlaceholder(cid, actorId, streamingMsg);- }- }+ const primary = _ensureRuntimeActorPlaceholders(+ cid, streamingMsg, activeTurns, inFlight, hasActiveTurnsField,+ );+ const pendingState = pendingConvs.get(cid);+ if (primary && pendingState && !pendingState.aborted) pendingState.loadingEl = primary;// Reconcile against the snapshot. `state` is level-triggered — the relay// Server stores it last-write-wins and replays it on every WS reconnect —// so an actor that has dropped out of `in_flight` is no longer running.diff --git a/test/e2e/commander_e2e_orchestration.spec.ts b/test/e2e/commander_e2e_orchestration.spec.tsindex fc74c909..7b666c9e 100644--- a/test/e2e/commander_e2e_orchestration.spec.ts+++ b/test/e2e/commander_e2e_orchestration.spec.ts@@ -68,6 +68,22 @@ test.describe('Commander orchestration', () => {const runningConversationId = await page.locator('#conversation-list .conv-item').first().getAttribute('data-cid');expect(runningConversationId).toBeTruthy();+ // Switch away and back WITHOUT recreating the renderer. Unlike reload,+ // this preserves pendingConvs.loadingEl — exactly the field report where+ // the settled Commander row used to be reattached beside its canonical+ // history row while ContentWriter was still the active turn.+ await page.locator('#new-chat-btn').click();+ await page.locator(`.conv-item[data-cid="${runningConversationId}"]`).click();+ await expect(page.locator(+ '#chat-history .chat-message.assistant[data-from-actor="commander"]',+ )).toHaveCount(1);+ await expect(page.locator(+ '#chat-history .chat-message.assistant[data-from-actor="commander"]',+ )).toContainText(commanderNarration);+ await expect(page.locator(+ `#chat-history .chat-message.assistant[data-from-actor="${CONTENT_WRITER_ID}"]`,+ )).toHaveCount(1);+// Recreate the renderer while the delegated Agent is still running.// This exercises active-turn recovery plus history rendering together,// the path that a terminal-only assertion completely misses.@@ -151,6 +167,16 @@ test.describe('Commander orchestration', () => {`#chat-history .chat-message.assistant[data-from-actor="${CONTENT_WRITER_ID}"]`,)).toHaveCount(1);await expect(commanderBubbles).toHaveCount(0);++ const runningConversationId = await page.locator('#conversation-list .conv-item').first()+ .getAttribute('data-cid');+ expect(runningConversationId).toBeTruthy();+ await page.locator('#new-chat-btn').click();+ await page.locator(`.conv-item[data-cid="${runningConversationId}"]`).click();+ await expect(page.locator(+ `#chat-history .chat-message.assistant[data-from-actor="${CONTENT_WRITER_ID}"]`,+ )).toHaveCount(1);+ await expect(commanderBubbles).toHaveCount(0);} finally {modelOrkas.releaseAgentHandoffReply();}diff --git a/test/renderer/conversation-keyed-rendering.test.ts b/test/renderer/conversation-keyed-rendering.test.tsindex 1888c65d..2f9c2f9e 100644--- a/test/renderer/conversation-keyed-rendering.test.ts+++ b/test/renderer/conversation-keyed-rendering.test.ts@@ -396,6 +396,26 @@ describe('keyed rendering › silent turns', () => {});describe('keyed rendering › level-triggered placeholder reconciliation', () => {+ it('moves pending recovery ownership to the actor in the latest active snapshot', () => {+ const { context, container } = loadRenderer(CID);+ const staleCommander = new FakeNode();+ staleCommander.dataset.fromActor = 'commander';+ staleCommander.dataset.turnId = TURN;+ staleCommander.dataset.renderKey = `s:${TURN}:0`;+ context.pendingConvs.set(CID, { loadingEl: staleCommander, aborted: false });++ context._handleGroupBusEvent(CID, staleCommander, {+ type: 'state_changed',+ cid: CID,+ state: { status: 'running', in_flight: ['agent-a'], active_recipient: 'agent-a' },+ active_turns: [{ actor: 'agent-a', turn_id: 'turn-a' }],+ });++ const agentRow = container.rows.find((row) => row.dataset.fromActor === 'agent-a');+ expect(agentRow).toBeTruthy();+ expect(context.pendingConvs.get(CID).loadingEl).toBe(agentRow);+ });+it('removes an empty placeholder after its actor leaves the active snapshot', () => {const { context, container } = loadRenderer(CID);diff --git a/test/renderer/conversation-sidebar.test.ts b/test/renderer/conversation-sidebar.test.tsindex 71bb6222..c509a6fd 100644--- a/test/renderer/conversation-sidebar.test.ts+++ b/test/renderer/conversation-sidebar.test.ts@@ -572,6 +572,154 @@ describe('conversation history initial window', () => {expect(context._takeOffViewGroupProcessEvents('c1')).toEqual([]);});+ it('does not revive a completed Commander row when history reports an active Agent turn', async () => {+ const context = loadConversationRenderer();+ const appended: any[] = [];+ const ensured: any[] = [];+ const staleCommander = {+ dataset: {+ finalized: '1',+ fromActor: 'commander',+ msgId: 'commander-seg-0',+ renderKey: 's:commander-turn:0',+ turnId: 'commander-turn',+ },+ isConnected: false,+ parentElement: null,+ } as any;+ const activeAgent = {+ dataset: {},+ isConnected: true,+ parentElement: {},+ } as any;+ const history = {+ isConnected: true,+ classList: { remove() {} },+ innerHTML: '',+ scrollHeight: 100,+ scrollTop: 0,+ style: {+ scrollBehavior: '',+ removeProperty() {},+ },+ addEventListener() {},+ querySelector: () => null,+ querySelectorAll: () => [],+ appendChild(node: any) { node.isConnected = true; },+ insertBefore(node: any) { node.isConnected = true; },+ } as any;+ context.currentCid = 'c1';+ context.performance = performance;+ context.convAgentEnabledByCid = new Map();+ context.pollMsgCounts = new Map();+ context.messageQueues = new Map();+ context.pendingConvs.set('c1', {+ loadingEl: staleCommander,+ needsIndicator: true,+ controller: { abort() {} },+ aborted: false,+ });+ context.document.getElementById = (id: string) => (id === 'chat-history' ? history : null);+ context._ensureCreateAgentInlineObserver = () => {};+ context._ensureConvCreateAgentInline = () => {};+ context._refreshGroupMembers = async () => [];+ context._evaluateAutoRecipient = async () => {};+ context._renderConvDisabledBanner = () => {};+ context._updateConvSendUI = () => {};+ context.startPolling = () => {};+ context._appendBeforeSpacer = (_container: any, node: any) => {+ appended.push(node);+ node.isConnected = true;+ };+ context._createStreamingAssistantMessage = () => activeAgent;+ context._ensureActorPlaceholder = (...args: any[]) => {+ ensured.push(args);+ return args[2];+ };+ context.apiFetch = async () => ({+ json: async () => ({+ ok: true,+ history: [],+ conversation: {+ agent_enabled: true,+ processing: true,+ processing_since: new Date().toISOString(),+ in_flight: ['agent-a'],+ active_recipient: 'agent-a',+ active_turns: [{ actor: 'agent-a', turn_id: 'agent-turn' }],+ },+ next_cursor: null,+ }),+ });++ await context.loadConversationHistory('c1');++ expect(appended, 'settled history-owned rows must never be reattached').not.toContain(staleCommander);+ expect(ensured).toHaveLength(1);+ expect(ensured[0][1]).toBe('agent-a');+ expect(ensured[0][2], 'the active Agent must receive a fresh reusable row').toBe(activeAgent);+ expect(context.pendingConvs.get('c1').loadingEl).toBe(activeAgent);+ });++ it.each([+ {+ name: 'persisted row',+ dataset: { finalized: '1', msgId: 'msg-1', fromActor: 'agent-a', turnId: 'turn-a' },+ activeTurns: [{ actor: 'agent-a', turn_id: 'turn-a' }],+ inFlight: ['agent-a'],+ authoritative: true,+ expected: false,+ },+ {+ name: 'previous actor',+ dataset: { fromActor: 'commander', turnId: 'turn-c', renderKey: 's:turn-c:0' },+ activeTurns: [{ actor: 'agent-a', turn_id: 'turn-a' }],+ inFlight: ['agent-a'],+ authoritative: true,+ expected: false,+ },+ {+ name: 'previous turn of the same actor',+ dataset: { fromActor: 'agent-a', turnId: 'turn-old', renderKey: 's:turn-old:0' },+ activeTurns: [{ actor: 'agent-a', turn_id: 'turn-new' }],+ inFlight: ['agent-a'],+ authoritative: true,+ expected: false,+ },+ {+ name: 'matching active turn',+ dataset: { fromActor: 'agent-a', turnId: 'turn-a', renderKey: 's:turn-a:0' },+ activeTurns: [{ actor: 'agent-a', turn_id: 'turn-a' }],+ inFlight: ['agent-a'],+ authoritative: true,+ expected: true,+ },+ {+ name: 'unclaimed controller row',+ dataset: {},+ activeTurns: [{ actor: 'agent-a', turn_id: 'turn-a' }],+ inFlight: ['agent-a'],+ authoritative: true,+ expected: true,+ },+ {+ name: 'legacy snapshot without actor identity',+ dataset: { fromActor: 'agent-a', turnId: 'turn-a', renderKey: 's:turn-a:0' },+ activeTurns: [],+ inFlight: [],+ authoritative: false,+ expected: true,+ },+ ])('classifies a $name for pending history recovery', ({+ dataset, activeTurns, inFlight, authoritative, expected,+ }) => {+ const context = loadConversationRenderer();++ expect(context._canReattachPendingLoadingEl(+ { dataset }, activeTurns, inFlight, authoritative,+ )).toBe(expected);+ });+it('recognizes a stale deleted-conversation result as recoverable', () => {const context = loadConversationRenderer();