feat(daemon): relocate the Windows daemon host out of the install dir to survive updates
Phase 1 of Windows terminal update-survival. On win32 packaged, the terminal daemon is now forked from a copy of the Electron runtime staged under userData/daemon-host/<version> (run as node, ELECTRON_RUN_AS_NODE), so its process image and all loaded modules live outside the install dir the NSIS updater deletes and force-closes. Keeping the Electron binary (not stock node.exe) means run-as-node behavior is byte-identical — no console flashing, asar-correct — which the reverted #7473 attempt broke. Proven on CI by tools/daemon-relocation-spike: a copied Orca.exe boots the daemon, drives a real ConPTY session, and holds zero loaded-module handles into the install dir, on the minimal file set. - daemon-host-relocation.ts: materialize (atomic staging + marker-last + fail-open), version-keyed dir, PID-pinned GC of old versions. - daemon-init.ts: fork from the relocated exe/entry when available; byte-identical in-dir fork otherwise (non-win32, dev, or fail-open). - Adoption-neutral: protocol/pipe unchanged; a new app still adopts an old in-dir daemon. - win-update-survival-e2e.yml: builds a branch installer and runs the harness with --expect survival to prove sessions survive an update.
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
name: Windows Update-Survival E2E (branch build)
|
||||
|
||||
# Why: proves the Phase 1 daemon-host relocation actually makes terminal
|
||||
# sessions SURVIVE a Windows update. Builds an (unsigned) installer FROM THIS
|
||||
# BRANCH, then runs the win-update-e2e harness with --expect survival: install,
|
||||
# open a terminal, silently update over it, relaunch, and assert the daemon PID
|
||||
# is unchanged and the pre-update terminal is still interactive with no console
|
||||
# flashing. Runs from the feature branch via push (workflow_dispatch only works
|
||||
# on the default branch); main is never touched. A CI runner is the only safe
|
||||
# place to install/update — see the relocation post-mortem.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- Jinwoo-H/windows-update-survival
|
||||
paths:
|
||||
- 'src/main/daemon/**'
|
||||
- 'src/main/pty/**'
|
||||
- 'tools/win-update-e2e/**'
|
||||
- 'config/electron-builder.config.cjs'
|
||||
- '.github/workflows/win-update-survival-e2e.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
expect:
|
||||
description: Expected outcome profile
|
||||
required: true
|
||||
type: choice
|
||||
default: survival
|
||||
options:
|
||||
- survival
|
||||
- cold-restore
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: win-update-survival-e2e-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
survival:
|
||||
name: survival (branch build over itself)
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 50
|
||||
env:
|
||||
EXPECT: ${{ inputs.expect || 'survival' }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
run_install: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# Why: cache the built installer keyed on the inputs that affect it, so a
|
||||
# harness-only edit skips the ~20 min electron-builder build. The daemon
|
||||
# relocation code lives under src/, so changing it correctly rebuilds.
|
||||
- name: Cache branch installer
|
||||
id: cache-installer
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: dist/orca-windows-setup.exe
|
||||
key: branch-installer-${{ hashFiles('src/**', 'config/**', 'package.json', 'pnpm-lock.yaml') }}
|
||||
|
||||
- name: Build Windows installer (unsigned)
|
||||
if: steps.cache-installer.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
node config/scripts/ensure-native-runtime.mjs --runtime=electron
|
||||
pnpm run build:desktop
|
||||
pnpm exec electron-builder --config config/electron-builder.config.cjs --win --publish never
|
||||
|
||||
# Why: install the branch build, open a terminal, update the SAME build
|
||||
# over it, and assert the relocated daemon survives. Same build on both
|
||||
# sides isolates the survival mechanism (NSIS kill sweep + userData daemon
|
||||
# + adoption) from cross-version staleness policy. No --install-dir: a CI
|
||||
# runner has no real Orca to protect.
|
||||
- name: Run survival harness
|
||||
id: harness
|
||||
shell: pwsh
|
||||
env:
|
||||
ORCA_E2E_DIAG_DIR: artifacts/diag
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force artifacts | Out-Null
|
||||
$exe = "dist/orca-windows-setup.exe"
|
||||
if (-not (Test-Path $exe)) { throw "Installer not found at $exe" }
|
||||
$log = "artifacts/survival-output.log"
|
||||
node tools/win-update-e2e/run.mjs `
|
||||
--from "$exe" `
|
||||
--to "$exe" `
|
||||
--expect "$env:EXPECT" `
|
||||
--soak-seconds 60 2>&1 | Tee-Object -FilePath $log
|
||||
exit $LASTEXITCODE
|
||||
|
||||
- name: Upload survival output
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: win-update-survival-output
|
||||
path: |
|
||||
artifacts/survival-output.log
|
||||
artifacts/diag/**
|
||||
retention-days: 7
|
||||
if-no-files-found: warn
|
||||
@@ -0,0 +1,226 @@
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Mutable Electron app stub, hoisted so the vi.mock factory closes over it.
|
||||
const { electronApp } = vi.hoisted(() => ({
|
||||
electronApp: {
|
||||
isPackaged: true,
|
||||
userDataPath: '',
|
||||
version: '9.9.9',
|
||||
getPath: (): string => electronApp.userDataPath,
|
||||
getVersion: (): string => electronApp.version
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({ app: electronApp }))
|
||||
|
||||
import {
|
||||
buildDaemonHostManifest,
|
||||
collectPinnedDaemonVersions,
|
||||
getRelocatedDaemonHost,
|
||||
materializeRelocatedDaemonHost,
|
||||
pruneOldDaemonHosts
|
||||
} from './daemon-host-relocation'
|
||||
|
||||
let tempDir: string
|
||||
let installDir: string
|
||||
let userDataDir: string
|
||||
const originalPlatform = process.platform
|
||||
const originalExecPath = process.execPath
|
||||
const originalResourcesPath = process.resourcesPath
|
||||
|
||||
function setProcessProp(key: string, value: unknown): void {
|
||||
Object.defineProperty(process, key, { value, configurable: true, writable: true })
|
||||
}
|
||||
|
||||
// Build a win-unpacked fixture: exe + blobs + DLLs at root, daemon bundle and
|
||||
// node-pty under resources, mirroring the packaged layout the copy expects.
|
||||
function buildInstallFixture(root: string): void {
|
||||
mkdirSync(root, { recursive: true })
|
||||
writeFileSync(join(root, 'Orca.exe'), 'exe-bytes')
|
||||
for (const name of ['icudtl.dat', 'snapshot_blob.bin', 'v8_context_snapshot.bin']) {
|
||||
writeFileSync(join(root, name), name)
|
||||
}
|
||||
writeFileSync(join(root, 'ffmpeg.dll'), 'dll')
|
||||
writeFileSync(join(root, 'libEGL.dll'), 'dll')
|
||||
const mainDir = join(root, 'resources', 'app.asar.unpacked', 'out', 'main')
|
||||
mkdirSync(join(mainDir, 'chunks'), { recursive: true })
|
||||
writeFileSync(join(mainDir, 'daemon-entry.js'), 'entry')
|
||||
writeFileSync(join(mainDir, 'chunks', 'a.js'), 'chunk')
|
||||
writeFileSync(join(root, 'resources', 'app.asar.unpacked', 'out', 'package.json'), '{}')
|
||||
const nativeDir = join(root, 'resources', 'node_modules', 'node-pty', 'build', 'Release')
|
||||
mkdirSync(nativeDir, { recursive: true })
|
||||
writeFileSync(join(nativeDir, 'conpty.node'), 'native')
|
||||
mkdirSync(join(nativeDir, 'conpty'), { recursive: true })
|
||||
writeFileSync(join(nativeDir, 'conpty', 'conpty.dll'), 'conpty-dll')
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(os.tmpdir(), 'daemon-host-relocation-'))
|
||||
installDir = join(tempDir, 'app')
|
||||
userDataDir = join(tempDir, 'userData')
|
||||
mkdirSync(userDataDir, { recursive: true })
|
||||
buildInstallFixture(installDir)
|
||||
electronApp.isPackaged = true
|
||||
electronApp.userDataPath = userDataDir
|
||||
electronApp.version = '9.9.9'
|
||||
setProcessProp('platform', 'win32')
|
||||
setProcessProp('execPath', join(installDir, 'Orca.exe'))
|
||||
setProcessProp('resourcesPath', join(installDir, 'resources'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
setProcessProp('platform', originalPlatform)
|
||||
setProcessProp('execPath', originalExecPath)
|
||||
setProcessProp('resourcesPath', originalResourcesPath)
|
||||
try {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
} catch {
|
||||
// Best-effort
|
||||
}
|
||||
})
|
||||
|
||||
describe('buildDaemonHostManifest', () => {
|
||||
it('mirrors the win-unpacked layout: root exe/blobs/dlls, resources tree verbatim', () => {
|
||||
const appDir = 'C:\\app'
|
||||
const ops = buildDaemonHostManifest(
|
||||
{
|
||||
appDir,
|
||||
execPath: 'C:\\app\\Orca.exe',
|
||||
resourcesPath: 'C:\\app\\resources',
|
||||
entrySourcePath: 'C:\\app\\resources\\app.asar.unpacked\\out\\main\\daemon-entry.js',
|
||||
entryRelPath: 'resources/app.asar.unpacked/out/main/daemon-entry.js'
|
||||
},
|
||||
['ffmpeg.dll', 'libEGL.dll']
|
||||
)
|
||||
const byDest = new Map(ops.map((op) => [op.destRel, op]))
|
||||
expect(byDest.get('Orca.exe')?.kind).toBe('file')
|
||||
expect(byDest.has('icudtl.dat')).toBe(true)
|
||||
expect(byDest.has('ffmpeg.dll')).toBe(true)
|
||||
expect(byDest.has('libEGL.dll')).toBe(true)
|
||||
// Daemon bundle + node-pty mirrored at their real resources-relative paths.
|
||||
expect(byDest.get('resources/app.asar.unpacked/out/main/daemon-entry.js')?.kind).toBe('file')
|
||||
expect(byDest.get('resources/app.asar.unpacked/out/main/chunks')?.kind).toBe('dir')
|
||||
expect(byDest.get('resources/node_modules/node-pty')?.kind).toBe('dir')
|
||||
})
|
||||
})
|
||||
|
||||
describe('materializeRelocatedDaemonHost', () => {
|
||||
it('copies the tree, writes the marker, and returns mirrored fork paths', () => {
|
||||
const result = materializeRelocatedDaemonHost()
|
||||
expect(result).not.toBeNull()
|
||||
const dest = join(userDataDir, 'daemon-host', '9.9.9')
|
||||
expect(result?.execPath).toBe(join(dest, 'Orca.exe'))
|
||||
expect(result?.entryPath).toBe(
|
||||
join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'daemon-entry.js')
|
||||
)
|
||||
expect(existsSync(result!.execPath)).toBe(true)
|
||||
expect(existsSync(result!.entryPath)).toBe(true)
|
||||
// node-pty native + conpty runtime copied at the require-resolvable path.
|
||||
expect(
|
||||
existsSync(
|
||||
join(dest, 'resources', 'node_modules', 'node-pty', 'build', 'Release', 'conpty.node')
|
||||
)
|
||||
).toBe(true)
|
||||
expect(
|
||||
existsSync(join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'chunks', 'a.js'))
|
||||
).toBe(true)
|
||||
// Marker records the version + entry rel path, written into the published dir.
|
||||
const marker = JSON.parse(readFileSync(join(dest, '.materialized.json'), 'utf8'))
|
||||
expect(marker.version).toBe('9.9.9')
|
||||
expect(marker.entryRelPath).toBe('resources/app.asar.unpacked/out/main/daemon-entry.js')
|
||||
})
|
||||
|
||||
it('is idempotent: a valid marker short-circuits without recopying', () => {
|
||||
materializeRelocatedDaemonHost()
|
||||
const dest = join(userDataDir, 'daemon-host', '9.9.9')
|
||||
// A recopy would rm the dest; a sentinel inside it must survive the 2nd call.
|
||||
const sentinel = join(dest, 'sentinel.txt')
|
||||
writeFileSync(sentinel, 'keep')
|
||||
const result = materializeRelocatedDaemonHost()
|
||||
expect(result?.execPath).toBe(join(dest, 'Orca.exe'))
|
||||
expect(existsSync(sentinel)).toBe(true)
|
||||
})
|
||||
|
||||
it('fails open on a missing required input, leaving no dest or staging dir', () => {
|
||||
rmSync(join(installDir, 'resources', 'node_modules', 'node-pty'), {
|
||||
recursive: true,
|
||||
force: true
|
||||
})
|
||||
const result = materializeRelocatedDaemonHost()
|
||||
expect(result).toBeNull()
|
||||
const hostRoot = join(userDataDir, 'daemon-host')
|
||||
// Neither the published dest nor any leftover staging dir remains.
|
||||
const remaining = existsSync(hostRoot) ? readdirSync(hostRoot) : []
|
||||
expect(remaining).toEqual([])
|
||||
})
|
||||
|
||||
it('returns null off win32', () => {
|
||||
setProcessProp('platform', 'darwin')
|
||||
expect(materializeRelocatedDaemonHost()).toBeNull()
|
||||
expect(existsSync(join(userDataDir, 'daemon-host'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getRelocatedDaemonHost', () => {
|
||||
it('returns null when the marker version does not match the current version', () => {
|
||||
const dest = join(userDataDir, 'daemon-host', '9.9.9')
|
||||
mkdirSync(dirname(join(dest, 'x')), { recursive: true })
|
||||
writeFileSync(join(dest, 'Orca.exe'), 'exe')
|
||||
mkdirSync(join(dest, 'resources', 'app.asar.unpacked', 'out', 'main'), { recursive: true })
|
||||
writeFileSync(
|
||||
join(dest, 'resources', 'app.asar.unpacked', 'out', 'main', 'daemon-entry.js'),
|
||||
'e'
|
||||
)
|
||||
writeFileSync(
|
||||
join(dest, '.materialized.json'),
|
||||
JSON.stringify({
|
||||
version: '8.8.8',
|
||||
completedAt: '',
|
||||
entryRelPath: 'resources/app.asar.unpacked/out/main/daemon-entry.js'
|
||||
})
|
||||
)
|
||||
expect(getRelocatedDaemonHost()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('pruneOldDaemonHosts', () => {
|
||||
it('removes unpinned non-current version dirs, keeping current and pinned', () => {
|
||||
const root = join(userDataDir, 'daemon-host')
|
||||
for (const v of ['9.9.9', '1.0.0', '2.0.0']) {
|
||||
mkdirSync(join(root, v), { recursive: true })
|
||||
}
|
||||
pruneOldDaemonHosts(new Set(['2.0.0']))
|
||||
expect(existsSync(join(root, '9.9.9'))).toBe(true)
|
||||
expect(existsSync(join(root, '2.0.0'))).toBe(true)
|
||||
expect(existsSync(join(root, '1.0.0'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('collectPinnedDaemonVersions', () => {
|
||||
it('pins the app version of a live daemon pid file and skips dead ones', () => {
|
||||
const runtimeDir = join(userDataDir, 'daemon')
|
||||
mkdirSync(runtimeDir, { recursive: true })
|
||||
writeFileSync(
|
||||
join(runtimeDir, 'daemon-v4.pid'),
|
||||
JSON.stringify({ pid: process.pid, startedAtMs: null, appVersion: '7.0.0' })
|
||||
)
|
||||
writeFileSync(
|
||||
join(runtimeDir, 'daemon-v3.pid'),
|
||||
JSON.stringify({ pid: 2147483646, startedAtMs: null, appVersion: '6.0.0' })
|
||||
)
|
||||
const pinned = collectPinnedDaemonVersions(runtimeDir)
|
||||
expect(pinned.has('7.0.0')).toBe(true)
|
||||
expect(pinned.has('6.0.0')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,351 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { basename, dirname, join, relative, sep } from 'node:path'
|
||||
import { app } from 'electron'
|
||||
import { parseDaemonPidFile, startTimeMatches } from './daemon-health'
|
||||
|
||||
/**
|
||||
* Relocates the terminal daemon's process image out of the app install
|
||||
* directory into userData so it survives Windows auto-updates.
|
||||
*
|
||||
* Why: the daemon is forked as plain Node via ELECTRON_RUN_AS_NODE, so its
|
||||
* image is the install-dir Orca.exe and its loaded modules (node-pty native,
|
||||
* ConPTY runtime) map from the install dir. On update, electron-builder's NSIS
|
||||
* installer deletes the old install and force-closes every process whose image
|
||||
* lives under it — killing the daemon and every live terminal it owns. Copying
|
||||
* the daemon's whole file closure to a version-keyed userData dir and forking
|
||||
* from that copy takes its image + loaded modules out of the installer's reach.
|
||||
*
|
||||
* The copy keeps the ELECTRON binary run as node (not stock node.exe): a copied
|
||||
* Orca.exe is byte-identical, so run-as-node behavior — no console flashing,
|
||||
* asar-correct — matches the in-dir fork exactly. The win-unpacked layout is
|
||||
* mirrored verbatim so require('node-pty') and node-pty's native loader resolve
|
||||
* the relocated tree identically to the packaged app.
|
||||
*
|
||||
* Fail-open everywhere: any failure returns null and the caller forks the
|
||||
* install-dir host — the pre-relocation behavior, byte-identical off win32.
|
||||
*/
|
||||
|
||||
export type RelocatedDaemonHost = {
|
||||
/** The copied Orca.exe to fork the daemon from (run as node). */
|
||||
execPath: string
|
||||
/** The copied daemon-entry.js, mirrored under the relocated resources tree. */
|
||||
entryPath: string
|
||||
}
|
||||
|
||||
const HOST_SUBDIR = 'daemon-host'
|
||||
const MARKER_NAME = '.materialized.json'
|
||||
|
||||
// V8 snapshots + ICU data the Electron bootstrap reads even under
|
||||
// ELECTRON_RUN_AS_NODE; siblings of Orca.exe in win-unpacked.
|
||||
const RUNTIME_DATA_FILES = ['icudtl.dat', 'snapshot_blob.bin', 'v8_context_snapshot.bin']
|
||||
|
||||
type CopyOp = {
|
||||
sourcePath: string
|
||||
/** Destination path relative to the host root, posix-separated. */
|
||||
destRel: string
|
||||
kind: 'file' | 'dir'
|
||||
/** When true, a missing source is skipped rather than failing the copy. */
|
||||
optional?: boolean
|
||||
}
|
||||
|
||||
type DaemonHostSources = {
|
||||
appDir: string
|
||||
execPath: string
|
||||
resourcesPath: string
|
||||
entrySourcePath: string
|
||||
entryRelPath: string
|
||||
}
|
||||
|
||||
type MaterializeMarker = {
|
||||
version: string
|
||||
completedAt: string
|
||||
entryRelPath: string
|
||||
}
|
||||
|
||||
function toPosixRelative(fromDir: string, absPath: string): string {
|
||||
return relative(fromDir, absPath).split(sep).join('/')
|
||||
}
|
||||
|
||||
function destPath(root: string, destRel: string): string {
|
||||
return join(root, ...destRel.split('/'))
|
||||
}
|
||||
|
||||
// Mirror getDaemonEntryPath()'s resolution order (unpacked root first, then
|
||||
// out/main) so the copied entry is the exact file the in-dir fork would run.
|
||||
function resolveEntrySourcePath(resourcesPath: string): string {
|
||||
const unpackedRoot = join(resourcesPath, 'app.asar.unpacked')
|
||||
const direct = join(unpackedRoot, 'daemon-entry.js')
|
||||
if (existsSync(direct)) {
|
||||
return direct
|
||||
}
|
||||
return join(unpackedRoot, 'out', 'main', 'daemon-entry.js')
|
||||
}
|
||||
|
||||
// Discover the relocation inputs from the live packaged process, or null when
|
||||
// relocation does not apply (non-win32, dev, or missing resourcesPath).
|
||||
function collectDaemonHostSources(): DaemonHostSources | null {
|
||||
if (process.platform !== 'win32' || !app.isPackaged) {
|
||||
return null
|
||||
}
|
||||
const resourcesPath = process.resourcesPath
|
||||
if (typeof resourcesPath !== 'string' || resourcesPath.length === 0) {
|
||||
return null
|
||||
}
|
||||
const execPath = process.execPath
|
||||
const appDir = dirname(execPath)
|
||||
const entrySourcePath = resolveEntrySourcePath(resourcesPath)
|
||||
return {
|
||||
appDir,
|
||||
execPath,
|
||||
resourcesPath,
|
||||
entrySourcePath,
|
||||
entryRelPath: toPosixRelative(appDir, entrySourcePath)
|
||||
}
|
||||
}
|
||||
|
||||
function listTopLevelDlls(appDir: string): string[] {
|
||||
try {
|
||||
return readdirSync(appDir).filter((name) => name.toLowerCase().endsWith('.dll'))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ordered copy plan. Every destRel mirrors the source's win-unpacked
|
||||
* relative path so require() and node-pty's native loader resolve the mirror
|
||||
* identically to the packaged app. Pure over its inputs so tests can assert the
|
||||
* layout without a real build.
|
||||
*/
|
||||
export function buildDaemonHostManifest(
|
||||
sources: DaemonHostSources,
|
||||
topLevelDlls: string[]
|
||||
): CopyOp[] {
|
||||
const { appDir, execPath, resourcesPath, entrySourcePath, entryRelPath } = sources
|
||||
const ops: CopyOp[] = []
|
||||
|
||||
// Electron host binary + runtime data blobs at the dest root.
|
||||
ops.push({ sourcePath: execPath, destRel: basename(execPath), kind: 'file' })
|
||||
for (const name of RUNTIME_DATA_FILES) {
|
||||
ops.push({ sourcePath: join(appDir, name), destRel: name, kind: 'file', optional: true })
|
||||
}
|
||||
// All top-level runtime DLLs: exe size dominates the copy, so carry them all
|
||||
// rather than guess which the run-as-node host loads.
|
||||
for (const name of topLevelDlls) {
|
||||
ops.push({ sourcePath: join(appDir, name), destRel: name, kind: 'file' })
|
||||
}
|
||||
|
||||
// Daemon bundle: entry + its sibling chunks/ + the unpacked out/package.json
|
||||
// (CJS/ESM loader resolution), mirrored verbatim.
|
||||
ops.push({ sourcePath: entrySourcePath, destRel: entryRelPath, kind: 'file' })
|
||||
const chunksDir = join(dirname(entrySourcePath), 'chunks')
|
||||
ops.push({
|
||||
sourcePath: chunksDir,
|
||||
destRel: toPosixRelative(appDir, chunksDir),
|
||||
kind: 'dir',
|
||||
optional: true
|
||||
})
|
||||
const pkgJson = join(resourcesPath, 'app.asar.unpacked', 'out', 'package.json')
|
||||
ops.push({
|
||||
sourcePath: pkgJson,
|
||||
destRel: toPosixRelative(appDir, pkgJson),
|
||||
kind: 'file',
|
||||
optional: true
|
||||
})
|
||||
|
||||
// node-pty package tree (native conpty.node + conpty/ runtime dir). It is a
|
||||
// sibling of app.asar.unpacked; require('node-pty') resolves it by walking up
|
||||
// from the mirrored daemon-entry dir to resources/node_modules.
|
||||
const nodePtyDir = join(resourcesPath, 'node_modules', 'node-pty')
|
||||
ops.push({ sourcePath: nodePtyDir, destRel: toPosixRelative(appDir, nodePtyDir), kind: 'dir' })
|
||||
|
||||
return ops
|
||||
}
|
||||
|
||||
function executeManifest(ops: CopyOp[], stagingRoot: string): void {
|
||||
for (const op of ops) {
|
||||
if (!existsSync(op.sourcePath)) {
|
||||
if (op.optional) {
|
||||
continue
|
||||
}
|
||||
throw new Error(`daemon-host relocation: missing required input ${op.sourcePath}`)
|
||||
}
|
||||
const dest = destPath(stagingRoot, op.destRel)
|
||||
mkdirSync(dirname(dest), { recursive: true })
|
||||
// Dereference symlinks so the copy holds no link back into the install dir.
|
||||
cpSync(op.sourcePath, dest, { recursive: op.kind === 'dir', dereference: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function readMarker(dir: string): MaterializeMarker | null {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
readFileSync(join(dir, MARKER_NAME), 'utf8')
|
||||
) as Partial<MaterializeMarker>
|
||||
if (typeof parsed.version === 'string' && typeof parsed.entryRelPath === 'string') {
|
||||
return {
|
||||
version: parsed.version,
|
||||
completedAt: typeof parsed.completedAt === 'string' ? parsed.completedAt : '',
|
||||
entryRelPath: parsed.entryRelPath
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Missing/corrupt marker — treat as not materialized.
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function hostRootDir(): string {
|
||||
return join(app.getPath('userData'), HOST_SUBDIR)
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap idempotency check: the relocated host for the current version, or null.
|
||||
* Valid only when the marker matches this version AND the exe + entry exist, so
|
||||
* a partial or stale copy never reports ready.
|
||||
*/
|
||||
export function getRelocatedDaemonHost(): RelocatedDaemonHost | null {
|
||||
const sources = collectDaemonHostSources()
|
||||
if (!sources) {
|
||||
return null
|
||||
}
|
||||
const version = app.getVersion()
|
||||
const dest = join(hostRootDir(), version)
|
||||
const marker = readMarker(dest)
|
||||
if (!marker || marker.version !== version) {
|
||||
return null
|
||||
}
|
||||
const execPath = join(dest, basename(sources.execPath))
|
||||
const entryPath = destPath(dest, marker.entryRelPath)
|
||||
if (!existsSync(execPath) || !existsSync(entryPath)) {
|
||||
return null
|
||||
}
|
||||
return { execPath, entryPath }
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the current version's daemon host is materialized under
|
||||
* userData/daemon-host/<version>, returning its fork paths or null (fail-open).
|
||||
* Idempotent: a valid marker for this version short-circuits without recopying.
|
||||
* The copy stages into a temp sibling and is published by atomic rename, so a
|
||||
* crash mid-copy never leaves a half-populated dest.
|
||||
*/
|
||||
export function materializeRelocatedDaemonHost(): RelocatedDaemonHost | null {
|
||||
const existing = getRelocatedDaemonHost()
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
const sources = collectDaemonHostSources()
|
||||
if (!sources) {
|
||||
return null
|
||||
}
|
||||
const version = app.getVersion()
|
||||
const root = hostRootDir()
|
||||
const dest = join(root, version)
|
||||
const staging = join(root, `${version}.staging-${randomBytes(6).toString('hex')}`)
|
||||
try {
|
||||
mkdirSync(root, { recursive: true })
|
||||
rmSync(staging, { recursive: true, force: true })
|
||||
executeManifest(buildDaemonHostManifest(sources, listTopLevelDlls(sources.appDir)), staging)
|
||||
// Marker written LAST: an interrupted copy leaves a marker-less staging dir
|
||||
// that the next launch discards, never a dest the cheap check trusts.
|
||||
const marker: MaterializeMarker = {
|
||||
version,
|
||||
completedAt: new Date().toISOString(),
|
||||
entryRelPath: sources.entryRelPath
|
||||
}
|
||||
writeFileSync(join(staging, MARKER_NAME), JSON.stringify(marker))
|
||||
// Replace any stale/partial dest, then publish the staging dir atomically.
|
||||
rmSync(dest, { recursive: true, force: true })
|
||||
renameSync(staging, dest)
|
||||
} catch {
|
||||
try {
|
||||
rmSync(staging, { recursive: true, force: true })
|
||||
} catch {
|
||||
// Best-effort staging cleanup.
|
||||
}
|
||||
return null
|
||||
}
|
||||
return getRelocatedDaemonHost()
|
||||
}
|
||||
|
||||
function isDaemonPidAlive(pid: number, startedAtMs: number | null): boolean {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return startTimeMatches(pid, startedAtMs)
|
||||
}
|
||||
|
||||
/**
|
||||
* App versions still pinned by a live daemon, read from the daemon-v<N>.pid
|
||||
* files under `runtimeDir`. A surviving daemon runs from its version's host dir,
|
||||
* so its dir must never be reclaimed while the process is alive. On win32 the
|
||||
* start-time check cannot verify, so a matching pid pins conservatively.
|
||||
*/
|
||||
export function collectPinnedDaemonVersions(runtimeDir: string): Set<string> {
|
||||
const pinned = new Set<string>()
|
||||
let entries
|
||||
try {
|
||||
entries = readdirSync(runtimeDir, { withFileTypes: true })
|
||||
} catch {
|
||||
return pinned
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !/^daemon-v\d+\.pid$/.test(entry.name)) {
|
||||
continue
|
||||
}
|
||||
let parsed
|
||||
try {
|
||||
parsed = parseDaemonPidFile(readFileSync(join(runtimeDir, entry.name), 'utf8'))
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
// appVersion null => a pre-relocation daemon forked from the install dir,
|
||||
// which pins no host dir here.
|
||||
if (parsed && parsed.appVersion !== null && isDaemonPidAlive(parsed.pid, parsed.startedAtMs)) {
|
||||
pinned.add(parsed.appVersion)
|
||||
}
|
||||
}
|
||||
return pinned
|
||||
}
|
||||
|
||||
/**
|
||||
* Reclaim daemon-host/<ver> dirs whose ver is neither the current version nor
|
||||
* pinned by a live daemon. Best-effort — never throws; a still-locked or
|
||||
* concurrently-staging dir is simply retried on a future launch.
|
||||
*/
|
||||
export function pruneOldDaemonHosts(pinnedVersions: ReadonlySet<string>): void {
|
||||
if (process.platform !== 'win32' || !app.isPackaged) {
|
||||
return
|
||||
}
|
||||
const version = app.getVersion()
|
||||
const root = hostRootDir()
|
||||
let entries
|
||||
try {
|
||||
entries = readdirSync(root, { withFileTypes: true })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory() || entry.name === version || pinnedVersions.has(entry.name)) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
rmSync(join(root, entry.name), { recursive: true, force: true })
|
||||
} catch {
|
||||
// Still locked or already gone — retry on a future launch.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,11 @@ import {
|
||||
isDaemonStaleForCurrentBundle,
|
||||
killStaleDaemon
|
||||
} from './daemon-health'
|
||||
import {
|
||||
collectPinnedDaemonVersions,
|
||||
materializeRelocatedDaemonHost,
|
||||
pruneOldDaemonHosts
|
||||
} from './daemon-host-relocation'
|
||||
import { DegradedDaemonPtyProvider } from './degraded-daemon-pty-provider'
|
||||
import {
|
||||
getLocalPtyProvider,
|
||||
@@ -273,8 +278,18 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
await killStaleDaemon(runtimeDir, socketPath, tokenPath)
|
||||
|
||||
const userDataPath = app.getPath('userData')
|
||||
// Why: on win32 packaged, fork from a copy of the Electron runtime staged
|
||||
// in userData so the daemon's image + loaded modules escape the install dir
|
||||
// the NSIS updater deletes and force-closes. Staged here (not at app start)
|
||||
// so the one-time copy stays off the first-paint path and is skipped on
|
||||
// launches that adopt a live daemon. Fail-open: null → in-dir host, below.
|
||||
const relocatedHost = materializeRelocatedDaemonHost()
|
||||
// Reclaim old version host dirs no surviving daemon still pins (best-effort).
|
||||
pruneOldDaemonHosts(collectPinnedDaemonVersions(runtimeDir))
|
||||
// Fork the relocated entry when available; otherwise the install-dir entry.
|
||||
const forkEntryPath = relocatedHost ? relocatedHost.entryPath : entryPath
|
||||
const child = fork(
|
||||
entryPath,
|
||||
forkEntryPath,
|
||||
['--socket', socketPath, '--token', tokenPath, ...daemonLogArgs()],
|
||||
{
|
||||
// Why: detached daemons can outlive dev worktrees. Starting from
|
||||
@@ -285,6 +300,10 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher {
|
||||
// open, which would prevent Electron from exiting cleanly.
|
||||
detached: true,
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
||||
// Why: run the relocated Orca.exe copy instead of the install-dir one.
|
||||
// It is byte-identical, so run-as-node behavior is unchanged; only the
|
||||
// image path moves out of the updater's kill zone.
|
||||
...(relocatedHost ? { execPath: relocatedHost.execPath } : {}),
|
||||
// Why: ELECTRON_RUN_AS_NODE makes the forked process run as a plain
|
||||
// Node.js process instead of an Electron renderer/main process. Without
|
||||
// it, Electron's GPU/display initialization can interfere with native
|
||||
|
||||
Reference in New Issue
Block a user