Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): ephemeral single-file window server-liveness (PRD-8211) (#3819)
omar-inkeepd81cb4aa02c1
diff --git a/.changeset/ephemeral-window-liveness.md b/.changeset/ephemeral-window-liveness.mdnew file mode 100644index 000000000..960814b97--- /dev/null+++ b/.changeset/ephemeral-window-liveness.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Reopening a single-file window (`ok open <file>`) after its background server has stopped now starts a fresh, live editing session instead of silently reconnecting to the dead one. The desktop app remembers an open single-file window by the file's path, but it was only checking that the window was still on screen, not that the server behind it was still running. So if that server had exited (a crash, an idle shutdown, or a manual stop) while the window stayed open, opening the same file again reported success but left you with an editor that could never connect. The app now checks that the server is actually alive before reusing a window, and it also notices when a single-file server exits on its own and retires the stale session so the next open starts clean.diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 7d8122fe3..64eee77b9 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -2079,6 +2079,10 @@ function ensureWindowManager() {// state, so it holds for the whole session. See `firstLaunchAfterUpgrade`.isFirstLaunchAfterUpgrade: () => firstLaunchAfterUpgrade,setTimeout: (cb, ms) => setTimeout(cb, ms),+ // Repeating timer for the ephemeral single-file server-liveness watch —+ // unref'd so it never keeps the event loop alive on its own.+ setInterval: (cb, ms) => setInterval(cb, ms).unref(),+ clearInterval: (handle) => clearInterval(handle as ReturnType<typeof setInterval>),killProbe: (pid, signal) => {process.kill(pid, signal as NodeJS.Signals | 0);},@@ -3008,14 +3012,26 @@ async function openEphemeralFile(filePath: string): Promise<void> {}try {+ // Capture any pre-existing live session BEFORE the call so the log can tell a+ // focus-dedup from a fresh spawn: `createEphemeralWindow` returns the SAME+ // context object when it focuses an existing live window, and a NEW one when+ // it spawns (including when it reaps a dead session and re-spawns).+ const existingBefore = wm.getWindowFor(plan.canonicalFilePath);const ctx = await wm.createEphemeralWindow({canonicalFilePath: plan.canonicalFilePath,contentDir: plan.contentDir,docName: plan.docName,});+ const deduped = existingBefore !== undefined && existingBefore === ctx;getLogger('project').info(- { file: plan.canonicalFilePath, apiOrigin: ctx.apiOrigin },- 'ephemeral single-file window created',+ {+ file: plan.canonicalFilePath,+ apiOrigin: ctx.apiOrigin,+ outcome: deduped ? 'focused-existing' : 'spawned-fresh',+ },+ deduped+ ? 'ephemeral single-file window focused (deduped)'+ : 'ephemeral single-file window created',);// The external-link / asset safety net is attached by the window factory// (WindowManager.attachSafetyNet) — for ephemeral windows the asset root isdiff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 33152d551..dc0a227f1 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -73,6 +73,20 @@ const DEFAULT_SPAWN_STARTUP_DEADLINE_MS = 15_000;*/const SPAWN_WAIT_EXTENSION_FACTOR = 8;+/**+ * Cadence (ms) of the ephemeral single-file session's server-liveness poll. An+ * ephemeral server is a DETACHED process whose lifetime is decoupled from its+ * window's, so it can die (kill / crash / idle-shutdown) while the window stays+ * open. The spawner observes the child's `'exit'` but exposes it only as a pull+ * snapshot (`readExit`), not a push signal to this class — so this poll is how+ * the window manager proactively notices a dead session and reaps it. A few+ * seconds is well inside human re-open latency while staying a cheap+ * `process.kill(pid, 0)` probe. Tests inject `deps.setInterval` (see+ * `wireIntervalTimers` / `tick` in the ephemeral-window test suite) to advance+ * it deterministically.+ */+const EPHEMERAL_SERVER_WATCH_POLL_MS = 3_000;+/*** Local mirror of `isValidLockPid` from `@inkeep/open-knowledge-server`. Same* import-surface rationale as `isProcessAliveLocal` above.@@ -752,6 +766,19 @@ export interface WindowManagerDeps {isFirstLaunchAfterUpgrade?(): boolean;/** Schedule a one-shot timer (test injection for the post-exit liveness probe). */setTimeout(cb: () => void, ms: number): unknown;+ /**+ * Schedule a repeating timer for the ephemeral single-file session's+ * server-liveness watch. Kept SEPARATE from `setTimeout` (which+ * several tests inject as an immediate-firing stub to advance the bounded+ * spawn-lock poll) because the watch is an UNBOUNDED periodic poll — reusing+ * an immediate `setTimeout` would recurse forever. Production wires+ * `setInterval`; when unwired (test harnesses that don't exercise the watch),+ * the exit-watch is simply not armed and the probe-on-dedup backstop still+ * repairs the reported symptom. Paired with `clearInterval` (all-or-nothing).+ */+ setInterval?(cb: () => void, ms: number): unknown;+ /** Cancel a timer started by `setInterval`. Wired iff `setInterval` is. */+ clearInterval?(handle: unknown): void;/** `process.kill(pid, signal)` — used in the post-exit liveness probe. */killProbe(pid: number, signal: number | NodeJS.Signals): void;/**@@ -1415,6 +1442,31 @@ export class WindowManager {}}+ /**+ * Whether the detached server backing an ephemeral single-file session is+ * still live. The ephemeral dedup and the exit-watch must gate on SERVER+ * liveness, not just WINDOW liveness — a detached server can die (kill /+ * crash / idle-shutdown) while its window stays open, leaving the cached+ * `apiOrigin` pointing at nothing.+ *+ * Pid liveness is authoritative: `isPidAlive` always has a probe (it falls+ * back to the required `killProbe` dep), so there is no configuration in which+ * a dead server reads as alive, and a dead pid is dead regardless of a stale+ * lock a SIGKILL left behind. When the pid IS alive, a gone or `draining` lock+ * still counts as dead — that is a server mid-shutdown (the same signal+ * `pollServerLock` treats as not-ready) whose pid has not exited yet. With no+ * lock reader wired, the live pid is trusted on its own.+ */+ private isEphemeralServerAlive(ctx: ProjectContext): boolean {+ const eph = ctx.ephemeral;+ if (eph === undefined) return true; // not an ephemeral ctx — nothing to probe+ if (!this.isPidAlive(eph.pid)) return false;+ const reader = this.deps.readServerLock;+ if (!reader) return true; // pid alive, no lock reader to corroborate — trust it+ const lock = reader(eph.lockDir);+ return lock !== null && lock.draining !== true;+ }+/*** Terminate a server by pid using the same SIGTERM → grace-poll → SIGKILL* ladder as `stopAllOwnedServers`, but returning a caller-consumable outcome@@ -2239,18 +2291,25 @@ export class WindowManager {/*** Open (or focus) an ephemeral single-file editing session for a no-project- * file (`ok <file>`). Distinct from `createProjectWindow` in three ways that- * make a dedicated method cleaner than threading an `ephemeral` flag through- * that 450-line path:- * - **Dedup on the canonical FILE path**: a second `ok <samefile>`- * focuses the existing window rather than spawning a second server on the- * same inode (which would clobber the file). The dedup check runs BEFORE- * any temp-dir creation so a focus never leaks a throwaway dir.+ * file (`ok <file>`). Distinct from `createProjectWindow` in ways that make a+ * dedicated method cleaner than threading an `ephemeral` flag through that+ * 450-line path:+ * - **Dedup on the canonical FILE path, gated on SERVER liveness**: a second+ * `ok <samefile>` focuses the existing window rather than spawning a second+ * server on the same inode (which would clobber the file) — but ONLY when+ * that window's detached server is still alive. A dead cached session is+ * reaped and re-spawned instead of re-served (see `isEphemeralServerAlive`).+ * The dedup check runs BEFORE any temp-dir creation so a focus never leaks+ * a throwaway dir.* - **Slim single-file boot** in a throwaway temp `projectDir` (git + MCP* off, content scoped to the one doc): no `.ok/` lands in the user's dir.* - **Deterministic teardown** on window-close: a detached server would* otherwise survive the close. The `'closed'`* handler terminates the pid then removes the temp dir, sequentially.+ * - **Server-liveness exit-watch**: because the server is detached, it can+ * die while the window stays open; a per-session poll (armed when the+ * `setInterval` dep is wired) reaps the dead server's temp dir. It leaves+ * the window itself open — the dedup gate above handles the next re-open.** Requires the ephemeral deps (`createEphemeralProjectDir`,* `spawnDetachedServer`, `removeDir`) to be wired — there is no fallback for an@@ -2271,15 +2330,43 @@ export class WindowManager {const canonicalKey = this.canonicalizeKey(opts.canonicalFilePath);const existing = this.windowsByPath.get(canonicalKey);if (existing) {- if (existing.window.isDestroyed?.() !== true) {+ const windowAlive = existing.window.isDestroyed?.() !== true;+ // Dedup only onto a session that is BOTH window-alive AND server-alive. An+ // ephemeral server is detached and can die while its window stays open; the+ // pre-fix check trusted window liveness alone and re-served a dead+ // `apiOrigin`, so `ok open <file>` "succeeded" with no live session.+ if (windowAlive && this.isEphemeralServerAlive(existing)) {this.bringToFront(existing.window);return existing;}this.deps.log?.warn(- { canonicalKey },- '[window-manager] stale destroyed ephemeral entry — clearing and re-creating',+ {+ event: 'desktop-ephemeral-stale-entry',+ canonicalKey,+ windowAlive,+ pid: existing.ephemeral?.pid,+ apiOrigin: existing.apiOrigin,+ lockDir: existing.ephemeral?.lockDir,+ },+ windowAlive+ ? '[window-manager] ephemeral entry has a dead server — clearing and re-spawning'+ : '[window-manager] stale destroyed ephemeral entry — clearing and re-creating',);this.windowsByPath.delete(canonicalKey);+ // Reap the dead session's temp dir + (already-dead) pid only when the+ // window is still open here. A destroyed window already ran its `'closed'`+ // teardown; teardown is idempotent, but skipping the redundant SIGTERM/rm+ // keeps the destroyed-window path single-pass, as before.+ //+ // The stale window itself is left open, not closed — deliberately, unlike+ // `restartAttachedServer` (which closes the old window once the replacement+ // exists). That path has a synchronous in-place replacement; here the user+ // explicitly re-opened, and gracefully retiring the dead-server window is+ // the renderer "server gone" affordance's job, not main's. Closing it here+ // would preempt that and yank a window the user may still be reading.+ if (windowAlive && existing.ephemeral) {+ void this.teardownEphemeralSession(existing.ephemeral);+ }}// A same-file open already in flight (mid spawn/load) → await it and focus@@ -2488,7 +2575,24 @@ export class WindowManager {ephemeral: { projectDir: tempProjectDir, pid: handle.pid, lockDir },};+ // Exit-watch handle — shared by the `'closed'` handler (below) and the+ // liveness poll (further below). The spawner observes the child's `'exit'`+ // but exposes it only as a pull snapshot (`readExit`), not a push signal to+ // this class, so the poll is how the manager proactively notices a death;+ // once the window closes or the session is invalidated, the interval must be+ // cleared.+ let watchHandle: unknown;+ let watchCleared = false;+ const stopExitWatch = (): void => {+ if (watchCleared) return;+ watchCleared = true;+ if (watchHandle !== undefined) this.deps.clearInterval?.(watchHandle);+ };+window.on('closed', () => {+ // Stop the liveness poll first — the session is going away under the normal+ // teardown path; a straggling poll must not fire a second teardown.+ stopExitWatch();disposeShowGate();// Ownership guard — only tear down if THIS window still owns the slot. A// focus-dedup re-open or `stopAllOwnedServers` could have replaced/cleared@@ -2506,6 +2610,70 @@ export class WindowManager {});this.windowsByPath.set(canonicalKey, context);++ // Exit-watch: proactively notice a detached server that dies while its window+ // is still open (kill / crash / idle-shutdown) and reap its throwaway temp+ // dir, so it does not linger for the window's whole open lifetime. Armed only+ // when `setInterval` is wired (production); unwired harnesses rely on the+ // probe-on-dedup backstop, which alone repairs the reported re-open symptom.+ //+ // It deliberately does NOT delete the `windowsByPath` entry (unlike the+ // utility-fork `on('exit')` path). The entry is what keeps a still-open+ // window in the session-restore set (`getOpenWindows`); dropping it would+ // silently exclude the file from next-launch restore. Dedup correctness does+ // not need the delete — the dedup gate live-probes liveness on the next open+ // — so leaving the entry costs nothing and preserves restore. The window is+ // left open; retiring it gracefully is the renderer affordance's job.+ //+ // The whole body is wrapped in try/catch: this is the one new call site not+ // guarded by async/await propagation, and main runs with no+ // `uncaughtException` handler by design — a throw here (a probe dep, an errno+ // path) would take down every window, not just this one.+ if (this.deps.setInterval) {+ watchHandle = this.deps.setInterval(() => {+ try {+ if (watchCleared) return;+ // Superseded: a focus-dedup re-open or teardown replaced/cleared the+ // slot. Whoever owns it now runs its own watch — stop quietly.+ if (this.windowsByPath.get(canonicalKey) !== context) {+ stopExitWatch();+ return;+ }+ if (this.isEphemeralServerAlive(context)) return;+ // The detached server died while its window stayed open. Reap its temp+ // dir and stop; the entry stays for the reasons above.+ stopExitWatch();+ const eph = context.ephemeral as NonNullable<ProjectContext['ephemeral']>;+ this.deps.log?.warn(+ {+ event: 'desktop-ephemeral-server-exited',+ pid: eph.pid,+ lockDir: eph.lockDir,+ file: opts.canonicalFilePath,+ },+ '[window-manager] ephemeral server exited while its window was open — reaping the dead session temp dir',+ );+ // No `recordServerExit` here (unlike the utility-fork `on('exit')`+ // path): that record lands in `<lockDir>/last-server-exit.json`, and an+ // ephemeral lockDir lives inside the throwaway temp projectDir that this+ // teardown removes — a persistent project lock is re-attached and read+ // by a later bug-report bundle, but a throwaway one never is.+ void this.teardownEphemeralSession(eph);+ } catch (err) {+ this.deps.log?.warn(+ {+ event: 'desktop-ephemeral-watch-probe-failed',+ err,+ file: opts.canonicalFilePath,+ pid: context.ephemeral?.pid,+ lockDir: context.ephemeral?.lockDir,+ },+ '[window-manager] ephemeral server-liveness probe threw — skipping this poll cycle',+ );+ }+ }, EPHEMERAL_SERVER_WATCH_POLL_MS);+ }+return context;}@@ -2517,34 +2685,52 @@ export class WindowManager {* removing the dir under a live server is a race. Idempotent: a second call* (the `'closed'` handler and `stopAllOwnedServers` can both reach a session)* hits ESRCH on the already-dead pid and a no-op `force` rm on the gone dir.+ *+ * Guaranteed non-rejecting: every caller invokes it fire-and-forget (`void`),+ * so a rejection would surface as an unhandled rejection — and main runs with+ * no `unhandledRejection` handler by design, which would crash every window.+ * The top-level try/catch makes that guarantee structural rather than relying+ * on each callee (`terminateServerByPid`, `removeDir`) never throwing.*/private async teardownEphemeralSession(session: {projectDir: string;pid: number;lockDir: string;}): Promise<void> {- const term = await this.terminateServerByPid(session.lockDir, session.pid);- if (!term.ok) {+ try {+ const term = await this.terminateServerByPid(session.lockDir, session.pid);+ if (!term.ok) {+ this.deps.log?.warn(+ {+ event: 'desktop-ephemeral-teardown',+ outcome: term.reason,+ pid: session.pid,+ projectDir: session.projectDir,+ },+ '[window-manager] ephemeral server termination did not confirm; removing temp dir anyway',+ );+ }+ await this.deps.removeDir?.(session.projectDir).catch((err: unknown) => {+ this.deps.log?.warn(+ {+ event: 'desktop-ephemeral-teardown',+ err,+ projectDir: session.projectDir,+ },+ '[window-manager] failed to remove ephemeral temp dir',+ );+ });+ } catch (err) {this.deps.log?.warn({- event: 'desktop-ephemeral-teardown',- outcome: term.reason,+ event: 'desktop-ephemeral-teardown-unexpected',+ err,pid: session.pid,projectDir: session.projectDir,},- '[window-manager] ephemeral server termination did not confirm; removing temp dir anyway',+ '[window-manager] unexpected error tearing down ephemeral session',);}- await this.deps.removeDir?.(session.projectDir).catch((err: unknown) => {- this.deps.log?.warn(- {- event: 'desktop-ephemeral-teardown',- err,- projectDir: session.projectDir,- },- '[window-manager] failed to remove ephemeral temp dir',- );- });}/** Close a specific project window (called by IPC `ok:project:close`). */diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.tsindex f25945d41..b4bb7bbce 100644--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts@@ -90,6 +90,13 @@ interface EphemeralEnv {killCalls: Array<{ pid: number; signal: number | NodeJS.Signals }>;/** Control: when false, the spawn stub does NOT publish a lock (timeout path). */publishLock: boolean;+ /**+ * Simulate the detached server dying out-of-band (a `kill -TERM <pid>` from a+ * shell, a crash, or an idle-shutdown) — WITHOUT going through the manager's+ * own teardown. Mirrors a real exit: the pid stops being alive and its lock is+ * released. Used to exercise the server-liveness paths.+ */+ killServer: (pid: number) => void;}function buildEphemeralEnv(): EphemeralEnv {@@ -123,6 +130,12 @@ function buildEphemeralEnv(): EphemeralEnv {effectLog,killCalls,publishLock: true,+ killServer: (pid) => {+ killedPids.add(pid);+ for (const [dir, lock] of locks) {+ if (lock.pid === pid) locks.delete(dir);+ }+ },deps: {createWindow: (opts) => {createWindowOpts.push(opts);@@ -525,4 +538,269 @@ describe('createEphemeralWindow', () => {wm.createEphemeralWindow({ canonicalFilePath: FILE, contentDir: PARENT, docName: 'todo' }),).rejects.toThrow(/requires createEphemeralProjectDir/);});++ // --- dedup must gate on SERVER liveness, not just WINDOW liveness ---+ // An ephemeral server is a DETACHED process; it can die (kill / crash / idle-+ // shutdown) while its BrowserWindow stays open. The pre-fix dedup returned the+ // cached ProjectContext whenever the window was alive, handing the renderer a+ // dead `apiOrigin` — `ok open <file>` "succeeded" but started no session.++ /** Controllable `setInterval`/`clearInterval` stubs for the exit-watch. Each+ * interval is a record whose `cb` fires on `tick()` until cleared. */+ interface FakeInterval {+ cb: () => void;+ cleared: boolean;+ }+ function wireIntervalTimers(deps: WindowManagerDeps): FakeInterval[] {+ const intervals: FakeInterval[] = [];+ deps.setInterval = (cb: () => void) => {+ const rec: FakeInterval = { cb, cleared: false };+ intervals.push(rec);+ return rec;+ };+ deps.clearInterval = (handle: unknown) => {+ (handle as FakeInterval).cleared = true;+ };+ return intervals;+ }+ /** Advance every live interval `rounds` times (a cleared interval is inert). */+ function tick(intervals: FakeInterval[], rounds: number): void {+ for (let r = 0; r < rounds; r++) {+ for (const rec of intervals) {+ if (!rec.cleared) rec.cb();+ }+ }+ }++ test('re-open after the ephemeral server dies spawns a FRESH live session, not the dead one', async () => {+ const wm = new WindowManager(env.deps);+ const first = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ expect(env.spawnCalls).toHaveLength(1);+ const deadApiOrigin = first.apiOrigin;+ const deadPid = first.ephemeral?.pid;+ expect(deadPid).toBeDefined();++ // The detached server dies while the window stays open (isDestroyed stays+ // false). Pre-fix, the next open focus-dedups onto this dead session.+ env.killServer(deadPid as number);++ const second = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ // Fire-and-forget teardown of the dead session runs during the fresh spawn.+ await wait(20);++ // A fresh server was spawned; the returned context points at the LIVE origin.+ expect(env.spawnCalls).toHaveLength(2);+ expect(second.apiOrigin).not.toBe(deadApiOrigin);+ expect(second.ephemeral?.pid).not.toBe(deadPid);+ // The map now resolves the file to the live session.+ expect(wm.getWindowFor(FILE)?.apiOrigin).toBe(second.apiOrigin);+ // The dead session's throwaway temp dir was reaped (no leak on re-open).+ expect(env.removedDirs).toContain(first.ephemeral?.projectDir);+ });++ test('a live re-open still focus-dedups (server-liveness gate does not break the healthy path)', async () => {+ const wm = new WindowManager(env.deps);+ const first = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ // Server is alive → the second open must focus the SAME window, not respawn.+ const second = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ expect(second).toBe(first);+ expect(env.spawnCalls).toHaveLength(1);+ expect(env.removedDirs).toEqual([]);+ expect(env.windows[0]?.focus).toHaveBeenCalledTimes(1);+ });++ test('exit-watch reaps the dead server temp dir but keeps the window in the restore set', async () => {+ const intervals = wireIntervalTimers(env.deps);+ const wm = new WindowManager(env.deps);+ const ctx = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ const pid = ctx.ephemeral?.pid as number;+ expect(wm.getWindowFor(FILE)).toBe(ctx);++ // A poll while the server is ALIVE must not reap a healthy session.+ tick(intervals, 1);+ expect(wm.getWindowFor(FILE)).toBe(ctx);+ expect(env.removedDirs).toEqual([]);++ // The server dies out-of-band; the next poll reaps its throwaway temp dir.+ env.killServer(pid);+ tick(intervals, 1);+ await wait(20);+ expect(env.removedDirs).toContain(ctx.ephemeral?.projectDir);++ // Regression guard: the map entry is deliberately KEPT so the still-open+ // window stays in the session-restore snapshot (`getOpenWindows`). Dropping+ // it here would silently exclude the loose file from next-launch restore.+ // Dedup correctness is the live-probe's job on the next open, not a delete.+ expect(wm.getWindowFor(FILE)).toBe(ctx);+ expect(wm.getOpenWindows()).toContainEqual({ kind: 'file', filePath: ctx.canonicalKey });++ // The watch stopped after the reap — a further poll does not reap again.+ const rmCount = env.removedDirs.length;+ tick(intervals, 3);+ await wait(20);+ expect(env.removedDirs).toHaveLength(rmCount);+ });++ test('a server mid-graceful-shutdown (lock draining, pid still alive) is treated as dead on re-open', async () => {+ const wm = new WindowManager(env.deps);+ const first = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ expect(env.spawnCalls).toHaveLength(1);++ // Pid stays alive, but its lock flips to `draining` — a server mid graceful+ // shutdown whose pid has not exited yet. `isEphemeralServerAlive` must treat+ // this as dead, so the re-open re-spawns instead of focusing the dying one.+ const lockDir = first.ephemeral?.lockDir as string;+ const realReader = env.deps.readServerLock as NonNullable<WindowManagerDeps['readServerLock']>;+ const original = realReader(lockDir) as ServerLockMetadataLike;+ env.deps.readServerLock = (dir) =>+ dir === lockDir ? { ...original, draining: true } : realReader(dir);++ const second = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ await wait(20);+ expect(env.spawnCalls).toHaveLength(2);+ expect(second).not.toBe(first);+ });++ test('a dead pid whose lock was never cleaned up (SIGKILL) is treated as dead on re-open', async () => {+ const wm = new WindowManager(env.deps);+ const first = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ const lockDir = first.ephemeral?.lockDir as string;+ const realReader = env.deps.readServerLock as NonNullable<WindowManagerDeps['readServerLock']>;+ const stale = realReader(lockDir) as ServerLockMetadataLike; // capture before kill++ // SIGKILL: pid dies but the lock file is never released, so a reader still+ // returns the stale, non-draining lock. Pid liveness is authoritative, so the+ // dead pid must win over the present lock and the re-open must re-spawn.+ env.killServer(first.ephemeral?.pid as number);+ env.deps.readServerLock = (dir) => (dir === lockDir ? stale : realReader(dir));++ const second = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ await wait(20);+ expect(env.spawnCalls).toHaveLength(2);+ expect(second).not.toBe(first);+ });++ test('a stale exit-watch from a superseded session does not act on the fresh re-open', async () => {+ const intervals = wireIntervalTimers(env.deps);+ const wm = new WindowManager(env.deps);+ const first = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ // Kill the first server, then re-open: probe-on-dedup reaps + drops the first+ // entry and spawns a fresh session (its OWN watch). The FIRST session's watch+ // is still armed and must self-stop on its next poll via the superseded-slot+ // check rather than tearing down the live replacement.+ env.killServer(first.ephemeral?.pid as number);+ const second = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ await wait(20);+ expect(second).not.toBe(first);+ expect(wm.getWindowFor(FILE)).toBe(second);++ const rmBefore = env.removedDirs.length;+ tick(intervals, 1); // intervals[0] = stale first watch, intervals[1] = live second watch+ expect(wm.getWindowFor(FILE)).toBe(second); // live session untouched+ expect(intervals[0]?.cleared).toBe(true); // stale watch self-stopped+ expect(intervals[1]?.cleared).toBe(false); // live watch still armed+ expect(env.removedDirs).toHaveLength(rmBefore); // stale watch reaped nothing new+ });++ test('exit-watch stops once the window closes (no invalidation churn on a closed window)', async () => {+ const intervals = wireIntervalTimers(env.deps);+ const wm = new WindowManager(env.deps);+ await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });++ // Normal close reaps once (server SIGTERM + rm) and stops the watch.+ env.windows[0]?.fireClose();+ await wait(20);+ // Pin the close handler's `stopExitWatch()` directly: the interval is cleared+ // AT CLOSE, not merely self-healed on a later poll. Without this the test+ // would still pass via the superseded-slot check on the next `tick`, so it+ // would not catch a regression that dropped the close-handler stop call.+ expect(intervals[0]?.cleared).toBe(true);+ const rmAfterClose = env.removedDirs.length;+ const sigtermsAfterClose = env.killCalls.filter((k) => k.signal === 'SIGTERM').length;++ // Any subsequent poll after close must be inert — the interval was cleared,+ // so no second teardown fires.+ tick(intervals, 10);+ await wait(20);+ expect(env.removedDirs).toHaveLength(rmAfterClose);+ expect(env.killCalls.filter((k) => k.signal === 'SIGTERM')).toHaveLength(sigtermsAfterClose);+ });++ test('closing the stale window after dedup-repair does not tear down the live replacement', async () => {+ const wm = new WindowManager(env.deps);+ const first = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ // Server dies; re-open reaps the dead session and spawns a fresh one that now+ // owns the canonicalKey slot. The stale first window is deliberately left open.+ env.killServer(first.ephemeral?.pid as number);+ const second = await wm.createEphemeralWindow({+ canonicalFilePath: FILE,+ contentDir: PARENT,+ docName: 'todo',+ });+ await wait(20);+ expect(second).not.toBe(first);+ expect(wm.getWindowFor(FILE)).toBe(second);++ // The user now closes the STALE (first) window. Its `'closed'` ownership+ // guard must decline to touch the live replacement's server + temp dir.+ env.windows[0]?.fireClose();+ await wait(20);++ expect(wm.getWindowFor(FILE)).toBe(second);+ expect(env.removedDirs).not.toContain(second.ephemeral?.projectDir);+ // The live replacement's server was never SIGTERM'd by the stale close.+ expect(env.killCalls.filter((k) => k.pid === second.ephemeral?.pid)).toEqual([]);+ });});