Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/daemon/daemon-live-sleep-cwd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { DaemonClient } from './client'
import { teardownReadBudgetMs } from './daemon-request-deadline'

const LIVE_SLEEP_CWD_BUDGET_MS = 1_500

/**
* A native shell's folder at Sleep (OSC 7, else its process's cwd). Bash prints no OSC 7, so
* without this the checkpoint keeps the spawn folder and Wake opens there (e.g. on a Linux host).
*/
export async function readDaemonLiveSleepCwd(
client: Pick<DaemonClient, 'request'>,
sessionId: string,
deadlineMs?: number
): Promise<string | null> {
// Windows has no process-cwd lookup (it would spawn a missing lsof); the snapshot's OSC 7 cwd stands.
const budget = teardownReadBudgetMs(LIVE_SLEEP_CWD_BUDGET_MS, deadlineMs)
if (process.platform === 'win32' || budget <= 0) {
return null
}
try {
const { cwd } = await client.request<{ cwd: string | null }>('getCwd', { sessionId }, budget)
// A removed folder reads back from /proc as `<path> (deleted)`, which no shell can return to.
return cwd && !cwd.endsWith(' (deleted)') ? cwd : null
} catch {
return null
}
}
153 changes: 153 additions & 0 deletions src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd-relaunch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
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<WslGuestProcessRow[] | null> => null
)
)
vi.mock('../wsl/wsl-guest-pane-processes', async (importOriginal) => ({
...(await importOriginal<typeof GuestProcessesModule>()),
readWslGuestPaneProcesses: readRows
}))

const PANE_KEY = '11111111-1111-4111-8111-111111111111:22222222-2222-4222-8222-222222222222'
const WSL_CWD = '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo'

function shellIn(cwd: string): WslGuestProcessRow[] {
return [
{ pid: 10, ppid: 1, comm: 'bash', paneKey: PANE_KEY, cwd },
{ pid: 11, ppid: 10, comm: 'sleep', paneKey: PANE_KEY, cwd: '/tmp' }
]
}

// awin 5e: a bridge pane reopened or reattached around a reload or relaunch must still know its distro and pane key at Sleep.
describe('a sleeping bridge WSL pane keeps its shell folder across reloads and relaunches', () => {
let dir: string
let socketPath: string
let tokenPath: string
let server: DaemonServer
let harnessAdapter: DaemonPtyAdapter
let adapter: DaemonPtyAdapter | undefined
const platform = Object.getOwnPropertyDescriptor(process, 'platform')

beforeEach(async () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
readRows.mockReset()
readRows.mockResolvedValue(shellIn('/home/jin/repo/deep/er'))
const harness = await startDaemonAdapterHarness(() => createMockSubprocess())
;({ dir, socketPath, tokenPath, server } = harness)
harnessAdapter = harness.adapter
})

afterEach(async () => {
vi.restoreAllMocks()
if (platform) {
Object.defineProperty(process, 'platform', platform)
}
adapter?.dispose()
harnessAdapter.dispose()
await server.shutdown()
rmSync(dir, { recursive: true, force: true })
})

const historyDir = () => join(dir, 'history')
const checkpointCwd = (id: string) =>
JSON.parse(
readFileSync(join(historyDir(), getHistorySessionDirName(id), 'checkpoint.json'), 'utf-8')
).cwd

const spawnPane = (
a: DaemonPtyAdapter,
sessionId: string,
env: Record<string, string> | undefined
) => a.spawn({ cols: 80, rows: 24, cwd: WSL_CWD, ...(env ? { env } : {}), sessionId })

it('after a renderer reload re-spawns it with its environment', async () => {
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await spawnPane(adapter, 'repo::/repo@@s1', { ORCA_PANE_KEY: PANE_KEY })
await spawnPane(adapter, id, { ORCA_PANE_KEY: PANE_KEY })
await adapter.shutdown(id, { immediate: true, keepHistory: true })
expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`)
})

it('after a relaunch adopts it and the window re-spawns it with its environment', async () => {
const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await spawnPane(before, 'repo::/repo@@s2', { ORCA_PANE_KEY: PANE_KEY })
await before.disconnectOnly()
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
await adapter.reconcileOnStartup(new Set(['repo::/repo']))
await spawnPane(adapter, id, { ORCA_PANE_KEY: PANE_KEY })
await adapter.shutdown(id, { immediate: true, keepHistory: true })
expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`)
})

