diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index c822eff43..4bedc08e3 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -857,6 +857,128 @@ test("a resumed session crash is retained before its initial handshake", async ( await wrapper.destroyAndWait(); }); +/** A fake host whose children answer get_state with the id and file they were spawned for, so startRpcSession's live-owner scan can be driven without a real omp child. */ +async function scanHost(t) { + const { startRpcSession, getRpcSession } = await import("./rpc-manager.ts"); + const spawns = []; + const transports = []; + const host = { + id: `scan-test-${randomUUID()}`, + label: "Scan test host", + status: () => "online", + onStatus: () => () => {}, + async spawnRpc(request, sessionId) { + // A fresh child invents its own id (the resume path passes the key in); + // either way get_state reports the child's own id and file. + const childId = sessionId ?? `fresh-${randomUUID()}`; + const listeners = new Set(); + const transport = { + frames: [], + write(line, callback) { + const raw = JSON.parse(line); + if (raw.t === "event") this.frames.push(raw.event); + else if (raw.t !== "cmd") this.frames.push(readCommand(line)); + else { + const command = readCommand(line); + const data = command.type === "get_state" + ? { sessionId: childId, sessionFile: request.sessionFile, isStreaming: false, isCompacting: false } + : {}; + queueMicrotask(() => { + for (const listener of listeners) listener(ompLine({ type: "response", id: command.id, command: command.type, success: true, data })); + }); + } + callback(null); + }, + onLine(listener) { + listeners.add(listener); + queueMicrotask(() => listener(ompLine({ type: "ready" }))); + }, + onStderr() {}, + onExit(listener) { this.exit = listener; }, + endInput() { queueMicrotask(() => this.exit?.(0, null)); }, + killTree() { queueMicrotask(() => this.exit?.(null, "SIGTERM")); }, + }; + transports.push(transport); + spawns.push({ request, sessionId }); + return { transport, cwd: request.cwd, fellBack: false, launchAdvisor: false }; + }, + sessionFileExists: async () => false, + invalidateSessionLists() {}, + autoApproveExtension: () => false, + }; + const sessions = []; + t.after(async () => { + for (const session of sessions) await session.destroyAndWait().catch(() => {}); + }); + /** Start a session on this host; the child reports `sessionFile` as its own file. */ + async function start(sessionId, sessionFile, advisor) { + const { session } = await startRpcSession(sessionId, sessionFile, "/w", undefined, advisor, null, undefined, host); + sessions.push(session); + return { session, transport: transports.at(-1) }; + } + /** Kill a child's process without destroying its wrapper: handleProcessExit treats an expected proc's exit as planned, so the dead wrapper stays registered under its key. */ + async function killChildKeepingRegistry(session, transport) { + session.expectedExitProc = session.proc; + transport.killTree(); + await waitUntil(() => !session.isAlive()); + } + return { host, spawns, transports, sessions, start, killChildKeepingRegistry, getRpcSession, startRpcSession }; +} + +test("a dead keyed wrapper does not skip the live-owner scan", async (t) => { + const scan = await scanHost(t); + const file = `/s/scan-${randomUUID()}.jsonl`; + const deadId = `dead-${randomUUID()}`; + const liveId = `live-${randomUUID()}`; + const { session: dead, transport: deadTransport } = await scan.start(deadId, `/s/other-${randomUUID()}.jsonl`, false); + await scan.killChildKeepingRegistry(dead, deadTransport); + assert.equal(dead.isAlive(), false); + assert.equal(scan.getRpcSession(deadId), dead, "the dead wrapper stays registered under its key"); + const live = (await scan.start(liveId, file, false)).session; + assert.equal(live.sessionFile, file); + const spawnsBefore = scan.spawns.length; + const { session, realSessionId } = await scan.startRpcSession(deadId, file, "/w", undefined, undefined, null, undefined, scan.host); + assert.equal(session, live, "the live owner is reused instead of spawning a second --resume child"); + assert.equal(realSessionId, liveId); + assert.equal(scan.spawns.length, spawnsBefore, "no second child spawned"); + assert.equal(scan.getRpcSession(deadId), live, "the requested id now routes to the live owner"); +}); + +test("the live-owner scan replaces an idle owner whose advisor flag was toggled", async (t) => { + const scan = await scanHost(t); + const file = `/s/scan-${randomUUID()}.jsonl`; + const deadId = `dead-${randomUUID()}`; + const liveId = `live-${randomUUID()}`; + const { session: dead, transport: deadTransport } = await scan.start(deadId, `/s/other-${randomUUID()}.jsonl`, false); + await scan.killChildKeepingRegistry(dead, deadTransport); + const { session: live } = await scan.start(liveId, file, false); + assert.equal(live.advisorSpawned, false); + const spawnsBefore = scan.spawns.length; + const { session } = await scan.startRpcSession(deadId, file, "/w", undefined, true, null, undefined, scan.host); + scan.sessions.push(session); + assert.notEqual(session, live, "the mismatched owner is replaced, not silently reused"); + assert.equal(session.advisorSpawned, true, "the replacement spawns with the toggled flag"); + assert.equal(live.isAlive(), false, "the old owner is destroyed before the replacement spawns"); + assert.equal(scan.spawns.length, spawnsBefore + 1, "exactly one replacement child spawns"); + assert.equal(scan.spawns.at(-1).request.advisor, true); + assert.equal(scan.getRpcSession(deadId), session); +}); + +test("the live-owner scan reuses an owner whose advisor flag already matches", async (t) => { + const scan = await scanHost(t); + const file = `/s/scan-${randomUUID()}.jsonl`; + const deadId = `dead-${randomUUID()}`; + const liveId = `live-${randomUUID()}`; + const { session: dead, transport: deadTransport } = await scan.start(deadId, `/s/other-${randomUUID()}.jsonl`, false); + await scan.killChildKeepingRegistry(dead, deadTransport); + const { session: live } = await scan.start(liveId, file, true); + assert.equal(live.advisorSpawned, true); + const spawnsBefore = scan.spawns.length; + const { session } = await scan.startRpcSession(deadId, file, "/w", undefined, true, null, undefined, scan.host); + assert.equal(session, live, "the matching owner is reused"); + assert.equal(scan.spawns.length, spawnsBefore, "no replacement child spawns"); +}); + /** One reachable (hidden) tab in an isolated notification hub; `restore()` tears it down. */ async function reachableTab() { const { mkdtempSync, rmSync } = await import("node:fs"); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index a8f562699..cdc22d479 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -3885,13 +3885,39 @@ export async function startRpcSession( // omp >= 18.5 lets only one process own a session file; a second `--resume` // child would fork into a new nested session on its first write. Reuse the // live wrapper that already reports this file (e.g. after it moved files). - if (sessionFile && !existing) { + // A dead keyed wrapper must not skip this scan: it owns nothing anymore, + // and a live wrapper under another key may already own this file. + if (sessionFile && (!existing || !existing.isAlive())) { for (const candidate of new Set(registry.values())) { - if (candidate.isAlive() && candidate.sessionFile && samePath(candidate.sessionFile, sessionFile)) { - registry.set(sessionId, candidate); - notifyRunningChange({ refreshSessionList: true }); - return { session: candidate, realSessionId: candidate.sessionId }; + if (!candidate.isAlive() || !candidate.sessionFile || !samePath(candidate.sessionFile, sessionFile)) continue; + // The scan must not silently reuse a live owner whose spawn-time + // --advisor flag the caller just toggled: apply the same gate as the + // keyed path above (unknown legacy flag, no opinion, busy child, or an + // unreplaceable host-owned child all reuse; an idle mismatch replaces). + const candidateEffectiveAdvisor = advisor === true || candidate.launchAdvisor === true; + const reuseCandidate = advisor === undefined + || (candidate.adopted && !candidate.hostOwnedLifecycle) + || candidate.advisorSpawned === candidateEffectiveAdvisor + || candidate.isRunning() + || candidate.isEditingHistory() + || (candidate.hostOwnedLifecycle && !candidate.canReplaceAdvisor()); + if (!reuseCandidate) { + if (candidate.hostOwnedLifecycle) { + replacement = await candidate.replaceAdvisorIfIdle(launch, preparingCommand) ?? undefined; + if (replacement) break; + // The daemon could not replace it: keep the live owner, as the + // keyed path does when its replacement comes back null. + } else { + // Replace the mismatched owner instead of spawning beside it: a + // second --resume child would fork into a nested session. + await candidate.destroyAndWait("advisor", true); + if (candidate.destroyPromise) await untilHostDown(candidate.host, candidate.destroyPromise); + continue; + } } + registry.set(sessionId, candidate); + notifyRunningChange({ refreshSessionList: true }); + return { session: candidate, realSessionId: candidate.sessionId }; } }