diff --git a/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts b/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts new file mode 100644 index 000000000000..9dbf9aecc336 --- /dev/null +++ b/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts @@ -0,0 +1,149 @@ +// Bridge bash reports no folder; a distro stopped while Orca was quit left the pane at its spawn folder. +import './mock-descendant-sweep' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { join } from 'node:path' +import { readFileSync, rmSync } from 'node:fs' +import { DaemonPtyAdapter } from './daemon-pty-adapter' +import type { DaemonServer } from './daemon-server' +import { getHistorySessionDirName } from './history-paths' +import { createMockSubprocess, startDaemonAdapterHarness } from './daemon-pty-adapter-test-harness' +import type { WslGuestProcessRow } from '../wsl/wsl-guest-pane-processes' +import type * as GuestProcessesModule from '../wsl/wsl-guest-pane-processes' +import * as startupCwdProbe from '../ipc/pty/host-env/startup-cwd-directory-exists' + +const readRows = vi.hoisted(() => + vi.fn( + async ( + _distro: string, + _timeoutMs: number, + _opts?: { running?: boolean } + ): Promise => null + ) +) +vi.mock('../wsl/wsl-guest-pane-processes', async (importOriginal) => ({ + ...(await importOriginal()), + readWslGuestPaneProcesses: readRows +})) + +const PANE_KEY = '11111111-1111-4111-8111-111111111111:22222222-2222-4222-8222-222222222222' +const WSL_CWD = '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo' +const DEEP = `${WSL_CWD}\\deep` + +/** Shortens quit's folder budget so an unanswering distro is not a real-time wait. */ +class QuickQuitDaemonPtyAdapter extends DaemonPtyAdapter { + protected quitWslCwdBudgetMs = 5 +} + +describe('a bridge WSL pane keeps its shell folder across quit', () => { + let dir: string + let socketPath: string + let tokenPath: string + let server: DaemonServer + let harnessAdapter: DaemonPtyAdapter + let adapters: DaemonPtyAdapter[] = [] + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + const spawnCwds: (string | undefined)[] = [] + let lastSubprocess: ReturnType + + beforeEach(async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + readRows.mockReset() + readRows.mockResolvedValue([ + { pid: 10, ppid: 1, comm: 'bash', paneKey: PANE_KEY, cwd: '/home/jin/repo/deep' } + ]) + spawnCwds.length = 0 + const harness = await startDaemonAdapterHarness((opts) => { + spawnCwds.push(opts.cwd) + lastSubprocess = createMockSubprocess() + return lastSubprocess + }) + ;({ dir, socketPath, tokenPath, server } = harness) + harnessAdapter = harness.adapter + }) + + afterEach(async () => { + vi.restoreAllMocks() + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + for (const adapter of adapters) { + adapter.dispose() + } + adapters = [] + harnessAdapter.dispose() + await server.shutdown() + rmSync(dir, { recursive: true, force: true }) + }) + + const historyDir = () => join(dir, 'history') + const launch = (Adapter: typeof DaemonPtyAdapter = DaemonPtyAdapter) => { + const adapter = new Adapter({ socketPath, tokenPath, historyPath: historyDir() }) + adapters.push(adapter) + return adapter + } + const checkpointCwd = (id: string) => + JSON.parse( + readFileSync(join(historyDir(), getHistorySessionDirName(id), 'checkpoint.json'), 'utf-8') + ).cwd + const openBridgePane = (adapter: DaemonPtyAdapter, sessionId: string, cwd = WSL_CWD) => + adapter.spawn({ cols: 80, rows: 24, cwd, env: { ORCA_PANE_KEY: PANE_KEY }, sessionId }) + + it("saves the shell's folder in quit's final checkpoint, never booting the distro", async () => { + const app = launch() + const { id } = await openBridgePane(app, 'repo::/repo@@quit') + lastSubprocess._simulateData('$ cd deep\r\n') + + await app.disconnectOnly() + + // `running` lets the read skip its check only when the running-distro cache confirms it. + expect(readRows).toHaveBeenCalledWith('Ubuntu', expect.any(Number), { running: true }) + expect(checkpointCwd(id)).toBe(DEEP) + }) + + it('reopens in that folder when the distro stopped while Orca was quit', async () => { + vi.spyOn(startupCwdProbe, 'probeRecoveredStartupCwdDirectory').mockResolvedValue(true) + const app = launch() + const { id } = await openBridgePane(app, 'repo::/repo@@terminated') + lastSubprocess._simulateData('$ cd deep\r\n') + await app.disconnectOnly() + // `wsl --terminate` ends the bridge's wsl.exe; the daemon reaps the session. + lastSubprocess._simulateExit(1) + + const relaunched = launch() + await relaunched.reconcileOnStartup(new Set(['repo::/repo'])) + const restored = await openBridgePane(relaunched, id) + + expect(restored.coldRestore).toBeTruthy() + expect(spawnCwds.at(-1)).toBe(DEEP) + }) + + it('keeps the spawn folder when the distro cannot be read', async () => { + readRows.mockResolvedValue(null) + const app = launch() + const { id } = await openBridgePane(app, 'repo::/repo@@unreadable') + + await app.disconnectOnly() + + expect(checkpointCwd(id)).toBe(WSL_CWD) + }) + + it('quits on its budget when the distro does not answer', async () => { + readRows.mockReturnValue(new Promise(() => {})) + const app = launch(QuickQuitDaemonPtyAdapter) + const { id } = await openBridgePane(app, 'repo::/repo@@silent') + + await app.disconnectOnly() + + expect(readRows.mock.calls[0]?.[1]).toBe(5) + expect(checkpointCwd(id)).toBe(WSL_CWD) + }) + + it('reads no distro for a pane that is not a WSL pane', async () => { + const app = launch() + await openBridgePane(app, 'repo::/repo@@windows', 'C:\\repo') + + await app.disconnectOnly() + + expect(readRows).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/daemon/daemon-pty-checkpoint-persistence.ts b/src/main/daemon/daemon-pty-checkpoint-persistence.ts index b91c4f2c2e18..2675463ecd6d 100644 --- a/src/main/daemon/daemon-pty-checkpoint-persistence.ts +++ b/src/main/daemon/daemon-pty-checkpoint-persistence.ts @@ -112,8 +112,9 @@ export abstract class DaemonPtyCheckpointPersistence extends DaemonPtyCheckpoint ? { requiredPreviousPendingOutputSeq: take.seq - 1 } : {}) }) - const sleepCwd = opts.teardown ? this.sleepShellCwds.get(sessionId) : undefined - const snapshot = sleepCwd ? { ...durable, cwd: sleepCwd } : durable + // Set only inside an exclusive final pass (Sleep or quit), so no other checkpoint sees it. + const probedCwd = this.probedShellCwds.get(sessionId) + const snapshot = probedCwd ? { ...durable, cwd: probedCwd } : durable const checkpoint = await this.historyManager.checkpoint(sessionId, snapshot, { pendingOutputSeq: take.seq }) diff --git a/src/main/daemon/daemon-pty-event-subscriptions.ts b/src/main/daemon/daemon-pty-event-subscriptions.ts index a8bba5d70da0..27563bacddf8 100644 --- a/src/main/daemon/daemon-pty-event-subscriptions.ts +++ b/src/main/daemon/daemon-pty-event-subscriptions.ts @@ -10,6 +10,7 @@ import { } from './types' import type { DaemonIdleRetirementResult } from './daemon-pty-runtime-state' import type { PtyBackgroundStreamEvent } from '../providers/pty-provider-contract' +import { readDaemonWslQuitCwds } from './daemon-wsl-sleep-cwd' export abstract class DaemonPtyEventSubscriptions extends DaemonPtySessionInventory { onData(callback: (payload: DaemonPtyRouterDataEvent) => void): () => void { @@ -174,6 +175,14 @@ export abstract class DaemonPtyEventSubscriptions extends DaemonPtySessionInvent } } + private wslBridgePanesForQuit(): { sessionId: string; paneKey: string; wslDistro: string }[] { + return [...this.activeSessionIds].flatMap((sessionId) => { + const wslDistro = this.wslDistrosBySessionId.get(sessionId) + const paneKey = this.wslPaneKeysBySessionId.get(sessionId) + return wslDistro && paneKey ? [{ sessionId, paneKey, wslDistro }] : [] + }) + } + private reopenAfterRefusedIdleRetirement(): void { this.idleRetirementState = 'open' this.idleRetirementAdmissionClosed = false @@ -196,10 +205,27 @@ export abstract class DaemonPtyEventSubscriptions extends DaemonPtySessionInvent // Let admitted sleep shutdowns finish recovery and kill RPCs before disconnecting their client. await Promise.allSettled(keepHistoryShutdowns) this.respawnAdoptionClosed = true + // Bridge bash reports no folder and the daemon outlives quit; a distro stopped before relaunch leaves only this read. + const shellCwds = await readDaemonWslQuitCwds( + this.wslBridgePanesForQuit(), + this.quitWslCwdBudgetMs + ) // Await final checkpoints, including new sessions, before disconnect can reject their snapshot RPCs. - await this.runExclusiveCheckpoint(() => this.checkpointAllSessions(), { - rescheduleDirty: false - }) + await this.runExclusiveCheckpoint( + async () => { + for (const [id, cwd] of shellCwds) { + this.probedShellCwds.set(id, cwd) + } + try { + await this.checkpointAllSessions() + } finally { + for (const id of shellCwds.keys()) { + this.probedShellCwds.delete(id) + } + } + }, + { rescheduleDirty: false } + ) this.dirtySessionVersions.clear() this.lastFullCheckpointAt.clear() this.coldRestoreCache.clear() diff --git a/src/main/daemon/daemon-pty-runtime-state.ts b/src/main/daemon/daemon-pty-runtime-state.ts index 7e31dd49b209..03f8d99f3913 100644 --- a/src/main/daemon/daemon-pty-runtime-state.ts +++ b/src/main/daemon/daemon-pty-runtime-state.ts @@ -125,8 +125,10 @@ export abstract class DaemonPtyRuntimeState { protected readonly hostLossSessionIds = new Set() /** ORCA_PANE_KEY a WSL session was spawned with; its shell's folder is read by it at Sleep. */ protected wslPaneKeysBySessionId = new Map() - /** A sleeping WSL pane's shell folder, read before its final checkpoint; the checkpoint keeps it. */ - protected sleepShellCwds = new Map() + /** A WSL bridge shell's folder read before a final checkpoint (Sleep or quit); that checkpoint keeps it. */ + protected probedShellCwds = new Map() + /** Quit's whole wait for bridge shell folders; a slow distro must not hold up quitting. */ + protected quitWslCwdBudgetMs = 1_000 protected killedSessionTombstones = new Map() protected sleepRestoreSessionIds = new Set() protected coldRestoreCache = new ColdRestorePayloadCache(undefined, (sessionId) => { diff --git a/src/main/daemon/daemon-pty-session-control.ts b/src/main/daemon/daemon-pty-session-control.ts index d6970fbac0eb..a418f7eeb361 100644 --- a/src/main/daemon/daemon-pty-session-control.ts +++ b/src/main/daemon/daemon-pty-session-control.ts @@ -157,12 +157,12 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput { async () => { // Set inside: a caller past its deadline leaves this checkpoint running without it. if (sleepCwd) { - this.sleepShellCwds.set(id, sleepCwd) + this.probedShellCwds.set(id, sleepCwd) } try { await this.checkpointSessions([id], { final: true, teardown: true }) } finally { - this.sleepShellCwds.delete(id) + this.probedShellCwds.delete(id) } }, { callerDeadlineMs: opts.deadlineMs } diff --git a/src/main/daemon/daemon-wsl-sleep-cwd.test.ts b/src/main/daemon/daemon-wsl-sleep-cwd.test.ts index c4e076d769c5..02548482b982 100644 --- a/src/main/daemon/daemon-wsl-sleep-cwd.test.ts +++ b/src/main/daemon/daemon-wsl-sleep-cwd.test.ts @@ -10,7 +10,7 @@ vi.mock('../wsl/wsl-guest-pane-processes', async (importOriginal) => ({ readWslGuestPaneProcesses: readRows })) -const { readDaemonWslSleepCwd } = await import('./daemon-wsl-sleep-cwd') +const { readDaemonWslQuitCwds, readDaemonWslSleepCwd } = await import('./daemon-wsl-sleep-cwd') const pane = { paneKey: 'tab-1:leaf-1', wslDistro: 'Ubuntu', live: true } const shell: WslGuestProcessRow = { @@ -58,6 +58,19 @@ describe('readDaemonWslSleepCwd', () => { expect(await read).toBeNull() }) + it("answers quit's panes within its own budget, leaving out panes it cannot read", async () => { + readRows.mockResolvedValue([shell]) + const cwds = await readDaemonWslQuitCwds( + [ + { sessionId: 's1', paneKey: pane.paneKey, wslDistro: 'Ubuntu' }, + { sessionId: 's2', paneKey: 'tab-2:leaf-2', wslDistro: 'Ubuntu' } + ], + 1_000 + ) + expect(cwds).toEqual(new Map([['s1', '\\\\wsl.localhost\\Ubuntu\\home\\a\\deep']])) + expect(readRows).toHaveBeenCalledWith('Ubuntu', 1_000, { running: true }) + }) + it('reads nothing off Windows', async () => { Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) expect(await readDaemonWslSleepCwd(pane)).toBeNull() diff --git a/src/main/daemon/daemon-wsl-sleep-cwd.ts b/src/main/daemon/daemon-wsl-sleep-cwd.ts index 5b711bbc85b0..c9d27267a471 100644 --- a/src/main/daemon/daemon-wsl-sleep-cwd.ts +++ b/src/main/daemon/daemon-wsl-sleep-cwd.ts @@ -12,9 +12,10 @@ const READ_BUDGET_MS = 3_000 /** The shell's folder in the bridge's UNC spelling, which wake reads; else null. */ export async function readDaemonWslSleepCwd( pane: { paneKey: string; wslDistro: string; live: boolean }, - deadlineMs?: number + deadlineMs?: number, + capMs = READ_BUDGET_MS ): Promise { - const budget = teardownReadBudgetMs(READ_BUDGET_MS, deadlineMs) + const budget = teardownReadBudgetMs(capMs, deadlineMs) if (process.platform !== 'win32' || budget <= 0) { return null } @@ -35,3 +36,21 @@ export async function readDaemonWslSleepCwd( clearTimeout(timer) } } + +/** Quit's once-only read of live bridge panes' folders, in parallel within one budget; a distro read is shared. */ +export async function readDaemonWslQuitCwds( + panes: readonly { sessionId: string; paneKey: string; wslDistro: string }[], + budgetMs: number +): Promise> { + const cwds = new Map() + await Promise.all( + panes.map(async (pane) => { + // `live` only skips a fresh running check when the running-distro cache already confirms it. + const cwd = await readDaemonWslSleepCwd({ ...pane, live: true }, undefined, budgetMs) + if (cwd) { + cwds.set(pane.sessionId, cwd) + } + }) + ) + return cwds +}