Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Let one ACP launch own a thread at a time (PRD-9330) (#6191)
Andrew Mikofalvy1efd42910e3c
diff --git a/.changeset/prd-9330-context-window-during-start.md b/.changeset/prd-9330-context-window-during-start.mdnew file mode 100644index 000000000..ed9713abf--- /dev/null+++ b/.changeset/prd-9330-context-window-during-start.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Changing a Codex chat's context window while its agent is still starting, or retrying a chat whose agent failed to start, no longer leaves a second agent running. The chat's first message is sent once when its context window changes during start.diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.tsindex f8478c3ad..0433496ef 100644--- a/packages/server/src/acp/managed-runtime-flow.integration.test.ts+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts@@ -1074,6 +1074,68 @@ describe('interpreter health probe', () => {}, 30_000);});+describe('a context window change superseding a launch inside its interpreter probe', () => {+ test.skipIf(process.platform === 'win32')(+ 'the superseded launch asks for no runtime consent once its interpreter crashes',+ async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const runtimeRoot = tmp();+ const brokenBin = tmp();+ const control = tmp();+ const probes = join(control, 'probes.log');+ const gate = join(control, 'gate');+ writeFileSync(+ join(brokenBin, 'npx'),+ `#!/bin/sh\necho "$*" >> ${JSON.stringify(probes)}\nwhile [ ! -e ${JSON.stringify(gate)} ]; do /bin/sleep 0.05; done\necho "dyld[1]: Library not loaded: libicui18n.74.dylib" >&2\nkill -ABRT $$\n`,+ { mode: 0o755 },+ );+ const manager = makeManager({+ contentDir,+ localDir,+ runtimeRoot,+ fetchImpl: fakeNodeFetch(Buffer.from('unused'), 'x'.repeat(64), {+ ...NPX_AGENT,+ id: 'codex-acp',+ distribution: { npx: { package: '@fake/agent', env: { PATH: brokenBin } } },+ }),+ });+ const probeCount = (): number =>+ existsSync(probes)+ ? readFileSync(probes, 'utf8')+ .split('\n')+ .filter((line) => line !== '').length+ : 0;+ const events: ThreadEvent[] = [];+ const consentReasons = () =>+ events.flatMap((e) => (e.kind === 'runtime_consent_request' ? [e.reason] : []));+ try {+ const info = await manager.createThread({ agent: { source: 'registry', id: 'codex-acp' } });+ await collect(manager, info.threadId, events);+ await waitFor(+ () => probeCount() === 1,+ 10_000,+ 'the first launch to probe its interpreter',+ );+ void manager.setContextWindow(info.threadId, 400_000).catch(() => {});+ await waitFor(() => probeCount() === 2, 3_000, 'the restart to probe its interpreter');+ writeFileSync(gate, '');+ await waitFor(() => consentReasons().length > 0, 10_000, 'a runtime consent request');+ await waitFor(+ () => consentReasons().length > 1,+ 1_500,+ 'a consent request from the superseded launch',+ ).catch(() => {});++ expect(consentReasons()).toEqual(['broken']);+ } finally {+ writeFileSync(gate, '');+ }+ },+ 30_000,+ );+});+async function pollInstalled(runtimeRoot: string,): Promise<Awaited<ReturnType<typeof findManagedRuntime>>> {diff --git a/packages/server/src/acp/mcp-injection-skip.test.ts b/packages/server/src/acp/mcp-injection-skip.test.tsindex 65c283aea..3bb0f044f 100644--- a/packages/server/src/acp/mcp-injection-skip.test.ts+++ b/packages/server/src/acp/mcp-injection-skip.test.ts@@ -41,14 +41,18 @@ afterEach(async () => {dirs = [];});+type SeamLaunchTicket = { initialPrompt: null };+type BuildMcpServersSeam = {buildMcpServers: (record: {agentRef: { source: 'registry' | 'custom'; id: string };cwd: string;info: { threadId: string };+ launchTicket: SeamLaunchTicket;agentNpmCache?: string | null;},+ ticket: SeamLaunchTicket,init: { agentCapabilities?: { mcpCapabilities?: { http?: boolean } } },consentBudgetMs?: number,) => Promise<{@@ -60,6 +64,7 @@ type BuildMcpServersSeam = {}>;hostedMarker: OkMcpHostedMarker;browserUnavailable: 'no-node' | 'failed' | null;+ browserInjected: boolean;}>;};@@ -119,10 +124,13 @@ const THREAD_ID = '6f1c2d3e-4a5b-4c6d-8e7f-9a0b1c2d3e4f';const PROJECT = '/tmp/acp-injection-skip-project';+const LAUNCH: SeamLaunchTicket = { initialPrompt: null };+const record = (source: 'registry' | 'custom', id: string) => ({agentRef: { source, id },cwd: PROJECT,info: { threadId: THREAD_ID },+ launchTicket: LAUNCH,});const HTTP_INIT = { agentCapabilities: { mcpCapabilities: { http: true } } };@@ -136,15 +144,17 @@ const hit: HarnessManagedMcpEntryHit = {describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {test('skips injection entirely on a probe hit (http-capable and stdio agents)', async () => {const m = makeManager(() => hit);- expect((await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT)).servers).toEqual(+ expect(+ (await m.buildMcpServers(record('registry', 'codex-acp'), LAUNCH, HTTP_INIT)).servers,+ ).toEqual([]);+ expect((await m.buildMcpServers(record('registry', 'claude-acp'), LAUNCH, {})).servers).toEqual([],);- expect((await m.buildMcpServers(record('registry', 'claude-acp'), {})).servers).toEqual([]);});test('injects on a probe miss', async () => {const m = makeManager(() => null);- const { servers } = await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT);+ const { servers } = await m.buildMcpServers(record('registry', 'codex-acp'), LAUNCH, HTTP_INIT);expect(servers).toHaveLength(1);expect(servers[0]).toMatchObject({ name: 'open-knowledge', type: 'http' });});@@ -153,8 +163,8 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {vi.stubEnv('OK_CHANNEL', 'beta');try {const m = makeManager(() => null);- const http = await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT);- const stdio = await m.buildMcpServers(record('registry', 'claude-acp'), {});+ const http = await m.buildMcpServers(record('registry', 'codex-acp'), LAUNCH, HTTP_INIT);+ const stdio = await m.buildMcpServers(record('registry', 'claude-acp'), LAUNCH, {});expect(http.servers[0]).toMatchObject({ name: 'open-knowledge-beta', type: 'http' });expect(stdio.servers[0]).toMatchObject({ name: 'open-knowledge-beta' });} finally {@@ -166,6 +176,7 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {const m = makeManager(() => null);const { servers, hostedMarker } = await m.buildMcpServers(record('registry', 'codex-acp'),+ LAUNCH,HTTP_INIT,);expect(servers[0]).toMatchObject({@@ -177,7 +188,11 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {test('the injected stdio server carries the hosted-agent marker and PATH', async () => {const m = makeManager(() => null);- const { servers, hostedMarker } = await m.buildMcpServers(record('registry', 'claude-acp'), {});+ const { servers, hostedMarker } = await m.buildMcpServers(+ record('registry', 'claude-acp'),+ LAUNCH,+ {},+ );expect(servers).toHaveLength(1);expect(servers[0]).toMatchObject({ name: 'open-knowledge' });const env = (servers[0] as { env: Array<{ name: string; value: string }> }).env;@@ -187,7 +202,7 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {test('the injected stdio PATH is the agent spawn PATH, not the server process PATH', async () => {const m = makeManager(() => null);- const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), {});+ const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), LAUNCH, {});const env = (servers[0] as { env: Array<{ name: string; value: string }> }).env;const declared = env.find((e) => e.name === 'PATH')?.value;expect(declared).toBe(agentSpawnPath());@@ -203,12 +218,12 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {calls += 1;return hit;});- expect((await m.buildMcpServers(record('custom', 'my-agent'), HTTP_INIT)).servers).toHaveLength(- 1,- );- expect((await m.buildMcpServers(record('registry', 'gemini'), HTTP_INIT)).servers).toHaveLength(- 1,- );+ expect(+ (await m.buildMcpServers(record('custom', 'my-agent'), LAUNCH, HTTP_INIT)).servers,+ ).toHaveLength(1);+ expect(+ (await m.buildMcpServers(record('registry', 'gemini'), LAUNCH, HTTP_INIT)).servers,+ ).toHaveLength(1);expect(calls).toBe(0);});@@ -218,9 +233,13 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {calls += 1;return { ...hit, editorId: 'cursor' as const };});- const { servers, hostedMarker } = await m.buildMcpServers(record('registry', 'cursor'), {- agentCapabilities: { mcpCapabilities: { http: true } },- });+ const { servers, hostedMarker } = await m.buildMcpServers(+ record('registry', 'cursor'),+ LAUNCH,+ {+ agentCapabilities: { mcpCapabilities: { http: true } },+ },+ );expect(servers).toHaveLength(1);expect(servers[0]).toMatchObject({ name: 'open-knowledge', type: 'http' });expect(hostedMarker).toBe('http-header');@@ -231,28 +250,28 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {const m = makeManager(() => {throw new Error('probe exploded');});- const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), {});+ const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), LAUNCH, {});expect(servers).toHaveLength(1);expect(servers[0]).toMatchObject({ name: 'open-knowledge', command: 'open-knowledge' });});test('unwired seam keeps unconditional injection', async () => {const m = makeManager(undefined);- expect((await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT)).servers).toEqual([- expect.objectContaining({ name: 'open-knowledge' }),- ]);+ expect(+ (await m.buildMcpServers(record('registry', 'codex-acp'), LAUNCH, HTTP_INIT)).servers,+ ).toEqual([expect.objectContaining({ name: 'open-knowledge' })]);});});describe('buildMcpServers hosted-marker outcomes', () => {test('a skip-branch thread reports `unknown`, not a false negative', async () => {const m = makeManager(() => hit);- expect((await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT)).hostedMarker).toBe(- 'unknown',- );- expect((await m.buildMcpServers(record('registry', 'claude-acp'), {})).hostedMarker).toBe(- 'unknown',- );+ expect(+ (await m.buildMcpServers(record('registry', 'codex-acp'), LAUNCH, HTTP_INIT)).hostedMarker,+ ).toBe('unknown');+ expect(+ (await m.buildMcpServers(record('registry', 'claude-acp'), LAUNCH, {})).hostedMarker,+ ).toBe('unknown');});test('an agent with no usable transport reports `none` and gets no servers', async () => {@@ -260,7 +279,11 @@ describe('buildMcpServers hosted-marker outcomes', () => {() => null,() => null,);- const { servers, hostedMarker } = await m.buildMcpServers(record('registry', 'claude-acp'), {});+ const { servers, hostedMarker } = await m.buildMcpServers(+ record('registry', 'claude-acp'),+ LAUNCH,+ {},+ );expect(servers).toEqual([]);expect(hostedMarker).toBe('none');});@@ -274,9 +297,9 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserToreturn { npx: join(dir, 'npx'), path: dir };};const names = async (m: BuildMcpServersSeam, id: string, init = HTTP_INIT) =>- (await m.buildMcpServers(record('registry', id), init)).servers.map((s) => s.name);+ (await m.buildMcpServers(record('registry', id), LAUNCH, init)).servers.map((s) => s.name);const unavailable = async (m: BuildMcpServersSeam, id = 'claude-acp') =>- (await m.buildMcpServers(record('registry', id), HTTP_INIT)).browserUnavailable;+ (await m.buildMcpServers(record('registry', id), LAUNCH, HTTP_INIT)).browserUnavailable;test('adds the browser after OK tools, relayed through the node beside the resolved npx, from its own folder', async () => {const localDir = tmp();@@ -292,7 +315,7 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserTolocalDir,globalDir,});- const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), {});+ const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), LAUNCH, {});expect(servers.map((s) => s.name)).toEqual(['open-knowledge', 'ok-browser']);const browser = servers[1] as { command?: string; args?: string[]; env?: unknown };expect(browser.command).toBe(join(npx.path, 'node'));@@ -318,7 +341,11 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserToconst npx = resolveOnPath('npx', agentSpawnPath());if (npx === null) return;const m = makeManager(undefined, undefined, undefined, { enabled: () => true });- const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), HTTP_INIT);+ const { servers } = await m.buildMcpServers(+ record('registry', 'claude-acp'),+ LAUNCH,+ HTTP_INIT,+ );const browser = servers.find((s) => s.name === 'ok-browser') as| { args: string[]; env: Array<{ name: string; value: string }> }| undefined;@@ -385,6 +412,7 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserTo});const { servers, browserUnavailable } = await m.buildMcpServers(record('registry', 'claude-acp'),+ LAUNCH,HTTP_INIT,);expect(servers.map((s) => s.name)).toEqual(['open-knowledge']);@@ -412,6 +440,7 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserTo});const { servers } = await m.buildMcpServers({ ...record('registry', 'codex-acp'), agentNpmCache: '/runtime/npm-cache' },+ LAUNCH,HTTP_INIT,);const browser = servers.find((s) => s.name === 'ok-browser');@@ -429,6 +458,7 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserTo});const { servers, browserUnavailable } = await m.buildMcpServers(record('registry', 'claude-acp'),+ LAUNCH,HTTP_INIT,);expect(servers.map((s) => s.name)).toEqual(['open-knowledge']);@@ -444,6 +474,7 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserTo});const { browserUnavailable } = await m.buildMcpServers(record('registry', 'claude-acp'),+ LAUNCH,HTTP_INIT,20,);@@ -462,7 +493,7 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserToexpect(await names(on, id)).toEqual(['open-knowledge']);}expect(await names(on, 'pi-acp')).toEqual([]);- const custom = await on.buildMcpServers(record('custom', 'claude-acp'), HTTP_INIT);+ const custom = await on.buildMcpServers(record('custom', 'claude-acp'), LAUNCH, HTTP_INIT);expect(custom.servers.map((s) => s.name)).toEqual(['open-knowledge']);});@@ -482,7 +513,11 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserToaccept,),});- const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), HTTP_INIT);+ const { servers } = await m.buildMcpServers(+ record('registry', 'claude-acp'),+ LAUNCH,+ HTTP_INIT,+ );const browser = servers.find((s) => s.name === 'ok-browser') as { args?: string[] } | undefined;expect(browser?.args?.[4]).toBe(safe.npx);expect(tried).toEqual([join(PROJECT, 'node_modules', '.bin'), bare, safe.path]);@@ -542,21 +577,24 @@ describe('buildMcpServers × pi-acp', () => {test('never injects for pi, even with an http-capable init and a working stdio command', async () => {const m = makeManager(() => null, undefined, { probePiAcpBridge: () => PI_LOADABLE });- expect((await m.buildMcpServers(record('registry', 'pi-acp'), HTTP_INIT)).servers).toEqual([]);- expect((await m.buildMcpServers(record('registry', 'pi-acp'), {})).servers).toEqual([]);+ expect(+ (await m.buildMcpServers(record('registry', 'pi-acp'), LAUNCH, HTTP_INIT)).servers,+ ).toEqual([]);+ expect((await m.buildMcpServers(record('registry', 'pi-acp'), LAUNCH, {})).servers).toEqual([]);});test('a loadable bridge reports `unknown` — the bridge spawns the server, not us', async () => {const m = makeManager(() => null, undefined, { probePiAcpBridge: () => PI_LOADABLE });- expect((await m.buildMcpServers(record('registry', 'pi-acp'), HTTP_INIT)).hostedMarker).toBe(- 'unknown',- );+ expect(+ (await m.buildMcpServers(record('registry', 'pi-acp'), LAUNCH, HTTP_INIT)).hostedMarker,+ ).toBe('unknown');});test('unwired seams suppress injection and report `unknown`, not `none`', async () => {const m = makeManager(() => null);const { servers, hostedMarker } = await m.buildMcpServers(record('registry', 'pi-acp'),+ LAUNCH,HTTP_INIT,);expect(servers).toEqual([]);@@ -569,9 +607,9 @@ describe('buildMcpServers × pi-acp', () => {throw new Error('probe exploded');},});- expect((await m.buildMcpServers(record('registry', 'pi-acp'), HTTP_INIT)).hostedMarker).toBe(- 'unknown',- );+ expect(+ (await m.buildMcpServers(record('registry', 'pi-acp'), LAUNCH, HTTP_INIT)).hostedMarker,+ ).toBe('unknown');});test('an unprovisioned bridge with no ensure seam reports `none` without prompting', async () => {@@ -585,6 +623,7 @@ describe('buildMcpServers × pi-acp', () => {});const { servers, hostedMarker } = await m.buildMcpServers(record('registry', 'pi-acp'),+ LAUNCH,HTTP_INIT,);expect(servers).toEqual([]);@@ -593,7 +632,7 @@ describe('buildMcpServers × pi-acp', () => {test('a custom agent named like the registry entry still gets normal injection', async () => {const m = makeManager(() => null, undefined, { probePiAcpBridge: () => PI_LOADABLE });- const { servers } = await m.buildMcpServers(record('custom', 'pi-acp'), HTTP_INIT);+ const { servers } = await m.buildMcpServers(record('custom', 'pi-acp'), LAUNCH, HTTP_INIT);expect(servers).toHaveLength(1);});});diff --git a/packages/server/src/acp/superseded-launch.integration.test.ts b/packages/server/src/acp/superseded-launch.integration.test.tsnew file mode 100644index 000000000..f91324050--- /dev/null+++ b/packages/server/src/acp/superseded-launch.integration.test.ts@@ -0,0 +1,1749 @@+import {+ existsSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { ACP_LAUNCH_FAILURE_LOG } from '@inkeep/open-knowledge-core';+import type { ThreadEvent, ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import { afterEach, describe, expect, test, vi } from 'vitest';+import type { AgentSessionManager } from '../agent-sessions.ts';+import { getLogger } from '../logger.ts';+import { waitWithinTestBudget } from '../wait-within-test-budget.test-helper.ts';+import {+ type HeldInstallRegistry,+ withHeldInstallRegistry,+} from './held-install-registry.test-helper.ts';+import { descendantsOf, processEnded } from './npx-cache-entry.test-helper.ts';+import { AcpPermissionStore } from './permissions.ts';+import { AcpRegistry, type RegistryAgent } from './registry.ts';+import { AcpThreadManager, type PiAcpBridgeProbe } from './thread-manager.ts';++const log = getLogger('superseded-launch-test');+const CODEX = 'codex-acp';+const PI = 'pi-acp';+const NEW_WINDOW = 400_000;+const WAIT = { timeoutMs: 15_000 };+const QUIET_MS = 1_500;+const SUPERSEDED_STATUS_LOG = '[acp-threads] status suppressed for a superseded launch';++const sessionManager = {+ getSession: async () => {+ throw new Error('the scripted agent never uses client fs');+ },+ closeAllForAgent: async () => {},+} as unknown as AgentSessionManager;++const SCRIPTED_AGENT = `+import { appendFileSync, existsSync, readFileSync } from 'node:fs';+const STATE = process.env.AGENT_STATE;+const startsPath = STATE + '/starts.jsonl';+let window = null;+try {+ window = JSON.parse(process.env.CODEX_CONFIG ?? '{}').model_context_window ?? null;+} catch {}+appendFileSync(startsPath, JSON.stringify({ pid: process.pid, window }) + '\\n');+const startedPids = () =>+ readFileSync(startsPath, 'utf8').split('\\n').filter((l) => l !== '').map((l) => JSON.parse(l).pid);+const startIndex = startedPids().indexOf(process.pid) + 1;+const youngerStarted = () => {+ const pids = startedPids();+ return pids.length > pids.indexOf(process.pid) + 1;+};+const caps = (process.env.FAKE_CAPS ?? '').split(',').filter(Boolean);+const known = new Set(['sess-' + process.pid]);+const modelOptions = (value) => [+ {+ id: 'model',+ name: 'Model',+ type: 'select',+ category: 'model',+ currentValue: value,+ options: [{ value: 'a', name: 'A' }, { value: 'b', name: 'B' }],+ },+];+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');+const when = (ready, fn) => {+ if (ready()) return fn();+ const timer = setInterval(() => {+ if (ready()) {+ clearInterval(timer);+ fn();+ }+ }, 20);+};+const opened = (name) => () => existsSync(STATE + '/' + name);+const always = () => true;+const lingersAfterFailedInit = process.env.FAIL_FIRST_INIT_AND_LINGER === '1' && startIndex === 1;+if (lingersAfterFailedInit) process.on('SIGTERM', () => {});+setInterval(() => {+ if (existsSync(STATE + '/shutdown')) process.exit(0);+ if (lingersAfterFailedInit && existsSync(STATE + '/first-exit-open')) process.exit(0);+}, 50);+process.stdin.on('end', () => {+ if (!lingersAfterFailedInit) process.exit(0);+});+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });+ const fail = (code, message) => write({ jsonrpc: '2.0', id: msg.id, error: { code, message } });+ if (msg.method === 'initialize') {+ const agentCapabilities = {};+ if (caps.includes('resume')) agentCapabilities.sessionCapabilities = { resume: {} };+ const initResult = { protocolVersion: 1, agentCapabilities };+ if (process.env.AUTH_MODE === '1') initResult.authMethods = [{ id: 'login', name: 'Log in' }];+ const accept = () => reply(initResult);+ if (lingersAfterFailedInit) {+ fail(-32603, 'initialize refused by the first agent (pid ' + process.pid + ')');+ } else if (process.env.FAIL_INIT_WHEN_YOUNGER === '1') {+ when(+ () => youngerStarted() || opened('init-open')(),+ () =>+ youngerStarted()+ ? fail(-32603, 'initialize refused: a younger agent started (pid ' + process.pid + ')')+ : accept(),+ );+ } else {+ when(process.env.HOLD_FIRST_INIT === '1' && startIndex === 1 ? opened('init-open') : always, accept);+ }+ } else if (msg.method === 'authenticate') {+ appendFileSync(STATE + '/authed', process.pid + '\\n');+ reply({});+ } else if (msg.method === 'session/new' && process.env.AUTH_MODE === '1' && !existsSync(STATE + '/authed')) {+ fail(-32000, 'Authentication required');+ } else if (msg.method === 'session/new') {+ appendFileSync(STATE + '/session-requests.log', process.pid + '\\n');+ const result = { sessionId: 'sess-' + process.pid };+ if (process.env.CONFIG_MODE === '1') result.configOptions = modelOptions('a');+ when(+ process.env.HOLD_FIRST_SESSION === '1' && startIndex === 1 ? opened('first-session-open') : always,+ () => reply(result),+ );+ } else if (msg.method === 'session/set_config_option') {+ appendFileSync(STATE + '/config-requests.log', process.pid + '\\n');+ when(+ process.env.HOLD_FIRST_CONFIG === '1' && startIndex === 1 ? opened('first-config-open') : always,+ () => reply({ configOptions: modelOptions(msg.params.value) }),+ );+ } else if (msg.method === 'session/resume') {+ known.add(msg.params.sessionId);+ reply({});+ } else if (msg.method === 'session/prompt') {+ const text = msg.params.prompt+ .filter((block) => block.type === 'text')+ .map((block) => block.text)+ .join('\\n');+ appendFileSync(+ STATE + '/prompts.jsonl',+ JSON.stringify({ pid: process.pid, sessionId: msg.params.sessionId, text }) + '\\n',+ );+ if (known.has(msg.params.sessionId)) {+ write({+ jsonrpc: '2.0',+ method: 'session/update',+ params: {+ sessionId: msg.params.sessionId,+ update: {+ sessionUpdate: 'agent_message_chunk',+ content: { type: 'text', text: 'served by ' + process.pid },+ },+ },+ });+ reply({ stopReason: 'end_turn' });+ } else {+ fail(-32002, 'unknown session ' + msg.params.sessionId + ' (agent pid ' + process.pid + ')');+ }+ } else if (msg.id !== undefined) {+ reply({});+ }+ }+});+`;++type StartedAgent = { pid: number; window: number | null };+type Received = { pid: number; sessionId: string; text: string };+type Settled = { ok: true; info: ThreadInfo } | { ok: false; error: string };++let dirs: string[] = [];+let managers: AcpThreadManager[] = [];+let agentStates: string[] = [];++afterEach(async () => {+ vi.restoreAllMocks();+ await Promise.allSettled(managers.map((manager) => manager.destroy()));+ for (const state of agentStates) writeFileSync(join(state, 'shutdown'), '');+ await waitWithinTestBudget(+ 'every scripted agent to exit',+ () => agentStates.every((state) => startedIn(state).every(({ pid }) => processEnded(pid))),+ { timeoutMs: 10_000 },+ ).catch(() => {});+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });+ dirs = [];+ managers = [];+ agentStates = [];+});++function tmp(): string {+ const dir = mkdtempSync(join(tmpdir(), 'superseded-launch-'));+ dirs.push(dir);+ return dir;+}++function linesOf(path: string): string[] {+ return existsSync(path)+ ? readFileSync(path, 'utf8')+ .split('\n')+ .filter((line) => line !== '')+ : [];+}++function startedIn(state: string): StartedAgent[] {+ return linesOf(join(state, 'starts.jsonl')).map((line) => JSON.parse(line) as StartedAgent);+}++function settle(change: Promise<ThreadInfo>): Promise<Settled> {+ return change.then(+ (info) => ({ ok: true as const, info }),+ (err: unknown) => ({+ ok: false as const,+ error: err instanceof Error ? err.message : String(err),+ }),+ );+}++async function anchorOrQuiet(what: string, anchor: () => boolean): Promise<void> {+ const startedAt = Date.now();+ try {+ await waitWithinTestBudget(what, anchor, { timeoutMs: QUIET_MS });+ } catch (err) {+ const quietHeld =+ err instanceof Error &&+ err.message.startsWith(`timed out waiting for ${what} after `) &&+ Date.now() - startedAt >= QUIET_MS;+ if (!quietHeld) throw err;+ }+}++function supersededFailureReports(warn: ReturnType<typeof vi.spyOn>, threadId: string): number {+ return warn.mock.calls.filter((call: unknown[]) => {+ const [fields, message] = call;+ const report = fields as { threadId?: string; status?: string };+ return (+ message === SUPERSEDED_STATUS_LOG && report.threadId === threadId && report.status === 'error'+ );+ }).length;+}++function quietPeriod(): Promise<void> {+ return anchorOrQuiet('a superseded launch to act', () => false);+}++function scriptedHarness(+ env: Record<string, string> = {},+ entry: { id?: string; command?: string } = {},+) {+ const contentDir = tmp();+ const localDir = tmp();+ const state = tmp();+ agentStates.push(state);+ const agentPath = join(localDir, 'scripted-agent.mjs');+ writeFileSync(agentPath, SCRIPTED_AGENT);+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([+ {+ id: entry.id ?? CODEX,+ name: 'Scripted agent',+ command: entry.command ?? 'node',+ args: [agentPath],+ env: { AGENT_STATE: state, ...env },+ },+ ]),+ );+ const held: Array<PromiseWithResolvers<string | null>> = [];+ let holding = false;+ let closeGate: PromiseWithResolvers<void> | null = null;+ let closeReached = false;+ const manager = new AcpThreadManager({+ contentDir,+ localDir,+ globalDir: null,+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: (async () => {+ throw new Error('offline test');+ }) as typeof fetch,+ }),+ permissions: new AcpPermissionStore(localDir, log),+ sessionManager: {+ ...sessionManager,+ closeAllForAgent: async () => {+ closeReached = true;+ await closeGate?.promise;+ },+ } as unknown as AgentSessionManager,+ isExcludedPath: () => false,+ isIgnoredPath: () => false,+ log,+ projectSkillSourceDir: null,+ resolveLoginShellPath: async () => {+ if (!holding) return null;+ const call = Promise.withResolvers<string | null>();+ held.push(call);+ return call.promise;+ },+ });+ managers.push(manager);+ const started = (): StartedAgent[] => startedIn(state);+ return {+ manager,+ localDir,+ hold: (on: boolean) => {+ holding = on;+ },+ heldCount: () => held.length,+ release: (call: number) => held[call]?.resolve(null),+ holdClose: () => {+ closeGate = Promise.withResolvers<void>();+ },+ closeHeld: () => closeReached,+ releaseClose: () => closeGate?.resolve(),+ started,+ liveAgents: (): StartedAgent[] => started().filter(({ pid }) => !processEnded(pid)),+ received: (): Received[] =>+ linesOf(join(state, 'prompts.jsonl')).map((line) => JSON.parse(line) as Received),+ configRequests: () => linesOf(join(state, 'config-requests.log')),+ sessionRequests: () => linesOf(join(state, 'session-requests.log')),+ open: (gate: string) => writeFileSync(join(state, gate), ''),+ launchFailures: (): string[] => {+ const path = join(localDir, ACP_LAUNCH_FAILURE_LOG);+ if (!existsSync(path)) return [];+ return readFileSync(path, 'utf8')+ .split('=== acp launch failure ')+ .slice(1)+ .map((entry) => {+ const [header = '', detail = ''] = entry.split('\n');+ return `${/reason=(\S+)/.exec(header)?.[1] ?? 'unknown'}: ${detail}`;+ });+ },+ };+}++const PI_PROJECT = {+ project: 'ready',+ cwd: '/tmp/pi-project',+ canonicalCwd: '/tmp/pi-project',+ bridgePath: '/tmp/pi-project/.pi/extensions/open-knowledge.ts',+ trustPath: '/tmp/pi-home/.pi/agent/trust.json',+ otherExtensions: [],+} as const;+const PI_BRIDGE_LOADABLE: PiAcpBridgeProbe = {+ ...PI_PROJECT,+ bridge: 'own-current',+ trust: 'trusted',+ bridgeLoadable: true,+};+const PI_BRIDGE_ABSENT: PiAcpBridgeProbe = {+ ...PI_PROJECT,+ bridge: 'absent',+ trust: 'untrusted',+ bridgeLoadable: false,+};+const PI_BRIDGE_FOREIGN: PiAcpBridgeProbe = {+ ...PI_PROJECT,+ bridge: 'foreign',+ trust: 'untrusted',+ bridgeLoadable: false,+};++function piHarness(env: Record<string, string> = {}) {+ const localDir = tmp();+ const state = tmp();+ const binDir = tmp();+ agentStates.push(state);+ const agentPath = join(localDir, 'scripted-agent.mjs');+ writeFileSync(agentPath, SCRIPTED_AGENT);+ const node = JSON.stringify(process.execPath);+ writeFileSync(join(binDir, 'node'), `#!/bin/sh\nexec ${node} "$@"\n`, { mode: 0o755 });+ writeFileSync(+ join(binDir, 'npx'),+ `#!/bin/sh\nif [ "$1" = "--version" ]; then echo 1.0.0; exit 0; fi\nexec ${node} ${JSON.stringify(agentPath)}\n`,+ { mode: 0o755 },+ );+ const agent: RegistryAgent = {+ id: PI,+ name: 'Scripted Pi',+ version: '1.0.0',+ distribution: {+ npx: { package: '@fake/pi', env: { PATH: binDir, AGENT_STATE: state, ...env } },+ },+ };+ const held: Array<PromiseWithResolvers<PiAcpBridgeProbe>> = [];+ let holding = false;+ const manager = new AcpThreadManager({+ contentDir: tmp(),+ localDir,+ globalDir: null,+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: (async () => new Response(JSON.stringify({ agents: [agent] }))) as typeof fetch,+ }),+ permissions: new AcpPermissionStore(localDir, log),+ sessionManager,+ isExcludedPath: () => false,+ isIgnoredPath: () => false,+ log,+ projectSkillSourceDir: null,+ resolveLoginShellPath: async () => null,+ probePiAcpBridge: () => {+ if (!holding) return PI_BRIDGE_LOADABLE;+ const call = Promise.withResolvers<PiAcpBridgeProbe>();+ held.push(call);+ return call.promise;+ },+ ensurePiAcpBridge: () => ({+ ok: true,+ bridgePath: PI_PROJECT.bridgePath,+ bridge: 'written',+ trust: 'added',+ }),+ });+ managers.push(manager);+ return {+ manager,+ holdProbes: (on: boolean) => {+ holding = on;+ },+ heldProbes: () => held.length,+ releaseProbe: (call: number, answer: PiAcpBridgeProbe) => held[call]?.resolve(answer),+ };+}++function catalogHarness(opts: { browser?: boolean } = {}) {+ const localDir = tmp();+ const state = tmp();+ const binDir = tmp();+ agentStates.push(state);+ const agentPath = join(localDir, 'scripted-agent.mjs');+ writeFileSync(agentPath, SCRIPTED_AGENT);+ const node = JSON.stringify(process.execPath);+ writeFileSync(join(binDir, 'node'), `#!/bin/sh\nexec ${node} "$@"\n`, { mode: 0o755 });+ writeFileSync(+ join(binDir, 'npx'),+ `#!/bin/sh\nif [ "$1" = "--version" ]; then echo 1.0.0; exit 0; fi\nexec ${node} ${JSON.stringify(agentPath)}\n`,+ { mode: 0o755 },+ );+ const agent: RegistryAgent = {+ id: CODEX,+ name: 'Scripted catalog codex',+ version: '1.0.0',+ distribution: { npx: { package: '@fake/codex', env: { PATH: binDir, AGENT_STATE: state } } },+ };+ const heldCatalogs: Array<PromiseWithResolvers<RegistryAgent[]>> = [];+ let holdingCatalog = false;+ const heldShells: Array<PromiseWithResolvers<string | null>> = [];+ let holdingShell = false;+ let browserNpxLookups = 0;+ let browserInstalls = 0;+ const browserSeams =+ opts.browser === true+ ? {+ globalDir: tmp(),+ agentBrowserTools: () => true,+ resolveBrowserNpx: () => {+ browserNpxLookups += 1;+ return { npx: join(binDir, 'npx'), path: binDir };+ },+ ensureBrowserPackage: async () => {+ browserInstalls += 1;+ },+ }+ : {};+ const manager = new AcpThreadManager({+ contentDir: tmp(),+ localDir,+ globalDir: null,+ registry: new AcpRegistry({+ localDir,+ log,+ ttlMs: 0,+ fetchImpl: (async () => {+ if (!holdingCatalog) return new Response(JSON.stringify({ agents: [agent] }));+ const call = Promise.withResolvers<RegistryAgent[]>();+ heldCatalogs.push(call);+ return new Response(JSON.stringify({ agents: await call.promise }));+ }) as typeof fetch,+ }),+ permissions: new AcpPermissionStore(localDir, log),+ sessionManager,+ isExcludedPath: () => false,+ isIgnoredPath: () => false,+ log,+ projectSkillSourceDir: null,+ ...browserSeams,+ resolveLoginShellPath: async () => {+ if (!holdingShell) return null;+ const call = Promise.withResolvers<string | null>();+ heldShells.push(call);+ return call.promise;+ },+ });+ managers.push(manager);+ const started = (): StartedAgent[] => startedIn(state);+ return {+ manager,+ agent,+ holdCatalog: (on: boolean) => {+ holdingCatalog = on;+ },+ heldCatalogs: () => heldCatalogs.length,+ releaseCatalog: (call: number, agents: RegistryAgent[]) => heldCatalogs[call]?.resolve(agents),+ holdShell: (on: boolean) => {+ holdingShell = on;+ },+ heldShells: () => heldShells.length,+ releaseShell: (call: number) => heldShells[call]?.resolve(null),+ browserNpxLookups: () => browserNpxLookups,+ browserInstalls: () => browserInstalls,+ liveAgents: (): StartedAgent[] => started().filter(({ pid }) => !processEnded(pid)),+ received: (): Received[] =>+ linesOf(join(state, 'prompts.jsonl')).map((line) => JSON.parse(line) as Received),+ };+}++async function observe(manager: AcpThreadManager, threadId: string) {+ const seen = new Map<number, ThreadEvent>();+ await manager.subscribe(threadId, 0, (frame) => {+ if (frame.op === 'event') seen.set(frame.seq, frame.event);+ else if (frame.op === 'events') {+ frame.events.forEach((event, index) => {+ seen.set(frame.fromSeq + index, event);+ });+ }+ });+ const events = (afterSeq = -1): Array<{ seq: number; event: ThreadEvent }> =>+ [...seen.entries()]+ .filter(([seq]) => seq > afterSeq)+ .sort(([a], [b]) => a - b)+ .map(([seq, event]) => ({ seq, event }));+ const statuses = (afterSeq = -1): string[] =>+ events(afterSeq).flatMap(({ event }) =>+ event.kind === 'status'+ ? [event.detail === undefined ? event.status : `${event.status}: ${event.detail}`]+ : [],+ );+ return { events, statuses };+}++type View = Awaited<ReturnType<typeof observe>>;++function userMessagesIn(view: View): string[] {+ return view+ .events()+ .flatMap(({ event }) => (event.kind === 'user_message' ? [event.content] : []));+}++function launchReadiesBeforeFirstUserMessage(view: View): string[] {+ const events = view.events().map(({ event }) => event);+ const firstUserMessage = events.findIndex((event) => event.kind === 'user_message');+ return readiesIn(+ events+ .slice(0, firstUserMessage === -1 ? events.length : firstUserMessage)+ .flatMap((event) => (event.kind === 'status' ? [event.status] : [])),+ );+}++function piBridgeEventsIn(view: View): string[] {+ return view+ .events()+ .flatMap(({ event }) =>+ event.kind === 'pi_bridge_consent_request' || event.kind === 'pi_bridge_status'+ ? [event.kind]+ : [],+ );+}++function errorsIn(statuses: string[]): string[] {+ return statuses.filter((status) => status.startsWith('error'));+}++function readiesIn(statuses: string[]): string[] {+ return statuses.filter((status) => status === 'ready');+}++async function promptTurn(+ manager: AcpThreadManager,+ threadId: string,+ view: View,+ text: string,+): Promise<{ refused: string | null; stopReason: string | null; servedBy: number | null }> {+ const from = manager.getInfo(threadId)?.lastSeq ?? -1;+ try {+ manager.sendPrompt(threadId, text);+ } catch (err) {+ return {+ refused: err instanceof Error ? err.message : String(err),+ stopReason: null,+ servedBy: null,+ };+ }+ await waitWithinTestBudget(+ `the turn for "${text}" to end or fail`,+ () =>+ view+ .events(from)+ .some(+ ({ event }) =>+ event.kind === 'turn_ended' || (event.kind === 'status' && event.status === 'error'),+ ),+ WAIT,+ );+ const after = view.events(from).map(({ event }) => event);+ const ended = after.find((event) => event.kind === 'turn_ended');+ const served = /served by (\d+)/.exec(JSON.stringify(after));+ return {+ refused: null,+ stopReason: ended?.kind === 'turn_ended' ? ended.stopReason : null,+ servedBy: served === null ? null : Number(served[1]),+ };+}++async function closeAndAwaitAgentsGone(+ harness: ReturnType<typeof scriptedHarness>,+ threadId: string,+): Promise<StartedAgent[]> {+ await harness.manager.closeThread(threadId);+ await waitWithinTestBudget(+ 'every agent the thread started to exit after close',+ () => harness.liveAgents().length === 0,+ { timeoutMs: 5_000 },+ ).catch(() => {});+ return harness.liveAgents();+}++describe('a context window change superseding a thread first launch', () => {+ test('a change before the first launch spawns leaves one agent on the new window, ready once, serving prompts and stopped on close', async () => {+ const harness = scriptedHarness();+ harness.hold(true);+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ const changed = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ await waitWithinTestBudget(+ 'the restart to wait before spawning',+ () => harness.heldCount() === 2,+ WAIT,+ );+ harness.hold(false);+ harness.release(0);+ harness.release(1);++ expect(await changed).toMatchObject({+ ok: true,+ info: { status: 'ready', contextWindow: NEW_WINDOW },+ });+ await anchorOrQuiet(+ 'a second ready from the superseded launch',+ () => readiesIn(view.statuses()).length >= 2,+ );+ const live = harness.liveAgents();+ expect.soft(live.map(({ window }) => window)).toEqual([NEW_WINDOW]);+ expect.soft(readiesIn(view.statuses())).toEqual(['ready']);+ expect+ .soft(await promptTurn(harness.manager, info.threadId, view, 'hello'))+ .toEqual({ refused: null, stopReason: 'end_turn', servedBy: live[0]?.pid });+ expect(await closeAndAwaitAgentsGone(harness, info.threadId)).toEqual([]);+ }, 45_000);++ test('a first launch superseded before it spawns starts no agent when released ahead of the restart', async () => {+ const harness = scriptedHarness();+ harness.hold(true);+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ const changed = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ await waitWithinTestBudget(+ 'the restart to wait before spawning',+ () => harness.heldCount() === 2,+ WAIT,+ );+ harness.hold(false);+ harness.release(0);+ await anchorOrQuiet('the superseded launch to spawn', () => harness.started().length > 0);+ expect(harness.started()).toEqual([]);+ harness.release(1);+ const outcome = await changed;+ await anchorOrQuiet(+ 'a second ready from the superseded launch',+ () => readiesIn(view.statuses()).length >= 2,+ );++ expect.soft(outcome).toMatchObject({+ ok: true,+ info: { status: 'ready', contextWindow: NEW_WINDOW },+ });+ const live = harness.liveAgents();+ expect.soft(live.map(({ window }) => window)).toEqual([NEW_WINDOW]);+ expect.soft(readiesIn(view.statuses())).toEqual(['ready']);+ expect+ .soft(await promptTurn(harness.manager, info.threadId, view, 'hello'))+ .toEqual({ refused: null, stopReason: 'end_turn', servedBy: live[0]?.pid });+ expect(await closeAndAwaitAgentsGone(harness, info.threadId)).toEqual([]);+ }, 45_000);++ test('a first launch the change stops during initialize reports no failure while the restart is pending', async () => {+ const warn = vi.spyOn(log, 'warn');+ const harness = scriptedHarness({ HOLD_FIRST_INIT: '1' });+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first agent to start and wait on initialize',+ () => harness.started().length === 1,+ WAIT,+ );+ harness.hold(true);+ const changed = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ await waitWithinTestBudget(+ 'the restart to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ await waitWithinTestBudget(+ 'the stopped first launch to settle its failure as superseded',+ () => supersededFailureReports(warn, info.threadId) === 1,+ WAIT,+ );+ await quietPeriod();++ expect.soft(errorsIn(view.statuses())).toEqual([]);+ expect.soft(harness.launchFailures()).toEqual([]);+ harness.hold(false);+ harness.release(0);+ expect.soft(await changed).toMatchObject({+ ok: true,+ info: { status: 'ready', contextWindow: NEW_WINDOW },+ });+ const live = harness.liveAgents();+ expect.soft(live.map(({ window }) => window)).toEqual([NEW_WINDOW]);+ expect+ .soft(await promptTurn(harness.manager, info.threadId, view, 'hello'))+ .toEqual({ refused: null, stopReason: 'end_turn', servedBy: live[0]?.pid });+ expect(await closeAndAwaitAgentsGone(harness, info.threadId)).toEqual([]);+ }, 45_000);++ test('a first launch the change stops while its session opens reports no failure while the restart is pending', async () => {+ const warn = vi.spyOn(log, 'warn');+ const harness = scriptedHarness({ HOLD_FIRST_SESSION: '1' });+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first agent to request its session and wait for it',+ () => harness.sessionRequests().length === 1,+ WAIT,+ );+ harness.hold(true);+ const changed = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ await waitWithinTestBudget(+ 'the restart to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ await waitWithinTestBudget(+ 'the stopped first launch to settle its failure as superseded',+ () => supersededFailureReports(warn, info.threadId) === 1,+ WAIT,+ );+ await quietPeriod();++ expect.soft(errorsIn(view.statuses())).toEqual([]);+ expect.soft(harness.launchFailures()).toEqual([]);+ harness.hold(false);+ harness.release(0);+ expect.soft(await changed).toMatchObject({+ ok: true,+ info: { status: 'ready', contextWindow: NEW_WINDOW },+ });+ await quietPeriod();+ expect.soft(errorsIn(view.statuses())).toEqual([]);+ expect.soft(harness.launchFailures()).toEqual([]);+ const live = harness.liveAgents();+ expect.soft(live.map(({ window }) => window)).toEqual([NEW_WINDOW]);+ expect+ .soft(await promptTurn(harness.manager, info.threadId, view, 'hello'))+ .toEqual({ refused: null, stopReason: 'end_turn', servedBy: live[0]?.pid });+ expect(await closeAndAwaitAgentsGone(harness, info.threadId)).toEqual([]);+ }, 45_000);++ test('a first launch superseded before it spawns starts no agent when released after the restart agent has started', async () => {+ const harness = scriptedHarness({ FAIL_INIT_WHEN_YOUNGER: '1' });+ harness.hold(true);+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ const changed = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ await waitWithinTestBudget(+ 'the restart to wait before spawning',+ () => harness.heldCount() === 2,+ WAIT,+ );+ harness.hold(false);+ harness.release(1);+ await waitWithinTestBudget(+ 'the restart agent to start and wait on initialize',+ () => harness.started().length === 1,+ WAIT,+ );+ harness.release(0);+ await anchorOrQuiet('the superseded launch to spawn', () => harness.started().length > 1);+ expect(harness.started()).toHaveLength(1);+ harness.open('init-open');++ expect.soft(await changed).toMatchObject({+ ok: true,+ info: { status: 'ready', contextWindow: NEW_WINDOW },+ });+ expect.soft(errorsIn(view.statuses())).toEqual([]);+ expect.soft(harness.launchFailures()).toEqual([]);+ const live = harness.liveAgents();+ expect.soft(live.map(({ window }) => window)).toEqual([NEW_WINDOW]);+ expect+ .soft(await promptTurn(harness.manager, info.threadId, view, 'hello'))+ .toEqual({ refused: null, stopReason: 'end_turn', servedBy: live[0]?.pid });+ expect(await closeAndAwaitAgentsGone(harness, info.threadId)).toEqual([]);+ }, 45_000);++ test('a change while the remembered model applies delivers the initial prompt exactly once, to the agent the thread owns', async () => {+ const harness = scriptedHarness({ CONFIG_MODE: '1', HOLD_FIRST_CONFIG: '1' });+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: CODEX },+ prompt: 'hello first',+ settings: { config: { model: 'b' } },+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to publish config options and send the remembered model',+ () =>+ harness.manager.getInfo(info.threadId)?.configOptions != null &&+ harness.configRequests().length === 1,+ WAIT,+ );+ expect({+ status: harness.manager.getInfo(info.threadId)?.status,+ hasStartedWork: harness.manager.hasStartedWork(info.threadId),+ }).toEqual({ status: 'spawning', hasStartedWork: false });++ expect+ .soft(await settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW)))+ .toMatchObject({ ok: true, info: { status: 'running', contextWindow: NEW_WINDOW } });+ await waitWithinTestBudget(+ 'the initial prompt turn to end',+ () => view.events().some(({ event }) => event.kind === 'turn_ended'),+ { timeoutMs: 10_000 },+ ).catch(() => {});+ await quietPeriod();++ const live = harness.liveAgents();+ const events = view.events().map(({ event }) => event);+ const firstUserMessage = events.findIndex((event) => event.kind === 'user_message');+ const launchStatuses = events+ .slice(0, firstUserMessage === -1 ? events.length : firstUserMessage)+ .flatMap((event) => (event.kind === 'status' ? [event.status] : []));+ expect.soft(errorsIn(view.statuses())).toEqual([]);+ expect.soft(readiesIn(launchStatuses)).toEqual(['ready']);+ expect+ .soft(events.flatMap((event) => (event.kind === 'user_message' ? [event.content] : [])))+ .toEqual(['hello first']);+ expect.soft(live.map(({ window }) => window)).toEqual([NEW_WINDOW]);+ expect(+ harness+ .received()+ .map(({ pid, text }) => ({ pid, initialPrompt: text.includes('hello first') })),+ ).toEqual([{ pid: live[0]?.pid, initialPrompt: true }]);+ }, 45_000);++ test('a first launch released after an archive and resume never acts on the resumed thread', async () => {+ const harness = scriptedHarness({ FAKE_CAPS: 'resume' });+ await harness.manager.init();+ harness.hold(true);+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ harness.hold(false);+ expect(await settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW))).toMatchObject(+ { ok: true, info: { status: 'ready' } },+ );+ expect(await promptTurn(harness.manager, info.threadId, view, 'first turn')).toMatchObject({+ stopReason: 'end_turn',+ });+ await harness.manager.closeThread(info.threadId);+ expect(harness.manager.getInfo(info.threadId)?.archived).toBe(true);+ expect((await harness.manager.resumeThread(info.threadId)).status).toBe('ready');+ const resumed = harness.liveAgents();+ expect(resumed).toHaveLength(1);+ const startedBeforeRelease = harness.started().length;+ const releasedAt = harness.manager.getInfo(info.threadId)?.lastSeq ?? -1;++ harness.release(0);+ await anchorOrQuiet(+ 'the superseded launch to spawn',+ () => harness.started().length > startedBeforeRelease,+ );+ await quietPeriod();++ expect.soft(view.statuses(releasedAt)).toEqual([]);+ expect.soft(harness.liveAgents()).toEqual(resumed);+ expect+ .soft(await promptTurn(harness.manager, info.threadId, view, 'after release'))+ .toEqual({ refused: null, stopReason: 'end_turn', servedBy: resumed[0]?.pid });+ expect(await closeAndAwaitAgentsGone(harness, info.threadId)).toEqual([]);+ }, 60_000);++ test('a change requested after the first launch opens its session but before it is ready is refused once that launch delivers the initial prompt exactly once, after one ready', async () => {+ const harness = scriptedHarness({ CONFIG_MODE: '1' });+ harness.hold(true);+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: CODEX },+ prompt: 'hello first',+ });+ const change: { outcome?: Promise<Settled> } = {};+ await harness.manager.subscribe(info.threadId, 0, (frame) => {+ if (+ change.outcome !== undefined ||+ frame.op !== 'info' ||+ frame.info.status !== 'spawning' ||+ frame.info.configOptions == null+ ) {+ return;+ }+ change.outcome = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ harness.hold(false);+ harness.release(0);+ await waitWithinTestBudget(+ 'the first launch to open its session and publish config options',+ () => change.outcome !== undefined,+ WAIT,+ );++ expect+ .soft(await change.outcome)+ .toEqual({ ok: false, error: 'start a new chat to change the context window' });+ await waitWithinTestBudget(+ 'the initial prompt turn to end',+ () => view.events().some(({ event }) => event.kind === 'turn_ended'),+ { timeoutMs: 10_000 },+ ).catch(() => {});+ await quietPeriod();++ const live = harness.liveAgents();+ expect.soft(errorsIn(view.statuses())).toEqual([]);+ expect.soft(launchReadiesBeforeFirstUserMessage(view)).toEqual(['ready']);+ expect.soft(userMessagesIn(view)).toEqual(['hello first']);+ expect.soft(live.map(({ window }) => window)).toEqual([null]);+ expect(+ harness+ .received()+ .map(({ pid, text }) => ({ pid, initialPrompt: text.includes('hello first') })),+ ).toEqual([{ pid: live[0]?.pid, initialPrompt: true }]);+ }, 45_000);++ test.skipIf(process.platform === 'win32')(+ 'a change requested at the failed first launch failure report sends no initial prompt',+ async () => {+ const binDir = tmp();+ const agentNode = join(binDir, 'agent-node');+ symlinkSync(process.execPath, agentNode);+ const harness = scriptedHarness({}, { command: agentNode });+ harness.hold(true);+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: CODEX },+ prompt: 'hello first',+ });+ const change: { outcome?: Promise<Settled> } = {};+ await harness.manager.subscribe(info.threadId, 0, (frame) => {+ if (change.outcome !== undefined || frame.op !== 'info' || frame.info.status !== 'error') {+ return;+ }+ symlinkSync(process.execPath, agentNode);+ change.outcome = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ unlinkSync(agentNode);+ harness.release(0);+ await waitWithinTestBudget(+ 'the restart to wait before spawning',+ () => harness.heldCount() === 2,+ WAIT,+ );+ await quietPeriod();+ harness.hold(false);+ harness.release(1);++ expect(change.outcome).toBeDefined();+ expect+ .soft(await change.outcome)+ .toMatchObject({ ok: true, info: { status: 'ready', contextWindow: NEW_WINDOW } });+ await quietPeriod();++ expect.soft(userMessagesIn(view)).toEqual([]);+ expect.soft(harness.received()).toEqual([]);+ const live = harness.liveAgents();+ expect.soft(live.map(({ window }) => window)).toEqual([NEW_WINDOW]);+ expect(await promptTurn(harness.manager, info.threadId, view, 'hello')).toEqual({+ refused: null,+ stopReason: 'end_turn',+ servedBy: live[0]?.pid,+ });+ },+ 45_000,+ );++ test.skipIf(process.platform === 'win32')(+ 'a change requested at the failed first launch failure report sends no initial prompt while the failed agent is still exiting',+ async () => {+ const harness = scriptedHarness({ FAIL_FIRST_INIT_AND_LINGER: '1' });+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: CODEX },+ prompt: 'hello first',+ });+ const change: { outcome?: Promise<Settled> } = {};+ await harness.manager.subscribe(info.threadId, 0, (frame) => {+ if (change.outcome !== undefined || frame.op !== 'info' || frame.info.status !== 'error') {+ return;+ }+ change.outcome = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the change to start a second agent',+ () => harness.started().length === 2,+ WAIT,+ );+ const [failed] = harness.started();+ expect(change.outcome).toBeDefined();+ expect(failed !== undefined && !processEnded(failed.pid)).toBe(true);+ harness.open('first-exit-open');++ expect+ .soft(await change.outcome)+ .toMatchObject({ ok: true, info: { status: 'ready', contextWindow: NEW_WINDOW } });+ await waitWithinTestBudget(+ 'the failed first agent to exit',+ () => failed !== undefined && processEnded(failed.pid),+ WAIT,+ );+ await quietPeriod();++ expect.soft(userMessagesIn(view)).toEqual([]);+ expect.soft(harness.received()).toEqual([]);+ const live = harness.liveAgents();+ expect.soft(live.map(({ window }) => window)).toEqual([NEW_WINDOW]);+ expect(await promptTurn(harness.manager, info.threadId, view, 'hello')).toEqual({+ refused: null,+ stopReason: 'end_turn',+ servedBy: live[0]?.pid,+ });+ },+ 45_000,+ );+});++describe('a retry superseding a thread first launch', () => {+ test.skipIf(process.platform === 'win32')(+ 'a retry requested at the failed first launch failure report reports no failure after its own spawning status and serves the thread from one agent',+ async () => {+ const binDir = tmp();+ const agentNode = join(binDir, 'agent-node');+ symlinkSync(process.execPath, agentNode);+ const harness = scriptedHarness({}, { id: 'retried-agent', command: agentNode });+ harness.hold(true);+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: 'retried-agent' },+ });+ const retry: { outcome?: Promise<Settled>; afterSeq?: number } = {};+ await harness.manager.subscribe(info.threadId, 0, (frame) => {+ if (retry.outcome !== undefined || frame.op !== 'info' || frame.info.status !== 'error') {+ return;+ }+ symlinkSync(process.execPath, agentNode);+ retry.afterSeq = frame.info.lastSeq;+ retry.outcome = settle(harness.manager.retryThread(info.threadId));+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ unlinkSync(agentNode);+ harness.release(0);+ await waitWithinTestBudget(+ 'the retry to wait before spawning',+ () => harness.heldCount() === 2,+ WAIT,+ );+ await quietPeriod();++ const takeover = view+ .events(retry.afterSeq)+ .find(({ event }) => event.kind === 'status' && event.status === 'spawning');+ expect(takeover).toBeDefined();+ expect.soft(errorsIn(view.statuses(takeover?.seq))).toEqual([]);+ harness.hold(false);+ harness.release(1);+ expect.soft(await retry.outcome).toMatchObject({ ok: true, info: { status: 'ready' } });+ const live = harness.liveAgents();+ expect.soft(live).toHaveLength(1);+ expect+ .soft(await promptTurn(harness.manager, info.threadId, view, 'hello'))+ .toEqual({ refused: null, stopReason: 'end_turn', servedBy: live[0]?.pid });+ expect(await closeAndAwaitAgentsGone(harness, info.threadId)).toEqual([]);+ },+ 45_000,+ );++ test.skipIf(process.platform === 'win32')(+ 'a retry requested at the failed first launch failure report sends no initial prompt',+ async () => {+ const binDir = tmp();+ const agentNode = join(binDir, 'agent-node');+ symlinkSync(process.execPath, agentNode);+ const harness = scriptedHarness({}, { id: 'retried-agent', command: agentNode });+ harness.hold(true);+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: 'retried-agent' },+ prompt: 'hello first',+ });+ const retry: { outcome?: Promise<Settled> } = {};+ await harness.manager.subscribe(info.threadId, 0, (frame) => {+ if (retry.outcome !== undefined || frame.op !== 'info' || frame.info.status !== 'error') {+ return;+ }+ symlinkSync(process.execPath, agentNode);+ retry.outcome = settle(harness.manager.retryThread(info.threadId));+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ unlinkSync(agentNode);+ harness.release(0);+ await waitWithinTestBudget(+ 'the retry to wait before spawning',+ () => harness.heldCount() === 2,+ WAIT,+ );+ await quietPeriod();+ harness.hold(false);+ harness.release(1);++ expect(retry.outcome).toBeDefined();+ expect.soft(await retry.outcome).toMatchObject({ ok: true, info: { status: 'ready' } });+ await quietPeriod();++ expect.soft(userMessagesIn(view)).toEqual([]);+ expect.soft(harness.received()).toEqual([]);+ const live = harness.liveAgents();+ expect(await promptTurn(harness.manager, info.threadId, view, 'hello')).toEqual({+ refused: null,+ stopReason: 'end_turn',+ servedBy: live[0]?.pid,+ });+ },+ 45_000,+ );+});++describe.skipIf(process.platform === 'win32')(+ 'a context window change while the catalog agent npx package installs',+ () => {+ function heldCodexManager(held: HeldInstallRegistry): AcpThreadManager {+ const localDir = mkdtempSync(join(held.home, 'local-'));+ const contentDir = mkdtempSync(join(held.home, 'content-'));+ const agent: RegistryAgent = {+ id: CODEX,+ name: 'Held install codex',+ version: '1.0.0',+ distribution: { npx: { package: held.npmPackage } },+ };+ return new AcpThreadManager({+ contentDir,+ localDir,+ globalDir: null,+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: (async () =>+ new Response(JSON.stringify({ agents: [agent] }))) as typeof fetch,+ }),+ permissions: new AcpPermissionStore(localDir, log),+ sessionManager,+ isExcludedPath: () => false,+ isIgnoredPath: () => false,+ log,+ resolveLoginShellPath: async () => null,+ projectSkillSourceDir: null,+ });+ }++ test('the change starts one agent, reports ready once, and leaves nothing the thread started alive after close', async () => {+ expect(+ () => descendantsOf(process.pid),+ 'this test reads the process table with ps',+ ).not.toThrow();+ await withHeldInstallRegistry(async (held) => {+ const preexisting = new Set(descendantsOf(process.pid));+ const started = new Set<number>();+ const liveSinceStart = (): number[] => {+ const live = descendantsOf(process.pid).filter((pid) => !preexisting.has(pid));+ for (const pid of live) started.add(pid);+ return live;+ };+ const manager = heldCodexManager(held);+ try {+ const info = await manager.createThread({ agent: { source: 'registry', id: CODEX } });+ const view = await observe(manager, info.threadId);+ await waitWithinTestBudget(+ 'npm to request the held dependency tarball mid-install',+ () => {+ liveSinceStart();+ return held.requested('npm-dependency') === 1;+ },+ { timeoutMs: 60_000 },+ );+ const changed = settle(manager.setContextWindow(info.threadId, NEW_WINDOW));+ await waitWithinTestBudget(+ 'the restart to join the in-flight install',+ () => {+ liveSinceStart();+ return view.statuses().filter((status) => status === 'installing').length >= 2;+ },+ { timeoutMs: 30_000 },+ );+ held.release('npm-dependency');++ expect+ .soft(await changed)+ .toMatchObject({ ok: true, info: { status: 'ready', contextWindow: NEW_WINDOW } });+ await anchorOrQuiet('a second ready from the superseded launch', () => {+ liveSinceStart();+ return readiesIn(view.statuses()).length >= 2;+ });+ expect.soft(readiesIn(view.statuses())).toEqual(['ready']);+ await manager.closeThread(info.threadId);+ await waitWithinTestBudget(+ 'every process the thread started to exit after close',+ () => liveSinceStart().length === 0 && [...started].every(processEnded),+ { timeoutMs: 15_000 },+ ).catch(() => {});+ expect(liveSinceStart()).toEqual([]);+ } finally {+ held.release('npm-dependency');+ await manager.destroy();+ }+ });+ }, 150_000);+ },+);++describe.skipIf(process.platform === 'win32')(+ 'a Pi bridge step of a launch that is no longer current',+ () => {+ test('a sign-in the retry superseded asks for no Pi bridge consent once its bridge probe returns', async () => {+ const harness = piHarness({ AUTH_MODE: '1' });+ const info = await harness.manager.createThread({ agent: { source: 'registry', id: PI } });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to park on sign-in',+ () => harness.manager.getInfo(info.threadId)?.status === 'auth_required',+ WAIT,+ );+ harness.holdProbes(true);+ const signIn = settle(harness.manager.authenticateThread(info.threadId, 'login'));+ await waitWithinTestBudget(+ 'the sign-in to probe the Pi bridge',+ () => harness.heldProbes() === 1,+ WAIT,+ );+ harness.holdProbes(false);+ expect(await settle(harness.manager.retryThread(info.threadId))).toMatchObject({+ ok: true,+ info: { status: 'ready' },+ });++ harness.releaseProbe(0, PI_BRIDGE_ABSENT);+ expect+ .soft(await signIn)+ .toEqual({ ok: false, error: 'the thread was restarted during the sign-in' });+ await anchorOrQuiet(+ 'the superseded sign-in to touch the Pi bridge',+ () => piBridgeEventsIn(view).length > 0,+ );+ expect(piBridgeEventsIn(view)).toEqual([]);+ }, 45_000);++ test('a resume closed while its bridge probe is pending reports no Pi bridge status on the archived thread', async () => {+ const harness = piHarness();+ await harness.manager.init();+ const info = await harness.manager.createThread({ agent: { source: 'registry', id: PI } });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to be ready',+ () => harness.manager.getInfo(info.threadId)?.status === 'ready',+ WAIT,+ );+ expect(await promptTurn(harness.manager, info.threadId, view, 'first turn')).toMatchObject({+ stopReason: 'end_turn',+ });+ await harness.manager.closeThread(info.threadId);+ harness.holdProbes(true);+ const resumed = settle(harness.manager.resumeThread(info.threadId));+ await waitWithinTestBudget(+ 'the resume to probe the Pi bridge',+ () => harness.heldProbes() === 1,+ WAIT,+ );+ await harness.manager.closeThread(info.threadId);+ expect(harness.manager.getInfo(info.threadId)?.archived).toBe(true);++ harness.releaseProbe(0, PI_BRIDGE_FOREIGN);+ expect.soft(await resumed).toEqual({ ok: false, error: 'thread closed during resume' });+ await anchorOrQuiet(+ 'the closed resume to touch the Pi bridge',+ () => piBridgeEventsIn(view).length > 0,+ );+ expect(piBridgeEventsIn(view)).toEqual([]);+ }, 45_000);+ },+);++describe.skipIf(process.platform === 'win32')(+ 'a browser step of a launch that is no longer current',+ () => {+ test('a first launch a context window change supersedes while it looks up its login shell for the browser never finds the browser npx or installs the browser', async () => {+ const harness = catalogHarness({ browser: true });+ harness.holdShell(true);+ const info = await harness.manager.createThread({ agent: { source: 'registry', id: CODEX } });+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldShells() === 1,+ WAIT,+ );+ harness.releaseShell(0);+ await waitWithinTestBudget(+ 'the first launch to look up its login shell for the browser',+ () => harness.heldShells() === 2,+ WAIT,+ );+ const changed = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ await waitWithinTestBudget(+ 'the restart to wait before spawning',+ () => harness.heldShells() === 3,+ WAIT,+ );+ harness.holdShell(false);+ harness.releaseShell(2);+ expect(await changed).toMatchObject({+ ok: true,+ info: { status: 'ready', contextWindow: NEW_WINDOW },+ });+ expect({+ lookups: harness.browserNpxLookups(),+ installs: harness.browserInstalls(),+ }).toEqual({ lookups: 1, installs: 1 });++ harness.releaseShell(1);+ await anchorOrQuiet(+ 'the superseded launch to look up the browser npx',+ () => harness.browserNpxLookups() > 1,+ );++ expect({+ lookups: harness.browserNpxLookups(),+ installs: harness.browserInstalls(),+ }).toEqual({ lookups: 1, installs: 1 });+ expect(harness.manager.getInfo(info.threadId)?.status).toBe('ready');+ }, 45_000);+ },+);++describe('a first launch that stays current', () => {+ test('a change refused before it takes over leaves the first launch to start the thread and deliver its prompt once', async () => {+ const harness = scriptedHarness();+ harness.hold(true);+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: CODEX },+ prompt: 'hello first',+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ writeFileSync(join(harness.localDir, 'acp-agents.json'), JSON.stringify([]));++ await expect(harness.manager.setContextWindow(info.threadId, NEW_WINDOW)).rejects.toThrow(+ /no custom agent/,+ );+ harness.hold(false);+ harness.release(0);+ await waitWithinTestBudget(+ 'the initial prompt turn to end',+ () => view.events().some(({ event }) => event.kind === 'turn_ended'),+ WAIT,+ );+ await quietPeriod();++ const live = harness.liveAgents();+ expect.soft(errorsIn(view.statuses())).toEqual([]);+ expect.soft(launchReadiesBeforeFirstUserMessage(view)).toEqual(['ready']);+ expect.soft(userMessagesIn(view)).toEqual(['hello first']);+ expect.soft(harness.started().map(({ window }) => window)).toEqual([null]);+ expect.soft(harness.manager.getInfo(info.threadId)?.contextWindow).toBeNull();+ expect(+ harness+ .received()+ .map(({ pid, text }) => ({ pid, initialPrompt: text.includes('hello first') })),+ ).toEqual([{ pid: live[0]?.pid, initialPrompt: true }]);+ }, 45_000);++ test.skipIf(process.platform === 'win32')(+ 'a change refused while the first launch moves past a check leaves that launch to start the thread and deliver its prompt once',+ async () => {+ const harness = catalogHarness();+ harness.holdShell(true);+ const info = await harness.manager.createThread({+ agent: { source: 'registry', id: CODEX },+ prompt: 'hello first',+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldShells() === 1,+ WAIT,+ );+ harness.holdCatalog(true);+ const changed = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ await waitWithinTestBudget(+ 'the change to look its agent up in the catalog',+ () => harness.heldCatalogs() === 1,+ WAIT,+ );+ harness.holdShell(false);+ harness.releaseShell(0);+ await waitWithinTestBudget(+ 'the initial prompt turn to end',+ () => view.events().some(({ event }) => event.kind === 'turn_ended'),+ WAIT,+ ).catch(() => {});+ harness.releaseCatalog(0, [{ ...harness.agent, id: 'another-agent' }]);++ expect+ .soft(await changed)+ .toEqual({ ok: false, error: `agent '${CODEX}' is not in the registry` });+ await quietPeriod();+ const live = harness.liveAgents();+ expect.soft(errorsIn(view.statuses())).toEqual([]);+ expect.soft(launchReadiesBeforeFirstUserMessage(view)).toEqual(['ready']);+ expect.soft(userMessagesIn(view)).toEqual(['hello first']);+ expect.soft(harness.manager.getInfo(info.threadId)?.contextWindow).toBeNull();+ expect(+ harness+ .received()+ .map(({ pid, text }) => ({ pid, initialPrompt: text.includes('hello first') })),+ ).toEqual([{ pid: live[0]?.pid, initialPrompt: true }]);+ },+ 45_000,+ );++ test.skipIf(process.platform === 'win32')(+ 'a retry after the first launch has failed sends no initial prompt',+ async () => {+ const binDir = tmp();+ const agentNode = join(binDir, 'agent-node');+ symlinkSync(process.execPath, agentNode);+ const harness = scriptedHarness({}, { id: 'retried-agent', command: agentNode });+ harness.hold(true);+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: 'retried-agent' },+ prompt: 'hello first',+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ unlinkSync(agentNode);+ harness.hold(false);+ harness.release(0);+ await waitWithinTestBudget(+ 'the first launch to fail',+ () => errorsIn(view.statuses()).length > 0,+ WAIT,+ );+ await quietPeriod();++ symlinkSync(process.execPath, agentNode);+ expect+ .soft(await settle(harness.manager.retryThread(info.threadId)))+ .toMatchObject({ ok: true, info: { status: 'ready' } });+ await quietPeriod();++ expect.soft(userMessagesIn(view)).toEqual([]);+ expect.soft(harness.received()).toEqual([]);+ const live = harness.liveAgents();+ expect(await promptTurn(harness.manager, info.threadId, view, 'hello')).toEqual({+ refused: null,+ stopReason: 'end_turn',+ servedBy: live[0]?.pid,+ });+ },+ 45_000,+ );+});++describe('a launch requested while the thread is closing', () => {+ test.skipIf(process.platform === 'win32')(+ 'a retry requested while the thread is closing is refused and starts no agent',+ async () => {+ const binDir = tmp();+ const agentNode = join(binDir, 'agent-node');+ symlinkSync(process.execPath, agentNode);+ const harness = scriptedHarness({}, { id: 'retried-agent', command: agentNode });+ harness.hold(true);+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: 'retried-agent' },+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ unlinkSync(agentNode);+ harness.hold(false);+ harness.release(0);+ await waitWithinTestBudget(+ 'the first launch to fail',+ () => errorsIn(view.statuses()).length > 0,+ WAIT,+ );+ await quietPeriod();++ harness.holdClose();+ const closing = harness.manager.closeThread(info.threadId);+ await waitWithinTestBudget('the close to clean up sessions', () => harness.closeHeld(), WAIT);+ symlinkSync(process.execPath, agentNode);+ const retried = await settle(harness.manager.retryThread(info.threadId));+ harness.releaseClose();+ await closing;+ await anchorOrQuiet(+ 'an agent to start for the closed thread',+ () => harness.started().length > 0,+ );++ expect.soft(retried).toEqual({ ok: false, error: 'the thread is closing' });+ expect.soft(harness.manager.getInfo(info.threadId)?.archived).toBe(true);+ expect(harness.started()).toEqual([]);+ },+ 45_000,+ );++ test('a context window change requested while the thread is closing is refused and starts no agent', async () => {+ const harness = scriptedHarness();+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ await waitWithinTestBudget(+ 'the first launch to be ready',+ () => harness.manager.getInfo(info.threadId)?.status === 'ready',+ WAIT,+ );+ const first = harness.started();++ harness.holdClose();+ const closing = harness.manager.closeThread(info.threadId);+ await waitWithinTestBudget('the close to clean up sessions', () => harness.closeHeld(), WAIT);+ const changed = await settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ harness.releaseClose();+ await closing;+ await anchorOrQuiet(+ 'an agent to start for the closed thread',+ () => harness.started().length > first.length,+ );++ expect.soft(changed).toEqual({ ok: false, error: 'the thread is closing' });+ expect(harness.started()).toEqual(first);+ }, 45_000);++ test.skipIf(process.platform === 'win32')(+ 'a retry requested just before a close begins is refused when its agent lookup returns and starts no agent',+ async () => {+ const binDir = tmp();+ const agentNode = join(binDir, 'agent-node');+ symlinkSync(process.execPath, agentNode);+ const harness = scriptedHarness({}, { id: 'retried-agent', command: agentNode });+ harness.hold(true);+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: 'retried-agent' },+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the first launch to wait before spawning',+ () => harness.heldCount() === 1,+ WAIT,+ );+ unlinkSync(agentNode);+ harness.hold(false);+ harness.release(0);+ await waitWithinTestBudget(+ 'the first launch to fail',+ () => errorsIn(view.statuses()).length > 0,+ WAIT,+ );+ await quietPeriod();+ symlinkSync(process.execPath, agentNode);++ harness.holdClose();+ const retried = settle(harness.manager.retryThread(info.threadId));+ const closing = harness.manager.closeThread(info.threadId);+ await waitWithinTestBudget('the close to clean up sessions', () => harness.closeHeld(), WAIT);+ expect.soft(await retried).toEqual({ ok: false, error: 'the thread is closing' });+ harness.releaseClose();+ await closing;+ await anchorOrQuiet(+ 'an agent to start for the closed thread',+ () => harness.started().length > 0,+ );++ expect.soft(harness.manager.getInfo(info.threadId)?.archived).toBe(true);+ expect(harness.started()).toEqual([]);+ },+ 45_000,+ );++ test('a context window change requested just before a close begins is refused when its agent lookup returns and starts no agent', async () => {+ const harness = scriptedHarness();+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ await waitWithinTestBudget(+ 'the first launch to be ready',+ () => harness.manager.getInfo(info.threadId)?.status === 'ready',+ WAIT,+ );+ const first = harness.started();++ harness.holdClose();+ const changed = settle(harness.manager.setContextWindow(info.threadId, NEW_WINDOW));+ const closing = harness.manager.closeThread(info.threadId);+ await waitWithinTestBudget('the close to clean up sessions', () => harness.closeHeld(), WAIT);+ expect.soft(await changed).toEqual({ ok: false, error: 'the thread is closing' });+ harness.releaseClose();+ await closing;+ await anchorOrQuiet(+ 'an agent to start for the closed thread',+ () => harness.started().length > first.length,+ );++ expect(harness.started()).toEqual(first);+ }, 45_000);++ test('a sign-in requested while the thread is closing is refused as closing, as a retry is', async () => {+ const harness = scriptedHarness({ AUTH_MODE: '1' });+ const info = await harness.manager.createThread({ agent: { source: 'custom', id: CODEX } });+ await waitWithinTestBudget(+ 'the first launch to park on a sign-in',+ () => harness.manager.getInfo(info.threadId)?.status === 'auth_required',+ WAIT,+ );++ harness.holdClose();+ const closing = harness.manager.closeThread(info.threadId);+ await waitWithinTestBudget('the close to clean up sessions', () => harness.closeHeld(), WAIT);+ const signIn = await settle(harness.manager.authenticateThread(info.threadId, 'login'));+ const retried = await settle(harness.manager.retryThread(info.threadId));+ harness.releaseClose();+ await closing;++ expect.soft(signIn).toEqual({ ok: false, error: 'the thread is closing' });+ expect(retried).toEqual({ ok: false, error: 'the thread is closing' });+ }, 45_000);++ test('a resume requested while the thread is closing is refused and starts no agent', async () => {+ const harness = scriptedHarness({ FAKE_CAPS: 'resume' });+ await harness.manager.init();+ const info = await harness.manager.createThread({+ agent: { source: 'custom', id: CODEX },+ prompt: 'hello first',+ });+ const view = await observe(harness.manager, info.threadId);+ await waitWithinTestBudget(+ 'the initial prompt turn to end',+ () => view.events().some(({ event }) => event.kind === 'turn_ended'),+ WAIT,+ );+ const first = harness.started();+ const resume: { outcome?: Promise<Settled> } = {};+ await harness.manager.subscribe(info.threadId, 0, (frame) => {+ if (resume.outcome !== undefined || frame.op !== 'info' || frame.info.archived !== true) {+ return;+ }+ resume.outcome = settle(harness.manager.resumeThread(info.threadId));+ });++ await harness.manager.closeThread(info.threadId);+ await anchorOrQuiet(+ 'an agent to start for the closing thread',+ () => harness.started().length > first.length,+ );++ expect(resume.outcome).toBeDefined();+ expect.soft(await resume.outcome).toEqual({ ok: false, error: 'the thread is closing' });+ expect.soft(harness.manager.getInfo(info.threadId)?.archived).toBe(true);+ expect(harness.started()).toEqual(first);+ }, 45_000);+});diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex f61c5b56f..607109e33 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -8591,9 +8591,14 @@ describe.skipIf(process.platform === 'win32')(const NPX_ENTRY_HASH = '4142609e2aa780f6';const NPX_RELAUNCH_LOG = '[acp-threads] cleared a stale npx cache entry; relaunching the agent';const NPX_CLOSED_CLEAR_LOG =- '[acp-threads] cleared a stale npx cache entry; the thread was closed, so the agent is not relaunched';+ '[acp-threads] cleared a stale npx cache entry; the launch was closed or superseded, so the agent is not relaunched';const NPX_JOIN_LOG ='[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again';+const NPX_REINSTALL_LOG =+ '[acp-threads] npx refused to install a missing agent package; reinstalling it before relaunch';+const SUPERSEDED_STATUS_LOG = '[acp-threads] status suppressed for a superseded launch';+const CONTEXT_WINDOW_AGENT = 'codex-acp';+const CHANGED_CONTEXT_WINDOW = 400_000;type NpxEnoentMode =| 'while-entry-exists'@@ -8652,6 +8657,54 @@ function logCount(warn: ReturnType<typeof vi.spyOn>, message: string): number {return warn.mock.calls.filter((call) => call[1] === message).length;}+function supersededFailureReports(warn: ReturnType<typeof vi.spyOn>, threadId: string): number {+ return warn.mock.calls.filter((call: unknown[]) => {+ const [fields, message] = call;+ const report = fields as { threadId?: string; status?: string };+ return (+ message === SUPERSEDED_STATUS_LOG && report.threadId === threadId && report.status === 'error'+ );+ }).length;+}++async function observeEvents(+ manager: AcpThreadManager,+ threadId: string,+): Promise<(afterSeq: number) => ThreadEvent[]> {+ const seen = new Map<number, ThreadEvent>();+ await manager.subscribe(threadId, 0, (frame) => {+ if (frame.op === 'event') seen.set(frame.seq, frame.event);+ else if (frame.op === 'events') {+ frame.events.forEach((event, index) => {+ seen.set(frame.fromSeq + index, event);+ });+ }+ });+ return (afterSeq) =>+ [...seen.entries()]+ .filter(([seq]) => seq > afterSeq)+ .sort(([a], [b]) => a - b)+ .map(([, event]) => event);+}++function statusesIn(events: ThreadEvent[]): string[] {+ return events.flatMap((event) => (event.kind === 'status' ? [event.status] : []));+}++async function expectServingAgent(+ manager: AcpThreadManager,+ threadId: string,+ eventsAfter: (afterSeq: number) => ThreadEvent[],+): Promise<void> {+ const from = manager.getInfo(threadId)?.lastSeq ?? -1;+ manager.sendPrompt(threadId, 'are you still there');+ await waitUntil(+ () => eventsAfter(from).some((event) => event.kind === 'session_update'),+ 10_000,+ 'the agent to answer the prompt',+ );+}+function hasLaunchFailureEntry(logPath: string, threadId: string): boolean {if (!existsSync(logPath)) return false;const text = readFileSync(logPath, 'utf8');@@ -8667,6 +8720,7 @@ async function withNpxLaunchFixture(localDir: string;warn: ReturnType<typeof vi.spyOn>;}) => Promise<void>,+ options: { agentId?: string } = {},): Promise<void> {await withAcquisitionHome(async (home) => {const localDir = tmp();@@ -8687,6 +8741,7 @@ ${npmEnoentSource(entryDir, mode)}`,const env = { PATH: [bin, process.env.PATH ?? ''].join(delimiter) };const agent = registryPackage('fixture-bootstrap', 'npx', env);agent.distribution.npx = { package: 'fixture-bootstrap', env };+ if (options.agentId !== undefined) agent.id = options.agentId;const registry = new AcpRegistry({localDir,log,@@ -8769,6 +8824,42 @@ describe('launch failure diagnostics and npx cache recovery', () => {);}, 40_000);+ test('a first launch a context window change supersedes while it reports a stale npx entry clears the entry without relaunching over the current agent', async () => {+ await withNpxLaunchFixture(+ 'held-after-stdout-eof',+ async ({ manager, agentId, entryDir, warn }) => {+ mkdirSync(entryDir, { recursive: true });+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });+ const eventsAfter = await observeEvents(manager, info.threadId);+ await waitUntil(+ () => existsSync(stdoutEndedMarker(entryDir)),+ 20_000,+ 'the failing launch to close its stdout',+ );+ const changedFrom = manager.getInfo(info.threadId)?.lastSeq ?? -1;++ expect(await manager.setContextWindow(info.threadId, CHANGED_CONTEXT_WINDOW)).toMatchObject(+ { status: 'ready', contextWindow: CHANGED_CONTEXT_WINDOW },+ );+ await waitUntil(+ () => supersededFailureReports(warn, info.threadId) === 1,+ 5_000,+ 'the superseded launch to settle its failure',+ );++ expect.soft(logCount(warn, NPX_RELAUNCH_LOG)).toBe(0);+ expect.soft(logCount(warn, NPX_CLOSED_CLEAR_LOG)).toBe(1);+ expect.soft(existsSync(entryDir)).toBe(false);+ const statuses = statusesIn(eventsAfter(changedFrom));+ expect.soft(statuses).not.toContain('error');+ expect.soft(statuses).not.toContain('exited');+ expect.soft(manager.getInfo(info.threadId)?.status).toBe('ready');+ await expectServingAgent(manager, info.threadId, eventsAfter);+ },+ { agentId: CONTEXT_WINDOW_AGENT },+ );+ }, 40_000);+test('a launch that keeps failing on the npx cache is reported after one retry', async () => {await withNpxLaunchFixture('always', async ({ manager, agentId, entryDir, localDir, warn }) => {mkdirSync(entryDir, { recursive: true });@@ -8996,6 +9087,74 @@ describe('launch failure diagnostics and npx cache recovery', () => {});}, 40_000);+ test('a first launch a context window change supersedes while npx refuses its install reinstalls nothing over the current agent', async () => {+ await withAcquisitionHome(async (home) => {+ const localDir = tmp();+ const bin = join(home, 'bin');+ mkdirSync(bin);+ installNodeFixture(bin);+ writeRecordingNpm(bin, join(home, 'probes.log'));+ const refusedOnce = join(home, 'refused-once');+ const refusalStdoutEnded = join(home, 'refusal-stdout-ended');+ const descriptor = '[email protected]';+ const refusal = `npm error npx canceled due to missing packages and no YES option: ${JSON.stringify([descriptor])}\n`;+ writeExecutable(+ join(bin, 'npx'),+ `const { existsSync, writeFileSync } = require('node:fs');+ const args = process.argv.slice(2);+ if (args.join(' ') === '--version' || args.includes('--call=exit 0')) process.exit(0);+ if (!existsSync(${JSON.stringify(refusedOnce)})) {+ writeFileSync(${JSON.stringify(refusedOnce)}, '');+ process.stderr.write(${JSON.stringify(refusal)}, () => process.stdout.end(() => {+ writeFileSync(${JSON.stringify(refusalStdoutEnded)}, '');+ setTimeout(() => process.exit(1), 10_000);+ }));+ } else {+ import(${JSON.stringify(pathToFileURL(EXAMPLE_AGENT).href)});+ }`,+ );+ const agent = {+ ...registryPackage(descriptor, 'npx', { PATH: bin }),+ id: CONTEXT_WINDOW_AGENT,+ };+ const registry = new AcpRegistry({+ localDir,+ log,+ fetchImpl: async () => new Response(JSON.stringify({ agents: [agent] })),+ });+ const warn = vi.spyOn(log, 'warn');+ const manager = makeManager(home, localDir, { registry });+ try {+ const info = await manager.createThread({ agent: { source: 'registry', id: agent.id } });+ const eventsAfter = await observeEvents(manager, info.threadId);+ await waitUntil(+ () => existsSync(refusalStdoutEnded),+ 20_000,+ 'the refused launch to close its stdout',+ );+ const changedFrom = manager.getInfo(info.threadId)?.lastSeq ?? -1;++ expect(await manager.setContextWindow(info.threadId, CHANGED_CONTEXT_WINDOW)).toMatchObject(+ { status: 'ready', contextWindow: CHANGED_CONTEXT_WINDOW },+ );+ await waitUntil(+ () => supersededFailureReports(warn, info.threadId) === 1,+ 5_000,+ 'the superseded launch to settle its failure',+ );++ expect.soft(logCount(warn, NPX_REINSTALL_LOG)).toBe(0);+ const statuses = statusesIn(eventsAfter(changedFrom));+ expect.soft(statuses).not.toContain('error');+ expect.soft(statuses).not.toContain('exited');+ expect.soft(manager.getInfo(info.threadId)?.status).toBe('ready');+ await expectServingAgent(manager, info.threadId, eventsAfter);+ } finally {+ await manager.destroy();+ }+ });+ }, 40_000);+test('a session setup failure is recorded with its reason', async () => {const localDir = tmp();writeSessionFailingAgentEntry(diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 6c855f1d9..5bda83b18 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -333,6 +333,10 @@ interface PendingConsent {timer: ReturnType<typeof setTimeout>;}+interface LaunchTicket {+ initialPrompt: { content: string; attachments?: readonly AttachmentPart[] } | null;+}+interface ThreadRecord {info: ThreadInfo;docName?: string;@@ -364,6 +368,7 @@ interface ThreadRecord {midTurnOnDisk: boolean;resumeInFlight: boolean;authInFlight: boolean;+ launchTicket: LaunchTicket | null;suppressUpdates: boolean;lastSuppressedAt: number;subscribers: Set<Subscriber>;@@ -726,6 +731,7 @@ export class AcpThreadManager {midTurnOnDisk: false,resumeInFlight: false,authInFlight: false,+ launchTicket: null,suppressUpdates: false,lastSuppressedAt: 0,subscribers: new Set(),@@ -761,11 +767,20 @@ export class AcpThreadManager {chatGrants: new Set(),};this.threads.set(threadId, record);+ const hasContent =+ (params.prompt !== undefined && params.prompt !== '') ||+ (params.attachments !== undefined && params.attachments.length > 0);+ const ticket = beginLaunch(+ record,+ hasContent ? { content: params.prompt ?? '', attachments: params.attachments } : null,+ );this.emitStatus(record, 'spawning');- void this.startThread(record, params, custom).catch((err) => {+ void this.startThread(record, ticket, params, custom).catch((err) => {this.opts.log.error({ err, threadId }, '[acp-threads] thread start failed');- this.emitStatus(record, 'error', err instanceof Error ? err.message : String(err));+ if (isCurrentLaunch(record, ticket)) {+ this.emitStatus(record, 'error', err instanceof Error ? err.message : String(err));+ }});return { ...record.info };@@ -848,6 +863,7 @@ export class AcpThreadManager {private async connectAgent(record: ThreadRecord,+ ticket: LaunchTicket,custom: CustomAgentEntry | null,acquisition: AcquisitionPolicy = 'reuse',consentBudgetMs: number,@@ -855,7 +871,12 @@ export class AcpThreadManager {): Promise<{ conn: ClientConnection; init: InitializeResponse; launch: ResolvedLaunch } | null> {let launch: ResolvedLaunch | null;if (custom !== null) {- launch = await this.ensureLaunchable(record, resolveCustomLaunch(custom), consentBudgetMs);+ launch = await this.ensureLaunchable(+ record,+ ticket,+ resolveCustomLaunch(custom),+ consentBudgetMs,+ );} else {const manifest = await this.opts.registry.getAgent(record.agentRef.id);if (manifest === undefined) throw new ThreadOpError('unknown-agent', 'agent vanished');@@ -865,11 +886,13 @@ export class AcpThreadManager {registryPlatformKey(),this.opts.log,undefined,- (candidate) => this.ensureLaunchable(record, candidate, consentBudgetMs),+ (candidate) => this.ensureLaunchable(record, ticket, candidate, consentBudgetMs),{reacquire: acquisition === 'reacquire',install: true,- onAcquiring: () => this.emitStatus(record, 'installing'),+ onAcquiring: () => {+ if (isCurrentLaunch(record, ticket)) this.emitStatus(record, 'installing');+ },onResolved: ({ acquired, outcome, source, elapsedMs }) =>this.opts.log.info({@@ -889,20 +912,21 @@ export class AcpThreadManager {err instanceof AgentLaunchError &&err.npxCacheEntry !== undefined &&npxLaunchRecovery === 'available' &&- (await this.clearStaleNpxCacheEntry(record, err.npxCacheEntry))+ (await this.clearStaleNpxCacheEntry(record, ticket, err.npxCacheEntry))) {- return this.connectAgent(record, custom, 'reacquire', consentBudgetMs, 'spent');+ return this.connectAgent(record, ticket, custom, 'reacquire', consentBudgetMs, 'spent');}throw err;}}- if (launch === null || isThreadClosed(record)) return null;+ if (launch === null || !isCurrentLaunch(record, ticket)) return null;const loginShellPath = await this.resolveLoginShellPath().catch(() => null);- if (isThreadClosed(record)) return null;+ if (!isCurrentLaunch(record, ticket)) return null;- record.projectSkill = await this.stageProjectSkillFor(record);- if (isThreadClosed(record)) return null;+ const projectSkill = await this.stageProjectSkillFor(record);+ if (!isCurrentLaunch(record, ticket)) return null;+ record.projectSkill = projectSkill;const terminals = new AcpTerminalSet({defaultCwd: record.cwd,@@ -971,7 +995,8 @@ export class AcpThreadManager {capturingStartup &&npxLaunchRecovery === 'available' &&(staleNpxCacheEntry(rawStartupStderr) !== null || npxInstallRefused(rawStartupStderr));- const launchStatusMuted = (): boolean => launchSuperseded || npxLaunchRecoveryPending();+ const launchStatusMuted = (): boolean =>+ launchSuperseded || npxLaunchRecoveryPending() || !isCurrentLaunch(record, ticket);child.stderr?.setEncoding('utf8');child.stderr?.on('data', diagnosticCapture.write);@@ -1176,18 +1201,18 @@ export class AcpThreadManager {launchKind === 'npx' && npxLaunchRecovery === 'available'? staleNpxCacheEntry(rawStartupStderr): null;- if (staleEntry !== null && (await this.clearStaleNpxCacheEntry(record, staleEntry))) {+ if (staleEntry !== null && (await this.clearStaleNpxCacheEntry(record, ticket, staleEntry))) {launchSuperseded = true;- return this.connectAgent(record, custom, 'reacquire', consentBudgetMs, 'spent');+ return this.connectAgent(record, ticket, custom, 'reacquire', consentBudgetMs, 'spent');}if (launchKind === 'npx' &&npxLaunchRecovery === 'available' &&npxInstallRefused(rawStartupStderr) &&- (await this.discardRefusedNpxLaunch(record, launch))+ (await this.discardRefusedNpxLaunch(record, ticket, launch))) {launchSuperseded = true;- return this.connectAgent(record, custom, 'reacquire', consentBudgetMs, 'spent');+ return this.connectAgent(record, ticket, custom, 'reacquire', consentBudgetMs, 'spent');}throw new ThreadOpError('spawn-failed', `initialize failed: ${agentErrorMessage(err)}`);} finally {@@ -1195,7 +1220,7 @@ export class AcpThreadManager {startupStderr = '';rawStartupStderr = '';}- if (isThreadClosed(record)) return null;+ if (!isCurrentLaunch(record, ticket)) return null;record.lastInit = init;record.info.promptCapabilities = init.agentCapabilities?.promptCapabilities ?? {};this.emitInfo(record);@@ -1204,9 +1229,10 @@ export class AcpThreadManager {private async discardRefusedNpxLaunch(record: ThreadRecord,+ ticket: LaunchTicket,launch: ResolvedLaunch,): Promise<boolean> {- if (isThreadClosed(record)) return false;+ if (!isCurrentLaunch(record, ticket)) return false;this.opts.log.warn({threadId: record.info.threadId,@@ -1216,11 +1242,12 @@ export class AcpThreadManager {'[acp-threads] npx refused to install a missing agent package; reinstalling it before relaunch',);await this.discardFailedLaunch(record);- return !isThreadClosed(record);+ return isCurrentLaunch(record, ticket);}private async clearStaleNpxCacheEntry(record: ThreadRecord,+ ticket: LaunchTicket,entryDir: NpxCacheEntry,): Promise<boolean> {const logContext = {@@ -1230,11 +1257,11 @@ export class AcpThreadManager {};const outcome = await this.removeStaleNpxCacheEntry(entryDir, logContext);if (outcome === 'kept') return false;- if (isThreadClosed(record)) {+ if (!isCurrentLaunch(record, ticket)) {if (outcome === 'removed') {this.opts.log.warn(logContext,- '[acp-threads] cleared a stale npx cache entry; the thread was closed, so the agent is not relaunched',+ '[acp-threads] cleared a stale npx cache entry; the launch was closed or superseded, so the agent is not relaunched',);}return false;@@ -1246,7 +1273,7 @@ export class AcpThreadManager {: '[acp-threads] cleared a stale npx cache entry; relaunching the agent',);await this.discardFailedLaunch(record);- return !isThreadClosed(record);+ return isCurrentLaunch(record, ticket);}private async removeStaleNpxCacheEntry(@@ -1315,6 +1342,7 @@ export class AcpThreadManager {private async ensureLaunchable(record: ThreadRecord,+ ticket: LaunchTicket,launch: ResolvedLaunch,consentBudgetMs: number,): Promise<ResolvedLaunch | null> {@@ -1326,31 +1354,39 @@ export class AcpThreadManager {if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') throw err;const viaLoginShell = await this.retryWithLoginShellPath(launch);if (viaLoginShell === null)- return this.fallbackToManagedRuntime(record, launch, err, undefined, consentBudgetMs);+ return this.fallbackToManagedRuntime(+ record,+ ticket,+ launch,+ err,+ undefined,+ consentBudgetMs,+ );candidate = viaLoginShell;}- if (isThreadClosed(record)) return null;- return this.ensureInterpreterRuns(record, candidate, consentBudgetMs);+ if (!isCurrentLaunch(record, ticket)) return null;+ return this.ensureInterpreterRuns(record, ticket, candidate, consentBudgetMs);}private async ensureInterpreterRuns(record: ThreadRecord,+ ticket: LaunchTicket,launch: ResolvedLaunch,consentBudgetMs: number,): Promise<ResolvedLaunch | null> {if (launch.kind !== 'npx' && launch.kind !== 'uvx') return launch;const failure = await this.probeInterpreterOnce(launch);- if (isThreadClosed(record)) return null;+ if (!isCurrentLaunch(record, ticket)) return null;if (failure === null) return launch;if (failure.kind === 'incompatible') {const preferred = await this.withPreferredLoginShellPathIfEligible(launch);- if (isThreadClosed(record)) return null;+ if (!isCurrentLaunch(record, ticket)) return null;if (envPath(preferred.env) !== envPath(launch.env)) {try {await preflightLaunch(preferred);const preferredFailure = await this.probeInterpreterOnce(preferred);- if (isThreadClosed(record)) return null;+ if (!isCurrentLaunch(record, ticket)) return null;if (preferredFailure === null) {this.opts.log.info({ threadId: record.info.threadId, agentId: record.info.agent.id },@@ -1401,6 +1437,7 @@ export class AcpThreadManager {);return this.fallbackToManagedRuntime(record,+ ticket,launch,declined,{ declined, expired },@@ -1410,6 +1447,7 @@ export class AcpThreadManager {private async fallbackToManagedRuntime(record: ThreadRecord,+ ticket: LaunchTicket,launch: ResolvedLaunch,cause: AgentLaunchError,refusalCauses: { declined: AgentLaunchError; expired: AgentLaunchError } | undefined,@@ -1420,6 +1458,7 @@ export class AcpThreadManager {if (!runtimeDownloadSupported(runtimeKind)) throw cause;const runtime = await this.provideManagedRuntime(record,+ ticket,runtimeKind,refusalCauses === undefined ? 'missing' : 'broken',consentBudgetMs,@@ -1442,6 +1481,7 @@ export class AcpThreadManager {}return this.repairManagedRuntime(record,+ ticket,launch,runtimeKind,brokenManaged.detail,@@ -1451,11 +1491,13 @@ export class AcpThreadManager {private async repairManagedRuntime(record: ThreadRecord,+ ticket: LaunchTicket,launch: ResolvedLaunch,runtimeKind: ManagedRuntimeKind,detail: string,consentBudgetMs: number,): Promise<ResolvedLaunch | null> {+ if (!isCurrentLaunch(record, ticket)) return null;const logContext = {threadId: record.info.threadId,agentId: record.info.agent.id,@@ -1477,6 +1519,7 @@ export class AcpThreadManager {const fresh = await this.provideManagedRuntime(record,+ ticket,runtimeKind,'damaged',consentBudgetMs,@@ -1561,6 +1604,7 @@ export class AcpThreadManager {private async provideManagedRuntime(record: ThreadRecord,+ ticket: LaunchTicket,runtimeKind: ManagedRuntimeKind,reason: 'missing' | 'broken' | 'damaged',consentBudgetMs: number,@@ -1569,9 +1613,10 @@ export class AcpThreadManager {await cleanupManagedRuntimeStaging(runtimeKind, this.opts.log, root);const existing = await findManagedRuntime(runtimeKind, root).catch(() => null);if (existing !== null) return existing;+ if (!isCurrentLaunch(record, ticket)) return null;const decision = await this.requestRuntimeConsent(record, runtimeKind, reason, consentBudgetMs);- if (decision === 'closed' || isThreadClosed(record)) return null;+ if (decision === 'closed' || !isCurrentLaunch(record, ticket)) return null;if (decision !== 'granted') {throw new RuntimeConsentRefusedError(decision,@@ -1580,8 +1625,8 @@ export class AcpThreadManager {}try {- const runtime = await this.downloadRuntime(record, runtimeKind);- return isThreadClosed(record) ? null : runtime;+ const runtime = await this.downloadRuntime(record, ticket, runtimeKind);+ return isCurrentLaunch(record, ticket) ? runtime : null;} catch (err) {const name = describeRuntime(runtimeKind).displayName;throw new AgentLaunchError(@@ -1650,6 +1695,7 @@ export class AcpThreadManager {private async downloadRuntime(record: ThreadRecord,+ ticket: LaunchTicket,runtimeKind: ManagedRuntimeKind,): Promise<ManagedRuntime> {this.emitStatus(record, 'installing');@@ -1661,7 +1707,7 @@ export class AcpThreadManager {const now = Date.now();if (now - lastProgressAt < RUNTIME_PROGRESS_THROTTLE_MS) return;lastProgressAt = now;- if (isThreadClosed(record)) return;+ if (!isCurrentLaunch(record, ticket)) return;this.appendEvent(record, {kind: 'runtime_install_progress',runtime: runtimeKind,@@ -1676,18 +1722,21 @@ export class AcpThreadManager {private async buildMcpServers(record: ThreadRecord,+ ticket: LaunchTicket,init: InitializeResponse,consentBudgetMs: number = CONSENT_TIMEOUT_MS,): Promise<{servers: McpServer[];hostedMarker: OkMcpHostedMarker;browserUnavailable: BrowserUnavailableReason | null;+ browserInjected: boolean;}> {const servers: McpServer[] = [];let browserUnavailable: BrowserUnavailableReason | null = null;+ let browserInjected = false;let hostedMarker: OkMcpHostedMarker;if (isPiBridgeAgent(record.agentRef)) {- const outcome = await this.settlePiBridge(record, consentBudgetMs);+ const outcome = await this.settlePiBridge(record, ticket, consentBudgetMs);hostedMarker = outcome === 'unavailable' ? 'none' : 'unknown';} else if ((await this.harnessAlreadyHasOkMcp(record)) !== null) {hostedMarker = 'unknown';@@ -1722,15 +1771,14 @@ export class AcpThreadManager {}}}- record.browserInjected = false;- if (this.opts.agentBrowserTools?.() === true) {+ if (this.opts.agentBrowserTools?.() === true && isCurrentLaunch(record, ticket)) {if (agentGetsBrowser(record.agentRef)) {- const browser = await this.agentBrowserServer(record, consentBudgetMs);+ const browser = await this.agentBrowserServer(record, ticket, consentBudgetMs);if (typeof browser === 'string') {browserUnavailable = browser;} else {servers.push(browser);- record.browserInjected = true;+ browserInjected = true;}} else {this.opts.log.info(@@ -1750,7 +1798,7 @@ export class AcpThreadManager {'[acp-threads] OK MCP injection outcome',);}- return { servers, hostedMarker, browserUnavailable };+ return { servers, hostedMarker, browserUnavailable, browserInjected };}private noteBrowserUnavailable(@@ -1768,6 +1816,7 @@ export class AcpThreadManager {private async agentBrowserServer(record: ThreadRecord,+ ticket: LaunchTicket,waitBudgetMs: number,): Promise<McpServerStdio | BrowserUnavailableReason> {const context = { threadId: record.info.threadId, agentId: record.agentRef.id };@@ -1780,6 +1829,7 @@ export class AcpThreadManager {return 'failed';}const loginShellPath = await this.resolveLoginShellPath().catch(() => null);+ if (!isCurrentLaunch(record, ticket)) return 'failed';const rejectedNpx: string[] = [];const npx = (this.opts.resolveBrowserNpx ?? resolveBrowserNpx)([record.agentLaunchPath, loginShellPath, agentSpawnPath()],@@ -1821,6 +1871,7 @@ export class AcpThreadManager {);return 'no-node';}+ if (!isCurrentLaunch(record, ticket)) return 'failed';const waitMs = Math.min(this.browserInstallWaitMs, waitBudgetMs);let waitTimer: ReturnType<typeof setTimeout> | undefined;const installed = await Promise.race([@@ -1925,6 +1976,7 @@ export class AcpThreadManager {private async settlePiBridge(record: ThreadRecord,+ ticket: LaunchTicket,consentBudgetMs: number,): Promise<PiBridgeOutcome> {const probe = this.opts.probePiAcpBridge;@@ -1943,7 +1995,7 @@ export class AcpThreadManager {this.opts.log.warn({ err, threadId }, '[acp-threads] Pi bridge probe failed');return 'unknown';}- if (record.closed) return 'unknown';+ if (!isCurrentLaunch(record, ticket)) return 'unknown';if (state.project === 'unavailable') {this.opts.log.warn({ threadId, cwd: state.cwd, err: new Error(state.error) },@@ -1997,7 +2049,7 @@ export class AcpThreadManager {const requestId = crypto.randomUUID();const decision = await this.requestPiBridgeConsent(record, requestId, state, consentBudgetMs);if (decision === 'declined') record.piBridgeDeclined = true;- if (record.closed) return 'unknown';+ if (!isCurrentLaunch(record, ticket)) return 'unknown';if (decision !== 'granted') {this.opts.log.info({ threadId, decision },@@ -2012,7 +2064,9 @@ export class AcpThreadManager {} catch (err) {const detail = err instanceof Error ? err.message : String(err);this.opts.log.warn({ err, threadId }, '[acp-threads] Pi bridge provisioning threw');- this.appendPiBridgeFailure(record, requestId, 'bridge-failed', state.bridgePath, { detail });+ this.appendPiBridgeFailure(record, ticket, requestId, 'bridge-failed', state.bridgePath, {+ detail,+ });return 'unavailable';}if (result.ok) {@@ -2020,7 +2074,7 @@ export class AcpThreadManager {{ threadId, bridge: result.bridge, trust: result.trust, bridgePath: result.bridgePath },'[acp-threads] provisioned the Pi bridge extension for this project',);- if (record.closed) return 'unknown';+ if (!isCurrentLaunch(record, ticket)) return 'unknown';this.appendEvent(record, {kind: 'pi_bridge_status',requestId,@@ -2054,7 +2108,7 @@ export class AcpThreadManager {},'[acp-threads] Pi bridge provisioning did not complete — the thread continues without OK tools',);- this.appendPiBridgeFailure(record, requestId, state2, result.bridgePath, {+ this.appendPiBridgeFailure(record, ticket, requestId, state2, result.bridgePath, {bridge: result.bridge,trust: result.trust,...(result.error !== undefined ? { detail: result.error } : {}),@@ -2064,12 +2118,13 @@ export class AcpThreadManager {private appendPiBridgeFailure(record: ThreadRecord,+ ticket: LaunchTicket,requestId: string,state: PiBridgeThreadState,bridgePath: string,extra: { bridge?: PiBridgeWriteAction; trust?: PiTrustWriteAction; detail?: string },): void {- if (record.closed) return;+ if (!isCurrentLaunch(record, ticket)) return;this.appendEvent(record, {kind: 'pi_bridge_status',requestId,@@ -2142,10 +2197,9 @@ export class AcpThreadManager {private async startThread(record: ThreadRecord,+ ticket: LaunchTicket,params: {agent: { source: 'registry' | 'custom'; id: string };- prompt?: string;- attachments?: readonly AttachmentPart[];settings?: {config?: Record<string, string | boolean>;modeId?: string;@@ -2158,22 +2212,33 @@ export class AcpThreadManager {): Promise<void> {let handshake: Awaited<ReturnType<AcpThreadManager['connectAgent']>>;try {- handshake = await this.connectAgent(record, custom, acquisition, consentBudgetMs);+ handshake = await this.connectAgent(record, ticket, custom, acquisition, consentBudgetMs);} catch (err) {- const failure = await connectionFailureDetail(err, record);- this.emitStatus(record, 'error', failure.agentMessage, failure);- if (!isThreadClosed(record)) await this.teardownFailedAgent(record);+ const failure = await connectionFailureDetail(+ err,+ record,+ isCurrentLaunch(record, ticket) || isThreadClosed(record),+ );+ await this.failLaunch(record, ticket, failure.agentMessage, failure);return;}if (handshake === null) return;const { conn, init, launch } = handshake;if (- (await this.openSession(record, conn, init, params.settings, 'park', consentBudgetMs)) !==- true+ (await this.openSession(+ record,+ ticket,+ conn,+ init,+ params.settings,+ 'park',+ consentBudgetMs,+ )) !== true) {return;}+ if (!isCurrentLaunch(record, ticket)) return;this.opts.log.info({threadId: record.info.threadId,@@ -2184,16 +2249,16 @@ export class AcpThreadManager {'[acp-threads] agent ready',);- const hasContent =- (params.prompt !== undefined && params.prompt !== '') ||- (params.attachments !== undefined && params.attachments.length > 0);- if (hasContent) {- this.sendPrompt(record.info.threadId, params.prompt ?? '', params.attachments);+ const prompt = ticket.initialPrompt;+ ticket.initialPrompt = null;+ if (prompt !== null) {+ this.sendPrompt(record.info.threadId, prompt.content, prompt.attachments);}}private async openSession(record: ThreadRecord,+ ticket: LaunchTicket,conn: ClientConnection,init: InitializeResponse,settings?: { config?: Record<string, string | boolean>; modeId?: string },@@ -2201,18 +2266,20 @@ export class AcpThreadManager {consentBudgetMs: number = CONSENT_TIMEOUT_MS,): Promise<boolean | 'auth-required'> {record.info.availableCommands = null;- const { servers: mcpServers, browserUnavailable } = await this.buildMcpServers(- record,- init,- consentBudgetMs,- );- if (isThreadClosed(record)) return false;+ const {+ servers: mcpServers,+ browserUnavailable,+ browserInjected,+ } = await this.buildMcpServers(record, ticket, init, consentBudgetMs);+ if (!isCurrentLaunch(record, ticket)) return false;+ record.browserInjected = browserInjected;this.noteBrowserUnavailable(record, browserUnavailable);try {const session = await conn.agent.request(acpMethods.agent.session.new, {cwd: record.cwd,mcpServers,});+ if (!isCurrentLaunch(record, ticket)) return false;record.sessionId = session.sessionId;record.info.resumable = resumableFromCapabilities(init);record.confirmedContextWindow = appliedContextWindow(record);@@ -2228,37 +2295,43 @@ export class AcpThreadManager {this.emitInfo(record);}} catch (err) {+ const agentMessage = agentErrorMessage(err);if (isAuthRequiredError(err)) {- if (onAuthRequired === 'report') return 'auth-required';- this.emitStatus(record, 'auth_required', `sign in required: ${agentErrorMessage(err)}`, {+ const detail = `sign in required: ${agentMessage}`;+ const failure: ThreadFailureDetail = {reason: 'auth-required',- agentMessage: agentErrorMessage(err),+ agentMessage,machineDetail: authMachineDetail(err, record),authMethods: threadAuthMethods(init.authMethods, record.terminalAuthBase),- });- } else {- const tail = await stderrTailDetail(record);- this.emitStatus(record, 'error', `session setup failed: ${agentErrorMessage(err)}`, {- reason: 'session-setup',- agentMessage: agentErrorMessage(err),- machineDetail: joinMachineDetail({- primary: agentErrorData(err),- tail,- }),- });- if (!isThreadClosed(record)) await this.teardownFailedAgent(record);+ };+ if (!isCurrentLaunch(record, ticket)) {+ this.logSuppressedStatus(record, 'auth_required', detail, failure);+ return false;+ }+ if (onAuthRequired === 'report') return 'auth-required';+ this.emitStatus(record, 'auth_required', detail, failure);+ return false;}+ const ownsStderrTail = isCurrentLaunch(record, ticket) || isThreadClosed(record);+ await this.failLaunch(record, ticket, `session setup failed: ${agentMessage}`, {+ reason: 'session-setup',+ agentMessage,+ machineDetail: joinMachineDetail({+ primary: agentErrorData(err),+ tail: ownsStderrTail ? await stderrTailDetail(record) : undefined,+ }),+ });return false;}- if (isThreadClosed(record)) return false;+ if (!isCurrentLaunch(record, ticket)) return false;if (settings?.config !== undefined) {- await this.applyInitialConfig(record, conn, settings.config);- if (isThreadClosed(record)) return false;+ await this.applyInitialConfig(record, ticket, conn, settings.config);+ if (!isCurrentLaunch(record, ticket)) return false;}if (settings?.modeId !== undefined) {- await this.applyInitialMode(record, conn, settings.modeId);- if (isThreadClosed(record)) return false;+ await this.applyInitialMode(record, ticket, conn, settings.modeId);+ if (!isCurrentLaunch(record, ticket)) return false;}this.emitStatus(record, 'ready');@@ -2272,6 +2345,7 @@ export class AcpThreadManager {): Promise<ThreadInfo> {if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');const t = this.mustGet(threadId);+ if (t.closed) throw new ThreadOpError('not-ready', 'the thread is closing');if (t.info.archived !== true) {throw new ThreadOpError('not-ready', 'thread is not archived');}@@ -2294,6 +2368,7 @@ export class AcpThreadManager {`maximum of ${this.maxThreads} concurrent agent threads`,);}+ const ticket = beginLaunch(t);t.info.agent = agentInfo;t.info.archived = false;t.info.availableCommands = null;@@ -2321,7 +2396,13 @@ export class AcpThreadManager {'this thread never completed an agent session',);}- const handshake = await this.connectAgent(t, custom, 'reuse', BLOCKING_CONSENT_TIMEOUT_MS);+ const handshake = await this.connectAgent(+ t,+ ticket,+ custom,+ 'reuse',+ BLOCKING_CONSENT_TIMEOUT_MS,+ );if (handshake === null) {throw new ThreadOpError('not-ready', 'thread closed during resume');}@@ -2329,14 +2410,15 @@ export class AcpThreadManager {t.info.resumable = resumableFromCapabilities(init);t.confirmedContextWindow = appliedContextWindow(t);t.info.contextWindow = t.confirmedContextWindow;- const { servers: mcpServers, browserUnavailable } = await this.buildMcpServers(- t,- init,- BLOCKING_CONSENT_TIMEOUT_MS,- );- if (isThreadClosed(t)) {+ const {+ servers: mcpServers,+ browserUnavailable,+ browserInjected,+ } = await this.buildMcpServers(t, ticket, init, BLOCKING_CONSENT_TIMEOUT_MS);+ if (!isCurrentLaunch(t, ticket)) {throw new ThreadOpError('not-ready', 'thread closed during resume');}+ t.browserInjected = browserInjected;this.noteBrowserUnavailable(t, browserUnavailable);const caps = init.agentCapabilities;const viaResume = caps?.sessionCapabilities?.resume != null;@@ -2370,6 +2452,9 @@ export class AcpThreadManager {`${t.info.agent.name} doesn't support resuming previous sessions`,);}+ if (!isCurrentLaunch(t, ticket)) {+ throw new ThreadOpError('not-ready', 'thread closed during resume');+ }t.sessionId = sessionId;const resumedConfig: Record<string, string | boolean> = Object.fromEntries((t.info.configOptions ?? []).map((option) => [option.id, option.currentValue]),@@ -2381,11 +2466,13 @@ export class AcpThreadManager {if (configOptions !== undefined && configOptions !== null) {t.info.configOptions = configOptions;}- await this.applyInitialConfig(t, conn, resumedConfig, configOptions == null);- if (isThreadClosed(t)) throw new ThreadOpError('not-ready', 'thread closed during resume');+ await this.applyInitialConfig(t, ticket, conn, resumedConfig, configOptions == null);+ if (!isCurrentLaunch(t, ticket)) {+ throw new ThreadOpError('not-ready', 'thread closed during resume');+ }if (resumedModeId !== undefined) {- await this.applyInitialMode(t, conn, resumedModeId, modes == null);- if (isThreadClosed(t)) {+ await this.applyInitialMode(t, ticket, conn, resumedModeId, modes == null);+ if (!isCurrentLaunch(t, ticket)) {throw new ThreadOpError('not-ready', 'thread closed during resume');}}@@ -2404,7 +2491,7 @@ export class AcpThreadManager {}return { ...t.info };} catch (err) {- await this.abortResume(t, await connectionFailureDetail(err, t));+ await this.abortResume(t, await connectionFailureDetail(err, t, true));if (err instanceof ThreadOpError) throw err;if (err instanceof AgentLaunchError) {throw new ThreadOpError(@@ -2432,27 +2519,16 @@ export class AcpThreadManager {async setContextWindow(threadId: string, tokens: number): Promise<ThreadInfo> {if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');const t = this.mustGet(threadId);- if (!Number.isFinite(tokens) || tokens <= 0) {- throw new ThreadOpError('not-ready', 'a context window must be a positive number of tokens');- }- const change = contextWindowChangeFor({- agentId: t.agentRef.id,- archived: t.info.archived === true,- turnActive: t.turnActive,- hasStartedWork: this.hasStartedWork(threadId),- });- if (change.kind === 'unsupported') {- throw new ThreadOpError('not-ready', 'this agent takes its context window from the model');- }- if (change.kind === 'needs-new-chat') {- throw new ThreadOpError('not-ready', 'start a new chat to change the context window');- }- if (t.resumeInFlight) throw new ThreadOpError('not-ready', 'a restart is already in progress');+ this.assertContextWindowChangeable(t, tokens);+ const { custom } = await this.resolveAgentInfo(t.agentRef);+ this.assertContextWindowChangeable(t, tokens);const previousWindow = t.launchSettings?.contextWindow;const previousConfirmed = t.confirmedContextWindow ?? null;t.launchSettings = { ...t.launchSettings, contextWindow: Math.floor(tokens) };t.resumeInFlight = true;+ const carried = t.launchTicket?.initialPrompt ?? null;+ const ticket = beginLaunch(t);let applied = false;t.sessionBeforeRestart = {sessionId: t.sessionId,@@ -2460,7 +2536,6 @@ export class AcpThreadManager {contextWindow: t.info.contextWindow,};try {- const { custom } = await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t);t.stderrTail = [];t.cancelRequested = false;@@ -2468,16 +2543,20 @@ export class AcpThreadManager {this.emitStatus(t, 'spawning');await this.startThread(t,+ ticket,{ agent: t.agentRef, settings: t.launchSettings },custom,BLOCKING_CONSENT_TIMEOUT_MS,);- if (isThreadClosed(t)) {+ if (!isCurrentLaunch(t, ticket)) {throw new ThreadOpError('not-ready', 'thread closed during the context window change');}const settled = this.getInfo(threadId)?.status;if (settled === 'ready' || settled === 'running') {applied = true;+ if (carried !== null) {+ this.dispatchPrompt(t, carried.content, carried.attachments, { echo: true });+ }return { ...t.info };}throw new ThreadOpError(@@ -2490,6 +2569,12 @@ export class AcpThreadManager {this.emitStatus(t, 'error', detail, { reason: 'connect', agentMessage: detail });throw new ThreadOpError('spawn-failed', detail);} finally {+ if (!applied && carried !== null) {+ this.opts.log.info(+ { threadId, agentId: t.agentRef.id },+ '[acp-threads] pending first message dropped: the context window change did not start the agent',+ );+ }if (!applied && this.threads.has(threadId)) {t.launchSettings = { ...t.launchSettings, contextWindow: previousWindow };t.confirmedContextWindow = previousConfirmed;@@ -2503,19 +2588,35 @@ export class AcpThreadManager {}}- async retryThread(threadId: string): Promise<ThreadInfo> {+ private assertContextWindowChangeable(t: ThreadRecord, tokens: number): void {if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');- const t = this.mustGet(threadId);- if (t.info.archived === true) {- throw new ThreadOpError('not-ready', 'the thread is archived — resume it instead');+ if (t.closed) throw new ThreadOpError('not-ready', 'the thread is closing');+ if (!Number.isFinite(tokens) || tokens <= 0) {+ throw new ThreadOpError('not-ready', 'a context window must be a positive number of tokens');}- if (t.info.status !== 'error' && t.info.status !== 'auth_required' && !t.authInFlight) {- throw new ThreadOpError('not-ready', 'this thread did not fail to start');+ const change = contextWindowChangeFor({+ agentId: t.agentRef.id,+ archived: t.info.archived === true,+ turnActive: t.turnActive,+ hasStartedWork: this.hasStartedWork(t.info.threadId),+ });+ if (change.kind === 'unsupported') {+ throw new ThreadOpError('not-ready', 'this agent takes its context window from the model');}- if (t.resumeInFlight) {- throw new ThreadOpError('not-ready', 'a retry is already in progress');+ if (change.kind === 'needs-new-chat') {+ throw new ThreadOpError('not-ready', 'start a new chat to change the context window');}+ if (t.resumeInFlight) throw new ThreadOpError('not-ready', 'a restart is already in progress');+ }++ async retryThread(threadId: string): Promise<ThreadInfo> {+ if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');+ const t = this.mustGet(threadId);+ this.assertRetryable(t);+ const { info: agentInfo, custom } = await this.resolveAgentInfo(t.agentRef);+ this.assertRetryable(t);t.resumeInFlight = true;+ const ticket = beginLaunch(t);t.sessionBeforeRestart = {sessionId: t.sessionId,resumable: t.info.resumable,@@ -2524,7 +2625,6 @@ export class AcpThreadManager {try {resetSharedLoginShellPathProvider();this.healthyInterpreters.clear();- const { info: agentInfo, custom } = await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t);t.info.agent = agentInfo;t.stderrTail = [];@@ -2534,6 +2634,7 @@ export class AcpThreadManager {try {await this.startThread(t,+ ticket,{ agent: t.agentRef, settings: t.launchSettings },custom,BLOCKING_CONSENT_TIMEOUT_MS,@@ -2544,7 +2645,9 @@ export class AcpThreadManager {this.emitStatus(t, 'error', detail, { reason: 'connect', agentMessage: detail });throw new ThreadOpError('spawn-failed', detail);}- if (isThreadClosed(t)) throw new ThreadOpError('not-ready', 'thread closed during retry');+ if (!isCurrentLaunch(t, ticket)) {+ throw new ThreadOpError('not-ready', 'thread closed during retry');+ }const settled = this.getInfo(threadId)?.status;if (settled === 'ready' || settled === 'running') {this.opts.log.info(@@ -2560,6 +2663,20 @@ export class AcpThreadManager {}}+ private assertRetryable(t: ThreadRecord): void {+ if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');+ if (t.closed) throw new ThreadOpError('not-ready', 'the thread is closing');+ if (t.info.archived === true) {+ throw new ThreadOpError('not-ready', 'the thread is archived — resume it instead');+ }+ if (t.info.status !== 'error' && t.info.status !== 'auth_required' && !t.authInFlight) {+ throw new ThreadOpError('not-ready', 'this thread did not fail to start');+ }+ if (t.resumeInFlight) {+ throw new ThreadOpError('not-ready', 'a retry is already in progress');+ }+ }+terminalAuthLaunch(threadId: string, methodId: string): ThreadAuthTerminalLaunch {const t = this.mustGet(threadId);const launch = terminalAuthLaunch(t.lastInit?.authMethods, t.terminalAuthBase, methodId);@@ -2572,6 +2689,7 @@ export class AcpThreadManager {async authenticateThread(threadId: string, methodId: string): Promise<ThreadInfo> {if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');const t = this.mustGet(threadId);+ if (t.closed) throw new ThreadOpError('not-ready', 'the thread is closing');if (t.info.archived === true) {throw new ThreadOpError('not-ready', 'the thread is archived — resume it instead');}@@ -2580,7 +2698,8 @@ export class AcpThreadManager {}const conn = t.conn;const init = t.lastInit;- if (conn === null || init === null || t.child === null) {+ const ticket = t.launchTicket;+ if (conn === null || init === null || t.child === null || ticket === null) {throw new ThreadOpError('not-ready',`${t.info.agent.name} is no longer running — use Retry to start it again`,@@ -2619,6 +2738,7 @@ export class AcpThreadManager {if (t.conn !== conn) throw threadRestartedDuringSignIn();const opened = await this.openSession(t,+ ticket,conn,init,t.launchSettings,@@ -2646,6 +2766,8 @@ export class AcpThreadManager {}}if (opened !== true) {+ if (isThreadClosed(t)) throw new ThreadOpError('not-ready', 'thread closed during sign-in');+ if (!isCurrentLaunch(t, ticket)) throw threadRestartedDuringSignIn();throw new ThreadOpError('not-ready',lastFailureMessage(t) ?? `${t.info.agent.name} still couldn't start a conversation`,@@ -2676,6 +2798,7 @@ export class AcpThreadManager {}private async abortResume(t: ThreadRecord, failure: ThreadFailureDetail): Promise<void> {+ t.launchTicket = null;if (isThreadClosed(t)) {await this.stopFailedAgent(t);this.emitStatus(t, 'exited', 'resume failed', failure);@@ -3232,6 +3355,7 @@ export class AcpThreadManager {private async applyInitialConfig(record: ThreadRecord,+ ticket: LaunchTicket,conn: NonNullable<ThreadRecord['conn']>,config: Record<string, string | boolean>,sessionStateUnknown = false,@@ -3261,6 +3385,7 @@ export class AcpThreadManager {acpMethods.agent.session.setConfigOption,request,);+ if (!isCurrentLaunch(record, ticket)) return;record.info.configOptions = response.configOptions;rejected.delete(configId);applied = true;@@ -3272,7 +3397,7 @@ export class AcpThreadManager {'[acp-threads] initial config apply attempt failed',);}- if (record.closed) return;+ if (!isCurrentLaunch(record, ticket)) return;}if (!changed) break;pending = Object.entries(config).filter(@@ -3313,6 +3438,7 @@ export class AcpThreadManager {private async applyInitialMode(record: ThreadRecord,+ ticket: LaunchTicket,conn: NonNullable<ThreadRecord['conn']>,modeId: string,sessionStateUnknown = false,@@ -3325,6 +3451,7 @@ export class AcpThreadManager {if (!sessionStateUnknown && modes.currentModeId === modeId) return;try {await conn.agent.request(acpMethods.agent.session.setMode, { sessionId, modeId });+ if (!isCurrentLaunch(record, ticket)) return;record.info.modes = { ...modes, currentModeId: modeId };this.emitInfo(record);} catch (err) {@@ -3346,6 +3473,7 @@ export class AcpThreadManager {acpMethods.agent.session.setConfigOption,{ sessionId, configId: option.id, value: modeId },);+ if (!isCurrentLaunch(record, ticket)) return;record.info.configOptions = response.configOptions;this.emitInfo(record);} catch (err) {@@ -3416,6 +3544,7 @@ export class AcpThreadManager {const t = this.threads.get(threadId);if (t === undefined || t.info.archived === true || t.closed) return;t.closed = true;+ t.launchTicket = null;this.clearSteer(t);this.failPendingPermissions(t);this.failPendingConsents(t);@@ -3787,29 +3916,40 @@ export class AcpThreadManager {failure?: ThreadFailureDetail,): void {if (isThreadClosed(t)) {- const log =- status === 'error' || status === 'auth_required' ? this.opts.log.warn : this.opts.log.info;- log.call(- this.opts.log,- {- threadId: t.info.threadId,- agentId: t.info.agent.id,- status,- suppressed: true,- detail: detail === undefined ? undefined : redactDiagnostic(detail),- reason: failure?.reason,- machineDetail:- failure?.machineDetail === undefined- ? undefined- : redactDiagnostic(failure.machineDetail),- },- '[acp-threads] status suppressed after thread close',- );+ this.logSuppressedStatus(t, status, detail, failure);return;}this.recordTerminalStatus(t, status, detail, failure);}+ private logSuppressedStatus(+ t: ThreadRecord,+ status: ThreadStatus,+ detail: string | undefined,+ failure: ThreadFailureDetail | undefined,+ ): void {+ const log =+ status === 'error' || status === 'auth_required' ? this.opts.log.warn : this.opts.log.info;+ log.call(+ this.opts.log,+ {+ threadId: t.info.threadId,+ agentId: t.info.agent.id,+ status,+ suppressed: true,+ detail: detail === undefined ? undefined : redactDiagnostic(detail),+ reason: failure?.reason,+ machineDetail:+ failure?.machineDetail === undefined+ ? undefined+ : redactDiagnostic(failure.machineDetail),+ },+ isThreadClosed(t)+ ? '[acp-threads] status suppressed after thread close'+ : '[acp-threads] status suppressed for a superseded launch',+ );+ }+private recordTerminalStatus(t: ThreadRecord,status: ThreadStatus,@@ -3821,6 +3961,17 @@ export class AcpThreadManager {this.clearSteer(t);this.clearStall(t);}+ if (+ t.launchTicket !== null &&+ t.launchTicket.initialPrompt !== null &&+ (status === 'exited' || status === 'error' || status === 'auth_required')+ ) {+ t.launchTicket.initialPrompt = null;+ this.opts.log.info(+ { threadId: t.info.threadId, agentId: t.info.agent.id, status },+ '[acp-threads] pending first message dropped: the launch settled without starting a turn',+ );+ }t.info.status = status;t.info.lastActivityAt = Date.now();if (status === 'error' || status === 'auth_required') {@@ -3862,6 +4013,20 @@ export class AcpThreadManager {this.emitInfo(t);}+ private async failLaunch(+ record: ThreadRecord,+ ticket: LaunchTicket,+ message: string | undefined,+ failure: ThreadFailureDetail,+ ): Promise<void> {+ if (!isCurrentLaunch(record, ticket)) {+ this.logSuppressedStatus(record, 'error', message, failure);+ return;+ }+ this.emitStatus(record, 'error', message, failure);+ if (isCurrentLaunch(record, ticket)) await this.teardownFailedAgent(record);+ }+private async teardownFailedAgent(t: ThreadRecord): Promise<void> {t.sessionId = null;t.info.resumable = false;@@ -4091,6 +4256,7 @@ function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {midTurnOnDisk: false,resumeInFlight: false,authInFlight: false,+ launchTicket: null,suppressUpdates: false,lastSuppressedAt: 0,subscribers: new Set(),@@ -4201,6 +4367,7 @@ function lastFailureMessage(t: ThreadRecord): string | undefined {async function connectionFailureDetail(err: unknown,record: ThreadRecord,+ ownsStderrTail: boolean,): Promise<ThreadFailureDetail> {const detail =err instanceof AgentLaunchError || err instanceof ThreadOpError ? err.message : String(err);@@ -4209,7 +4376,7 @@ async function connectionFailureDetail(agentMessage: detail,machineDetail: joinMachineDetail({primary: err instanceof AgentLaunchError ? err.machineDetail : undefined,- tail: await stderrTailDetail(record),+ tail: ownsStderrTail ? await stderrTailDetail(record) : undefined,}),};}@@ -4226,6 +4393,19 @@ function isThreadClosed(t: ThreadRecord): boolean {return t.closed || t.info.archived === true;}+function beginLaunch(+ t: ThreadRecord,+ initialPrompt: LaunchTicket['initialPrompt'] = null,+): LaunchTicket {+ const ticket: LaunchTicket = { initialPrompt };+ t.launchTicket = ticket;+ return ticket;+}++function isCurrentLaunch(t: ThreadRecord, ticket: LaunchTicket): boolean {+ return t.launchTicket === ticket;+}+async function stderrTailDetail(t: ThreadRecord): Promise<string | undefined> {const lines = t.stderrTail;await t.drainStderr?.();diff --git a/packages/server/tsconfig.test-helper-callers.json b/packages/server/tsconfig.test-helper-callers.jsonindex 2cb7def1c..db2141167 100644--- a/packages/server/tsconfig.test-helper-callers.json+++ b/packages/server/tsconfig.test-helper-callers.json@@ -5,6 +5,7 @@"src/acp/browser-install-teardown.integration.test.ts","src/acp/npx-install-server-exit.integration.test.ts","src/acp/npx-install-teardown.integration.test.ts",+ "src/acp/superseded-launch.integration.test.ts","src/config-file-watcher-readiness.test.ts","src/expect-stable.test.ts","src/file-watcher-chokidar-fallback.test.ts",