π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(hetero): persist resume session id at stream_start so errors don't lose it (#16855)
Arvin Xu6b349e108048
diff --git a/packages/heterogeneous-agents/src/adapters/codex.test.ts b/packages/heterogeneous-agents/src/adapters/codex.test.tsindex b3cad360133..1a592dab078 100644--- a/packages/heterogeneous-agents/src/adapters/codex.test.ts+++ b/packages/heterogeneous-agents/src/adapters/codex.test.ts@@ -25,6 +25,30 @@ describe('CodexAdapter', () => {expect(adapter.sessionId).toBe('thread-123');});+ it('stamps the thread id on stream_start so the resume token persists early (ratelimit regression)', () => {+ // Regression: codex used to emit stream_start WITHOUT a sessionId, so the+ // resume token could only be persisted in `finish()` β a rate-limit error+ // (no finish / error branch) lost the session. After thread.started sets+ // it, every stream_start must carry it (matching claudeCode) so BOTH the+ // server (HeterogeneousPersistenceHandler) and the desktop renderer persist+ // it at stream_start time, before any error can short-circuit the run.++ // Before thread.started reports an id, stream_start omits sessionId.+ const withoutThread = new CodexAdapter();+ const [startBefore] = withoutThread.adapt({ type: 'turn.started' });+ expect(startBefore).toMatchObject({ data: { provider: 'codex' }, type: 'stream_start' });+ expect((startBefore.data as { sessionId?: string }).sessionId).toBeUndefined();++ // After thread.started, the stream_start carries the thread id.+ const withThread = new CodexAdapter();+ withThread.adapt({ thread_id: 'thread-xyz', type: 'thread.started' });+ const [startAfter] = withThread.adapt({ type: 'turn.started' });+ expect(startAfter).toMatchObject({+ data: { provider: 'codex', sessionId: 'thread-xyz' },+ type: 'stream_start',+ });+ });+it('emits stream start and text chunks for turn + agent messages', () => {const adapter = new CodexAdapter();diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.tsindex 88dfd3e8555..94fa57d193a 100644--- a/packages/heterogeneous-agents/src/adapters/codex.ts+++ b/packages/heterogeneous-agents/src/adapters/codex.ts@@ -1066,6 +1066,13 @@ export class CodexAdapter implements AgentEventAdapter {return {...(this.currentModel ? { model: this.currentModel } : {}),provider: CODEX_IDENTIFIER,+ // Stamp the codex thread id on every stream_start (set from+ // `thread.started`, which fires before `turn.started` emits this), so+ // the resume token persists at stream_start on BOTH the server+ // (HeterogeneousPersistenceHandler) and desktop renderer paths β matching+ // claudeCode. Without it codex relied solely on `finish()`, so a+ // rate-limit error (no finish / error branch) lost the session.+ ...(this.sessionId ? { sessionId: this.sessionId } : {}),...extra,};}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 79caf7a63cb..aad0c24a8d8 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -912,6 +912,47 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(contentWrite).toBeDefined();});+ it('persists the resume session id from stream_start even when sendPrompt rejects (ratelimit regression)', async () => {+ // Regression for tpc_k9pUn1yf151P: a rate-limit makes the CLI exit+ // non-zero, so `sendPrompt` REJECTS and control jumps to `catch` β+ // skipping the success-path metadata write. The session id used to be+ // lost, so the next turn started a FRESH session and dropped ~41k of+ // context. The stream_start early-write must land the resume token before+ // the rejection, regardless of how the run ends.+ const store = createMockStore();+ const get = vi.fn(() => store);++ // sendPrompt rejects (non-zero CLI exit) β drives the catch-block path,+ // so the success-path getSessionInfo write never runs.+ let rejectSendPrompt!: (e: unknown) => void;+ mockSendPrompt.mockReturnValue(+ new Promise<void>((_, rej) => {+ rejectSendPrompt = rej;+ }),+ );++ const executorPromise = executeHeterogeneousAgent(get, defaultParams);+ await flush();++ // CC reports its session id via system:init β stream_start (the early+ // resume-token write fires here), streams a little, then the run fails.+ ipc.emitRawLine('ipc-sess-1', ccInit('cc-sess-ratelimit'));+ ipc.emitRawLine('ipc-sess-1', ccText('msg_01', 'partial content'));+ await flush();++ // Reject sendPrompt β catch block (success path skipped entirely).+ rejectSendPrompt(new Error('rate limit exceeded'));+ await executorPromise.catch(() => {});+ await flush();++ // The resume token was persisted at stream_start, BEFORE the catch block+ // ran β so the next turn resumes this session instead of starting fresh.+ expect(store.updateTopicMetadata).toHaveBeenCalledWith(+ 'topic-1',+ expect.objectContaining({ heteroSessionId: 'cc-sess-ratelimit' }),+ );+ });+it('should not persist streamed auth error echoes as assistant content when the session errors', async () => {const rawAuthError ='Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}';diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex d82b23318eb..5b53f4c5b80 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -1190,7 +1190,32 @@ export const executeHeterogeneousAgent = async (// server handler). Stable per run; the copy makes a mid-topic fork visible.if (event.type === 'stream_start') {const sid = (event.data as { sessionId?: string } | undefined)?.sessionId;- if (typeof sid === 'string' && sid.length > 0) heteroSessionId = sid;+ if (typeof sid === 'string' && sid.length > 0 && sid !== heteroSessionId) {+ heteroSessionId = sid;+ // Persist the resume token the MOMENT the CLI reports it β but only on+ // a FRESH run. The success-path write below only runs when `sendPrompt`+ // resolves; a rate-limit / API error rejects it and jumps straight to+ // `catch`, so without this early write the token is lost and the next+ // turn starts a fresh session (the `tpc_k9pUn1yf151P` regression). On a+ // `--resume` run the id is already in metadata (it's where+ // `resumeSessionId` came from), so skip β a failed resume is cleaned up+ // by the retry/clear path, not re-stamped here. Fire-and-forget ++ // guarded so it never throws past the persistQueue chain nor delays+ // event processing; the success path re-writes it on completion.+ if (!resumeSessionId && context.topicId && updateTopicMetadata) {+ const topicMetadata = getTopicMetadataById(get(), context.topicId);+ updateTopicMetadata(context.topicId, {+ heteroSessionId: sid,+ heteroSessionIdByWorkingDirectory: setHeteroSessionIdForWorkingDirectory(+ topicMetadata,+ workingDirectory,+ sid,+ ),+ }).catch((err) =>+ console.error('[HeterogeneousAgent] Failed to early-persist resume session id:', err),+ );+ }+ }}const ctx: MainAgentReduceCtx = {