diff --git a/apps/desktop/src/main/services/chat/agentChatService.ts b/apps/desktop/src/main/services/chat/agentChatService.ts index aeb4799932..713f81a0f1 100644 --- a/apps/desktop/src/main/services/chat/agentChatService.ts +++ b/apps/desktop/src/main/services/chat/agentChatService.ts @@ -2067,6 +2067,8 @@ type CodexResumeFailureError = Error & { resumeFailureClassification: ResumeFailureClassification; /** The app-server's structured error `data`, carried past the rewrite of its message. */ data?: unknown; + /** The resume request itself hit its deadline: the process never answered. */ + codexRequestTimeout?: true; }; function isCodexResumeFailureError(error: unknown): error is CodexResumeFailureError { @@ -2917,6 +2919,16 @@ function isCodexRequestTimeoutError(error: unknown): boolean { return /^Codex request '.+' timed out after \d+ms\.$/.test(message); } +/** + * A Codex app-server request hit its deadline, also when the raw timeout was + * wrapped in the resume failure ADE reports (`thread/resume`). The process + * stayed "ready" without answering, so nothing on it can be trusted. + */ +function isCodexAppServerUnresponsiveError(error: unknown): boolean { + return isCodexRequestTimeoutError(error) + || (isCodexResumeFailureError(error) && error.codexRequestTimeout === true); +} + function rejectPendingCodexRequests( pending: Map, message: string, @@ -6285,6 +6297,8 @@ type PreparedSendMessage = { laneDirectiveKey?: string | null; /** The epoch directives this turn's prompt carries, marked delivered after the run. */ epochDirectiveKeys?: EpochDirectiveKeys; + /** The epoch directives this prompt revokes; their delivery keys are forgotten after the run. */ + revokedEpochDirectives?: EpochDirective[]; providerSlashCommand?: boolean; forceClaudeUserMessage?: boolean; onDispatched?: () => void; @@ -10087,6 +10101,26 @@ function composeLaunchDirectives(baseText: string, directives: Array instructions no longer apply: this lane has no Apple device or Android emulator. Create one with `ade apple start` or `ade android device-create` if this chat needs it."; + case "laneGuidance": + return "ADE's guidance for this session changed. Earlier guidance no longer applies."; + } +} + /** * Materialize a session's attached Linear issues into a per-session context * file the spawned agent (ADE chat or CLI) can read without Linear creds, and @@ -30538,6 +30572,15 @@ export function createAgentChatService(args: { * defers forever. */ deadCodexRuntime?: "turn_imminent" | "settle"; + /** + * Codex: a request on this app-server hit its deadline without an answer + * (turn/start, thread/start or thread/resume), so the process is + * presumed stuck. A private one, or the last chat on a shared one, is + * stopped; a shared one other chats are still using is retired from the + * pool instead. The chat's thread pointer is kept, so its delivered + * epoch directives are kept too: the resumed thread still holds them. + */ + codexAppServerUnresponsive?: boolean; }, ): void => { runtimeTeardownEpochs.set(managed, runtimeTeardownEpoch(managed) + 1); @@ -30595,8 +30638,13 @@ export function createAgentChatService(args: { // next send resumes that thread (a failed resume throws rather than opening // a new one). The resumed thread already holds the lane and computer-use // directives; forgetting them re-sent ~10k chars on every idle restart. + // A process retired for silence is the same case: the pointer survives, so + // the old thread still holds its directives and must keep their keys, or a + // capability that disappeared is never revoked (`revokedEpochDirectives`). const preserveDeliveredDirectives = preserveProviderResumeState - || (managed.runtime.kind === "codex" && reasonAllowsPreservation && Boolean(managed.session.threadId)); + || (managed.runtime.kind === "codex" + && (reasonAllowsPreservation || options?.codexAppServerUnresponsive === true) + && Boolean(managed.session.threadId)); if (managed.runtime.kind === "codex") { const runtime = managed.runtime; failOpenCodexCompactions(managed, runtime, "teardown"); @@ -30607,7 +30655,7 @@ export function createAgentChatService(args: { && !managed.deleted; runtime.suppressExitError = true; clearCodexNoFirstEventWatchdog(managed); - if (!releaseCodexRuntimeHost(managed, runtime)) { + if (!releaseCodexRuntimeHost(managed, runtime, { unresponsive: options?.codexAppServerUnresponsive === true })) { try { runtime.reader.close(); } catch { /* ignore */ } runtime.killTimer = terminateChildProcessTree( runtime.process, @@ -47493,8 +47541,19 @@ export function createAgentChatService(args: { * the chat's running turn is interrupted and its threads unsubscribed, so * nothing of it keeps running unseen; a process that cannot answer that is * presumed stuck and stopped, and every chat on it recovers as from a crash. - */ - const releaseCodexRuntimeHost = (managed: ManagedChatSession | null, runtime: CodexRuntime): boolean => { + * `unresponsive` says a request already hit its deadline with no answer: + * the process is presumed stuck, so on a private one (or the last chat on a + * shared one) it is stopped at once, without waiting out the release + * requests on a server known to be silent. A shared process other chats are + * still using is not stopped: one chat's deadline can be a slow machine, and + * killing it would fail their live turns. It is retired from the pool + * instead, so no new chat joins it, and stops with its last chat. + */ + const releaseCodexRuntimeHost = ( + managed: ManagedChatSession | null, + runtime: CodexRuntime, + options?: { unresponsive?: boolean }, + ): boolean => { const seat = codexHostByRuntime.get(runtime); if (!seat) return false; codexHostByRuntime.delete(runtime); @@ -47502,8 +47561,14 @@ export function createAgentChatService(args: { const ownThreadId = managed?.session.threadId ?? null; const turnId = runtime.activeTurnId ?? runtime.startedTurnId ?? null; const threadIds = [ownThreadId, ...runtime.codexSubagentThreads.keys()].filter((id): id is string => Boolean(id)); + const remaining = host.detach(client, threadIds); + if (options?.unresponsive) { + // `detach` already stopped a private process and the last chat's one. + if (remaining > 0) host.poison(); + return true; + } // A process that already exited holds nothing to release. - if (host.detach(client, threadIds) === 0 || !threadIds.length || host.isGone()) return true; + if (remaining === 0 || !threadIds.length || host.isGone()) return true; const release = (async () => { if (ownThreadId && turnId) { await host.request("turn/interrupt", { threadId: ownThreadId, turnId }, CODEX_SHARED_RELEASE_TIMEOUT_MS) @@ -59725,10 +59790,10 @@ export function createAgentChatService(args: { // on whether the capability set had changed since the agent was last told. // It is now epoch-scoped like the lane directive, and re-sent whenever the // available backends change, so a changed capability set is re-announced - // rather than repeated. A transition to NO available backend emits no - // directive at all (there is nothing to say), so a capability that is lost - // entirely is not revoked mid-session — the agent simply stops being told - // it is available on the next turn that re-announces. + // rather than repeated. A transition to NO available backend has no new + // directive to send; one short revocation says the old block is void (the + // turn text is conversation history, so omitting it later is not a + // retraction). const computerUseDirective = personalSession ? null : currentComputerUseDirective(); const computerUseDirectiveKey = computerUseDirective ? `${laneDirectiveKey ?? "no-lane"}::${computerUseDirectiveFingerprint(computerUseDirective)}` @@ -59745,6 +59810,13 @@ export function createAgentChatService(args: { && effectiveCursorRuntime(managed, runtime) === "cloud"; // The lane's Android emulator goes in the same block (one hint names both // devices); an Apple-only lane keeps its text and key exactly. + // A lookup that throws returns null like "no device", but it says nothing + // about the device: a failed read must not revoke a hint that is still true. + // The two reads are tracked apart: a failed Apple read cannot explain an + // Android-only hint (nor the reverse), so the other platform's authoritative + // null still revokes it. + let laneAppleLookupFailed = false; + let laneAndroidLookupFailed = false; const laneDevices = personalSession || cursorCloudTurn ? null : resolveLaneDeviceDirective({ @@ -59752,16 +59824,22 @@ export function createAgentChatService(args: { appleLookup: laneAppleDeviceLookup, androidLookup: laneAndroidDeviceLookup, shell: laneDirectiveShell, - onAppleLookupError: (error) => logger.warn("agent_chat.lane_apple_device_lookup_failed", { - sessionId, - laneId: executionContext.laneId, - error: error instanceof Error ? error.message : String(error), - }), - onAndroidLookupError: (error) => logger.warn("agent_chat.lane_android_device_lookup_failed", { - sessionId, - laneId: executionContext.laneId, - error: error instanceof Error ? error.message : String(error), - }), + onAppleLookupError: (error) => { + laneAppleLookupFailed = true; + logger.warn("agent_chat.lane_apple_device_lookup_failed", { + sessionId, + laneId: executionContext.laneId, + error: error instanceof Error ? error.message : String(error), + }); + }, + onAndroidLookupError: (error) => { + laneAndroidLookupFailed = true; + logger.warn("agent_chat.lane_android_device_lookup_failed", { + sessionId, + laneId: executionContext.laneId, + error: error instanceof Error ? error.message : String(error), + }); + }, }); const shouldInjectLaneDevicesDirective = laneDevices != null && managed.deliveredDirectiveKeys.laneDevices !== laneDevices.key; @@ -59775,6 +59853,41 @@ export function createAgentChatService(args: { : null; const shouldInjectLaneScreenDirective = laneScreenDirectiveKey != null && managed.deliveredDirectiveKeys.laneScreen !== laneScreenDirectiveKey; + // A Devin Cloud turn runs on a Devin VM: every directive below describes + // this machine (its worktree path, the `ade` CLI, computer use) and none of + // it exists there. Its only framing is the branch pin `runAcpTurn` adds. + const devinCloudPrompt = isDevinCloudAcpSession(managed.session); + // An epoch directive the provider thread already holds whose capability is + // gone now. The old block is conversation history, so leaving it out of + // this turn does not retract it; the revocation text says it is void. + const revokedEpochDirectives: EpochDirective[] = []; + if (!personalSession && !cursorCloudTurn && !providerSlashCommand && !devinCloudPrompt) { + if (computerUseDirectiveKey == null && managed.deliveredDirectiveKeys.computerUse != null) { + revokedEpochDirectives.push("computerUse"); + } + if (laneDevices == null) { + // The delivered hint names the Apple device, the emulator or both, and + // its key says which. Only a failed read for a platform the hint names + // can hide a still-bound device in it; a failure for the other one + // leaves the delivered content fully explained by the reads that did + // answer, so the hint is revoked. + const deliveredLaneDeviceKey = managed.deliveredDirectiveKeys.laneDevices ?? null; + const deliveredHadApple = deliveredLaneDeviceKey != null + && !deliveredLaneDeviceKey.startsWith("android:"); + const deliveredHadAndroid = deliveredLaneDeviceKey != null + && (deliveredLaneDeviceKey.startsWith("android:") || deliveredLaneDeviceKey.includes("|android:")); + if ( + deliveredLaneDeviceKey != null + && !(deliveredHadApple && laneAppleLookupFailed) + && !(deliveredHadAndroid && laneAndroidLookupFailed) + ) { + revokedEpochDirectives.push("laneDevices"); + } + } + if (laneScreenDirectiveKey == null && managed.deliveredDirectiveKeys.laneScreen != null) { + revokedEpochDirectives.push("laneScreen"); + } + } const expandedSlashCommandPrompt = providerSlashCommand && !personalSession ? expandAdeSlashCommand(managed, trimmed) : null; @@ -59788,10 +59901,6 @@ export function createAgentChatService(args: { const slashCommandPromptWithMentions = expandedSlashCommandPrompt != null ? carryChatMentionBlocks(trimmed, expandedSlashCommandPrompt) : null; - // A Devin Cloud turn runs on a Devin VM: every directive below describes - // this machine (its worktree path, the `ade` CLI, computer use) and none of - // it exists there. Its only framing is the branch pin `runAcpTurn` adds. - const devinCloudPrompt = isDevinCloudAcpSession(managed.session); const promptText = devinCloudPrompt ? trimmed : providerSlashCommand && !personalSession @@ -59827,6 +59936,7 @@ export function createAgentChatService(args: { ? laneScreenDirective : null, shouldInjectLaneDevicesDirective ? laneDevices.directive : null, + ...revokedEpochDirectives.map(buildEpochDirectiveRevocation), contextAttachmentPrompt || null, ]); const codexGoalTitleSeed = managed.session.provider === "codex" && isCodexGoalSlashInput(trimmed) @@ -59886,6 +59996,7 @@ export function createAgentChatService(args: { ...(shouldInjectLaneDevicesDirective ? { laneDevices: laneDevices.key } : {}), ...(shouldInjectLaneScreenDirective ? { laneScreen: laneScreenDirectiveKey } : {}), }, + revokedEpochDirectives, providerSlashCommand: personalSession ? false : providerSlashCommand === true, forceClaudeUserMessage: managed.session.provider === "claude" && (providerSlashCommand == null || personalSession) && slashCommand != null, ...(runtime ? { runtime } : {}), @@ -59937,8 +60048,8 @@ export function createAgentChatService(args: { managed.runtime.agentMessagePhaseByItemId.clear(); managed.runtime.recentNotificationKeys.clear(); managed.runtime.reconciledItemSignaturesByTurn.clear(); - if (isCodexRequestTimeoutError(error)) { - teardownRuntime(managed, "handle_close"); + if (isCodexAppServerUnresponsiveError(error)) { + teardownRuntime(managed, "handle_close", { codexAppServerUnresponsive: true }); } } if (managed.runtime?.kind === "opencode" && !isBusyError) { @@ -60230,6 +60341,10 @@ export function createAgentChatService(args: { code: "provider_thread_resume_failed" as const, resumeFailureClassification: classification, data: asRecord(error)?.data, + // The message rewrite above hides the raw timeout shape from + // `isCodexRequestTimeoutError`; keep the fact, so the caller can retire + // an app-server that never answered instead of reusing it. + ...(isCodexRequestTimeoutError(error) ? { codexRequestTimeout: true as const } : {}), }, ); }; @@ -66118,6 +66233,7 @@ export function createAgentChatService(args: { reasoningEffort, laneDirectiveKey, epochDirectiveKeys, + revokedEpochDirectives, providerSlashCommand, forceClaudeUserMessage, steerId, @@ -66191,6 +66307,10 @@ export function createAgentChatService(args: { && managed.directiveDispatchGeneration !== (managed.directiveEpochGeneration ?? 0) ) return; Object.assign(managed.deliveredDirectiveKeys, epochDirectiveKeys); + // A revocation this turn delivered is done: forgetting the old key now + // keeps it from being repeated (and only now, after the run, so a failed + // send leaves the key and retries the revocation next turn). + for (const kind of revokedEpochDirectives ?? []) delete managed.deliveredDirectiveKeys[kind]; }; const sessionPresetTiers = sessionPresetReasoningTiers(managed); @@ -71589,6 +71709,13 @@ export function createAgentChatService(args: { } catch (error) { const classifiedError = codexResumeFailureError(managed, originalThreadId, error); const classification = classifiedError.resumeFailureClassification; + // The retry met an app-server that never answered, exactly as a send + // does (`emitManagedSendFailure`). Retire it here too: otherwise the + // pool hands the same silent process back, and every "Try again" + // waits out the same deadline without the process ever changing. + if (isCodexAppServerUnresponsiveError(classifiedError) && managed.runtime?.kind === "codex") { + teardownRuntime(managed, "handle_close", { codexAppServerUnresponsive: true }); + } if (!managed.session.continuityRecovery) { managed.session.continuityRecovery = { state: "required", diff --git a/apps/desktop/src/main/services/chat/agentChatServiceContinuity.test.ts b/apps/desktop/src/main/services/chat/agentChatServiceContinuity.test.ts index 5899ec834e..ac9749c548 100644 --- a/apps/desktop/src/main/services/chat/agentChatServiceContinuity.test.ts +++ b/apps/desktop/src/main/services/chat/agentChatServiceContinuity.test.ts @@ -19,6 +19,7 @@ import { tmpRoot, waitFor, waitForEvent, + waitForFakeTimerCondition, writePersistedChatState, } from "./agentChatService.testHarness"; import { afterEach, beforeEach, describe, expect, it, test, vi } from "vitest"; @@ -925,6 +926,82 @@ describe("explicit provider-thread continuity recovery", () => { await expect(first).resolves.toEqual(expect.objectContaining({ ok: true, mode: "retry_original" })); }); + it("retires an app-server that never answers thread/resume instead of reusing it", async () => { + const session = await createPersistedCodexThread(); + // The app-server answers initialize but never answers resume: a wedged + // process that stays "ready" from the outside. + mockState.delayedCodexMethods.add("thread/resume"); + vi.useFakeTimers(); + const { service } = createService(); + try { + const firstSend = service.sendMessage({ sessionId: session.id, text: "Continue." }, { awaitDispatch: true }); + firstSend.catch(() => {}); + await waitForFakeTimerCondition( + () => mockState.codexRequestPayloads.some((payload) => payload.method === "thread/resume"), + "the app-server to receive thread/resume", + ); + // The per-request deadline is the only signal the process gives. + await vi.advanceTimersByTimeAsync(30_001); + await expect(firstSend).rejects.toThrow(/Could not resume the original Codex thread/); + const initializesBefore = mockState.codexRequestPayloads + .filter((payload) => payload.method === "initialize").length; + expect(initializesBefore).toBe(1); + + mockState.delayedCodexMethods.clear(); + const secondSend = service.sendMessage({ sessionId: session.id, text: "Continue." }, { awaitDispatch: true }); + secondSend.catch(() => {}); + // The wedged process must be forgotten: the next send starts a fresh one. + await waitForFakeTimerCondition( + () => mockState.codexRequestPayloads.filter((payload) => payload.method === "initialize").length + > initializesBefore, + "a fresh app-server to be started", + ); + } finally { + vi.useRealTimers(); + } + }); + + it("retires an app-server that never answers thread/resume on an explicit retry", async () => { + const session = await createPersistedCodexThread(); + writePersistedChatState(session.id, { + ...readPersistedChatState(session.id), + continuityRecovery: { + state: "required", + reason: "unknown", + provider: "codex", + originalThreadId: "thread-1", + at: new Date().toISOString(), + }, + }); + mockState.codexResponseOverrides.set("thread/resume", { thread: { id: "thread-1" } }); + // The app-server answers initialize but never answers the retry's resume. + mockState.delayedCodexMethods.add("thread/resume"); + vi.useFakeTimers(); + const { service } = createService(); + try { + const firstRetry = service.recoverContinuity({ sessionId: session.id, mode: "retry_original" }); + firstRetry.catch(() => {}); + await waitForFakeTimerCondition( + () => mockState.codexRequestPayloads.some((payload) => payload.method === "thread/resume"), + "the app-server to receive thread/resume", + ); + await vi.advanceTimersByTimeAsync(30_001); + await expect(firstRetry).resolves.toMatchObject({ ok: false, mode: "retry_original" }); + const initializesBefore = mockState.codexRequestPayloads + .filter((payload) => payload.method === "initialize").length; + expect(initializesBefore).toBe(1); + + // The wedged process must not be handed back to the next "Try again". + mockState.delayedCodexMethods.clear(); + const secondRetry = service.recoverContinuity({ sessionId: session.id, mode: "retry_original" }); + await expect(secondRetry).resolves.toMatchObject({ ok: true, mode: "retry_original", threadId: "thread-1" }); + expect(mockState.codexRequestPayloads + .filter((payload) => payload.method === "initialize").length).toBe(initializesBefore + 1); + } finally { + vi.useRealTimers(); + } + }); + it("leaves required recovery untouched when disk pressure blocks history reconstruction", async () => { const session = await createPersistedCodexThread(); const continuityRecovery = { diff --git a/apps/desktop/src/main/services/chat/agentChatServiceCreate.test.ts b/apps/desktop/src/main/services/chat/agentChatServiceCreate.test.ts index 937d256ffa..be751bc316 100644 --- a/apps/desktop/src/main/services/chat/agentChatServiceCreate.test.ts +++ b/apps/desktop/src/main/services/chat/agentChatServiceCreate.test.ts @@ -762,6 +762,57 @@ describe("createAgentChatService", () => { expect(JSON.stringify(mockState.droidPromptCalls[1])).not.toContain(HINT_OPEN); service.forceDisposeAll(); }); + + it("revokes the hint once when the bound Apple device is detached", async () => { + const fixture = installClaudeResponseFixture({ sdkSessionId: "sdk-apple-revoke", responseText: "ok" }); + const device = laneDeviceLookup({ udid: "UDID-AAA", name: "iPhone 17 Pro" }); + const { service } = createService({ lookupLaneAppleDevice: device.lookup }); + const session = await service.createSession({ laneId: "lane-1", provider: "claude", model: "sonnet" }); + + await service.runSessionTurn({ sessionId: session.id, text: "alpha-turn" }); + await settleDirectiveBookkeeping(); + // `ade apple device-detach`: the lane has no device any more, but the + // thread's first turn still says it does. + device.set(null); + await service.runSessionTurn({ sessionId: session.id, text: "beta-turn" }); + await settleDirectiveBookkeeping(); + await service.runSessionTurn({ sessionId: session.id, text: "gamma-turn" }); + + const prompts = fixture.send.mock.calls.map(([message]) => claudeInputText(message)); + const first = prompts.find((text) => text.includes("alpha-turn")) ?? ""; + const second = prompts.find((text) => text.includes("beta-turn")) ?? ""; + const third = prompts.find((text) => text.includes("gamma-turn")) ?? ""; + expect(first).toContain(HINT_OPEN); + // No hint block this time; the revocation names the tag only in prose. + expect(second).not.toContain(`${HINT_OPEN}\n`); + expect(second).not.toContain("iPhone 17 Pro (UDID-AAA)"); + expect(second).toContain("Earlier instructions no longer apply"); + // Said once: a later turn does not repeat the revocation. + expect(third).not.toContain("Earlier instructions no longer apply"); + service.forceDisposeAll(); + }); + + it("revokes a detached Android hint and names the platform", async () => { + const fixture = installClaudeResponseFixture({ sdkSessionId: "sdk-android-revoke", responseText: "ok" }); + let androidDevice: { avdName: string } | null = { avdName: "Pixel_ADE" }; + const lookup = vi.fn(() => androidDevice); + const { service } = createService({ lookupLaneAndroidDevice: lookup }); + const session = await service.createSession({ laneId: "lane-1", provider: "claude", model: "sonnet" }); + + await service.runSessionTurn({ sessionId: session.id, text: "alpha-turn" }); + await settleDirectiveBookkeeping(); + androidDevice = null; + await service.runSessionTurn({ sessionId: session.id, text: "beta-turn" }); + + const prompts = fixture.send.mock.calls.map(([message]) => claudeInputText(message)); + const first = prompts.find((text) => text.includes("alpha-turn")) ?? ""; + const second = prompts.find((text) => text.includes("beta-turn")) ?? ""; + expect(first).toContain(HINT_OPEN); + expect(first).toContain("Pixel_ADE"); + expect(second).toContain("Earlier instructions no longer apply"); + expect(second).toContain("Android"); + service.forceDisposeAll(); + }); }); // -------------------------------------------------------------------------- diff --git a/apps/desktop/src/main/services/chat/codexAppServerPool.test.ts b/apps/desktop/src/main/services/chat/codexAppServerPool.test.ts index be7a279c4b..2b385d37fe 100644 --- a/apps/desktop/src/main/services/chat/codexAppServerPool.test.ts +++ b/apps/desktop/src/main/services/chat/codexAppServerPool.test.ts @@ -124,6 +124,26 @@ describe("codexAppServerPool", () => { expect(terminate).not.toHaveBeenCalled(); }); + it("retires a poisoned shared process without stopping it, and stops it with its last chat", async () => { + const { proc, pool, host, terminate } = setup(); + const leaving = chat("chat-leaving", ["thread-leaving"]); + const staying = chat("chat-staying", ["thread-staying"]); + host.attach(leaving.client); + host.attach(staying.client); + + expect(host.detach(leaving.client, ["thread-leaving"])).toBe(1); + host.poison(); + // No new chat joins the retired process... + const replacement = fakeAppServer(); + expect(pool.acquire({ key: "same-launch", spawn: () => replacement })).not.toBe(host); + // ...but the chat still on it keeps its process (and its turn) alive. + expect(terminate).not.toHaveBeenCalled(); + expect(staying.exits).toEqual([]); + // The last chat leaving stops it, as it does for any shared process. + expect(host.detach(staying.client, ["thread-staying"])).toBe(0); + expect(terminate).toHaveBeenCalledWith(proc, null); + }); + it("unloads a thread a departed chat's request created, tells every chat when the process dies, and stops it with the last chat", async () => { const { proc, host, terminate } = setup(); const leaving = chat("chat-leaving"); diff --git a/apps/desktop/src/main/services/chat/codexAppServerPool.ts b/apps/desktop/src/main/services/chat/codexAppServerPool.ts index 12f1ab115f..7542e77e60 100644 --- a/apps/desktop/src/main/services/chat/codexAppServerPool.ts +++ b/apps/desktop/src/main/services/chat/codexAppServerPool.ts @@ -72,6 +72,12 @@ export type CodexAppServerHost = { */ detach(client: CodexAppServerClient, releasedThreadIds?: readonly string[]): number; clientCount(): number; + /** + * Removes this host from the shared pool so no new chat joins it, without + * touching the chats already on it. The process is not stopped: it stays + * until its last chat detaches, which stops it as usual. + */ + poison(): void; /** True once the process has exited or failed to start. */ isGone(): boolean; /** @@ -411,6 +417,12 @@ export function createCodexAppServerPool(args: { return clients.length; }, clientCount: () => clients.length, + poison: () => { + // Removing the pool entry is all: a live process must not be stopped + // under the chats still attached to it (their turns would fail), and + // `detach` stops it once its last client leaves. + forgetShared(); + }, isGone: () => gone, stderrTail: () => stderrTail, kill: () => {