it('after a relaunch adopts it and the window re-spawns it without its environment', async () => {
const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await spawnPane(before, 'repo::/repo@@s3', { ORCA_PANE_KEY: PANE_KEY })
await before.disconnectOnly()
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
await adapter.reconcileOnStartup(new Set(['repo::/repo']))
await spawnPane(adapter, id, undefined)
await adapter.shutdown(id, { immediate: true, keepHistory: true })
expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`)
})

it('after a relaunch whose window re-spawns it with its environment before adoption', async () => {
const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await spawnPane(before, 'repo::/repo@@s4', { ORCA_PANE_KEY: PANE_KEY })
await before.disconnectOnly()
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
await spawnPane(adapter, id, { ORCA_PANE_KEY: PANE_KEY })
await adapter.shutdown(id, { immediate: true, keepHistory: true })
expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`)
})

it('after a relaunch whose window re-spawns it without its environment before adoption', async () => {
const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await spawnPane(before, 'repo::/repo@@s5', { ORCA_PANE_KEY: PANE_KEY })
await before.disconnectOnly()
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
await spawnPane(adapter, id, undefined)
await adapter.shutdown(id, { immediate: true, keepHistory: true })
expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`)
})

it('when slept again after a wake, at the folder it moved to', async () => {
vi.spyOn(startupCwdProbe, 'probeRecoveredStartupCwdDirectory').mockResolvedValue(true)
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await spawnPane(adapter, 'repo::/repo@@s6', { ORCA_PANE_KEY: PANE_KEY })
await adapter.shutdown(id, { immediate: true, keepHistory: true })
readRows.mockResolvedValue(shellIn('/home/jin/repo/other'))
await spawnPane(adapter, id, { ORCA_PANE_KEY: PANE_KEY })
await adapter.shutdown(id, { immediate: true, keepHistory: true })
expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\other`)
})

it('when a woken pane is slept by a relaunched app that only adopted it', async () => {
vi.spyOn(startupCwdProbe, 'probeRecoveredStartupCwdDirectory').mockResolvedValue(true)
const before = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await spawnPane(before, 'repo::/repo@@s7', { ORCA_PANE_KEY: PANE_KEY })
await before.shutdown(id, { immediate: true, keepHistory: true })
await spawnPane(before, id, { ORCA_PANE_KEY: PANE_KEY })
await before.disconnectOnly()
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
await adapter.reconcileOnStartup(new Set(['repo::/repo']))
readRows.mockResolvedValue(shellIn('/home/jin/repo/other'))
await adapter.shutdown(id, { immediate: true, keepHistory: true })
expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\other`)
})
})
10 changes: 10 additions & 0 deletions src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,20 @@ describe('a sleeping bridge WSL pane keeps its shell folder', () => {
sessionId: 'repo::/repo@@spawned'
})

const info = vi.spyOn(console, 'info').mockImplementation(() => {})
await adapter.shutdown(id, { immediate: true, keepHistory: true })

expect(readRows).toHaveBeenCalledWith('Ubuntu', expect.any(Number), { running: true })
expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep\\er`)
const lines = info.mock.calls
.map(([line]) => String(line))
.filter((line) => line.includes('Sleep folder'))
// One line per Sleep, naming the branch, what the distro returned and whether a folder came back.
expect(lines).toHaveLength(1)
expect(lines[0]).toContain(`[history] Sleep folder for ${id}: wsl probe (budget `)
expect(lines[0]).toContain(
`rows 2, shells 1), distro Ubuntu, pane ${PANE_KEY}, live true, folder found in `
)
})

// awin verify-9: panes cd'd before a relaunch and slept before the window reopened them
Expand Down
55 changes: 20 additions & 35 deletions src/main/daemon/daemon-pty-session-control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { GET_SIZE_PROTOCOL_VERSION } from './daemon-protocol-version'
import { readDaemonAppliedPtySize, type DaemonAppliedPtySize } from './daemon-pty-applied-size'
import { FinalCheckpointWaitExpiredError } from './daemon-pty-lifecycle-errors'
import { DaemonPtySessionInput } from './daemon-pty-session-input'
import { remainingDaemonRequestTimeoutMs, teardownReadBudgetMs } from './daemon-request-deadline'
import { remainingDaemonRequestTimeoutMs } from './daemon-request-deadline'
import { readDaemonLiveSleepCwd } from './daemon-live-sleep-cwd'
import type { ColdRestoreInfo } from './history-reader'
import { normalizeWslColdRestoreCwd } from './wsl-cold-restore-cwd'
import { readDaemonWslSleepCwd } from './daemon-wsl-sleep-cwd'
import { describeSleepFolderRead, readDaemonWslSleepCwdWithFacts } from './daemon-wsl-sleep-cwd'
import * as unlistedSession from './daemon-unlisted-session'
import { SessionNotFoundError, type ListSessionsResult } from './types'
import { resolveSafePtyDefaultCwd } from '../providers/pty-default-cwd'
Expand All @@ -17,7 +18,6 @@ export const LIVENESS_PROBE_TIMEOUT_MS = 2_000

