Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(hetero): stop the topic spinner sticking after a local CC run finishes (#16745)

Arvin Xu7a484edc344e
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
index 4a858cbcdd1..65baee22a88 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
@@ -4,7 +4,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
-import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { buildRunLifecycle } from '../lifecycle/buildRunLifecycle';
import { createGatewayEventHandler } from '../transports/gateway/gatewayEventHandler';
@@ -514,7 +513,7 @@ describe('createGatewayEventHandler', () => {
});
describe('visible_output_end', () => {
- it('clears visible loading without completing the operation', async () => {
+ it('marks visible loading done without completing the operation or clearing topic loading', async () => {
const store = createMockStore();
const handler = createHandler(store);
@@ -530,25 +529,11 @@ describe('createGatewayEventHandler', () => {
visibleLoadingDone: true,
});
expect(store.completeOperation).not.toHaveBeenCalledWith('op-1');
- expect(store.internal_updateTopicLoading).toHaveBeenCalledWith('topic-1', false);
- });
-
- it('keeps topic loading when another message is queued in the same context', async () => {
- const store = createMockStore();
- (store as any).queuedMessages = {
- [messageMapKey({ agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any)]: [
- { content: 'next' },
- ],
- };
- const handler = createHandler(store);
-
- handler(makeEvent('visible_output_end'));
- await flush();
-
- expect(store.updateOperationMetadata).toHaveBeenCalledWith('op-1', {
- visibleLoadingDone: true,
- });
- expect(store.internal_updateTopicLoading).not.toHaveBeenCalledWith('topic-1', false);
+ // Sidebar "running" spinner is driven off `topic.status === 'running'`
+ // (persisted, reset at the terminal) for gateway/hetero runs β€” not the
+ // client-only `topicLoadingIds` overlay β€” so visible_output_end no longer
+ // clears it early.
+ expect(store.internal_updateTopicLoading).not.toHaveBeenCalled();
});
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 26cfa79af36..b1ae2fee347 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -73,6 +73,10 @@ vi.mock('@/services/electron/heterogeneousAgent', () => ({
// Gateway event handler β€” we spy on it but let it run (it calls getMessages)
vi.mock('../transports/gateway/gatewayEventHandler', () => ({
createGatewayEventHandler: vi.fn(() => vi.fn()),
+ // Faithful re-impl (the real one is unmocked to keep the import cycle out of
+ // this test): only 'interrupted' / 'waiting_for_async_tool' are non-clean.
+ isCompletedRuntimeEnd: (reason?: string | null) =>
+ reason !== 'interrupted' && reason !== 'waiting_for_async_tool',
}));
// isDesktop β€” defaults to `false` (matching the real test env / __ELECTRON__
@@ -4185,5 +4189,57 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
}),
);
});
+
+ // ── 5. stuck-spinner regression: status reset must not wait on the drain ──
+ it('resets topic status even when the persist queue never drains', async () => {
+ // A DB write that never settles β€” mirrors a dropped desktop-IPC reply. It
+ // strands the executor's persistQueue, which onComplete used to `await`
+ // unbounded BEFORE resetting topic status, leaving the sidebar spinning
+ // forever after the CLI had already exited (the bug this guards against).
+ let releaseWrite!: () => void;
+ const hangingWrite = new Promise<void>((r) => {
+ releaseWrite = r;
+ });
+ mockUpdateMessage.mockReturnValue(hangingWrite);
+
+ const updateTopicStatus = vi.fn();
+ const store = createMockStore({
+ activeTopicId: 'topic-1', // viewing β†’ a clean end writes 'active'
+ updateTopicStatus,
+ });
+ const get = vi.fn(() => store);
+
+ let resolveSendPrompt!: () => void;
+ mockSendPrompt.mockReturnValue(
+ new Promise<void>((r) => {
+ resolveSendPrompt = r;
+ }),
+ );
+
+ const executorPromise = executeHeterogeneousAgent(get, defaultParams);
+ await flush();
+
+ // A tool batch enqueues an awaited `updateMessage` onto persistQueue β€” the
+ // hanging write above stalls the queue before the terminal drain.
+ ipc.emitRawLine('ipc-sess-1', ccInit());
+ ipc.emitRawLine('ipc-sess-1', ccToolUse('msg_01', 'toolu_1', 'Read', { file_path: '/a' }));
+ ipc.emitRawLine('ipc-sess-1', ccToolResult('toolu_1', 'file content'));
+ ipc.emitRawLine('ipc-sess-1', ccResult());
+ ipc.emitComplete('ipc-sess-1');
+ await flush();
+
+ // The fix: status is reset synchronously at the top of onComplete, BEFORE
+ // the (now stalled + bounded) drain β€” so the spinner clears to 'active'
+ // even though the persist queue is still pending on the hanging write.
+ expect(updateTopicStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),
+ );
+
+ // Release so the queue drains and the executor settles cleanly.
+ releaseWrite();
+ resolveSendPrompt();
+ await executorPromise;
+ await flush();
+ });
});
});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 038e5d2ccd4..41f20e4dd7a 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -868,9 +868,12 @@ export class ConversationLifecycleActionImpl {
// branch returns early (line 498) and never reaches that clear.
this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null });
- if (heteroData.topicId && !optimisticTopicResolved) {
- this.#get().internal_updateTopicLoading(heteroData.topicId, true);
- }
+ // Sidebar "running" spinner for hetero runs is driven off the persisted
+ // `topic.status === 'running'` (written by the executor's writeTopicStatus,
+ // and bucketed by resolveStatusBucket) β€” no separate client-only
+ // `topicLoadingIds` overlay, which used to desync: it cleared on the
+ // linear sendPrompt path (below) while `status` stayed 'running' when the
+ // executor's onComplete stalled, leaving the topic spinning after finish.
// Start heterogeneous agent execution
const { operationId: heteroOpId } = this.#get().startOperation({
@@ -925,8 +928,6 @@ export class ConversationLifecycleActionImpl {
});
}
- if (heteroData.topicId) this.#get().internal_updateTopicLoading(heteroData.topicId, false);
-
return {
assistantMessageId: heteroData.assistantMessageId,
userMessageId: heteroData.userMessageId,
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 139f4a90e8c..ee5887742d4 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -583,7 +583,6 @@ export class GatewayActionImpl {
this.#get().moveQueuedMessages(messageMapKey(context), messageMapKey(execContext));
if (result.topicId) {
- if (!optimisticTopic) this.#get().internal_updateTopicLoading(result.topicId, true);
void this.#get().updateTopicStatus?.({
agentId: context.agentId,
groupId: context.groupId,
@@ -696,7 +695,6 @@ export class GatewayActionImpl {
// terminal-missing fallback so the op never sticks `running`.
if (!terminalReceived) this.#get().completeOperation(gatewayOpId);
if (result.topicId) {
- this.#get().internal_updateTopicLoading(result.topicId, false);
// A clean completion the user isn't watching is owned by
// `markTopicUnread` (status: 'unread'); skip the 'active' write so
// the two never race over the status field. Every other case (viewing,
@@ -848,8 +846,6 @@ export class GatewayActionImpl {
gatewayUrl: agentGatewayUrl,
onEvent: eventRouter,
onSessionComplete: ({ succeeded, terminalReceived, authFailed }) => {
- this.#get().internal_updateTopicLoading(topicId, false);
-
// A reconnect is a passive re-subscribe β€” it must not END a run it merely
// re-subscribed to. Only finalize when the close PROVES the op is over:
// - terminalReceived: a real agent_runtime_end / error streamed in, or
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index 6efb6b44eb4..5d8d3fd23f3 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -24,7 +24,6 @@ import type {
} from '@/store/chat/slices/agentRun/actions/lifecycle/types';
import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
-import { messageMapKey } from '@/store/chat/utils/messageMapKey';
// `agent_runtime_end` reasons that are NOT a clean completion: a mid-stream
// cancel and a deferred-tool park. These must NOT mark the topic unread, and
@@ -585,10 +584,11 @@ export const createGatewayEventHandler = (
// means visible output is done; the operation still waits for
// agent_runtime_end to preserve terminal side-effect ordering.
get().updateOperationMetadata(operationId, { visibleLoadingDone: true });
- const hasQueuedMessage =
- (get().queuedMessages?.[messageMapKey(context)]?.length ?? 0) > 0;
- if (context.topicId && !hasQueuedMessage)
- get().internal_updateTopicLoading(context.topicId, false);
+ // The sidebar "running" spinner is driven off `topic.status === 'running'`
+ // (persisted, reset at the terminal) for gateway/hetero runs β€” no
+ // client-only `topicLoadingIds` early-clear here, so the topic keeps
+ // spinning through the post-visible-output terminal side-effects until
+ // the run actually completes.
});
break;
}
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index e50c05515f6..fa42fb107b1 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -45,6 +45,7 @@ import {
import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
import { messageService } from '@/services/message';
import { threadService } from '@/services/thread';
+import { topicSelectors } from '@/store/chat/selectors';
import {
mergeQueuedMessages,
reconstructUploadFilesFromQueue,
@@ -55,7 +56,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import type { RunScope } from '../../lifecycle/types';
-import { createGatewayEventHandler } from '../gateway/gatewayEventHandler';
+import { createGatewayEventHandler, isCompletedRuntimeEnd } from '../gateway/gatewayEventHandler';
/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */
const generateThreadId = () => `thd_${createNanoId(16)()}`;
@@ -195,6 +196,28 @@ const isRecoverableResumeError = (
);
};
+/**
+ * How long the terminal callbacks wait for the persist queue to drain before
+ * proceeding regardless. Bounds the one place a completed run could otherwise
+ * hang forever β€” a queued DB write whose desktop-IPC reply never arrives β€” so op
+ * completion, the terminal forward, and the desktop notification still run.
+ * Topic status is reset ahead of this wait, so the sidebar spinner never depends
+ * on it at all.
+ */
+const PERSIST_DRAIN_TIMEOUT = 10_000;
+
+/** Await `queue`, but give up after `ms`; pending work is abandoned, not cancelled. */
+const drainWithTimeout = (queue: Promise<unknown>, ms: number): Promise<void> =>
+ new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, ms);
+ void Promise.resolve(queue)
+ .catch(() => {})
+ .finally(() => {
+ clearTimeout(timer);
+ resolve();
+ });
+ });
+
export interface HeterogeneousAgentExecutorParams {
assistantMessageId: string;
context: ConversationContext;
@@ -1403,10 +1426,38 @@ export const executeHeterogeneousAgent = async (
if (completed) return;
completed = true;
- // Wait for all tool persistence to finish before writing final state
- await persistQueue.catch(console.error);
-
const isErrorTerminal = deferredTerminalEvent?.type === 'error';
+
+ // Reset the sidebar "running" status BEFORE draining the persist queue.
+ // Topic status is independent of message persistence, so a stalled queue
+ // (e.g. a subagent-heavy run whose final DB write never settles) must not
+ // strand the topic spinning after the CLI has exited β€” the stuck-spinner
+ // this guards against. Content persistence + the terminal forward still
+ // wait for the (now bounded) drain below.
+ {
+ const reason = (deferredTerminalEvent?.data as { reason?: string } | undefined)?.reason;
+ if (isErrorTerminal) {
+ writeTopicStatus('failed');
+ } else if (!isAborted() && isCompletedRuntimeEnd(reason)) {
+ // Clean completion: the viewer sees 'active'; a background topic gets
+ // the unread badge (markTopicUnread self-guards on activeTopicId).
+ if (get().activeTopicId === context.topicId) writeTopicStatus('active');
+ else
+ get().markTopicUnread?.({
+ agentId: context.agentId,
+ groupId: context.groupId,
+ topicId: context.topicId,
+ });
+ } else {
+ // Cancel / deferred-tool park β€” back to a neutral 'active'.
+ writeTopicStatus('active');
+ }
+ }
+
+ // Bounded: a persist that never settles must not block op completion,
+ // the terminal forward, or the completion notification below.
+ await drainWithTimeout(persistQueue, PERSIST_DRAIN_TIMEOUT);
+
// Snapshot the final content BEFORE the terminal reduce resets the
// accumulator β€” used for the completion notification body below.
const finalContent = mainState.accContent;
@@ -1449,12 +1500,10 @@ export const executeHeterogeneousAgent = async (
pendingSubagentFlush.clear();
if (!isErrorTerminal) {
- // A clean completion the user isn't watching is owned by the gateway
- // handler's markTopicUnread (status: 'unread'); only clear back to
- // 'active' when the user is viewing so the two writes don't race.
- if (get().activeTopicId === context.topicId) writeTopicStatus('active');
- // NOW forward the deferred terminal event β€” handler will
- // fetchAndReplaceMessages and pick up the final persisted state.
+ // Topic status was already reset ahead of the drain (top of
+ // onComplete); forward the deferred terminal only so the handler runs
+ // the final fetchAndReplaceMessages + completeOperation against the
+ // now-persisted state.
eventHandler(terminalEvent);
}
@@ -1481,7 +1530,12 @@ export const executeHeterogeneousAgent = async (
if (retryWithoutResume(error)) return;
completed = true;
- await persistQueue.catch(console.error);
+ // Reset status ahead of the drain (see onComplete) so a stalled queue
+ // can't strand the spinner; persistTerminalError below re-asserts 'failed'
+ // with the full error UI.
+ writeTopicStatus(isAborted() ? 'active' : 'failed');
+
+ await drainWithTimeout(persistQueue, PERSIST_DRAIN_TIMEOUT);
const deferredMessageError =
deferredTerminalEvent?.type === 'error'
@@ -1637,6 +1691,32 @@ export const executeHeterogeneousAgent = async (
unsubscribe?.();
// Don't stopSession here β€” keep it alive for multi-turn resume.
// Session cleanup happens on topic deletion or Electron quit.
+
+ // Backstop: if neither onComplete nor onError ever ran (e.g. the
+ // heteroAgentSessionComplete IPC was missed, or its listener was torn down
+ // before it landed), the status reset above never happened. The CLI has
+ // exited by the time this linear path resolves, so a topic still persisted
+ // as 'running' would spin forever β€” reconcile it. Both terminal callbacks
+ // reset status ahead of their drain, so reaching here still 'running' means
+ // neither ran. Skipped on the resume-retry path, whose recursive run owns
+ // the lifecycle.
+ if (!resumeFallbackTriggered && context.topicId) {
+ // Best-effort: a finally must never throw (it would mask the real flow),
+ // and the topic map may be absent in edge/test states.
+ try {
+ const stuckRunning =
+ topicSelectors.getTopicById(context.topicId)(get())?.status === 'running';
+ if (stuckRunning) {
+ // Cast: TS narrows the closure-mutated `deferredTerminalEvent` back to
+ // `null` in this linear-flow scope (it can't see the async IPC writes).
+ const terminal = deferredTerminalEvent as AgentStreamEvent | null;
+ writeTopicStatus(terminal?.type === 'error' ? 'failed' : 'active');
+ get().completeOperation(operationId);
+ }
+ } catch (err) {
+ console.error('[HeterogeneousAgent] status reconcile backstop failed:', err);
+ }
+ }
}
if (fallbackPromise) {