diff --git a/config/nsis/orca-installer-hooks.nsh b/config/nsis/orca-installer-hooks.nsh index f40668b3143..9ac82b88a25 100644 --- a/config/nsis/orca-installer-hooks.nsh +++ b/config/nsis/orca-installer-hooks.nsh @@ -61,33 +61,52 @@ Pop $0 nsExec::Exec 'taskkill /F /IM "orca-terminal-daemon.exe" $2' Pop $0 - ; WSL hosts: the detached wsl.exe holders outlive the app and keep their distros running. Orca + ; WSL hosts: the detached wsl.exe holders and each host's server keep their distros running. Orca ; ends only the holders its profile recorded, each checked by pid, start time and command line. - ; Only a userData that has a holder folder launches it: everyone who never ran a WSL host sees - ; nothing here. These are the folders Electron's userData (app.getName()) can be, as the + ; The last install for this user also stops each recorded host's server in a running distro: the + ; HKCU/HKLM twin shares this userData, its host records and those servers, so it keeps them. + ; Only a userData with a holder folder or WSL host records launches it: everyone who never ran a + ; WSL host sees nothing here. These are the folders Electron's userData (app.getName()) can be, as the ; deleteAppData step lists them; a custom --user-data-dir can't be known here. - ; Sync the flag with WSL_HOLDER_UNINSTALL_FLAG in src/main/startup/wsl-holder-uninstall-preflight.ts. + ; Sync the flags with WSL_HOLDER_UNINSTALL_FLAG and WSL_SERVER_UNINSTALL_FLAG in + ; src/main/startup/wsl-holder-uninstall-preflight.ts. ${if} $installMode == "all" SetShellVarContext current ${endIf} StrCpy $1 "" + StrCpy $2 "" ${if} ${FileExists} "$APPDATA\${APP_FILENAME}\wsl-distro-holders\*.json" StrCpy $1 "1" ${endIf} + ${if} ${FileExists} "$APPDATA\${APP_FILENAME}\orca-wsl-host-deployments.json" + StrCpy $2 "1" + ${endIf} !ifdef APP_PRODUCT_FILENAME ${if} ${FileExists} "$APPDATA\${APP_PRODUCT_FILENAME}\wsl-distro-holders\*.json" StrCpy $1 "1" ${endIf} + ${if} ${FileExists} "$APPDATA\${APP_PRODUCT_FILENAME}\orca-wsl-host-deployments.json" + StrCpy $2 "1" + ${endIf} !endif !ifdef APP_PACKAGE_NAME ${if} ${FileExists} "$APPDATA\${APP_PACKAGE_NAME}\wsl-distro-holders\*.json" StrCpy $1 "1" ${endIf} + ${if} ${FileExists} "$APPDATA\${APP_PACKAGE_NAME}\orca-wsl-host-deployments.json" + StrCpy $2 "1" + ${endIf} !endif ${if} $installMode == "all" SetShellVarContext all ${endIf} - ${if} $1 == "1" + ${if} $2 == "1" + !insertmacro ORCA_OTHER_INSTALL_STATE $2 + ${endIf} + ${if} $2 == "none" + nsExec::Exec '"$INSTDIR\${APP_EXECUTABLE_FILENAME}" --orca-uninstall-release-wsl-holders --orca-uninstall-stop-wsl-servers' + Pop $0 + ${elseIf} $1 == "1" nsExec::Exec '"$INSTDIR\${APP_EXECUTABLE_FILENAME}" --orca-uninstall-release-wsl-holders' Pop $0 ${endIf} diff --git a/src/main/grok/grok-hook-backup-cleanup.test.ts b/src/main/grok/grok-hook-backup-cleanup.test.ts new file mode 100644 index 00000000000..1374d4fcf07 --- /dev/null +++ b/src/main/grok/grok-hook-backup-cleanup.test.ts @@ -0,0 +1,92 @@ +import { + copyFileSync, + existsSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) +vi.mock('os', async () => ({ + ...(await vi.importActual>('os')), + homedir: homedirMock +})) + +import { GrokHookService } from './hook-service' +import { removeGrokHookBackupEntries } from './grok-hook-backup-cleanup' + +const USER_HOOK = { matcher: '*', hooks: [{ type: 'command', command: 'my-own-hook' }] } + +describe('the Grok hook file backup after removal', () => { + let homeDir: string + let configPath: string + let backupPath: string + + beforeEach(() => { + homeDir = mkdtempSync(join(tmpdir(), 'orca-grok-backup-')) + homedirMock.mockReturnValue(homeDir) + configPath = join(homeDir, '.grok', 'hooks', 'orca-status.json') + backupPath = `${configPath}.bak` + }) + + afterEach(() => { + rmSync(homeDir, { recursive: true, force: true }) + vi.restoreAllMocks() + }) + + it.each(['sync', 'quit'] as const)( + 'deletes a backup that held only Orca entries (%s path)', + async (path) => { + const service = new GrokHookService() + expect(service.install().state).toBe('installed') + copyFileSync(configPath, backupPath) + + if (path === 'sync') { + service.remove() + } else { + await service.removeAsync() + } + + expect(existsSync(configPath)).toBe(false) + expect(existsSync(backupPath)).toBe(false) + } + ) + + it("strips Orca's entries from a backup that also holds the user's own", () => { + const service = new GrokHookService() + expect(service.install().state).toBe('installed') + const config: { hooks: Record } = JSON.parse( + readFileSync(configPath, 'utf8') + ) + config.hooks.UserCustomEvent = [USER_HOOK] + writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`) + copyFileSync(configPath, backupPath) + + service.remove() + + const backup = readFileSync(backupPath, 'utf8') + expect(backup).toContain('my-own-hook') + expect(backup).not.toContain('orca') + }) + + it('leaves a symlinked backup alone', () => { + const service = new GrokHookService() + expect(service.install().state).toBe('installed') + const target = join(homeDir, 'elsewhere.json') + copyFileSync(configPath, target) + symlinkSync(target, backupPath) + + removeGrokHookBackupEntries(configPath) + + expect(readFileSync(target, 'utf8')).toContain('orca') + }) + + it('does nothing without a backup', () => { + expect(() => removeGrokHookBackupEntries(configPath)).not.toThrow() + }) +}) diff --git a/src/main/grok/grok-hook-backup-cleanup.ts b/src/main/grok/grok-hook-backup-cleanup.ts new file mode 100644 index 00000000000..768d05e0ce7 --- /dev/null +++ b/src/main/grok/grok-hook-backup-cleanup.ts @@ -0,0 +1,67 @@ +import { lstatSync, rmSync, writeFileSync } from 'node:fs' +import { lstat, rm, writeFile } from 'node:fs/promises' +import { readHooksJsonWithRaw, type HooksConfig } from '../agent-hooks/installer-utils' +import { hasErrorCode } from '../daemon/daemon-process-inspection' +import { isOrcaOwnedRemnant, removeManagedGrokHookEntries } from './grok-hook-config-cleanup' +import { readGrokHookConfigSnapshot } from './grok-hook-config-file' +import { getGrokManagedScriptFileName } from './grok-hook-script' + +type BackupAction = { kind: 'delete' } | { kind: 'rewrite'; contents: string } | null + +/** Our writes keep a rolling `.bak` of the hook file, which still names Orca's script after + * removal: delete it when only Orca's entries were in it, otherwise strip just those. */ +function backupAction(config: HooksConfig | null, raw: string | null): BackupAction { + if (!config || raw === null) { + return null + } + const cleanup = removeManagedGrokHookEntries(config, getGrokManagedScriptFileName()) + if (isOrcaOwnedRemnant(cleanup.config)) { + return { kind: 'delete' } + } + return cleanup.removedAny + ? { kind: 'rewrite', contents: `${JSON.stringify(cleanup.config, null, 2)}\n` } + : null +} + +function warnUnlessMissing(error: unknown): void { + if (!hasErrorCode(error, 'ENOENT')) { + console.warn('[grok] could not clean the hook backup:', error) + } +} + +export function removeGrokHookBackupEntries(configPath: string): void { + const backup = `${configPath}.bak` + try { + if (lstatSync(backup).isSymbolicLink()) { + return + } + const snapshot = readHooksJsonWithRaw(backup) + const action = backupAction(snapshot.config, snapshot.raw) + if (action?.kind === 'delete') { + rmSync(backup, { force: true }) + } else if (action?.kind === 'rewrite') { + writeFileSync(backup, action.contents) + } + } catch (error) { + warnUnlessMissing(error) + } +} + +/** The quit path's variant: no synchronous fs calls. */ +export async function removeGrokHookBackupEntriesAsync(configPath: string): Promise { + const backup = `${configPath}.bak` + try { + if ((await lstat(backup)).isSymbolicLink()) { + return + } + const snapshot = await readGrokHookConfigSnapshot(backup) + const action = backupAction(snapshot.config, snapshot.raw) + if (action?.kind === 'delete') { + await rm(backup, { force: true }) + } else if (action?.kind === 'rewrite') { + await writeFile(backup, action.contents) + } + } catch (error) { + warnUnlessMissing(error) + } +} diff --git a/src/main/grok/hook-service.ts b/src/main/grok/hook-service.ts index abe2b6135e3..3f1783c2038 100644 --- a/src/main/grok/hook-service.ts +++ b/src/main/grok/hook-service.ts @@ -11,6 +11,10 @@ import { } from '../agent-hooks/installer-utils' import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' import { isOrcaOwnedRemnant, removeManagedGrokHookEntries } from './grok-hook-config-cleanup' +import { + removeGrokHookBackupEntries, + removeGrokHookBackupEntriesAsync +} from './grok-hook-backup-cleanup' import { buildInstalledGrokConfig, GROK_EVENTS, GROK_TOOL_EVENT_MATCHER } from './grok-hook-config' import { installRemoteGrokHook } from './grok-hook-remote-install' import { @@ -232,6 +236,7 @@ export class GrokHookService { } else { writeHooksJson(configPath, cleanup.config) } + removeGrokHookBackupEntries(configPath) return notInstalledStatus(configPath) } @@ -281,6 +286,9 @@ export class GrokHookService { if (updated && configIsSymlink) { await recordGrokSymlinkCleanup(configPath, serialized) } + if (updated) { + await removeGrokHookBackupEntriesAsync(configPath) + } return updated ? notInstalledStatus(configPath) : notInstalledStatus(configPath, 'Grok hook config changed during cleanup') diff --git a/src/main/startup/wsl-holder-uninstall-preflight.test.ts b/src/main/startup/wsl-holder-uninstall-preflight.test.ts new file mode 100644 index 00000000000..ab60dac8878 --- /dev/null +++ b/src/main/startup/wsl-holder-uninstall-preflight.test.ts @@ -0,0 +1,113 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { exit, stopServers, releaseAll } = vi.hoisted(() => ({ + exit: vi.fn(), + stopServers: vi.fn(async () => {}), + releaseAll: vi.fn(async (): Promise<{ distro: string; state: string }[]> => []) +})) +vi.mock('electron', () => ({ + app: { exit, getPath: () => 'C:\\Users\\u\\AppData\\Roaming\\orca' } +})) +vi.mock('./windows-app-data-path', () => ({ ensureWindowsAppDataPath: vi.fn() })) +vi.mock('../wsl/wsl-distro-holder', () => ({ createWslDistroHolder: () => ({ releaseAll }) })) +vi.mock('../wsl/wsl-host-uninstall-server-stop', () => ({ + stopWslHostServersForUninstall: stopServers, + wslHostUninstallStopDependencies: () => ({ distros: () => [], listRunning: async () => [] }) +})) + +import type { WslDistroHolder } from '../wsl/wsl-distro-holder' +import type { WslHostUninstallStopDependencies } from '../wsl/wsl-host-uninstall-server-stop' +import { + releaseWslHoldersForUninstall, + runWslHolderUninstallPreflight, + WSL_HOLDER_UNINSTALL_FLAG, + WSL_SERVER_UNINSTALL_FLAG +} from './wsl-holder-uninstall-preflight' + +function holderReleasing(states: { distro: string; state: string }[]): WslDistroHolder { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preflight only calls releaseAll. + return { releaseAll: vi.fn(async () => states) } as unknown as WslDistroHolder +} + +const SERVERS: WslHostUninstallStopDependencies = { + distros: () => ['Ubuntu'], + listRunning: async () => ['Ubuntu'], + stop: vi.fn() +} + +describe('releaseWslHoldersForUninstall', () => { + afterEach(() => { + stopServers.mockReset() + stopServers.mockImplementation(async () => {}) + }) + + it('stops the running hosts’ servers after releasing the holders', async () => { + const order: string[] = [] + const holder = holderReleasing([]) + vi.mocked(holder.releaseAll).mockImplementation(async () => { + order.push('release-holders') + return [{ distro: 'Ubuntu', state: 'exited' }] + }) + stopServers.mockImplementation(async () => { + order.push('stop-servers') + }) + + await expect(releaseWslHoldersForUninstall(holder, SERVERS)).resolves.toBe(0) + expect(order).toEqual(['release-holders', 'stop-servers']) + }) + + it('keeps the holder verdict as the exit code whatever the server stop does', async () => { + stopServers.mockRejectedValue(new Error('records unreadable')) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await expect( + releaseWslHoldersForUninstall( + holderReleasing([{ distro: 'U', state: 'unverifiable' }]), + SERVERS + ) + ).resolves.toBe(1) + }) +}) + +describe('runWslHolderUninstallPreflight', () => { + afterEach(() => { + stopServers.mockClear() + exit.mockClear() + }) + + it('leaves the servers alone unless the uninstaller says this is the last install', async () => { + expect(runWslHolderUninstallPreflight(['Orca.exe', WSL_HOLDER_UNINSTALL_FLAG])).toBe(true) + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0)) + + expect(stopServers).not.toHaveBeenCalled() + }) + + it('stops the servers when the uninstaller adds the server flag', async () => { + runWslHolderUninstallPreflight([ + 'Orca.exe', + WSL_HOLDER_UNINSTALL_FLAG, + WSL_SERVER_UNINSTALL_FLAG + ]) + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0)) + + expect(stopServers).toHaveBeenCalledTimes(1) + }) + + it('is only passed by the NSIS hook when no other install shares this userData', () => { + const hook = readFileSync( + join(__dirname, '..', '..', '..', 'config', 'nsis', 'orca-installer-hooks.nsh'), + 'utf8' + ) + const lines = hook.split('\n') + const withFlag = lines.findIndex((line) => line.includes(WSL_SERVER_UNINSTALL_FLAG)) + + expect(withFlag).toBeGreaterThan(0) + expect(lines.filter((line) => line.includes(WSL_SERVER_UNINSTALL_FLAG))).toHaveLength(1) + expect(lines[withFlag - 1].trim()).toBe('${if} $2 == "none"') + expect(lines.slice(withFlag - 6, withFlag - 1).join('\n')).toContain( + '!insertmacro ORCA_OTHER_INSTALL_STATE $2' + ) + }) +}) diff --git a/src/main/startup/wsl-holder-uninstall-preflight.ts b/src/main/startup/wsl-holder-uninstall-preflight.ts index a1148db9d36..150a64b3e0e 100644 --- a/src/main/startup/wsl-holder-uninstall-preflight.ts +++ b/src/main/startup/wsl-holder-uninstall-preflight.ts @@ -1,15 +1,27 @@ import { app } from 'electron' import { createWslDistroHolder, type WslDistroHolder } from '../wsl/wsl-distro-holder' import { ensureWindowsAppDataPath } from './windows-app-data-path' +import { + stopWslHostServersForUninstall, + wslHostUninstallStopDependencies, + type WslHostUninstallStopDependencies +} from '../wsl/wsl-host-uninstall-server-stop' /** The NSIS uninstaller's flag (config/nsis/orca-installer-hooks.nsh); keep the two in sync. */ export const WSL_HOLDER_UNINSTALL_FLAG = '--orca-uninstall-release-wsl-holders' +/** Added only by the last install for this user: its HKCU/HKLM twin shares these hosts' servers. */ +export const WSL_SERVER_UNINSTALL_FLAG = '--orca-uninstall-stop-wsl-servers' -// Uninstall must finish even if the process table never answers. -const UNINSTALL_RELEASE_TIMEOUT_MS = 30_000 +// Uninstall must finish even if the process table or a distro never answers. +const UNINSTALL_RELEASE_TIMEOUT_MS = 45_000 -/** Exit code 0 only when every recorded holder is proven gone; unverifiable ones are left running. */ -export async function releaseWslHoldersForUninstall(holder: WslDistroHolder): Promise { +/** Exit code 0 only when every recorded holder is proven gone; unverifiable ones are left running. + * Then each running host's server is stopped too, best effort, so its distro can stop. */ +export async function releaseWslHoldersForUninstall( + holder: WslDistroHolder, + servers?: WslHostUninstallStopDependencies +): Promise { + let code: number try { const released = await holder.releaseAll({ forUninstall: true }) for (const { distro, state } of released) { @@ -17,14 +29,21 @@ export async function releaseWslHoldersForUninstall(holder: WslDistroHolder): Pr console.warn(`[wsl] uninstall left the ${distro} holder ${state}`) } } - return released.every(({ state }) => state === 'exited') ? 0 : 1 + code = released.every(({ state }) => state === 'exited') ? 0 : 1 } catch (error) { console.warn('[wsl] uninstall could not release WSL distro holders:', error) - return 1 + code = 1 } + if (servers) { + // Never changes the exit code: a server left running costs memory, not a broken uninstall. + await stopWslHostServersForUninstall(servers).catch((error: unknown) => { + console.warn('[wsl] uninstall could not stop WSL host servers:', error) + }) + } + return code } -/** Uninstall only: ends the `wsl.exe` holders this profile recorded, so its distros idle-stop. */ +/** Uninstall only: ends the holders this profile recorded and its hosts' servers, so distros can stop. */ export function runWslHolderUninstallPreflight(argv: readonly string[] = process.argv): boolean { if (!argv.includes(WSL_HOLDER_UNINSTALL_FLAG)) { return false @@ -32,18 +51,22 @@ export function runWslHolderUninstallPreflight(argv: readonly string[] = process // Armed first: nothing below may leave the uninstaller waiting on an error box. const timeout = setTimeout(() => app.exit(1), UNINSTALL_RELEASE_TIMEOUT_MS) let holder: WslDistroHolder + let servers: WslHostUninstallStopDependencies | undefined try { process.env.ORCA_BACKGROUND_LAUNCH = '1' // The same userData the app records holders under; before any other preflight step. ensureWindowsAppDataPath(app) holder = createWslDistroHolder({ userDataPath: app.getPath('userData') }) + servers = argv.includes(WSL_SERVER_UNINSTALL_FLAG) + ? wslHostUninstallStopDependencies(app.getPath('userData')) + : undefined } catch (error) { console.warn('[wsl] uninstall could not start releasing WSL distro holders:', error) clearTimeout(timeout) app.exit(1) return true } - void releaseWslHoldersForUninstall(holder).then((code) => { + void releaseWslHoldersForUninstall(holder, servers).then((code) => { clearTimeout(timeout) app.exit(code) }) diff --git a/src/main/wsl/wsl-host-uninstall-server-stop.test.ts b/src/main/wsl/wsl-host-uninstall-server-stop.test.ts new file mode 100644 index 00000000000..6e8e0272bf5 --- /dev/null +++ b/src/main/wsl/wsl-host-uninstall-server-stop.test.ts @@ -0,0 +1,180 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { WslHostServerStop } from '../../shared/wsl-host-types' + +const { execCommand, decommission, dispose } = vi.hoisted(() => ({ + execCommand: vi.fn<(conn: unknown, command: string) => Promise>(), + decommission: vi.fn(), + dispose: vi.fn() +})) +vi.mock('../ssh/remote-exec/remote-exec-command', () => ({ execCommand })) +vi.mock('./wsl-orcad-host-transport', () => ({ + createWslOrcadHostTransport: () => ({ dispose }) +})) +vi.mock('./wsl-host-server-stop', async (importOriginal) => ({ + ...(await importOriginal>()), + decommissionWslHostOrcad: () => decommission +})) + +import { + stopWslHostServerFromGuest, + stopWslHostServersForUninstall, + type WslHostUninstallStopDependencies +} from './wsl-host-uninstall-server-stop' + +function deps( + overrides: Partial = {} +): WslHostUninstallStopDependencies { + return { + distros: () => ['Ubuntu', 'Debian'], + listRunning: async () => ['ubuntu'], + stop: vi.fn(async (): Promise => ({ stopped: true })), + ...overrides + } +} + +describe('stopWslHostServersForUninstall', () => { + afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() + }) + + it('stops only hosts whose distro is confirmed running, and never boots a stopped one', async () => { + const d = deps() + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await stopWslHostServersForUninstall(d) + + expect(d.stop).toHaveBeenCalledTimes(1) + expect(d.stop).toHaveBeenCalledWith('Ubuntu', expect.any(AbortSignal)) + }) + + it('stops nothing when the running list is unreadable', async () => { + const d = deps({ listRunning: async () => null }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await stopWslHostServersForUninstall(d) + + expect(d.stop).not.toHaveBeenCalled() + }) + + it('reads nothing when there are no WSL hosts', async () => { + const listRunning = vi.fn(async () => []) + await stopWslHostServersForUninstall(deps({ distros: () => [], listRunning })) + + expect(listRunning).not.toHaveBeenCalled() + }) + + it('stops a distro recorded twice once', async () => { + const d = deps({ distros: () => ['Ubuntu', 'ubuntu'] }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await stopWslHostServersForUninstall(d) + + expect(d.stop).toHaveBeenCalledTimes(1) + }) + + it('gives up on a distro that never answers, aborting its work', async () => { + vi.useFakeTimers() + let signal: AbortSignal | undefined + const d = deps({ + timeoutMs: 1_000, + stop: (_distro, s) => { + signal = s + return new Promise(() => {}) + } + }) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + + const done = stopWslHostServersForUninstall(d) + await vi.advanceTimersByTimeAsync(1_000) + await done + + expect(signal?.aborted).toBe(true) + expect(log).toHaveBeenCalledWith( + '[wsl] uninstall could not stop the Ubuntu host server: timed out after 1000 ms' + ) + }) + + it('logs a failed stop instead of throwing', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const d = deps({ + stop: async () => { + throw new Error('wsl.exe failed') + } + }) + + await expect(stopWslHostServersForUninstall(d)).resolves.toBeUndefined() + expect(log).toHaveBeenCalledWith( + '[wsl] uninstall could not stop the Ubuntu host server: wsl.exe failed' + ) + }) +}) + +describe('stopWslHostServerFromGuest', () => { + afterEach(() => { + execCommand.mockReset() + decommission.mockReset() + dispose.mockReset() + }) + + it("closes every terminal through the server's CLI, then decommissions the proven instance", async () => { + const open = new Set(['term_a', 'term_b']) + execCommand.mockImplementation(async (_conn, command) => { + if (command.includes('terminal list')) { + const terminals = [...open].map((handle) => ({ handle, worktreeId: 'w' })) + return `login banner\n${JSON.stringify({ result: { terminals } })}` + } + if (command.includes('terminal close')) { + open.delete(/--terminal '([^']+)'/.exec(command)?.[1] ?? '') + return JSON.stringify({ result: {} }) + } + if (command.includes(' status ')) { + return JSON.stringify({ result: { runtime: { runtimeId: 'rt-1' } } }) + } + throw new Error(`unexpected ${command}`) + }) + decommission.mockResolvedValue({ + outcome: 'decommissioned', + version: '1', + retirement: 'retired' + }) + + const result = await stopWslHostServerFromGuest('Ubuntu', new AbortController().signal) + + expect(result).toEqual({ stopped: true }) + expect(open.size).toBe(0) + expect(decommission).toHaveBeenCalledWith( + { liveSessions: 0, startedSinceActivation: null, daemonProtocolVersion: null }, + 'rt-1' + ) + expect( + execCommand.mock.calls.every(([, c]) => c.startsWith('"$HOME/.orca/cli/bin/orca" ')) + ).toBe(true) + // Remove host lists up to 1000; the CLI's default of 200 would leave terminals open. + const lists = execCommand.mock.calls + .map(([, c]) => c) + .filter((c) => c.includes('terminal list')) + expect(lists.length).toBeGreaterThan(0) + expect(lists.every((c) => c.includes('terminal list --limit 1000 --json'))).toBe(true) + expect(dispose).toHaveBeenCalled() + }) + + it('reports the server it could not prove stopped', async () => { + execCommand.mockImplementation(async (_conn, command) => + command.includes('status') + ? JSON.stringify({ result: { runtime: { runtimeId: 'rt-1' } } }) + : JSON.stringify({ result: { terminals: [] } }) + ) + decommission.mockResolvedValue({ + outcome: 'refused', + verdict: 'unverifiable', + code: 'x', + reason: 'not the active instance' + }) + + const result = await stopWslHostServerFromGuest('Ubuntu', new AbortController().signal) + + expect(result).toMatchObject({ stopped: false, verdict: 'unverifiable' }) + expect(dispose).toHaveBeenCalled() + }) +}) diff --git a/src/main/wsl/wsl-host-uninstall-server-stop.ts b/src/main/wsl/wsl-host-uninstall-server-stop.ts new file mode 100644 index 00000000000..73e6911f67b --- /dev/null +++ b/src/main/wsl/wsl-host-uninstall-server-stop.ts @@ -0,0 +1,168 @@ +// Uninstall only: end each running WSL host's terminals and orcad, so its distro can stop. +// No paired connection exists by then, so the server's own CLI inside the distro stands in for RPC. +import { z } from 'zod' +import { errorMessage } from '../../shared/error-message' +import type { WslHostServerStop } from '../../shared/wsl-host-types' +import { execCommand } from '../ssh/remote-exec/remote-exec-command' +import { listRunningWslDistrosAsync } from '../wsl' +import { readWslHostRecordsQuietly } from './wsl-host-connection-record' +import { + decommissionWslHostOrcad, + stopWslHostServer, + type WslHostTerminalLeftover +} from './wsl-host-server-stop' +import { defaultWslOrcadEnvironmentId } from './wsl-orcad-deploy' +import { createWslOrcadHostTransport } from './wsl-orcad-host-transport' +import type { WslOrcadHostTarget } from './wsl-orcad-host-target' + +/** Per distro; the uninstaller waits on the whole preflight. */ +export const WSL_HOST_UNINSTALL_STOP_TIMEOUT_MS = 15_000 + +/** orcad writes this launcher into its data root; older slots without a CLI have none. */ +const GUEST_CLI = '"$HOME/.orca/cli/bin/orca"' + +const TerminalListSchema = z.object({ + result: z.object({ + terminals: z.array(z.object({ handle: z.string().min(1), worktreeId: z.string() })) + }) +}) +const StatusSchema = z.object({ + result: z.object({ runtime: z.object({ runtimeId: z.string().min(1).optional() }) }) +}) + +/** The CLI's JSON envelope, past anything a login shell printed first. */ +function parseCliJson(stdout: string): unknown { + const start = stdout.indexOf('{') + if (start === -1) { + throw new Error(`no JSON from the server's CLI: ${stdout.slice(0, 200)}`) + } + return JSON.parse(stdout.slice(start)) +} + +/** Remove host's teardown, driven through the in-distro CLI; the census is the CLI's terminal list. */ +export async function stopWslHostServerFromGuest( + distro: string, + signal: AbortSignal +): Promise { + const target: WslOrcadHostTarget = { + kind: 'wsl', + id: defaultWslOrcadEnvironmentId(distro), + distro, + label: distro + } + const transport = createWslOrcadHostTransport({ target, commandLoops: false }) + const cli = async (args: string): Promise => + parseCliJson(await execCommand(transport, `${GUEST_CLI} ${args} --json`, { signal })) + const listTerminals = async () => + TerminalListSchema.parse(await cli('terminal list --limit 1000')).result.terminals + try { + return await stopWslHostServer({ + // Peers can't be asked without a paired connection; uninstall ends this host for everyone. + peerDesktops: async () => ({ kind: 'none' }), + endTerminals: async () => { + const leftovers: WslHostTerminalLeftover[] = [] + for (const terminal of await listTerminals()) { + try { + await cli(`terminal close --terminal '${terminal.handle.replace(/'/g, '')}'`) + } catch (error) { + leftovers.push({ ...terminal, reason: errorMessage(error) }) + } + } + return leftovers + }, + census: async () => { + const live = await listTerminals().catch(() => null) + return { + liveSessions: live ? live.length : null, + startedSinceActivation: null, + daemonProtocolVersion: null + } + }, + servingRuntimeId: async () => + StatusSchema.parse(await cli('status')).result.runtime.runtimeId ?? null, + closeBridge: async () => {}, + decommission: decommissionWslHostOrcad(target, transport) + }) + } finally { + transport.dispose() + } +} + +export type WslHostUninstallStopDependencies = { + distros: () => string[] + /** Confirmed running list; null when it can't be read. Must never start a distro. */ + listRunning: () => Promise + stop: (distro: string, signal: AbortSignal) => Promise + timeoutMs?: number +} + +export function wslHostUninstallStopDependencies( + userDataPath: string +): WslHostUninstallStopDependencies { + return { + distros: () => readWslHostRecordsQuietly(userDataPath).map((record) => record.distro), + listRunning: () => listRunningWslDistrosAsync({ requireConfirmed: true }).catch(() => null), + stop: stopWslHostServerFromGuest + } +} + +async function stopWithin( + distro: string, + deps: WslHostUninstallStopDependencies +): Promise { + const controller = new AbortController() + const timeoutMs = deps.timeoutMs ?? WSL_HOST_UNINSTALL_STOP_TIMEOUT_MS + let timer: NodeJS.Timeout | undefined + const timedOut = new Promise((resolve) => { + timer = setTimeout(() => { + controller.abort() + resolve({ + stopped: false, + verdict: 'unverifiable', + reason: `timed out after ${timeoutMs} ms` + }) + }, timeoutMs) + }) + try { + return await Promise.race([ + deps.stop(distro, controller.signal).catch((error: unknown): WslHostServerStop => ({ + stopped: false, + verdict: 'unverifiable', + reason: errorMessage(error) + })), + timedOut + ]) + } finally { + clearTimeout(timer) + } +} + +/** Best effort and bounded: a stopped or unconfirmed distro is skipped, never booted. */ +export async function stopWslHostServersForUninstall( + deps: WslHostUninstallStopDependencies +): Promise { + const distros = [...new Map(deps.distros().map((d) => [d.toLowerCase(), d])).values()] + if (distros.length === 0) { + return + } + const running = await deps.listRunning() + if (running === null) { + console.warn('[wsl] uninstall left WSL host servers alone: the running list was unreadable') + return + } + const isRunning = new Set(running.map((d) => d.toLowerCase())) + await Promise.all( + distros.map(async (distro) => { + if (!isRunning.has(distro.toLowerCase())) { + console.log(`[wsl] uninstall skipped the ${distro} host server: the distro is stopped`) + return + } + const result = await stopWithin(distro, deps) + console.log( + result.stopped + ? `[wsl] uninstall stopped the ${distro} host server` + : `[wsl] uninstall could not stop the ${distro} host server: ${result.reason}` + ) + }) + ) +}