const MAX_TOMBSTONES = 1000
// A busy daemon must not eat the final checkpoint's share of the Sleep deadline.
const LIVE_SLEEP_CWD_BUDGET_MS = 1_500

export abstract class DaemonPtySessionControl extends DaemonPtySessionInput {
protected abstract adoptListedSessionForSleep(
Expand Down Expand Up @@ -141,18 +141,26 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput {
if (opts.keepHistory) {
const sleepWslDistro = this.wslDistrosBySessionId.get(id)
const sleepPaneKey = this.wslPaneKeysBySessionId.get(id)
const sleepCwd =
const live = this.activeSessionIds.has(id)
const startedAt = Date.now()
const read =
sleepWslDistro && sleepPaneKey
? await readDaemonWslSleepCwd(
{
paneKey: sleepPaneKey,
wslDistro: sleepWslDistro,
// A live pane's own wsl.exe keeps its distro running.
live: this.activeSessionIds.has(id)
},
? // A live pane's own wsl.exe keeps its distro running.
await readDaemonWslSleepCwdWithFacts(
{ paneKey: sleepPaneKey, wslDistro: sleepWslDistro, live },
opts.deadlineMs
)
: await this.readLiveSleepCwd(id, opts.deadlineMs)
: { cwd: live ? await readDaemonLiveSleepCwd(this.client, id, opts.deadlineMs) : null }
const sleepCwd = read.cwd
// Device runs need to see why a WSL pane woke at its spawn folder (awin 5e).
console.info(
describeSleepFolderRead(id, read, {
wslDistro: sleepWslDistro,
paneKey: sleepPaneKey,
live,
elapsedMs: Date.now() - startedAt
})
)
const committed = await this.runExclusiveCheckpoint(
async () => {
// Set inside: a caller past its deadline leaves this checkpoint running without it.
Expand Down Expand Up @@ -301,29 +309,6 @@ export abstract class DaemonPtySessionControl extends DaemonPtySessionInput {
}
}

/**
* A native shell's folder at Sleep (OSC 7, else its process's cwd). Bash prints no OSC 7, so
* without this the checkpoint keeps the spawn folder and Wake opens there (e.g. on a Linux host).
*/
private async readLiveSleepCwd(id: string, deadlineMs?: number): Promise<string | null> {
// Windows has no process-cwd lookup (it would spawn a missing lsof); the snapshot's OSC 7 cwd stands.
const budget = teardownReadBudgetMs(LIVE_SLEEP_CWD_BUDGET_MS, deadlineMs)
if (process.platform === 'win32' || budget <= 0 || !this.activeSessionIds.has(id)) {
return null
}
try {
const { cwd } = await this.client.request<{ cwd: string | null }>(
'getCwd',
{ sessionId: id },
budget
)
// A removed folder reads back from /proc as `<path> (deleted)`, which no shell can return to.
return cwd && !cwd.endsWith(' (deleted)') ? cwd : null
} catch {
return null
}
}

async getInitialCwd(id: string): Promise<string> {
return this.initialCwds.get(id) ?? ''
}
Expand Down
22 changes: 21 additions & 1 deletion src/main/daemon/daemon-wsl-sleep-cwd.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ vi.mock('../wsl/wsl-guest-pane-processes', async (importOriginal) => ({
readWslGuestPaneProcesses: readRows
}))

const { readDaemonWslQuitCwds, readDaemonWslSleepCwd } = await import('./daemon-wsl-sleep-cwd')
const { readDaemonWslQuitCwds, readDaemonWslSleepCwd, readDaemonWslSleepCwdWithFacts } =
await import('./daemon-wsl-sleep-cwd')

const pane = { paneKey: 'tab-1:leaf-1', wslDistro: 'Ubuntu', live: true }
const shell: WslGuestProcessRow = {
Expand Down Expand Up @@ -71,6 +72,25 @@ describe('readDaemonWslSleepCwd', () => {
expect(readRows).toHaveBeenCalledWith('Ubuntu', 1_000, { running: true })
})

it('reports how many rows and pane shells the read saw', async () => {
readRows.mockResolvedValue([shell, { ...shell, pid: 11, cwd: '/home/a' }])
expect(await readDaemonWslSleepCwdWithFacts(pane)).toEqual({
cwd: null,
budgetMs: 3_000,
rows: 2,
shells: 2,
timedOut: false
})
})

it('reports a read that ran out of budget', async () => {
vi.useFakeTimers()
readRows.mockReturnValue(new Promise(() => {}))
const read = readDaemonWslSleepCwdWithFacts(pane)
await vi.advanceTimersByTimeAsync(3_000)
expect(await read).toMatchObject({ cwd: null, rows: null, shells: null, timedOut: true })
})

it('reads nothing off Windows', async () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' })
expect(await readDaemonWslSleepCwd(pane)).toBeNull()
Expand Down
Loading
Loading