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(desktop): clean up heterogeneous agent run sessions (#18250)

AmAzing-a469efd49fb1
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 c839e0c82cb..154654d344c 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -1946,6 +1946,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
workingDirectory: '/Users/me/repo',
workingDirectoryConfig: { path: '/Users/me/repo' },
});
+ expect(mockStopSession.mock.calls).toEqual([['ipc-sess-1'], ['ipc-sess-2']]);
});
it('persists a newly reported session id even when sendPrompt exits non-zero', async () => {
@@ -2192,6 +2193,54 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
});
+ describe('Desktop IPC session lifecycle', () => {
+ it('persists the native resume session before releasing the temporary run session', async () => {
+ const store = createMockStore();
+
+ await runWithEvents([ccInit('native-session-1'), ccResult()], { store });
+
+ expect(store.updateTopicMetadata).toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({ heteroSessionId: 'native-session-1' }),
+ );
+ expect(mockStopSession).toHaveBeenCalledOnce();
+ expect(mockStopSession).toHaveBeenCalledWith('ipc-sess-1');
+
+ const lastMetadataSave = store.updateTopicMetadata.mock.invocationCallOrder.at(-1)!;
+ const stopSessionCall = mockStopSession.mock.invocationCallOrder[0];
+ expect(stopSessionCall).toBeGreaterThan(lastMetadataSave);
+ });
+
+ it('preserves the run error when temporary session cleanup fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const runError = new Error('prompt failed');
+ const cleanupError = new Error('cleanup failed');
+ mockSendPrompt.mockRejectedValueOnce(runError);
+ mockStopSession.mockRejectedValueOnce(cleanupError);
+
+ try {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+
+ await expect(executeHeterogeneousAgent(get, defaultParams)).resolves.toBeUndefined();
+
+ expect(mockUpdateMessageError).toHaveBeenCalledWith(
+ 'ast-initial',
+ expect.objectContaining({ message: 'prompt failed' }),
+ expect.any(Object),
+ );
+ expect(mockStopSession).toHaveBeenCalledOnce();
+ expect(mockStopSession).toHaveBeenCalledWith('ipc-sess-1');
+ expect(consoleError).toHaveBeenCalledWith(
+ '[HeterogeneousAgent] IPC run session cleanup failed:',
+ cleanupError,
+ );
+ } finally {
+ consoleError.mockRestore();
+ }
+ });
+ });
+
describe('Codex multi-turn persistence', () => {
it('optimistically replaces TodoProgress state while Codex is still running', async () => {
const { store } = await runWithEvents(
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 1fedf89d1c3..aedf03cc453 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -588,7 +588,7 @@ export const executeHeterogeneousAgent = async (
);
};
- let agentSessionId: string | undefined;
+ let ipcRunSessionId: string | undefined;
let unsubscribe: (() => void) | undefined;
let completed = false;
let fallbackPromise: Promise<void> | undefined;
@@ -1848,15 +1848,15 @@ export const executeHeterogeneousAgent = async (
runExternalAccountId = quotaAccountPlan.externalAccountId;
});
}
- agentSessionId = result.sessionId;
- if (!agentSessionId) throw new Error('Agent session returned no sessionId');
+ ipcRunSessionId = result.sessionId;
+ if (!ipcRunSessionId) throw new Error('Agent session returned no sessionId');
writeTopicStatus('running');
// Register cancel hook on the operation β€” when the user hits Stop, the op
// framework calls this; we SIGINT the CC process via the main-process IPC
// so the CLI exits instead of running to completion off-screen.
- const sidForCancel = agentSessionId;
+ const sidForCancel = ipcRunSessionId;
get().onOperationCancel?.(operationId, () => {
heterogeneousAgentService.cancelSession(sidForCancel).catch(() => {});
});
@@ -2091,7 +2091,7 @@ export const executeHeterogeneousAgent = async (
}
};
- unsubscribe = subscribeBroadcasts(agentSessionId, {
+ unsubscribe = subscribeBroadcasts(ipcRunSessionId, {
onStreamEvent: handleStreamEvent,
onComplete: () => {
@@ -2330,7 +2330,7 @@ export const executeHeterogeneousAgent = async (
operationId,
prompt: message,
...(resumeReplayMessages?.length ? { resumeReplayMessages } : {}),
- sessionId: agentSessionId,
+ sessionId: ipcRunSessionId,
systemContext: systemContext || undefined,
topicId: context.topicId ?? undefined,
});
@@ -2348,7 +2348,7 @@ export const executeHeterogeneousAgent = async (
// IPC, which already returns the freshest `agentSessionId` main has
// mirrored from `pipeline.sessionId`.
const sessionInfo = await heterogeneousAgentService
- .getSessionInfo(agentSessionId)
+ .getSessionInfo(ipcRunSessionId)
.catch(() => undefined);
if (sessionInfo?.agentSessionId && context.topicId) {
// Best-effort: a rejected metadata save must NOT throw past the queue
@@ -2446,8 +2446,18 @@ export const executeHeterogeneousAgent = async (
} finally {
await waitForCompletionCallback();
unsubscribe?.();
- // Don't stopSession here β€” keep it alive for multi-turn resume.
- // Session cleanup happens on topic deletion or Electron quit.
+ // The desktop IPC session only owns this run's config and process handles.
+ // Multi-turn resume uses the native agentSessionId persisted above, so the
+ // IPC session must be released after every run instead of accumulating in
+ // the Electron main-process session map until quit.
+ if (ipcRunSessionId) {
+ try {
+ await heterogeneousAgentService.stopSession(ipcRunSessionId);
+ } catch (err) {
+ // Cleanup is best-effort and must not replace the run's real outcome.
+ console.error('[HeterogeneousAgent] IPC run session cleanup failed:', err);
+ }
+ }
// Backstop: if neither onComplete nor onError ever ran (e.g. the
// heteroAgentSessionComplete IPC was missed, or its listener was torn down