π€― 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(desktop): isolate concurrent Codex app-server runs (#20468)
Nekocc92e625a4d8
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 87eb2d307e6..23d94eb41fe 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -65,16 +65,13 @@ import {} from '@lobechat/heterogeneous-agents/rpc';import type {AgentStreamEvent,- DshAcpSessionHandle,+ CodexAppServerClient,UsageData,} from '@lobechat/heterogeneous-agents/spawn';import {AcpRpcResponseError,AgentStreamPipeline,buildAgentInput,- buildCodexAppServerArgs,- buildCodexAppServerInput,- buildCodexAppServerThreadParams,buildCursorAcpArgs,buildCursorAcpPrompt,buildDevinAcpArgs,@@ -86,8 +83,6 @@ import {buildTraeAcpArgs,buildTraeAcpPrompt,ClaudeAgentSdkSession,- CodexAppServerClient,- CodexThreadSession,createFileStoreImageUploader,CursorAcpSession,detectDshCommand,@@ -97,7 +92,6 @@ import {ensureClaudeCodeResumeTranscript,getCodexAppServerUnsupportedArgs,GrokAcpSession,- isCodexAppServerCompatibilityError,isCursorAcpSessionNotFoundError,isDevinAcpSessionNotFoundError,isDroidAcpSessionNotFoundError,@@ -113,7 +107,6 @@ import {import {buildClaudeCodeReplayTurn,claudeCodeReplayTurnMatchesPrompt,- truncateTitle,} from '@lobechat/heterogeneous-agents/transcript';import {describeUnusableWorkingDirectory,@@ -122,8 +115,6 @@ import {} from '@lobechat/heterogeneous-agents/workingDirectory';import type {HeterogeneousAgentModelCatalog,- HeterogeneousServerDefaultApiConfig,- HeteroSessionImportMessage,ListHeterogeneousAgentModelsParams,} from '@lobechat/types';import {@@ -186,6 +177,8 @@ import {import { createLogger } from '@/utils/logger';import BrowserControlCtr from './BrowserControlCtr';+import { sendPromptWithCodexAppServer } from './codexAppServer';+import type { AgentSession, CliTraceSession, SendPromptParams } from './heterogeneousAgentSession';import RemoteServerConfigCtr from './RemoteServerConfigCtr';const logger = createLogger('controllers:HeterogeneousAgentCtr');@@ -342,71 +335,6 @@ interface BrowserRunBinding {topicId?: string;}-interface SendPromptParams {- /**- * Agent this run belongs to. Rides along to the renderer so it can tell- * whether revealing the browser panel would yank the user's view to a run- * they aren't watching.- */- agentId?: string;- /** Assistant row this run streams into β recorded so recovery can scope to its branch. */- assistantMessageId?: string;- /** Image attachments to include in the prompt (downloaded from url, cached by id) */- imageList?: HeterogeneousAgentImageAttachment[];- /**- * Renderer-side operation id stamped onto every emitted `AgentStreamEvent`.- * Required: producer-side conversion is the V3 contract β by the time events- * reach the renderer they must already carry the operation they belong to.- */- operationId: string;- prompt: string;- /**- * Do not spawn the CLI. Instead, read the last turn of the session's on-disk- * transcript (Claude Code only) and stream it through the same pipeline a- * live process feeds, so a turn that finished or died while the app was- * down lands in the topic exactly as it would have live. Resolves with the- * replay outcome so the caller knows whether a `--resume` continuation is- * still owed.- */- replayTranscript?: boolean;- /**- * Claude profile root the transcript was written under. Passed by restart- * recovery from its ledger: this turn's own account routing may resolve a- * different profile, but the file to read is the one the interrupted run- * actually produced.- */- replayTranscriptConfigDir?: string;- /**- * ISO spawn time of the interrupted run whose transcript is being replayed.- * Pins the replay to that run's own turn β see- * `claudeCodeReplayTurnMatchesPrompt`.- */- replayTranscriptStartedAt?: string;- /**- * Prior conversation turns used to rebuild a Claude Code transcript that the- * CLI garbage-collected (`cleanupPeriodDays`, default 30 days). Only consumed- * when resuming and the on-disk transcript is missing β see- * `ensureClaudeCodeResumeTranscript`. Without it, `--resume <staleId>` fails- * with "No conversation found with session ID".- */- resumeReplayMessages?: HeteroSessionImportMessage[];- sessionId: string;- /** Extra context injected before the user prompt without mutating the prompt text. */- systemContext?: string;- /**- * Topic this run belongs to. Binds the op to its in-app browser session- * (`topic:<topicId>`) so the browser MCP tools act on the right page.- *- * Not to be confused with `sessionId`, which is the CC/Codex agent session β- * a different namespace entirely.- */- topicId?: string;- /** User the run belongs to; recovery only releases runs of the signed-in one. */- userId?: string;- /** Workspace the run belongs to; recovery only releases runs of the active one. */- workspaceId?: string;-}-interface CancelSessionParams {sessionId: string;}@@ -473,82 +401,8 @@ export interface SessionInfo {// βββ Internal session tracking βββ-interface AgentSession {- agentSessionId?: string;- agentType: HeterogeneousAgentType;- appServerSession?: CodexThreadSession;- args: string[];- /**- * True when *we* initiated the kill (cancelSession / stopSession / before-quit).- * The `exit` handler uses this to route signal-induced non-zero exits through- * the `complete` broadcast instead of surfacing them as runtime errors β- * SIGINT(130) / SIGTERM(143) / SIGKILL(137) from our own kill paths are- * intentional, not agent failures.- */- cancelledByUs?: boolean;- codexAppServerFallback?: boolean;- command: string;- cursorAcpSession?: CursorAcpSession;- cwd?: string;- devinAcpSession?: DevinAcpSession;- droidAcpSession?: DroidAcpSession;- dshSession?: DshAcpSessionHandle;- env?: Record<string, string>;- grokAcpSession?: GrokAcpSession;- hostedProviderBinding?: HostedProviderBinding;- model?: string;- modelSource?: string;- modelVerificationLastAttemptAt?: number;- modelVerificationLastAttemptSessionId?: string;- /** Active pi RPC run (per-run process; cleared when the run settles). */- piRpcSession?: PiRpcSession;- process?: ChildProcess;- processOwner?: { topicId?: string; agentId?: string };- /**- * Absolute CLI path resolved by spawn preflight detection. Used for spawn()- * when the configured command is bare: detection can find the CLI through- * the login-shell PATH or a well-known install location (e.g. an app-bundled- * Codex CLI) that plain spawn() with the inherited env can't resolve.- */- resolvedCommandPath?: string;- /**- * PATH the preflight detector used to resolve `resolvedCommandPath`, set only- * when it fell back to the login-shell PATH. Merged into the child PATH at- * spawn so a `#!/usr/bin/env node` shim still finds its interpreter β the- * shim resolving in preflight doesn't guarantee `node` is on the leaner- * inherited PATH (Finder-launched Electron).- */- resolvedCommandSearchPath?: string;- resumeSessionId?: string;- sdkSession?: ClaudeAgentSdkSession;- /** Present iff the session runs on the server-default (LobeHub) binding. */- serverDefaultApiConfig?: HeterogeneousServerDefaultApiConfig;- serverOperationToken?: string;- sessionId: string;- traeAcpSession?: TraeAcpSession;- /**- * Set when this turn had to rebuild a garbage-collected Claude Code- * transcript before resuming it. The rebuild is assembled from persisted- * chat rows, which never carried the session-scoped prompt context, so the- * resumed transcript has not seen it even though the session id survives.- */- transcriptRebuiltForResume?: boolean;- useClaudeCodeSdk?: boolean;- useCodexAppServer?: boolean;- verifiedModel?: string;- verifiedModelContextWindow?: number;- verifiedModelProvider?: string;- verifiedModelSessionId?: string;- verifiedModelSourceFile?: string;-}-type SessionErrorPayload = HeterogeneousAgentSessionError | string;-interface CliTraceSession {- dir: string;- writeQueue: Promise<void>;-}-export type LhHeteroExecCancellationResult = HeterogeneousAgentCancellationResult;interface LhHeteroExecTask {@@ -778,7 +632,7 @@ export default class HeterogeneousAgentCtr {private builtinMcpServer?: LobeBuiltinMcpServer;private builtinMcpStartPromise?: Promise<LobeBuiltinMcpServer>;/** One lazy, long-lived native Codex app-server connection shared by thread sessions. */- private codexAppServerClient?: CodexAppServerClient;+ private readonly codexAppServerState: { client?: CodexAppServerClient } = {};/** Cross-turn pi RPC process pool (reuse + idle reaping). */private readonly piRpcPool: PiRpcPool;private shuttingDown = false;@@ -2317,198 +2171,39 @@ export default class HeterogeneousAgentCtr {}}- private async sendPromptWithCodexAppServer(+ /**+ * Delegates the Codex transport while retaining controller-owned session services.+ *+ * Call stack:+ *+ * sendPrompt -> runtimeDispatchers -> {@link sendPromptWithCodexAppServer}+ */+ private sendPromptWithCodexAppServer(params: SendPromptParams,session: AgentSession,): Promise<boolean> {- const cwd = session.cwd || electronApp.getPath('desktop');- // One app-server serves multiple topics; ownership belongs to each thread, not its process.- const spawnEnv = this.buildSessionSpawnEnv(session, false);- const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);- const promptInput = buildHeterogeneousPrompt({- imageList: params.imageList,- isNewSession: this.needsSessionIntroduction(session),- prompt: params.prompt,- systemContext: params.systemContext,- });- let inputPlan;- try {- inputPlan = await buildAgentInput('codex', promptInput, { cacheDir: this.fileCacheDir });- } catch (error) {- logger.error('Failed to prepare Codex app-server input:', error);- throw new Error(- `Failed to attach image(s) to Codex app-server: ${this.getErrorMessage(error) || 'Unknown error'}`,- { cause: error },- );- }-- const input = buildCodexAppServerInput(inputPlan);- const appServerArgs = buildCodexAppServerArgs(session.args);- const initialModel = await resolveCodexInitialModel({ args: session.args, env: spawnEnv });- if (initialModel?.model) {- session.model = initialModel.model;- session.modelSource = initialModel.source;- }- const initialCumulativeUsage = session.agentSessionId- ? (await readCodexSessionModel(session.agentSessionId, { env: spawnEnv }))?.cumulativeUsage- : undefined;- const inputPayload = `${JSON.stringify(input)}\n`;- const traceSession = await this.createCliTraceSession({- cliArgs: appServerArgs,- cwd,- imageList: params.imageList ?? [],+ return sendPromptWithCodexAppServer(+ {+ clientState: this.codexAppServerState,+ fileCacheDir: this.fileCacheDir,+ appendCliTraceFile: this.appendCliTraceFile.bind(this),+ broadcast: this.broadcast.bind(this),+ buildSessionSpawnEnv: this.buildSessionSpawnEnv.bind(this),+ completeCancelledSessionBeforeLaunch: this.completeCancelledSessionBeforeLaunch.bind(this),+ createCliTraceSession: this.createCliTraceSession.bind(this),+ flushCliTrace: this.flushCliTrace.bind(this),+ getErrorMessage: this.getErrorMessage.bind(this),+ getInflightRuns: this.getInflightRuns.bind(this),+ getSessionErrorPayload: this.getSessionErrorPayload.bind(this),+ needsSessionIntroduction: this.needsSessionIntroduction.bind(this),+ recordInflightRun: this.recordInflightRun.bind(this),+ resolveSessionCommand: this.resolveSessionCommand.bind(this),+ writeCliTraceFile: this.writeCliTraceFile.bind(this),+ writeCliTraceJson: this.writeCliTraceJson.bind(this),+ },+ params,session,- stdinPayload: inputPayload,- });- void this.writeCliTraceFile(traceSession, 'stdin.txt', inputPayload);-- if (session.cancelledByUs) {- await this.completeCancelledSessionBeforeLaunch(session);- return true;- }-- const clientOptions = {- args: appServerArgs.slice(0, -1),- clientVersion: electronApp.getVersion(),- commandPath,- cwd,- env: spawnEnv,- };- const existingClient = this.codexAppServerClient;- if (existingClient && !existingClient.canReuseFor(clientOptions)) {- if (!existingClient.hasConsumers) {- existingClient.close();- if (this.codexAppServerClient === existingClient) this.codexAppServerClient = undefined;- } else {- const message =- 'The running Codex app-server uses a different binary, global configuration, or environment';- logger.error('Cannot reuse the native Codex app-server client:', {- sessionId: session.sessionId,- });- void this.writeCliTraceJson(traceSession, 'process-error.json', {- message,- transport: 'codex-app-server',- });- await this.flushCliTrace(traceSession);- this.broadcast('heteroAgentSessionError', {- error: message,- sessionId: session.sessionId,- });- throw new Error(message);- }- }-- const client =- this.codexAppServerClient ??- (this.codexAppServerClient = new CodexAppServerClient(clientOptions));- const appServerSession =- session.appServerSession ??- new CodexThreadSession({- client,- initialCumulativeUsage,- initialModel: session.model,- initialThreadId: session.agentSessionId,- threadName: truncateTitle(params.prompt),- onEvents: async (events) => {- for (const event of events) {- this.broadcast('heteroAgentEvent', {- event,- sessionId: session.sessionId,- });- }- },- onModel: (model) => {- session.model = model;- session.modelSource = 'codex-app-server';- },- onRuntimeStatus: (status) => {- this.broadcast('heteroAgentRuntimeStatus', status);- },- onSessionId: (agentSessionId) => {- if (agentSessionId !== session.agentSessionId) session.agentSessionId = agentSessionId;- },- sessionId: session.sessionId,- threadParams: buildCodexAppServerThreadParams(session.args, cwd, session.model),- });- session.appServerSession = appServerSession;-- logger.info('Starting Codex app-server session:', {- commandPath,- cwd,- sessionId: session.sessionId,- });-- try {- await appServerSession.run({- input,- onRawMessage: (line) => this.appendCliTraceFile(traceSession, 'stdout.jsonl', line),- operationId: params.operationId,- });- void this.writeCliTraceJson(traceSession, 'exit.json', {- finishedAt: new Date().toISOString(),- transport: 'codex-app-server',- });- await this.flushCliTrace(traceSession);- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });- return true;- } catch (error) {- if (appServerSession.canFallbackToExec && isCodexAppServerCompatibilityError(error)) {- session.codexAppServerFallback = true;- logger.warn('Falling back to codex exec because native app-server is unavailable:', {- message: this.getErrorMessage(error),- sessionId: session.sessionId,- });- void this.writeCliTraceJson(traceSession, 'fallback.json', {- message: this.getErrorMessage(error),- transport: 'codex-app-server',- });- await this.flushCliTrace(traceSession);- this.broadcast('heteroAgentEvent', {- event: {- data: {- message:- 'Codex app-server is unavailable or incompatible. Upgrade Codex to use the Labs transport; continuing with codex exec.',- },- operationId: params.operationId,- stepIndex: 0,- timestamp: Date.now(),- type: 'stream_retry',- } satisfies AgentStreamEvent,- sessionId: session.sessionId,- });- appServerSession.close();- if (session.appServerSession === appServerSession) session.appServerSession = undefined;- if (!client.hasConsumers) {- client.close();- if (this.codexAppServerClient === client) this.codexAppServerClient = undefined;- }- return false;- }-- logger.error('Codex app-server session error:', error);- appServerSession.close();- if (session.appServerSession === appServerSession) session.appServerSession = undefined;- void this.writeCliTraceJson(traceSession, 'process-error.json', {- message: error instanceof Error ? error.message : String(error),- name: error instanceof Error ? error.name : 'Error',- transport: 'codex-app-server',- });- await this.flushCliTrace(traceSession);-- if (session.cancelledByUs) {- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });- return true;- }-- const sessionError = this.getSessionErrorPayload(error, session);- this.broadcast('heteroAgentSessionError', {- error: sessionError,- sessionId: session.sessionId,- });- throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {- cause: error,- });- }+ );}private async sendPromptWithGrokAcp(@@ -4333,8 +4028,8 @@ export default class HeterogeneousAgentCtr {this.killProcessTree(session.process, 'SIGTERM');}}- this.codexAppServerClient?.close();- this.codexAppServerClient = undefined;+ this.codexAppServerState.client?.close();+ this.codexAppServerState.client = undefined;// Pooled pi processes outlive their IPC sessions β reap them on quit.piClosing.push(this.piRpcPool.closeAll());this.sessions.clear();diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.codexLifecycle.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.codexLifecycle.test.tsnew file mode 100644index 00000000000..97ba416c8ec--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.codexLifecycle.test.ts@@ -0,0 +1,197 @@+import type * as fsModule from 'node:fs';+import { existsSync, statSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import type * as spawnModule from '@lobechat/heterogeneous-agents/spawn';+import * as managedProcess from '@lobechat/utils/managedProcess';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import HeterogeneousAgentCtr from '../HeterogeneousAgentImpl';++const controls = vi.hoisted(() => ({+ codexAppServerCanReuse: { value: true },+ codexAppServerClientCloseMock: vi.fn(),+ codexAppServerClientConstructMock: vi.fn(),+ codexAppServerCloseMock: vi.fn(),+ codexAppServerConsumerCount: { value: 0 },+ codexAppServerConstructMock: vi.fn(),+ codexAppServerInterruptMock: vi.fn(),+ codexAppServerRunMock: vi.fn(),+ codexAppServerShouldFailAfterThread: { value: false },+ codexAppServerShouldFailResume: { value: false },+ codexAppServerShouldFallback: { value: false },+}));+const {+ codexAppServerClientConstructMock,+ codexAppServerConstructMock,+ codexAppServerRunMock,+ codexAppServerCloseMock,+} = controls;++vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {+ const { createCodexAppServerMocks } = await import('./testUtils');+ const actual = await importOriginal<typeof spawnModule>();+ return { ...actual, ...createCodexAppServerMocks(actual, controls) };+});++vi.mock('node:fs', async (importOriginal) => {+ const actual = await importOriginal<typeof fsModule>();+ return { ...actual, existsSync: vi.fn(() => true), statSync: vi.fn() };+});++vi.mock('@/modules/binaries', () => ({+ detectHeterogeneousCliCommand: vi.fn(async () => ({+ available: true,+ path: '/usr/local/bin/codex',+ resolvedPathEnv: '/usr/local/bin:/usr/bin',+ })),+}));++/** @example Concurrent topics retain their provenance and reload can release a native thread. */+describe('HeterogeneousAgentCtr Codex lifecycle', () => {+ let appStoragePath: string;++ beforeEach(async () => {+ vi.clearAllMocks();+ controls.codexAppServerConsumerCount.value = 0;+ controls.codexAppServerRunMock.mockReset();+ vi.stubEnv('LOBE_CODEX_APP_SERVER', '');+ vi.mocked(existsSync).mockReturnValue(true);+ // The fake desktop path is a directory for spawn preflight; ledger IO stays real.+ vi.mocked(statSync).mockReturnValue({ isDirectory: () => true } as ReturnType<typeof statSync>);+ appStoragePath = await mkdtemp(path.join(os.tmpdir(), 'lobehub-codex-lifecycle-'));+ });++ afterEach(async () => {+ vi.unstubAllEnvs();+ await rm(appStoragePath, { force: true, recursive: true });+ });++ /** @example Two overlapping turns use one compatible client and independent provenance. */+ it('reuses one native app-server client for sessions owned by different topics and agents', async () => {+ let releaseFirstRun!: () => void;+ const firstRun = new Promise<void>((resolve) => {+ releaseFirstRun = resolve;+ });+ const registry = new managedProcess.ManagedProcessRegistry();+ const environment = vi+ .spyOn(managedProcess, 'managedProcessEnvironment')+ .mockImplementation(registry.environment.bind(registry));+ try {+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as unknown as App);+ const first = await ctr.startSession({+ agentType: 'codex',+ command: 'codex',+ env: {+ LOBEHUB_AGENT_ID: 'agent-1',+ LOBEHUB_TOPIC_ID: 'topic-1',+ LOBEHUB_OPERATION_ID: 'op-1',+ },+ useCodexAppServer: true,+ });+ const second = await ctr.startSession({+ agentType: 'codex',+ command: 'codex',+ env: {+ LOBEHUB_AGENT_ID: 'agent-2',+ LOBEHUB_TOPIC_ID: 'topic-2',+ LOBEHUB_OPERATION_ID: 'op-2',+ },+ useCodexAppServer: true,+ });++ codexAppServerRunMock.mockImplementationOnce(() => firstRun);+ const firstPrompt = ctr.sendPrompt({+ agentId: 'agent-1',+ topicId: 'topic-1',+ operationId: 'op-1',+ prompt: 'first',+ sessionId: first.sessionId,+ });+ await vi.waitFor(() => expect(codexAppServerRunMock).toHaveBeenCalledTimes(1));+ const secondPrompt = ctr.sendPrompt({+ agentId: 'agent-2',+ topicId: 'topic-2',+ operationId: 'op-2',+ prompt: 'second',+ sessionId: second.sessionId,+ });++ // The second turn starts while the first still holds its consumer.+ await vi.waitFor(() => expect(codexAppServerRunMock).toHaveBeenCalledTimes(2));+ releaseFirstRun();+ await Promise.all([firstPrompt, secondPrompt]);+ expect(codexAppServerRunMock.mock.calls.map(([options]) => options.provenance)).toEqual([+ {+ LOBEHUB_AGENT_ID: 'agent-1',+ LOBEHUB_OPERATION_ID: 'op-1',+ LOBEHUB_TOPIC_ID: 'topic-1',+ },+ {+ LOBEHUB_AGENT_ID: 'agent-2',+ LOBEHUB_OPERATION_ID: 'op-2',+ LOBEHUB_TOPIC_ID: 'topic-2',+ },+ ]);+ expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);+ expect(codexAppServerConstructMock).toHaveBeenCalledTimes(2);+ const { env } = codexAppServerClientConstructMock.mock.calls[0][0];+ expect(env.LOBEHUB_PROCESS_TOPIC).toBeUndefined();+ expect(env.AGENT_BROWSER_NAMESPACE).toBeUndefined();+ } finally {+ releaseFirstRun();+ environment.mockRestore();+ }+ });++ /** @example Renderer recovery finds and closes an orphaned app-server run. */+ it('records app-server runs so reload recovery stops the orphaned session', async () => {+ let releaseRun!: () => void;+ codexAppServerRunMock.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ releaseRun = resolve;+ }),+ );+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as unknown as App);+ const { sessionId } = await ctr.startSession({+ agentType: 'codex',+ command: 'codex',+ resumeSessionId: 'thread-existing',+ useCodexAppServer: true,+ });+ const prompt = ctr.sendPrompt({+ agentId: 'agent-1',+ operationId: 'op-1',+ prompt: 'still running',+ sessionId,+ topicId: 'topic-1',+ });+ await vi.waitFor(() => expect(codexAppServerRunMock).toHaveBeenCalledTimes(1));++ // A reloaded renderer runs restart recovery before the next send in the same topic.+ // Without the ledger entry the old session keeps the native thread claimed.+ await expect(ctr.listInterruptedRuns({})).resolves.toEqual([+ expect.objectContaining({+ agentSessionId: 'thread-existing',+ agentType: 'codex',+ ipcSessionId: sessionId,+ topicId: 'topic-1',+ }),+ ]);+ expect(codexAppServerCloseMock).toHaveBeenCalled();++ releaseRun();+ await prompt;+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex 0a60a159842..970fd16b5e1 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -11,9 +11,8 @@ import {HETERO_EXEC_INHERIT_PROCESS_GROUP_ENV,lobeHubCliGuide,} from '@lobechat/heterogeneous-agents/protocol';-import type { CodexAppServerClient as NativeCodexAppServerClient } from '@lobechat/heterogeneous-agents/spawn';+import type * as spawnModule from '@lobechat/heterogeneous-agents/spawn';import { AcpRpcResponseError } from '@lobechat/heterogeneous-agents/spawn';-import * as managedProcess from '@lobechat/utils/managedProcess';// `electron` is mocked below; this binding is the mock object so tests can// flip `isPackaged` to exercise the packaged-build tracing gate.import { app as electronAppMock } from 'electron';@@ -265,7 +264,8 @@ const { ensureResumeTranscriptMock, readClaudeCodeSessionCostMock } = vi.hoisted}));vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {- const actual = await importOriginal<Record<string, unknown>>();+ const { createCodexAppServerMocks } = await import('./testUtils');+ const actual = await importOriginal<typeof spawnModule>();class MockClaudeAgentSdkSession {constructor(private readonly options: any) {@@ -319,95 +319,6 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {}}- class MockCodexAppServerClient extends (actual.CodexAppServerClient as typeof NativeCodexAppServerClient) {- constructor(options: any) {- super(options);- codexAppServerClientConstructMock(options);- }-- canReuseFor(options: Parameters<NativeCodexAppServerClient['canReuseFor']>[0]) {- return codexAppServerCanReuse.value && super.canReuseFor(options);- }-- get hasConsumers() {- return codexAppServerConsumerCount.value > 0;- }-- close() {- codexAppServerClientCloseMock();- }- }-- class MockCodexThreadSession {- canFallbackToExec = true;- private closed = false;-- constructor(private readonly options: any) {- codexAppServerConsumerCount.value += 1;- codexAppServerConstructMock(options);- }-- close() {- if (!this.closed) {- this.closed = true;- codexAppServerConsumerCount.value -= 1;- }- codexAppServerCloseMock();- }-- async interrupt() {- return codexAppServerInterruptMock();- }-- async run(runOptions: any) {- codexAppServerRunMock(runOptions);- if (codexAppServerShouldFailResume.value && this.options.initialThreadId) {- this.canFallbackToExec = false;- const error = new Error('Thread not found');- error.name = 'CodexAppServerConnectionError';- throw error;- }- if (codexAppServerShouldFallback.value) {- const error = new Error('Method not found: initialize');- error.name = 'CodexAppServerConnectionError';- throw error;- }-- const now = Date.now();- this.canFallbackToExec = false;- if (codexAppServerShouldFailAfterThread.value) {- const error = new Error('Codex app-server disconnected');- error.name = 'CodexAppServerConnectionError';- throw error;- }- this.options.onRuntimeStatus({- activeTasks: [],- lastEventAt: now,- operationId: runOptions.operationId,- sessionId: this.options.sessionId,- state: 'running',- transport: 'codex-app-server',- });- this.options.onSessionId('thread_app_server');- await this.options.onEvents([- {- data: { reason: 'complete', transport: 'codex-app-server' },- operationId: runOptions.operationId,- stepIndex: 0,- timestamp: now,- type: 'agent_runtime_end',- },- ]);- this.options.onRuntimeStatus({- activeTasks: [],- lastEventAt: now,- sessionId: this.options.sessionId,- state: 'closed',- transport: 'codex-app-server',- });- }- }-class MockGrokAcpSession {constructor(private readonly options: any) {grokAcpSessionConstructMock(options);@@ -612,8 +523,19 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {ensureClaudeCodeResumeTranscript: ensureResumeTranscriptMock,readClaudeCodeSessionCost: readClaudeCodeSessionCostMock,ClaudeAgentSdkSession: MockClaudeAgentSdkSession,- CodexAppServerClient: MockCodexAppServerClient,- CodexThreadSession: MockCodexThreadSession,+ ...createCodexAppServerMocks(actual, {+ codexAppServerCanReuse,+ codexAppServerClientCloseMock,+ codexAppServerClientConstructMock,+ codexAppServerCloseMock,+ codexAppServerConsumerCount,+ codexAppServerConstructMock,+ codexAppServerInterruptMock,+ codexAppServerRunMock,+ codexAppServerShouldFailAfterThread,+ codexAppServerShouldFailResume,+ codexAppServerShouldFallback,+ }),CursorAcpSession: MockCursorAcpSession,DroidAcpSession: MockDroidAcpSession,DevinAcpSession: MockDevinAcpSession,@@ -3639,52 +3561,6 @@ describe('HeterogeneousAgentCtr', () => {expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });});- it('reuses one native app-server client for sessions owned by different topics and agents', async () => {- const registry = new managedProcess.ManagedProcessRegistry();- const environment = vi- .spyOn(managedProcess, 'managedProcessEnvironment')- .mockImplementation(registry.environment.bind(registry));- try {- const ctr = new HeterogeneousAgentCtr({- appStoragePath,- storeManager: { get: vi.fn() },- } as any);- const first = await ctr.startSession({- agentType: 'codex',- command: 'codex',- useCodexAppServer: true,- });- const second = await ctr.startSession({- agentType: 'codex',- command: 'codex',- useCodexAppServer: true,- });-- await ctr.sendPrompt({- agentId: 'agent-1',- topicId: 'topic-1',- operationId: 'op-1',- prompt: 'first',- sessionId: first.sessionId,- });- await ctr.sendPrompt({- agentId: 'agent-2',- topicId: 'topic-2',- operationId: 'op-2',- prompt: 'second',- sessionId: second.sessionId,- });-- expect(codexAppServerClientConstructMock).toHaveBeenCalledTimes(1);- expect(codexAppServerConstructMock).toHaveBeenCalledTimes(2);- const { env } = codexAppServerClientConstructMock.mock.calls[0][0];- expect(env.LOBEHUB_PROCESS_TOPIC).toBeUndefined();- expect(env.AGENT_BROWSER_NAMESPACE).toBeUndefined();- } finally {- environment.mockRestore();- }- });-it('reuses one native thread session across multiple turns', async () => {const ctr = new HeterogeneousAgentCtr({appStoragePath,diff --git a/apps/desktop/src/main/controllers/__tests__/testUtils.ts b/apps/desktop/src/main/controllers/__tests__/testUtils.tsnew file mode 100644index 00000000000..9ff0b791b36--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/testUtils.ts@@ -0,0 +1,155 @@+import type {+ CodexAppServerClient as NativeCodexAppServerClient,+ CodexThreadSession,+} from '@lobechat/heterogeneous-agents/spawn';+import type { Mock } from 'vitest';++/** Mutable controls shared by the controller's Codex transport scenarios. */+interface CodexAppServerMocks {+ codexAppServerCanReuse: { value: boolean };+ codexAppServerClientCloseMock: Mock;+ codexAppServerClientConstructMock: Mock;+ codexAppServerCloseMock: Mock;+ codexAppServerConstructMock: Mock;+ codexAppServerConsumerCount: { value: number };+ codexAppServerInterruptMock: Mock;+ codexAppServerRunMock: Mock;+ codexAppServerShouldFailAfterThread: { value: boolean };+ codexAppServerShouldFailResume: { value: boolean };+ codexAppServerShouldFallback: { value: boolean };+}++/**+ * Creates the Codex transport doubles while retaining the real client reuse check.+ *+ * Use when:+ * - Controller integration tests need controlled turns without starting a native CLI.+ *+ * Expects:+ * - Each test file registers its own hoisted mock factory and resets its controls.+ *+ * Returns:+ * - Client and session constructors for the spawn module override.+ *+ * Call stack:+ *+ * vi.mock('@lobechat/heterogeneous-agents/spawn')+ * -> {@link createCodexAppServerMocks}+ * -> MockCodexThreadSession.run+ */+export function createCodexAppServerMocks(+ actual: { CodexAppServerClient: typeof NativeCodexAppServerClient },+ mocks: CodexAppServerMocks,+): {+ CodexAppServerClient: typeof NativeCodexAppServerClient;+ CodexThreadSession: new (+ options: ConstructorParameters<typeof CodexThreadSession>[0],+ ) => Pick<CodexThreadSession, 'canFallbackToExec' | 'close' | 'interrupt' | 'run'>;+} {+ const {+ codexAppServerCanReuse,+ codexAppServerClientCloseMock,+ codexAppServerClientConstructMock,+ codexAppServerCloseMock,+ codexAppServerConsumerCount,+ codexAppServerConstructMock,+ codexAppServerInterruptMock,+ codexAppServerRunMock,+ codexAppServerShouldFailAfterThread,+ codexAppServerShouldFailResume,+ codexAppServerShouldFallback,+ } = mocks;+ class MockCodexAppServerClient extends actual.CodexAppServerClient {+ constructor(options: ConstructorParameters<typeof NativeCodexAppServerClient>[0]) {+ super(options);+ codexAppServerClientConstructMock(options);+ }++ canReuseFor(options: Parameters<NativeCodexAppServerClient['canReuseFor']>[0]) {+ return codexAppServerCanReuse.value && super.canReuseFor(options);+ }++ get hasConsumers() {+ return codexAppServerConsumerCount.value > 0;+ }++ close() {+ codexAppServerClientCloseMock();+ }+ }++ class MockCodexThreadSession {+ canFallbackToExec = true;+ private closed = false;++ constructor(private readonly options: ConstructorParameters<typeof CodexThreadSession>[0]) {+ codexAppServerConsumerCount.value += 1;+ codexAppServerConstructMock(options);+ }++ close() {+ if (!this.closed) {+ this.closed = true;+ codexAppServerConsumerCount.value -= 1;+ }+ codexAppServerCloseMock();+ }++ async interrupt() {+ return codexAppServerInterruptMock();+ }++ async run(runOptions: Parameters<CodexThreadSession['run']>[0]) {+ await codexAppServerRunMock(runOptions);+ if (codexAppServerShouldFailResume.value && this.options.initialThreadId) {+ this.canFallbackToExec = false;+ const error = new Error('Thread not found');+ error.name = 'CodexAppServerConnectionError';+ throw error;+ }+ if (codexAppServerShouldFallback.value) {+ const error = new Error('Method not found: initialize');+ error.name = 'CodexAppServerConnectionError';+ throw error;+ }++ const now = Date.now();+ this.canFallbackToExec = false;+ if (codexAppServerShouldFailAfterThread.value) {+ const error = new Error('Codex app-server disconnected');+ error.name = 'CodexAppServerConnectionError';+ throw error;+ }+ this.options.onRuntimeStatus?.({+ activeTasks: [],+ lastEventAt: now,+ operationId: runOptions.operationId,+ sessionId: this.options.sessionId,+ state: 'running',+ transport: 'codex-app-server',+ });+ this.options.onSessionId?.('thread_app_server');+ await this.options.onEvents([+ {+ data: { reason: 'complete', transport: 'codex-app-server' },+ operationId: runOptions.operationId,+ stepIndex: 0,+ timestamp: now,+ type: 'agent_runtime_end',+ },+ ]);+ this.options.onRuntimeStatus?.({+ activeTasks: [],+ lastEventAt: now,+ sessionId: this.options.sessionId,+ state: 'closed',+ transport: 'codex-app-server',+ });+ }+ }++ return {+ CodexAppServerClient: MockCodexAppServerClient,+ CodexThreadSession: MockCodexThreadSession,+ };+}diff --git a/apps/desktop/src/main/controllers/codexAppServer.ts b/apps/desktop/src/main/controllers/codexAppServer.tsnew file mode 100644index 00000000000..6597a499010--- /dev/null+++ b/apps/desktop/src/main/controllers/codexAppServer.ts@@ -0,0 +1,294 @@+import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import { buildHeterogeneousPrompt } from '@lobechat/heterogeneous-agents/protocol';+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';+import {+ buildAgentInput,+ buildCodexAppServerArgs,+ buildCodexAppServerInput,+ buildCodexAppServerThreadParams,+ CodexAppServerClient,+ CodexThreadSession,+ isCodexAppServerCompatibilityError,+ pickCodexRunProvenance,+ readCodexSessionModel,+ resolveCodexInitialModel,+} from '@lobechat/heterogeneous-agents/spawn';+import { truncateTitle } from '@lobechat/heterogeneous-agents/transcript';+import { app as electronApp } from 'electron';++import type { HeteroInflightRunRegistry } from '@/modules/heterogeneousAgent/inflightRunRegistry';+import { createLogger } from '@/utils/logger';++import type { AgentSession, CliTraceSession, SendPromptParams } from './heterogeneousAgentSession';++const logger = createLogger('controllers:HeterogeneousAgentCtr');++/** Controller-owned services used by the Codex transport without owning other transports. */+interface CodexAppServerHost {+ appendCliTraceFile: (+ trace: CliTraceSession | undefined,+ name: string,+ data: string,+ ) => Promise<void> | undefined;+ broadcast: <T>(channel: string, data: T) => void;+ buildSessionSpawnEnv: (session: AgentSession, bindProcessOwner: boolean) => NodeJS.ProcessEnv;+ /** Shared process slot; individual native threads retain their own ownership. */+ clientState: { client?: CodexAppServerClient };+ completeCancelledSessionBeforeLaunch: (session: AgentSession) => Promise<void>;+ createCliTraceSession: (args: {+ cliArgs: string[];+ cwd: string;+ imageList: NonNullable<SendPromptParams['imageList']>;+ session: AgentSession;+ stdinPayload: string;+ }) => Promise<CliTraceSession | undefined>;+ /** Attachment cache shared with the other desktop transports. */+ fileCacheDir: string;+ flushCliTrace: (trace: CliTraceSession | undefined) => Promise<void>;+ getErrorMessage: (error: unknown) => string | undefined;+ getInflightRuns: () => HeteroInflightRunRegistry | undefined;+ getSessionErrorPayload: (+ error: unknown,+ session: AgentSession,+ ) => HeterogeneousAgentSessionError | string;+ needsSessionIntroduction: (session: AgentSession) => boolean;+ recordInflightRun: (args: {+ cwd: string;+ params: SendPromptParams;+ session: AgentSession;+ startedAt: string;+ }) => void;+ resolveSessionCommand: (session: AgentSession) => string;+ writeCliTraceFile: (+ trace: CliTraceSession | undefined,+ name: string,+ data: string,+ ) => Promise<void> | undefined;+ writeCliTraceJson: (+ trace: CliTraceSession | undefined,+ name: string,+ payload: unknown,+ ) => Promise<void> | undefined;+}++/**+ * Runs one desktop Codex turn through the shared app-server and its native thread.+ *+ * Use when:+ * - The controller dispatches a session using the Codex app-server transport.+ *+ * Expects:+ * - A controller-owned process slot and mutable session, with per-run identity in params.+ *+ * Returns:+ * - True after handling the turn; false only when the caller should fall back to exec.+ *+ * Call stack:+ *+ * HeterogeneousAgentCtr.sendPrompt+ * -> {@link sendPromptWithCodexAppServer}+ * -> {@link CodexThreadSession.run}+ */+export async function sendPromptWithCodexAppServer(+ host: CodexAppServerHost,+ params: SendPromptParams,+ session: AgentSession,+): Promise<boolean> {+ const startedAt = new Date().toISOString();+ const cwd = session.cwd || electronApp.getPath('desktop');+ // One app-server serves multiple topics; ownership belongs to each thread, not its process.+ const spawnEnv = host.buildSessionSpawnEnv(session, false);+ const commandPath = session.resolvedCommandPath ?? host.resolveSessionCommand(session);+ const promptInput = buildHeterogeneousPrompt({+ imageList: params.imageList,+ isNewSession: host.needsSessionIntroduction(session),+ prompt: params.prompt,+ systemContext: params.systemContext,+ });+ let inputPlan;+ try {+ inputPlan = await buildAgentInput('codex', promptInput, { cacheDir: host.fileCacheDir });+ } catch (error) {+ logger.error('Failed to prepare Codex app-server input:', error);+ throw new Error(+ `Failed to attach image(s) to Codex app-server: ${host.getErrorMessage(error) || 'Unknown error'}`,+ { cause: error },+ );+ }++ const input = buildCodexAppServerInput(inputPlan);+ const appServerArgs = buildCodexAppServerArgs(session.args);+ const initialModel = await resolveCodexInitialModel({ args: session.args, env: spawnEnv });+ if (initialModel?.model) {+ session.model = initialModel.model;+ session.modelSource = initialModel.source;+ }+ const initialCumulativeUsage = session.agentSessionId+ ? (await readCodexSessionModel(session.agentSessionId, { env: spawnEnv }))?.cumulativeUsage+ : undefined;+ const inputPayload = `${JSON.stringify(input)}\n`;+ const traceSession = await host.createCliTraceSession({+ cliArgs: appServerArgs,+ cwd,+ imageList: params.imageList ?? [],+ session,+ stdinPayload: inputPayload,+ });+ void host.writeCliTraceFile(traceSession, 'stdin.txt', inputPayload);++ if (session.cancelledByUs) {+ await host.completeCancelledSessionBeforeLaunch(session);+ return true;+ }++ const clientOptions = {+ args: appServerArgs.slice(0, -1),+ clientVersion: electronApp.getVersion(),+ commandPath,+ cwd,+ env: spawnEnv,+ };+ const existingClient = host.clientState.client;+ if (existingClient && !existingClient.canReuseFor(clientOptions)) {+ if (!existingClient.hasConsumers) {+ existingClient.close();+ if (host.clientState.client === existingClient) host.clientState.client = undefined;+ } else {+ const message =+ 'The running Codex app-server uses a different binary, global configuration, or environment';+ logger.error('Cannot reuse the native Codex app-server client:', {+ sessionId: session.sessionId,+ });+ void host.writeCliTraceJson(traceSession, 'process-error.json', {+ message,+ transport: 'codex-app-server',+ });+ await host.flushCliTrace(traceSession);+ host.broadcast('heteroAgentSessionError', {+ error: message,+ sessionId: session.sessionId,+ });+ throw new Error(message);+ }+ }++ const client =+ host.clientState.client ?? (host.clientState.client = new CodexAppServerClient(clientOptions));+ const appServerSession =+ session.appServerSession ??+ new CodexThreadSession({+ client,+ initialCumulativeUsage,+ initialModel: session.model,+ initialThreadId: session.agentSessionId,+ threadName: truncateTitle(params.prompt),+ onEvents: async (events) => {+ for (const event of events) {+ host.broadcast('heteroAgentEvent', {+ event,+ sessionId: session.sessionId,+ });+ }+ },+ onModel: (model) => {+ session.model = model;+ session.modelSource = 'codex-app-server';+ },+ onRuntimeStatus: (status) => {+ host.broadcast('heteroAgentRuntimeStatus', status);+ },+ onSessionId: (agentSessionId) => {+ if (agentSessionId === session.agentSessionId) return;+ session.agentSessionId = agentSessionId;+ host.getInflightRuns()?.patch(session.sessionId, { agentSessionId });+ },+ sessionId: session.sessionId,+ threadParams: buildCodexAppServerThreadParams(session.args, cwd, session.model),+ });+ session.appServerSession = appServerSession;+ // No pid: the app-server process is shared, so reaping this run stops its session instead.+ // A renderer reload then releases the native thread rather than leaving it claimed.+ host.recordInflightRun({ cwd, params, session, startedAt });++ logger.info('Starting Codex app-server session:', {+ commandPath,+ cwd,+ sessionId: session.sessionId,+ });++ try {+ await appServerSession.run({+ input,+ onRawMessage: (line) => host.appendCliTraceFile(traceSession, 'stdout.jsonl', line),+ operationId: params.operationId,+ provenance: pickCodexRunProvenance({+ ...spawnEnv,+ LOBEHUB_OPERATION_ID: params.operationId,+ }),+ });+ void host.writeCliTraceJson(traceSession, 'exit.json', {+ finishedAt: new Date().toISOString(),+ transport: 'codex-app-server',+ });+ await host.flushCliTrace(traceSession);+ host.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });+ return true;+ } catch (error) {+ if (appServerSession.canFallbackToExec && isCodexAppServerCompatibilityError(error)) {+ session.codexAppServerFallback = true;+ logger.warn('Falling back to codex exec because native app-server is unavailable:', {+ message: host.getErrorMessage(error),+ sessionId: session.sessionId,+ });+ void host.writeCliTraceJson(traceSession, 'fallback.json', {+ message: host.getErrorMessage(error),+ transport: 'codex-app-server',+ });+ await host.flushCliTrace(traceSession);+ host.broadcast('heteroAgentEvent', {+ event: {+ data: {+ message:+ 'Codex app-server is unavailable or incompatible. Upgrade Codex to use the Labs transport; continuing with codex exec.',+ },+ operationId: params.operationId,+ stepIndex: 0,+ timestamp: Date.now(),+ type: 'stream_retry',+ } satisfies AgentStreamEvent,+ sessionId: session.sessionId,+ });+ appServerSession.close();+ if (session.appServerSession === appServerSession) session.appServerSession = undefined;+ if (!client.hasConsumers) {+ client.close();+ if (host.clientState.client === client) host.clientState.client = undefined;+ }+ return false;+ }++ logger.error('Codex app-server session error:', error);+ appServerSession.close();+ if (session.appServerSession === appServerSession) session.appServerSession = undefined;+ void host.writeCliTraceJson(traceSession, 'process-error.json', {+ message: error instanceof Error ? error.message : String(error),+ name: error instanceof Error ? error.name : 'Error',+ transport: 'codex-app-server',+ });+ await host.flushCliTrace(traceSession);++ if (session.cancelledByUs) {+ host.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });+ return true;+ }++ const sessionError = host.getSessionErrorPayload(error, session);+ host.broadcast('heteroAgentSessionError', {+ error: sessionError,+ sessionId: session.sessionId,+ });+ throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {+ cause: error,+ });+ }+}diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsnew file mode 100644index 00000000000..433acb34a9e--- /dev/null+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -0,0 +1,163 @@+import type { ChildProcess } from 'node:child_process';++import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import type { PiRpcSession } from '@lobechat/heterogeneous-agents/rpc';+import type {+ ClaudeAgentSdkSession,+ CodexThreadSession,+ CursorAcpSession,+ DevinAcpSession,+ DroidAcpSession,+ DshAcpSessionHandle,+ GrokAcpSession,+ TraeAcpSession,+} from '@lobechat/heterogeneous-agents/spawn';+import type {+ HeterogeneousServerDefaultApiConfig,+ HeteroSessionImportMessage,+} from '@lobechat/types';++import type { HostedProviderBinding } from '@/modules/heterogeneousAgent/providerBindingHost';+import type { HeterogeneousAgentImageAttachment } from '@/modules/heterogeneousAgent/types';++/** Prompt and ownership context shared by desktop transports. */+export interface SendPromptParams {+ /**+ * Agent this run belongs to. Rides along to the renderer so it can tell+ * whether revealing the browser panel would yank the user's view to a run+ * they aren't watching.+ */+ agentId?: string;+ /** Assistant row this run streams into β recorded so recovery can scope to its branch. */+ assistantMessageId?: string;+ /** Image attachments to include in the prompt (downloaded from url, cached by id) */+ imageList?: HeterogeneousAgentImageAttachment[];+ /**+ * Renderer-side operation id stamped onto every emitted `AgentStreamEvent`.+ * Required: producer-side conversion is the V3 contract β by the time events+ * reach the renderer they must already carry the operation they belong to.+ */+ operationId: string;+ prompt: string;+ /**+ * Do not spawn the CLI. Instead, read the last turn of the session's on-disk+ * transcript (Claude Code only) and stream it through the same pipeline a+ * live process feeds, so a turn that finished or died while the app was+ * down lands in the topic exactly as it would have live. Resolves with the+ * replay outcome so the caller knows whether a `--resume` continuation is+ * still owed.+ */+ replayTranscript?: boolean;+ /**+ * Claude profile root the transcript was written under. Passed by restart+ * recovery from its ledger: this turn's own account routing may resolve a+ * different profile, but the file to read is the one the interrupted run+ * actually produced.+ */+ replayTranscriptConfigDir?: string;+ /**+ * ISO spawn time of the interrupted run whose transcript is being replayed.+ * Pins the replay to that run's own turn β see+ * `claudeCodeReplayTurnMatchesPrompt`.+ */+ replayTranscriptStartedAt?: string;+ /**+ * Prior conversation turns used to rebuild a Claude Code transcript that the+ * CLI garbage-collected (`cleanupPeriodDays`, default 30 days). Only consumed+ * when resuming and the on-disk transcript is missing β see+ * `ensureClaudeCodeResumeTranscript`. Without it, `--resume <staleId>` fails+ * with "No conversation found with session ID".+ */+ resumeReplayMessages?: HeteroSessionImportMessage[];+ sessionId: string;+ /** Extra context injected before the user prompt without mutating the prompt text. */+ systemContext?: string;+ /**+ * Topic this run belongs to. Binds the op to its in-app browser session+ * (`topic:<topicId>`) so the browser MCP tools act on the right page.+ *+ * Not to be confused with `sessionId`, which is the CC/Codex agent session β+ * a different namespace entirely.+ */+ topicId?: string;+ /** User the run belongs to; recovery only releases runs of the signed-in one. */+ userId?: string;+ /** Workspace the run belongs to; recovery only releases runs of the active one. */+ workspaceId?: string;+}++/** Mutable desktop session state shared by transport dispatch and recovery. */+export interface AgentSession {+ agentSessionId?: string;+ agentType: HeterogeneousAgentType;+ appServerSession?: CodexThreadSession;+ args: string[];+ /**+ * True when *we* initiated the kill (cancelSession / stopSession / before-quit).+ * The `exit` handler uses this to route signal-induced non-zero exits through+ * the `complete` broadcast instead of surfacing them as runtime errors β+ * SIGINT(130) / SIGTERM(143) / SIGKILL(137) from our own kill paths are+ * intentional, not agent failures.+ */+ cancelledByUs?: boolean;+ codexAppServerFallback?: boolean;+ command: string;+ cursorAcpSession?: CursorAcpSession;+ cwd?: string;+ devinAcpSession?: DevinAcpSession;+ droidAcpSession?: DroidAcpSession;+ dshSession?: DshAcpSessionHandle;+ env?: Record<string, string>;+ grokAcpSession?: GrokAcpSession;+ hostedProviderBinding?: HostedProviderBinding;+ model?: string;+ modelSource?: string;+ modelVerificationLastAttemptAt?: number;+ modelVerificationLastAttemptSessionId?: string;+ /** Active pi RPC run (per-run process; cleared when the run settles). */+ piRpcSession?: PiRpcSession;+ process?: ChildProcess;+ processOwner?: { topicId?: string; agentId?: string };+ /**+ * Absolute CLI path resolved by spawn preflight detection. Used for spawn()+ * when the configured command is bare: detection can find the CLI through+ * the login-shell PATH or a well-known install location (e.g. an app-bundled+ * Codex CLI) that plain spawn() with the inherited env can't resolve.+ */+ resolvedCommandPath?: string;+ /**+ * PATH the preflight detector used to resolve `resolvedCommandPath`, set only+ * when it fell back to the login-shell PATH. Merged into the child PATH at+ * spawn so a `#!/usr/bin/env node` shim still finds its interpreter β the+ * shim resolving in preflight doesn't guarantee `node` is on the leaner+ * inherited PATH (Finder-launched Electron).+ */+ resolvedCommandSearchPath?: string;+ resumeSessionId?: string;+ sdkSession?: ClaudeAgentSdkSession;+ /** Present iff the session runs on the server-default (LobeHub) binding. */+ serverDefaultApiConfig?: HeterogeneousServerDefaultApiConfig;+ serverOperationToken?: string;+ sessionId: string;+ traeAcpSession?: TraeAcpSession;+ /**+ * Set when this turn had to rebuild a garbage-collected Claude Code+ * transcript before resuming it. The rebuild is assembled from persisted+ * chat rows, which never carried the session-scoped prompt context, so the+ * resumed transcript has not seen it even though the session id survives.+ */+ transcriptRebuiltForResume?: boolean;+ useClaudeCodeSdk?: boolean;+ useCodexAppServer?: boolean;+ verifiedModel?: string;+ verifiedModelContextWindow?: number;+ verifiedModelProvider?: string;+ verifiedModelSessionId?: string;+ verifiedModelSourceFile?: string;+}++/** Serialized trace writes for one desktop CLI run. */+export interface CliTraceSession {+ dir: string;+ writeQueue: Promise<void>;+}diff --git a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.test.ts b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.test.tsindex ee414677c1d..b12586db1de 100644--- a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.test.ts+++ b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.test.ts@@ -138,6 +138,74 @@ afterEach(() => {});describe('CodexAppServerClient', () => {+ it('claims a native thread for one session at a time', () => {+ const client = createClient();+ const releaseFirst = client.acquireThread('thread-shared');++ expect(() => client.acquireThread('thread-shared')).toThrow('already has an active session');+ releaseFirst();+ const releaseSecond = client.acquireThread('thread-shared');+ // A stale release from the first owner must not free the second owner's claim.+ releaseFirst();+ expect(() => client.acquireThread('thread-shared')).toThrow('already has an active session');++ releaseSecond();+ client.close();+ });++ it('spawns the shared process without run provenance but keeps credentials', async () => {+ const proc = createProcess();+ spawnMock.mockReturnValue(proc.child);+ const env = Object.freeze({+ ...process.env,+ LOBEHUB_AGENT_ID: 'agent-a',+ LOBEHUB_JWT: 'test-token',+ LOBEHUB_OPERATION_ID: 'op-a',+ LOBEHUB_TOPIC_ID: 'topic-a',+ });+ const client = new CodexAppServerClient({+ clientVersion: 'test',+ commandPath: 'codex',+ cwd: '/workspace',+ env,+ });++ try {+ await client.connect();+ const spawnedEnv = spawnMock.mock.calls[0][2].env;+ expect(spawnedEnv).toMatchObject({ LOBEHUB_JWT: 'test-token' });+ expect(spawnedEnv).not.toHaveProperty('LOBEHUB_AGENT_ID');+ expect(spawnedEnv).not.toHaveProperty('LOBEHUB_OPERATION_ID');+ expect(spawnedEnv).not.toHaveProperty('LOBEHUB_TOPIC_ID');+ } finally {+ client.close();+ }+ });++ it('reuses a process across runs whose environments differ only in provenance', () => {+ const baseEnv = { ...process.env, CODEX_HOME: '/codex', LOBEHUB_JWT: 'token-a' };+ const options = { clientVersion: '1.0.0', commandPath: 'codex', cwd: '/workspace' };+ const client = new CodexAppServerClient({+ ...options,+ env: { ...baseEnv, LOBEHUB_AGENT_ID: 'a', LOBEHUB_OPERATION_ID: 'o', LOBEHUB_TOPIC_ID: 't' },+ });+ const reuse = (env: NodeJS.ProcessEnv) => client.canReuseFor({ ...options, env });++ expect(+ reuse({+ ...baseEnv,+ LOBEHUB_AGENT_ID: 'b',+ LOBEHUB_OPERATION_ID: 'p',+ LOBEHUB_TOPIC_ID: 'u',+ }),+ ).toBe(true);+ expect(reuse({ ...baseEnv, LOBEHUB_OPERATION_ID: undefined })).toBe(true);+ expect(reuse({ ...baseEnv, LOBEHUB_JWT: 'token-b' })).toBe(false);+ expect(reuse({ ...baseEnv, CODEX_HOME: undefined })).toBe(false);+ expect(reuse({ ...baseEnv, LOBEHUB_OPERATION_ID_EXTRA: 'setting' })).toBe(false);+ client.close();+ });+it('only reuses a process for the same binary, global arguments, and environment', () => {const client = new CodexAppServerClient({args: ['--config', 'model_provider="openai"'],diff --git a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.tsindex 3e6255c9f6c..71299fb93b6 100644--- a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts+++ b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts@@ -5,6 +5,7 @@ import { spawnManaged } from '@lobechat/utils/managedProcess';import { isRecord, pickString } from '@lobechat/utils/object';import { resolveCliSpawnPlan } from '../spawn/cliSpawn';+import { getCodexProcessEnv } from './environment';import type {ClientNotification,InitializeParams,@@ -110,6 +111,7 @@ export class CodexAppServerClient {private connectionError?: Error;private connected = false;private consumerCount = 0;+ private readonly claimedThreads = new Set<string>();private generationSequence = 0;private hasConnected = false;private nextRequestId = 0;@@ -126,7 +128,10 @@ export class CodexAppServerClient {private reconnectExhaustedEpoch?: number;private reconnectTimer?: ReturnType<typeof setTimeout>;- constructor(private readonly options: CodexAppServerClientOptions) {}+ constructor(private readonly options: CodexAppServerClientOptions) {+ // A shared child (including reconnects) must never inherit the first run's identity.+ this.options = { ...options, env: getCodexProcessEnv(options.env) };+ }get isConnected(): boolean {return this.connected && !this.connectionError;@@ -149,6 +154,24 @@ export class CodexAppServerClient {};}+ /**+ * Claims a native thread for one local session. Conflicting claims throw without disturbing+ * the owner; the returned release callback is idempotent.+ */+ acquireThread(threadId: string): () => void {+ if (this.closedByHost)+ throw new CodexAppServerConnectionError('Codex app-server client closed by host');+ if (this.claimedThreads.has(threadId))+ throw new Error(`Codex thread already has an active session: ${threadId}`);+ this.claimedThreads.add(threadId);+ let released = false;+ return () => {+ if (released) return;+ released = true;+ this.claimedThreads.delete(threadId);+ };+ }+/** Process-global options must stay identical while this long-lived client is reused. */canReuseFor(options: Pick<CodexAppServerClientOptions, 'args' | 'commandPath' | 'cwd' | 'env'>,@@ -167,8 +190,8 @@ export class CodexAppServerClient {return false;}- const currentEnv = Object.entries(this.options.env).filter(([, value]) => value !== undefined);- const nextEnv = Object.entries(options.env).filter(([, value]) => value !== undefined);+ const currentEnv = Object.entries(this.options.env);+ const nextEnv = Object.entries(getCodexProcessEnv(options.env));return (currentEnv.length === nextEnv.length &¤tEnv.every(([key, value]) => options.env[key] === value)diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.tsindex 91dcb1c4311..6a0b27e9297 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts@@ -41,6 +41,8 @@ const createClientHarness = (initialThreadId?: string;interruptError?: Error;malformedThreadStart?: boolean;+ /** Statuses returned by successive `thread/resume` calls; later calls report idle. */+ resumeStatuses?: Array<'active' | 'idle' | 'systemError'>;threadNameError?: Error;} = {},): ClientHarness => {@@ -72,6 +74,7 @@ const createClientHarness = (const client = {acquireConsumer: vi.fn(() => releaseConsumer),+ acquireThread: vi.fn(() => vi.fn()),connect: options.connectError? vi.fn().mockRejectedValue(options.connectError): vi.fn().mockResolvedValue({ userAgent: 'codex-test' }),@@ -84,7 +87,9 @@ const createClientHarness = (registerThread: vi.fn((_threadId: string, params: unknown, value: typeof registration) => {resumeParams = params;registration = value;- return vi.fn();+ return vi.fn(() => {+ if (registration === value) registration = undefined;+ });}),request: vi.fn(async (method: string, params: unknown) => {requests.push({ method, params });@@ -97,7 +102,10 @@ const createClientHarness = (if (options.failResume) throw new Error('Thread not found');return {model: 'gpt-5.5-codex',- thread: { id: options.initialThreadId ?? 'thread-1' },+ thread: {+ id: options.initialThreadId ?? 'thread-1',+ status: { type: options.resumeStatuses?.shift() ?? 'idle' },+ },};}if (method === 'thread/name/set') {@@ -195,6 +203,175 @@ const createSession = (};describe('CodexThreadSession', () => {+ const provenance = (operationId: string) => ({+ LOBEHUB_AGENT_ID: 'agent',+ LOBEHUB_OPERATION_ID: operationId,+ LOBEHUB_TOPIC_ID: 'topic',+ });+ const runWithProvenance = (session: CodexThreadSession, operationId: string) =>+ session.run({+ input: [{ text: 'hello', text_elements: [], type: 'text' }],+ onRawMessage: () => {},+ operationId,+ provenance: provenance(operationId),+ });++ it('unsubscribes and resumes the loaded thread with the current run provenance', async () => {+ const harness = createClientHarness();+ const { session } = createSession(harness);++ try {+ await runWithProvenance(session, 'op-a');+ await runWithProvenance(session, 'op-b');++ const threadRequests = harness.requests.filter(({ method }) =>+ ['thread/start', 'thread/unsubscribe', 'thread/resume'].includes(method),+ );+ expect(threadRequests.map(({ method }) => method)).toEqual([+ 'thread/start',+ 'thread/unsubscribe',+ 'thread/resume',+ ]);+ expect(threadRequests.at(-1)?.params).toMatchObject({+ config: {+ shell_environment_policy: {+ set: { LOBEHUB_OPERATION_ID: 'op-b', LOBEHUB_TOPIC_ID: 'topic' },+ },+ },+ });+ } finally {+ session.close();+ }+ });++ it('replaces queued reconnect params when the next run has new provenance', async () => {+ const harness = createClientHarness();+ const { session } = createSession(harness);++ try {+ await runWithProvenance(session, 'old');+ harness.disconnect();+ harness.client.connect.mockImplementationOnce(async () => {+ await harness.resume();+ });+ await runWithProvenance(session, 'new');++ const resume = harness.requests.filter(({ method }) => method === 'thread/resume');+ expect(resume.at(-1)?.params).toMatchObject({+ config: { shell_environment_policy: { set: { LOBEHUB_OPERATION_ID: 'new' } } },+ });+ expect(harness.registeredResumeParams()).toMatchObject({+ config: { shell_environment_policy: { set: { LOBEHUB_OPERATION_ID: 'new' } } },+ });+ } finally {+ session.close();+ }+ });++ it('does not resume after closing during an unsubscribe request', async () => {+ const harness = createClientHarness({ initialThreadId: 'existing' });+ const { session } = createSession(harness, { initialThreadId: 'existing' });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const request = harness.client.request.getMockImplementation();+ harness.client.request.mockImplementation(async (method: string, params: unknown) => {+ if (method === 'thread/unsubscribe') await gate;+ return request(method, params);+ });++ const run = runWithProvenance(session, 'old');+ await vi.waitFor(() =>+ expect(harness.client.request).toHaveBeenCalledWith('thread/unsubscribe', {+ threadId: 'existing',+ }),+ );+ session.close();+ release();+ await run;++ expect(harness.requests.map(({ method }) => method)).toEqual(['thread/unsubscribe']);+ });++ it('reports a claimed native thread as a run error instead of failing construction', async () => {+ const harness = createClientHarness({ initialThreadId: 'thread-existing' });+ harness.client.acquireThread.mockImplementation(() => {+ throw new Error('Codex thread already has an active session: thread-existing');+ });+ const { session, statuses } = createSession(harness, { initialThreadId: 'thread-existing' });++ await expect(runWithProvenance(session, 'op-a')).rejects.toThrow(+ 'already has an active session',+ );+ expect(statuses.at(-1)).toBe('error');+ expect(harness.requests).toEqual([]);+ session.close();+ });++ it('waits for a turn interrupted by a closed session to settle before resuming', async () => {+ const harness = createClientHarness({+ initialThreadId: 'thread-existing',+ resumeStatuses: ['active', 'active'],+ });+ const { session } = createSession(harness, { initialThreadId: 'thread-existing' });++ try {+ await runWithProvenance(session, 'op-next');+ expect(harness.requests.map(({ method }) => method)).toEqual([+ 'thread/unsubscribe',+ 'thread/resume',+ 'thread/unsubscribe',+ 'thread/resume',+ 'thread/unsubscribe',+ 'thread/resume',+ 'turn/start',+ ]);+ } finally {+ session.close();+ }+ });++ it('gives up when the previous turn never settles', async () => {+ vi.useFakeTimers();+ const harness = createClientHarness({+ initialThreadId: 'thread-existing',+ resumeStatuses: Array.from({ length: 100 }, () => 'active' as const),+ });+ const { session } = createSession(harness, { initialThreadId: 'thread-existing' });++ try {+ const run = runWithProvenance(session, 'op-next');+ const assertion = expect(run).rejects.toThrow('still finishing the previous turn');+ await vi.advanceTimersByTimeAsync(11_000);+ await assertion;+ expect(session.canFallbackToExec).toBe(false);+ expect(harness.requests.some(({ method }) => method === 'turn/start')).toBe(false);+ } finally {+ session.close();+ vi.useRealTimers();+ }+ });++ it('runs on a resumed thread that reports a non-active status', async () => {+ const harness = createClientHarness({+ initialThreadId: 'thread-existing',+ resumeStatuses: ['systemError'],+ });+ const { session } = createSession(harness, { initialThreadId: 'thread-existing' });++ try {+ await runWithProvenance(session, 'op-a');+ expect(harness.requests.map(({ method }) => method)).toEqual([+ 'thread/unsubscribe',+ 'thread/resume',+ 'turn/start',+ ]);+ } finally {+ session.close();+ }+ });+it('sets the original prompt as the name of a new persisted thread', async () => {const harness = createClientHarness();const { run, session } = createSession(harness, { threadName: 'Original prompt title' });diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.tsindex d77b72cb424..318e411bb49 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts@@ -7,11 +7,15 @@ import { toStreamEvent } from '../spawn/streamEvent';import type { UsageData } from '../types';import type { CodexAppServerClient } from './CodexAppServerClient';import { CodexAppServerConnectionError } from './CodexAppServerClient';+import type { CodexRunProvenance } from './environment';+import { isSameCodexRunProvenance, withCodexThreadEnv } from './environment';import type {ThreadResumeParams,ThreadResumeResponse,ThreadStartParams,ThreadStartResponse,+ ThreadUnsubscribeParams,+ ThreadUnsubscribeResponse,TurnCompletedNotification,TurnInterruptParams,TurnStartParams,@@ -20,6 +24,9 @@ import type {} from './protocol';const CODEX_APP_SERVER_TRANSPORT = 'codex-app-server' as const;+/** An interrupted turn settled within 250 ms in probes; this bounds slow tool teardown. */+const RESUME_SETTLE_DELAY_MS = 200;+const RESUME_SETTLE_TIMEOUT_MS = 10_000;const toThreadResumeParams = (threadId: string, params: ThreadStartParams): ThreadResumeParams => {const resumeParams = { ...params };@@ -53,6 +60,8 @@ export interface CodexThreadTurnOptions {input: UserInput[];onRawMessage: (line: string) => Promise<void> | void;operationId: string;+ /** IDs exposed to this run's shell tools; omitted keeps the caller's thread config. */+ provenance?: CodexRunProvenance;}export interface CodexThreadSessionOptions {@@ -74,6 +83,9 @@ export interface CodexThreadSessionOptions {export class CodexThreadSession {private activeTurn?: ActiveTurn;private attached = false;+ private provenance?: CodexRunProvenance;+ private releaseThread?: () => void;+ private threadParams: ThreadStartParams;private canFallback: boolean;private closedByHost = false;private cumulativeUsage?: UsageData;@@ -90,6 +102,7 @@ export class CodexThreadSession {this.cumulativeUsage = options.initialCumulativeUsage;this.model = options.initialModel;this.threadId = options.initialThreadId;+ this.threadParams = options.threadParams;this.sessionUnsubscribers.push(options.client.acquireConsumer(),options.client.onDisconnect(() => this.handleDisconnect()),@@ -111,6 +124,15 @@ export class CodexThreadSession {const traceUnsubscribers: Array<() => void> = [];try {+ if (options.provenance) {+ if (!this.provenance || !isSameCodexRunProvenance(this.provenance, options.provenance)) {+ // Re-resume with the new IDs; this also drops reconnect params queued with the old ones.+ this.unsubscribeAll(this.threadUnsubscribers);+ this.attached = false;+ }+ this.provenance = options.provenance;+ this.threadParams = withCodexThreadEnv(this.options.threadParams, options.provenance);+ }await this.ensureThread();if (this.closedByHost) return;const threadId = this.threadId;@@ -218,6 +240,8 @@ export class CodexThreadSession {}this.unsubscribeAll(this.threadUnsubscribers);this.unsubscribeAll(this.sessionUnsubscribers);+ this.releaseThread?.();+ this.releaseThread = undefined;if (this.lastOperationId) this.emitStatus('closed', this.lastOperationId);}@@ -228,19 +252,22 @@ export class CodexThreadSession {if (this.threadId) {// Once initialize succeeds, an existing native thread must never be replayed via exec.this.canFallback = false;- const params = toThreadResumeParams(this.threadId, this.options.threadParams);- const response = await this.options.client.request<ThreadResumeResponse>(- 'thread/resume',- params,- );- if (this.closedByHost) return;+ // Claimed before unsubscribing, which would otherwise cut off another local owner.+ this.releaseThread ??= this.options.client.acquireThread(this.threadId);+ const response = this.provenance+ ? await this.resumeWithShellEnv(this.threadId)+ : await this.options.client.request<ThreadResumeResponse>(+ 'thread/resume',+ toThreadResumeParams(this.threadId, this.threadParams),+ );+ if (!response || this.closedByHost) return;await this.attachThread(response.thread.id, response.model);return;}const response = await this.options.client.request<ThreadStartResponse>('thread/start',- this.options.threadParams,+ this.threadParams,);if (this.closedByHost) return;const threadId = response?.thread?.id;@@ -258,6 +285,39 @@ export class CodexThreadSession {}}+ /**+ * Resumes a thread so the next turn's shell sees this run's provenance.+ *+ * NOTICE:+ * Codex has no per-turn shell environment, and `thread/resume` ignores config overrides for a+ * thread that still has subscribers or a running turn. Unsubscribing lets an idle thread reload+ * with the new config; a turn interrupted by a closed session can stay `active` for a moment,+ * so retry until it settles. Verified against `codex-cli 0.160.1`; source:+ * `https://github.com/openai/codex/blob/rust-v0.160.1/codex-rs/app-server/src/request_processors/thread_processor.rs#L4336-L4386`.+ * Remove when `turn/start` can set the shell environment.+ */+ private async resumeWithShellEnv(threadId: string): Promise<ThreadResumeResponse | undefined> {+ const deadline = Date.now() + RESUME_SETTLE_TIMEOUT_MS;+ while (true) {+ await this.options.client.request<ThreadUnsubscribeResponse>('thread/unsubscribe', {+ threadId,+ } satisfies ThreadUnsubscribeParams);+ if (this.closedByHost) return;+ const response = await this.options.client.request<ThreadResumeResponse>(+ 'thread/resume',+ toThreadResumeParams(threadId, this.threadParams),+ );+ if (this.closedByHost || response.thread.status?.type !== 'active') return response;+ if (Date.now() >= deadline) {+ throw new Error(+ 'Codex is still finishing the previous turn in this conversation. Try again once it stops.',+ );+ }+ await new Promise((resolve) => setTimeout(resolve, RESUME_SETTLE_DELAY_MS));+ if (this.closedByHost) return;+ }+ }+private async setThreadName(threadId: string): Promise<void> {const name = this.options.threadName?.trim();if (!name) return;@@ -271,6 +331,7 @@ export class CodexThreadSession {}private async attachThread(threadId: string, model?: string): Promise<void> {+ this.releaseThread ??= this.options.client.acquireThread(threadId);this.threadId = threadId;this.attached = true;this.canFallback = false;@@ -292,7 +353,7 @@ export class CodexThreadSession {}),this.options.client.registerThread(threadId,- toThreadResumeParams(threadId, this.options.threadParams),+ toThreadResumeParams(threadId, this.threadParams),{onResume: (response) => this.handleReconnect(response),onResumeError: () => {diff --git a/packages/heterogeneous-agents/src/codex/environment.test.ts b/packages/heterogeneous-agents/src/codex/environment.test.tsnew file mode 100644index 00000000000..c4ce728233c--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/environment.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import { pickCodexRunProvenance, withCodexThreadEnv } from './environment';++describe('Codex thread environment', () => {+ it('picks only run provenance from a launch environment', () => {+ expect(+ pickCodexRunProvenance({+ CODEX_HOME: '/codex',+ LOBEHUB_JWT: 'test-token',+ LOBEHUB_OPERATION_ID: 'op',+ LOBEHUB_TOPIC_ID: 'topic',+ }),+ ).toEqual({+ LOBEHUB_AGENT_ID: undefined,+ LOBEHUB_OPERATION_ID: 'op',+ LOBEHUB_TOPIC_ID: 'topic',+ });+ });++ it('folds every shell policy override into one table carrying the run provenance', () => {+ const params = {+ config: {+ 'model_reasoning_effort': 'low',+ 'shell_environment_policy': {+ inherit: 'all',+ set: { EXTRA: 'kept', LOBEHUB_OPERATION_ID: 'old' },+ },+ 'shell_environment_policy.set': { ANOTHER: 'kept', LOBEHUB_TOPIC_ID: 'old' },+ 'shell_environment_policy.set.LOBEHUB_OPERATION_ID': 'old',+ 'shell_environment_policy.exclude': ['SECRET_*'],+ },+ cwd: '/workspace',+ };++ const result = withCodexThreadEnv(params, { LOBEHUB_OPERATION_ID: 'current' });++ // One key per subtree: Codex applies overrides in hash order, so a sibling spelling could+ // otherwise replace the run's IDs.+ expect(result.config).toEqual({+ model_reasoning_effort: 'low',+ shell_environment_policy: {+ exclude: ['SECRET_*'],+ inherit: 'all',+ set: {+ ANOTHER: 'kept',+ LOBEHUB_AGENT_ID: '',+ LOBEHUB_OPERATION_ID: 'current',+ LOBEHUB_TOPIC_ID: '',+ },+ },+ });+ expect(params.config.shell_environment_policy.set.LOBEHUB_OPERATION_ID).toBe('old');+ });+});diff --git a/packages/heterogeneous-agents/src/codex/environment.ts b/packages/heterogeneous-agents/src/codex/environment.tsnew file mode 100644index 00000000000..959dc1822ee--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/environment.ts@@ -0,0 +1,71 @@+import { isRecord } from '@lobechat/utils/object';++import type { ThreadStartParams } from './protocol';++/** These values identify one run; credentials and every other setting stay process-scoped. */+const CODEX_PROVENANCE_KEYS = [+ 'LOBEHUB_AGENT_ID',+ 'LOBEHUB_OPERATION_ID',+ 'LOBEHUB_TOPIC_ID',+] as const;++const isProvenanceKey = (key: string) => (CODEX_PROVENANCE_KEYS as readonly string[]).includes(key);++export type CodexRunProvenance = Partial<Record<(typeof CODEX_PROVENANCE_KEYS)[number], string>>;++/** Picks only the run provenance from a launch environment. */+export const pickCodexRunProvenance = (env: NodeJS.ProcessEnv): CodexRunProvenance =>+ Object.fromEntries(CODEX_PROVENANCE_KEYS.map((key) => [key, env[key]]));++/**+ * Environment for the shared app-server process: defined values only, without run provenance,+ * so neither reuse checks nor a reconnect can carry the first run's IDs. MCP servers that Codex+ * spawns inherit this environment, so only shell tools receive provenance.+ */+export const getCodexProcessEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {+ const processEnv = { ...env };+ for (const key of Object.keys(processEnv)) {+ if (isProvenanceKey(key) || processEnv[key] === undefined) delete processEnv[key];+ }+ return processEnv;+};++const SHELL_POLICY_KEY = 'shell_environment_policy';++/**+ * Sets run provenance in a thread's shell environment. Missing IDs become empty strings, so+ * config saved with the thread cannot revive an earlier run's values.+ */+export const withCodexThreadEnv = (+ params: ThreadStartParams,+ provenance: CodexRunProvenance,+): ThreadStartParams => {+ const config = { ...params.config };+ // Codex applies request overrides in hash-map order and an ancestor table replaces earlier+ // descendants, so user `-c shell_environment_policy...` overrides are folded into one table.+ const policy = isRecord(config[SHELL_POLICY_KEY])+ ? structuredClone(config[SHELL_POLICY_KEY])+ : {};+ delete config[SHELL_POLICY_KEY];+ for (const key of Object.keys(config)) {+ if (!key.startsWith(`${SHELL_POLICY_KEY}.`)) continue;+ const path = key.slice(SHELL_POLICY_KEY.length + 1).split('.');+ let target = policy;+ for (const segment of path.slice(0, -1)) {+ if (!isRecord(target[segment])) target[segment] = {};+ target = target[segment] as typeof target;+ }+ target[path.at(-1)!] = config[key];+ delete config[key];+ }+ policy.set = {+ ...(isRecord(policy.set) ? policy.set : {}),+ ...Object.fromEntries(CODEX_PROVENANCE_KEYS.map((key) => [key, provenance[key] ?? ''])),+ };+ config[SHELL_POLICY_KEY] = policy;+ return { ...params, config };+};++/** Whether two runs would give the thread's shell the same IDs. */+export const isSameCodexRunProvenance = (a: CodexRunProvenance, b: CodexRunProvenance) =>+ CODEX_PROVENANCE_KEYS.every((key) => (a[key] ?? '') === (b[key] ?? ''));diff --git a/packages/heterogeneous-agents/src/codex/index.ts b/packages/heterogeneous-agents/src/codex/index.tsindex ea1e8e9a2ea..12b48335842 100644--- a/packages/heterogeneous-agents/src/codex/index.ts+++ b/packages/heterogeneous-agents/src/codex/index.ts@@ -16,5 +16,6 @@ export {type CodexThreadSessionOptions,type CodexThreadTurnOptions,} from './CodexThreadSession';+export { type CodexRunProvenance, pickCodexRunProvenance } from './environment';export type * from './protocol';export { CODEX_APP_SERVER_PROTOCOL_REVISION } from './protocol';diff --git a/packages/heterogeneous-agents/src/codex/protocol/README.md b/packages/heterogeneous-agents/src/codex/protocol/README.mdindex 67fae0d0200..b4542517287 100644--- a/packages/heterogeneous-agents/src/codex/protocol/README.md+++ b/packages/heterogeneous-agents/src/codex/protocol/README.md@@ -9,5 +9,8 @@ Generate the upstream files with:codex app-server generate-ts --out <directory>```+The `ThreadUnsubscribe*` types come from the same command run by Codex CLI 0.160.0, where+`thread/unsubscribe` is part of the stable request set.+The vendored file is the transitive stable subset used by LobeHub's native app-server client. Keepwire names and nullability identical to the generated files; do not hand-edit protocol types.diff --git a/packages/heterogeneous-agents/src/codex/protocol/generated.ts b/packages/heterogeneous-agents/src/codex/protocol/generated.tsindex 3d11da83d0f..fe5da82915e 100644--- a/packages/heterogeneous-agents/src/codex/protocol/generated.ts+++ b/packages/heterogeneous-agents/src/codex/protocol/generated.ts@@ -643,6 +643,15 @@ export type ThreadTokenUsage = { total: TokenUsageBreakdown, last: TokenUsageBre// Source: v2/ThreadTokenUsageUpdatedNotification.tsexport type ThreadTokenUsageUpdatedNotification = { threadId: string, turnId: string, tokenUsage: ThreadTokenUsage, };+// Source: v2/ThreadUnsubscribeParams.ts+export type ThreadUnsubscribeParams = { threadId: string, };++// Source: v2/ThreadUnsubscribeResponse.ts+export type ThreadUnsubscribeResponse = { status: ThreadUnsubscribeStatus, };++// Source: v2/ThreadUnsubscribeStatus.ts+export type ThreadUnsubscribeStatus = "notLoaded" | "notSubscribed" | "unsubscribed";+// Source: v2/TokenUsageBreakdown.tsexport type TokenUsageBreakdown = { totalTokens: number, inputTokens: number, cachedInputTokens: number, cacheWriteInputTokens: number, outputTokens: number, reasoningOutputTokens: number, };diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex a9d28c96cee..5eab6c108a8 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -24,6 +24,7 @@ export {type CodexThreadSessionOptions,getCodexAppServerUnsupportedArgs,isCodexAppServerCompatibilityError,+ pickCodexRunProvenance,} from '../codex';export type { UsageData } from '../types';export {