Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 4 additions & 5 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ import { prepareEarlyMainUiLanguage, translateMain } from './i18n/main-i18n'
import { ProfileStateRecoveryRequiredError } from './persistence/profile-state/profile-state-recovery-required'
import { getProfileUserDataPath } from './orca-profiles/profile-storage-paths'
import { leaseAppImageGenerationForCurrentProcess } from './cli/appimage-generation-lease'
import { wakeRememberedWslHosts } from './wsl/wsl-host-early-wake'
import { wslHostsServing } from './wsl/wsl-host-gate'
import { deleteLegacyWslHostWakeList } from './wsl/wsl-host-early-wake'
import { configureWslHostsGateFromDisk } from './wsl/wsl-host-gate-startup'
import { ignoreInheritedWslHostsGateState } from '../shared/wsl-host-internal-gate'
import { registerOrcaProtocolClient } from './startup/orca-protocol-registration'
Expand Down Expand Up @@ -133,9 +132,9 @@ if (preflightReady) {
void leaseAppImageGenerationForCurrentProcess()
// Before any gate check: saved WSL work keeps a closed gate serving it.
configureWslHostsGateFromDisk(app.getPath('userData'), app.getVersion())
// Why this early: a cold distro takes seconds to boot; starting now overlaps it with app startup.
if (process.platform === 'win32' && wslHostsServing()) {
wakeRememberedWslHosts(app.getPath('userData'))
// A launch restore is passive (E9): it never boots a WSL host's distro, so drop the old wake list.
if (process.platform === 'win32') {
deleteLegacyWslHostWakeList(app.getPath('userData'))
}
app.on('open-url', (event, url) => {
if (!isRoutedOrcaDeepLink(url)) {
Expand Down
66 changes: 13 additions & 53 deletions src/main/wsl/wsl-host-early-wake.test.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,27 @@
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { writeWslHostDeployment } from '../../shared/wsl-host-deployment-store'
import {
forgetWslHostToWake,
forgetWslHostsToWake,
rememberWslHostsToWake,
wakeRememberedWslHosts
} from './wsl-host-early-wake'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { deleteLegacyWslHostWakeList } from './wsl-host-early-wake'

describe('WSL host early wake', () => {
describe('the old WSL host early-wake list', () => {
let userDataPath: string

beforeEach(() => {
userDataPath = mkdtempSync(join(tmpdir(), 'orca-wsl-wake-'))
writeWslHostDeployment(userDataPath, 'wsl:ubuntu', {
kind: 'wsl',
distro: 'Ubuntu',
localPort: 41000,
remotePort: 6768,
environmentId: 'wsl:ubuntu',
createdAt: 1
})
userDataPath = mkdtempSync(join(tmpdir(), 'orca-wsl-wake-list-'))
})
afterEach(() => rmSync(userDataPath, { recursive: true, force: true }))

it('wakes only the remembered distros that are still WSL hosts', () => {
rememberWslHostsToWake(userDataPath, ['Ubuntu', 'Removed'])
const spawn = vi.fn()
expect(wakeRememberedWslHosts(userDataPath, spawn)).toEqual(['Ubuntu'])
expect(spawn).toHaveBeenCalledExactlyOnceWith('Ubuntu')
afterEach(() => {
rmSync(userDataPath, { recursive: true, force: true })
})

it('wakes nothing once the open work is gone', () => {
rememberWslHostsToWake(userDataPath, ['Ubuntu'])
rememberWslHostsToWake(userDataPath, [])
const spawn = vi.fn()
expect(wakeRememberedWslHosts(userDataPath, spawn)).toEqual([])
expect(spawn).not.toHaveBeenCalled()
})
it('is deleted at launch, so no build boots a distro from it again (E9)', () => {
const wakeList = join(userDataPath, 'orca-wsl-host-wake.json')
writeFileSync(wakeList, JSON.stringify({ version: 1, distros: ['Ubuntu'] }))

it('wakes nothing without a list, or from an unreadable one', () => {
const spawn = vi.fn()
expect(wakeRememberedWslHosts(userDataPath, spawn)).toEqual([])
writeFileSync(join(userDataPath, 'orca-wsl-host-wake.json'), '{"version":1,"distros":["a b"]}')
expect(wakeRememberedWslHosts(userDataPath, spawn)).toEqual([])
expect(spawn).not.toHaveBeenCalled()
})

it('deletes the list when WSL hosts are turned off, so the next launch wakes nothing', () => {
rememberWslHostsToWake(userDataPath, ['Ubuntu'])
forgetWslHostsToWake(userDataPath)
expect(existsSync(join(userDataPath, 'orca-wsl-host-wake.json'))).toBe(false)
const spawn = vi.fn()
expect(wakeRememberedWslHosts(userDataPath, spawn)).toEqual([])
// Nothing to delete is fine too.
expect(() => forgetWslHostsToWake(userDataPath)).not.toThrow()
})
deleteLegacyWslHostWakeList(userDataPath)

it('forgets a removed host even while its record is still on disk', () => {
rememberWslHostsToWake(userDataPath, ['Ubuntu'])
forgetWslHostToWake(userDataPath, 'ubuntu')
const spawn = vi.fn()
expect(wakeRememberedWslHosts(userDataPath, spawn)).toEqual([])
expect(existsSync(wakeList)).toBe(false)
expect(() => deleteLegacyWslHostWakeList(userDataPath)).not.toThrow()
})
})
123 changes: 7 additions & 116 deletions src/main/wsl/wsl-host-early-wake.ts
Original file line number Diff line number Diff line change
@@ -1,127 +1,18 @@
/**
* Boots the distro of the WSL host the last run had focused, at the very start of the next launch,
* so the boot (seconds on a slow PC) overlaps the app's own startup instead of following it. Only
* the focused host is listed (E9: a launch boots the focused host, never others with saved tabs).
* Older builds booted the last focused WSL host's distro at launch from this list. That broke E9
* (a launch restore is passive), so nothing writes or reads the list now; a launch deletes a list
* an older build left behind.
*/
import { rmSync } from 'node:fs'
import { join } from 'node:path'
import { z } from 'zod'
import { spawnProcess } from '@orca/process-host'
import { writeSecureJsonFileWithinLimit } from '../../shared/bounded-secure-json-file'
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
import { readWslHostDeployments } from '../../shared/wsl-host-deployment-store'
import { buildWslExecArgs } from '../../shared/wsl-login-shell-command'
import { WslDistroNameSchema } from '../../shared/wsl-host-deployment-link'
import { resolveWslInteropSpawnCwd } from '../wsl-interop-spawn-directory'
import { wslDistroHolderKey } from './wsl-distro-holder-record'
import { resolveWslExecutablePath } from './wsl-executable-path'

const WAKE_FILE = 'orca-wsl-host-wake.json'
const MAX_WAKE_FILE_BYTES = 16 * 1024

const WakeListSchema = z.object({ version: z.literal(1), distros: z.array(WslDistroNameSchema) })

function wakeFile(userDataPath: string): string {
return join(userDataPath, WAKE_FILE)
}

function readWakeList(userDataPath: string): string[] {
try {
const { buffer } = readNodeFileSyncWithinLimit(wakeFile(userDataPath), MAX_WAKE_FILE_BYTES)
return WakeListSchema.parse(JSON.parse(buffer.toString('utf8'))).distros
} catch {
return []
}
}

/** Saves the distro of the host the user is focused on (or none); called on each focus entry. */
export function rememberWslHostsToWake(userDataPath: string, distros: readonly string[]): void {
const next = [...new Set(distros)].sort()
const current = readWakeList(userDataPath)
if (current.length === next.length && current.every((distro, i) => distro === next[i])) {
return
}
try {
writeSecureJsonFileWithinLimit(
wakeFile(userDataPath),
{ version: 1, distros: next },
MAX_WAKE_FILE_BYTES
)
} catch (error) {
console.warn('[wsl-hosts] Could not save the distros to wake at next launch:', error)
}
}

/**
* WSL hosts turned off: the file is the only thing the next launch reads (before settings load),
* so it goes now, synchronously. If it can't be deleted it is emptied instead, and if that fails
* too the failure is logged; a missing or unreadable file wakes nothing.
*/
export function forgetWslHostsToWake(userDataPath: string): void {
export function deleteLegacyWslHostWakeList(userDataPath: string): void {
try {
rmSync(wakeFile(userDataPath), { force: true })
rmSync(join(userDataPath, WAKE_FILE), { force: true })
} catch (error) {
console.warn('[wsl-hosts] Could not delete the early-wake list; emptying it:', error)
rememberWslHostsToWake(userDataPath, [])
}
}

/** A removed host is never woken early, even before its record is gone. */
export function forgetWslHostToWake(userDataPath: string, distro: string): void {
const key = wslDistroHolderKey(distro)
const remembered = readWakeList(userDataPath)
if (remembered.some((entry) => wslDistroHolderKey(entry) === key)) {
rememberWslHostsToWake(
userDataPath,
remembered.filter((entry) => wslDistroHolderKey(entry) !== key)
)
}
}

export type WslWakeSpawn = (distro: string) => void

function spawnWake(distro: string): void {
const child = spawnProcess({
program: resolveWslExecutablePath(),
args: buildWslExecArgs(distro, ['true']),
cwd: resolveWslInteropSpawnCwd(),
env: { ...process.env, WSL_UTF8: '1' },
stdio: 'ignore'
})
child.on('error', () => {})
child.unref()
}

/**
* Starts booting each remembered distro that is still a registered WSL host. Fire and forget: the
* connect that follows does the real work and reports any failure.
*/
export function wakeRememberedWslHosts(
userDataPath: string,
spawn: WslWakeSpawn = spawnWake
): string[] {
const remembered = readWakeList(userDataPath)
if (remembered.length === 0) {
return []
}
let registered: Set<string>
try {
// A host whose Remove is pending must not be booted: that would undo its stop's proof.
registered = new Set(
readWslHostDeployments(userDataPath)
.deployments.filter((record) => !record.pendingStop)
.map((record) => wslDistroHolderKey(record.distro))
)
} catch {
return []
}
const woken = remembered.filter((distro) => registered.has(wslDistroHolderKey(distro)))
for (const distro of woken) {
try {
spawn(distro)
} catch (error) {
console.warn(`[wsl-hosts] Could not start waking ${distro}:`, error)
}
// Nothing reads it any more; a leftover file is inert.
console.warn('[wsl-hosts] Could not delete the old early-wake list:', error)
}
return woken
}
32 changes: 1 addition & 31 deletions src/main/wsl/wsl-host-pending-removal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,10 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { listEnvironments } from '../../shared/runtime-environment-store'
import {
findWslHostDeployment,
setWslHostPendingStop
} from '../../shared/runtime-environment-wsl-host-store'
import { findWslHostDeployment } from '../../shared/runtime-environment-wsl-host-store'
import type { WslHostStatus } from '../../shared/wsl-host-types'
import { WslHostService, type WslHostConnector } from './wsl-host-service'
import { UBUNTU, UBUNTU_ID, makeConnector } from './wsl-host-service-test-connector'
import { rememberWslHostsToWake, wakeRememberedWslHosts } from './wsl-host-early-wake'

// E11: a Remove that can't prove the host's server stopped keeps the host, pending.
describe('WslHostService pending removal', () => {
Expand Down Expand Up @@ -231,32 +227,6 @@ describe('WslHostService pending removal', () => {
expect(connector.connect).not.toHaveBeenCalled()
})

it('never boots a pending host early at launch', async () => {
const connector = makeConnector([UBUNTU])
const service = makeService(connector)
await service.add({ distro: 'Ubuntu' })
rememberWslHostsToWake(userDataPath, ['Ubuntu'])
// A Remove left pending by a build that still remembered the host.
setWslHostPendingStop(userDataPath, 'wsl:ubuntu', { since: 1, reason: 'busy', verdict: 'live' })
const spawn = vi.fn()

expect(wakeRememberedWslHosts(userDataPath, spawn)).toEqual([])
expect(spawn).not.toHaveBeenCalled()
})

it('forgets the early wake of a host whose Remove ended pending', async () => {
const connector = makeConnector([UBUNTU])
connector.stopServer.mockResolvedValueOnce({ stopped: false, reason: 'busy', verdict: 'live' })
const service = makeService(connector)
await service.add({ distro: 'Ubuntu' })
service.focusHost('wsl:ubuntu')

await service.remove('wsl:ubuntu')
// Withdrawing the removal must not bring the early wake back by itself.
await service.connect('wsl:ubuntu', { withdrawPendingRemoval: true })
expect(wakeRememberedWslHosts(userDataPath, vi.fn())).toEqual([])
})

it('a due automation never boots a host whose Remove is pending', async () => {
const connector = makeConnector([UBUNTU])
connector.stopServer.mockResolvedValueOnce({ stopped: false, reason: 'busy', verdict: 'live' })
Expand Down
Loading
Loading