Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

fix(windows): start the WSL holder outside Orca's jobs so a crash doesn't take it down (#36178)

Neil393166063991
diff --git a/config/scripts/ensure-native-runtime.mjs b/config/scripts/ensure-native-runtime.mjs
index b03bd244952..59922b1156c 100644
--- a/config/scripts/ensure-native-runtime.mjs
+++ b/config/scripts/ensure-native-runtime.mjs
@@ -297,7 +297,7 @@ function loadNativeModule(moduleName) {
if (moduleName === '@orca/windows-security') {
const security = require(moduleName)
// currentUserSid loads the addon; a stale build that still loads lacks the newest export.
- if (!security.currentUserSid() || !security.hasNativeExport('spawnDetachedIsolated')) {
+ if (!security.currentUserSid() || !security.hasNativeExport('isolatedSpawnBreaksAwayFromJob')) {
throw new Error('stale build without the newest export; rebuild it')
}
return
diff --git a/config/scripts/rebuild-native-deps.mjs b/config/scripts/rebuild-native-deps.mjs
index 3c4a0752bf9..391cdd9ca5a 100644
--- a/config/scripts/rebuild-native-deps.mjs
+++ b/config/scripts/rebuild-native-deps.mjs
@@ -578,7 +578,7 @@ function loadNativeModule(moduleName) {
}
if (moduleName === '@orca/windows-security') {
const security = projectRequire(moduleName)
- if (!security.currentUserSid() || !security.hasNativeExport('spawnDetachedIsolated')) throw new Error('stale build without the newest export; rebuild it')
+ if (!security.currentUserSid() || !security.hasNativeExport('isolatedSpawnBreaksAwayFromJob')) throw new Error('stale build without the newest export; rebuild it')
return
}
if (moduleName === 'node-pty') {
diff --git a/native/windows-security/index.d.ts b/native/windows-security/index.d.ts
index e3b492b17ff..3fee353d9a1 100644
--- a/native/windows-security/index.d.ts
+++ b/native/windows-security/index.d.ts
@@ -74,12 +74,19 @@ export type StdHandleInheritanceFailure = { stream: 'stdin' | 'stdout' | 'stderr
*/
export declare function clearStdHandleInheritance(): StdHandleInheritanceFailure[]
-/** `exitWatchError` is the Win32 code when the exit can't be observed; the child still runs. */
-export type IsolatedSpawnResult = { pid: number; exitWatchError: number | null }
+/**
+ * `exitWatchError` is the Win32 code when the exit can't be observed; the child still runs.
+ * `breakawayDenied`: a job this process is in forbids breakaway, so the child stays in it.
+ */
+export type IsolatedSpawnResult = {
+ pid: number
+ exitWatchError: number | null
+ breakawayDenied: boolean
+}
/**
- * Starts `file` detached and hidden, inheriting only a NUL handle for its stdio, so none of this
- * process's other inheritable handles reach it. `commandLine` is the full, already quoted line
+ * Starts `file` detached, hidden and outside this process's jobs where they allow it, inheriting
+ * only a NUL handle for its stdio, so none of this process's other inheritable handles reach it. `commandLine` is the full, already quoted line
* (argv[0] included); an empty `cwd` keeps ours; `environmentBlock` is `K=V\0…\0\0`. `onExit` gets the exit code and never
* keeps the event loop alive. Throws an Error naming the failed Win32 call.
*/
@@ -93,3 +100,6 @@ export declare function spawnDetachedIsolated(
/** Whether the resolved binary exports `name`; loads it, but calls nothing else. */
export declare function hasNativeExport(name: string): boolean
+
+/** True on builds whose isolated spawn requests job breakaway; older binaries lack the export. */
+export declare function isolatedSpawnBreaksAwayFromJob(): boolean
diff --git a/native/windows-security/index.js b/native/windows-security/index.js
index ca849d405d2..e2b64a022e8 100644
--- a/native/windows-security/index.js
+++ b/native/windows-security/index.js
@@ -26,6 +26,7 @@ module.exports = {
clearStdHandleInheritance: () => getAddon().clearStdHandleInheritance(),
spawnDetachedIsolated: (file, commandLine, cwd, environmentBlock, onExit) =>
getAddon().spawnDetachedIsolated(file, commandLine, cwd, environmentBlock, onExit),
+ isolatedSpawnBreaksAwayFromJob: () => getAddon().isolatedSpawnBreaksAwayFromJob(),
// Reads the binding this package resolved, so a build probe tests the binary the app loads.
hasNativeExport: (name) => typeof getAddon()[name] === 'function'
}
diff --git a/native/windows-security/src/addon.cc b/native/windows-security/src/addon.cc
index 922bdff1c27..67a5bad40f4 100644
--- a/native/windows-security/src/addon.cc
+++ b/native/windows-security/src/addon.cc
@@ -564,6 +564,8 @@ Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set("grantAccessAsync", Napi::Function::New(env, GrantAccessAsync));
exports.Set("clearStdHandleInheritance", Napi::Function::New(env, ClearStdHandleInheritance));
exports.Set("spawnDetachedIsolated", Napi::Function::New(env, SpawnDetachedIsolated));
+ exports.Set("isolatedSpawnBreaksAwayFromJob",
+ Napi::Function::New(env, IsolatedSpawnBreaksAwayFromJob));
return exports;
}
diff --git a/native/windows-security/src/isolated-spawn.cc b/native/windows-security/src/isolated-spawn.cc
index 787f5ec23c7..5ac5496c173 100644
--- a/native/windows-security/src/isolated-spawn.cc
+++ b/native/windows-security/src/isolated-spawn.cc
@@ -1,6 +1,8 @@
// libuv spawns with bInheritHandles=TRUE and no handle list, so every inheritable handle in Orca
// reaches a long-lived child. This spawn lists exactly one NUL handle, used for all three stdio.
-// Flags mirror libuv's detached spawn; no PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, no breakaway.
+// Flags mirror libuv's detached spawn plus CREATE_BREAKAWAY_FROM_JOB: a holder must outlive a
+// kill-on-close job Orca was launched into (an OpenSSH session's, a terminal's). A job that forbids
+// breakaway fails that with ERROR_ACCESS_DENIED; the spawn then retries inside it and reports so.
#include "isolated-spawn.h"
@@ -93,12 +95,23 @@ Napi::Value SpawnDetachedIsolated(const Napi::CallbackInfo& info) {
PROCESS_INFORMATION created{};
const DWORD flags = CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP |
EXTENDED_STARTUPINFO_PRESENT;
- BOOL ok = CreateProcessW(reinterpret_cast<LPCWSTR>(file.c_str()),
- reinterpret_cast<LPWSTR>(commandLine.data()), nullptr, nullptr, TRUE,
- flags, environment.data(),
- cwd.empty() ? nullptr : reinterpret_cast<LPCWSTR>(cwd.c_str()),
- &startup.StartupInfo, &created);
- DWORD error = GetLastError();
+ DWORD error = ERROR_SUCCESS;
+ auto create = [&](DWORD extra) {
+ // CreateProcessW may write to the command line buffer, so each attempt gets a fresh copy.
+ std::u16string line = commandLine;
+ BOOL created_ok = CreateProcessW(
+ reinterpret_cast<LPCWSTR>(file.c_str()), reinterpret_cast<LPWSTR>(line.data()), nullptr,
+ nullptr, TRUE, flags | extra, environment.data(),
+ cwd.empty() ? nullptr : reinterpret_cast<LPCWSTR>(cwd.c_str()), &startup.StartupInfo,
+ &created);
+ error = created_ok ? ERROR_SUCCESS : GetLastError();
+ return created_ok;
+ };
+ BOOL ok = create(CREATE_BREAKAWAY_FROM_JOB);
+ const bool breakawayDenied = !ok && error == ERROR_ACCESS_DENIED;
+ if (breakawayDenied) {
+ ok = create(0);
+ }
DeleteProcThreadAttributeList(attributes);
CloseHandle(nul);
if (!ok) {
@@ -108,6 +121,7 @@ Napi::Value SpawnDetachedIsolated(const Napi::CallbackInfo& info) {
auto result = Napi::Object::New(env);
result.Set("pid", static_cast<double>(created.dwProcessId));
+ result.Set("breakawayDenied", Napi::Boolean::New(env, breakawayDenied));
auto* watch = new ExitWatch{created.hProcess};
watch->onExit = Napi::ThreadSafeFunction::New(env, info[4].As<Napi::Function>(),
"orcaIsolatedSpawnExit", 0, 1);
@@ -124,3 +138,8 @@ Napi::Value SpawnDetachedIsolated(const Napi::CallbackInfo& info) {
result.Set("exitWatchError", env.Null());
return result;
}
+
+// The newest export: build probes read it to reject an addon built before breakaway.
+Napi::Value IsolatedSpawnBreaksAwayFromJob(const Napi::CallbackInfo& info) {
+ return Napi::Boolean::New(info.Env(), true);
+}
diff --git a/native/windows-security/src/isolated-spawn.h b/native/windows-security/src/isolated-spawn.h
index a3a3ef05357..476abb31d27 100644
--- a/native/windows-security/src/isolated-spawn.h
+++ b/native/windows-security/src/isolated-spawn.h
@@ -3,3 +3,4 @@
#include <napi.h>
Napi::Value SpawnDetachedIsolated(const Napi::CallbackInfo& info);
+Napi::Value IsolatedSpawnBreaksAwayFromJob(const Napi::CallbackInfo& info);
diff --git a/src/main/startup/windows-install-dir-package-acl-grant.test.ts b/src/main/startup/windows-install-dir-package-acl-grant.test.ts
index c0739339fa1..580418fdda7 100644
--- a/src/main/startup/windows-install-dir-package-acl-grant.test.ts
+++ b/src/main/startup/windows-install-dir-package-acl-grant.test.ts
@@ -47,6 +47,7 @@ function installFakeAddon(
grantAccess: unexpected,
clearStdHandleInheritance: unexpected,
spawnDetachedIsolated: unexpected,
+ isolatedSpawnBreaksAwayFromJob: unexpected,
hasNativeExport: unexpected,
grantAccessAsync: async (path, sid, accessMask, options) => {
calls.push({ path: plain(path), sid, accessMask, options })
@@ -200,6 +201,7 @@ describe('install-dir package grant passes', () => {
grantAccess: unexpected,
clearStdHandleInheritance: unexpected,
spawnDetachedIsolated: unexpected,
+ isolatedSpawnBreaksAwayFromJob: unexpected,
hasNativeExport: unexpected,
grantAccessAsync: async (path) => {
seen.push(path)
diff --git a/src/main/startup/windows-isolated-spawner.test.ts b/src/main/startup/windows-isolated-spawner.test.ts
index 3b8b8b9f995..5fc8468e1a5 100644
--- a/src/main/startup/windows-isolated-spawner.test.ts
+++ b/src/main/startup/windows-isolated-spawner.test.ts
@@ -32,14 +32,29 @@ describe('installWindowsIsolatedSpawner', () => {
})
it('installs the native spawner when the binary exports it', () => {
+ const { security, spawnDetachedIsolated } = addonWith(() => true)
+ loadWindowsSecurity.mockReturnValue(security)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ installWindowsIsolatedSpawner('win32')
+
+ expect(setIsolatedSpawner).toHaveBeenCalledWith(spawnDetachedIsolated)
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('still installs a pre-breakaway spawner for its handle isolation, and logs it', () => {
const { security, spawnDetachedIsolated } = addonWith(
(name) => name === 'spawnDetachedIsolated'
)
loadWindowsSecurity.mockReturnValue(security)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
installWindowsIsolatedSpawner('win32')
expect(setIsolatedSpawner).toHaveBeenCalledWith(spawnDetachedIsolated)
+ expect(warn).toHaveBeenCalledWith(
+ '[startup] detached spawns stay in our jobs; the addon build predates breakaway'
+ )
})
it('keeps libuv and logs when the binary is stale', () => {
diff --git a/src/main/startup/windows-isolated-spawner.ts b/src/main/startup/windows-isolated-spawner.ts
index ef9f189361e..6b33f017468 100644
--- a/src/main/startup/windows-isolated-spawner.ts
+++ b/src/main/startup/windows-isolated-spawner.ts
@@ -19,6 +19,10 @@ export function installWindowsIsolatedSpawner(platform: NodeJS.Platform = proces
console.warn('[startup] detached spawns inherit handles; the addon build is stale')
return
}
+ if (!security.addon.hasNativeExport('isolatedSpawnBreaksAwayFromJob')) {
+ // Still isolates handles; only a kill-on-close job Orca runs in can take the holder down.
+ console.warn('[startup] detached spawns stay in our jobs; the addon build predates breakaway')
+ }
setIsolatedSpawner(security.addon.spawnDetachedIsolated)
} catch (error) {
console.warn('[startup] detached spawns inherit handles:', error)
diff --git a/src/main/startup/windows-isolated-spawner.win32.test.ts b/src/main/startup/windows-isolated-spawner.win32.test.ts
index 9cd2f2a9cf0..943af84ea0b 100644
--- a/src/main/startup/windows-isolated-spawner.win32.test.ts
+++ b/src/main/startup/windows-isolated-spawner.win32.test.ts
@@ -1,10 +1,10 @@
import { build } from 'esbuild'
import { once } from 'node:events'
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { spawnProcess } from '@orca/process-host'
import {
setIsolatedSpawner,
@@ -154,3 +154,82 @@ describeOnWindows('isolated detached spawn against real Windows processes', () =
expect(run.holderAliveAtClose).toBe(false)
}, 60_000)
})
+
+// Joins a kill-on-close job (strict: one that forbids breakaway), starts a sleeper through the
+// addon, reports, then exits so the job closes with it, as when Orca is killed in such a job.
+const JOB_HELPER = `
+const [conptyUtils, addonPath, mode, resultFile] = process.argv.slice(2)
+const conpty = require(conptyUtils).loadNativeModule('conpty').module
+const joined = mode === 'strict' ? conpty.assignCurrentProcessToStrictJob() : conpty.assignCurrentProcessToJob()
+const env = Object.entries(process.env).map(([k, v]) => k + '=' + v + '\\0').join('') + '\\0'
+const line = '"' + process.execPath + '" -e "setTimeout(() => {}, 60000)"'
+const spawned = require(addonPath).spawnDetachedIsolated(process.execPath, line, '', env, () => {})
+// Control: libuv's detached spawn never breaks away, so the job's close always takes it.
+const controlPid = require('child_process').spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)'], { detached: true, stdio: 'ignore' }).pid
+require('fs').writeFileSync(resultFile, JSON.stringify({ joined, controlPid, ...spawned }))
+process.exit(0)
+`
+
+describeOnWindows('isolated detached spawn inside a kill-on-close job', () => {
+ let jobRoot = ''
+
+ beforeAll(() => {
+ jobRoot = mkdtempSync(join(tmpdir(), 'orca-isolated-spawn-job-'))
+ })
+
+ afterAll(() => {
+ rmSync(jobRoot, { recursive: true, force: true })
+ })
+
+ async function spawnInJob(mode: 'breakaway-ok' | 'strict') {
+ const helper = join(jobRoot, 'job-helper.cjs')
+ writeFileSync(helper, JOB_HELPER)
+ const conptyUtils = createRequire(import.meta.url).resolve('node-pty/lib/utils')
+ const resultFile = join(jobRoot, `${mode}.json`)
+ const run = spawnProcess({
+ program: process.execPath,
+ args: [helper, conptyUtils, ADDON, mode, resultFile],
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
+ stdio: ['ignore', 'pipe', 'pipe']
+ })
+ let output = ''
+ run.stderr?.on('data', (chunk) => (output += chunk))
+ const [code] = await once(run, 'close', { signal: AbortSignal.timeout(30_000) })
+ expect(code, output).toBe(0)
+ const result: {
+ joined: boolean
+ controlPid: number
+ pid: number
+ breakawayDenied: boolean
+ } = JSON.parse(readFileSync(resultFile, 'utf8'))
+ return result
+ }
+
+ // A cold Node start on a loaded Windows runner can exceed the 5 s default.
+ it('the child breaks away and outlives the job closing with its parent', async (context) => {
+ const result = await spawnInJob('breakaway-ok')
+ if (!result.joined || result.breakawayDenied) {
+ // The runner's own job refuses nesting or breakaway; SSH sessions and terminals permit it.
+ context.skip()
+ }
+ try {
+ // The control dying proves the job closed; only then does the child's survival mean anything.
+ await vi.waitFor(() => expect(isAlive(result.controlPid)).toBe(false), { timeout: 10_000 })
+ expect(isAlive(result.pid)).toBe(true)
+ } finally {
+ if (isAlive(result.pid)) {
+ process.kill(result.pid)
+ }
+ }
+ }, 40_000)
+
+ // A cold Node start on a loaded Windows runner can exceed the 5 s default.
+ it('a job that forbids breakaway gets the child instead, and says so', async (context) => {
+ const result = await spawnInJob('strict')
+ if (!result.joined) {
+ context.skip()
+ }
+ expect(result.breakawayDenied).toBe(true)
+ await vi.waitFor(() => expect(isAlive(result.pid)).toBe(false), { timeout: 10_000 })
+ }, 40_000)
+})
diff --git a/src/main/wsl/wsl-distro-holder.ts b/src/main/wsl/wsl-distro-holder.ts
index 9f0e0888a89..00722b6a6d0 100644
--- a/src/main/wsl/wsl-distro-holder.ts
+++ b/src/main/wsl/wsl-distro-holder.ts
@@ -42,7 +42,8 @@ const RELEASE_EXIT_TIMEOUT_MS = 5_000
export const WSL_HOLDER_UNVERIFIABLE_REPLACE_AFTER_MS = 5 * 60_000
function spawnDetachedHolder(distro: string): WslDistroHolderChild {
- // Detached holders outlive Orca's libuv kill-on-close job; explicit taskkill /T still reaches descendants.
+ // Detached and broken away from Orca's jobs where they allow it, so a holder outlives a crash of
+ // Orca even inside a kill-on-close job (an OpenSSH session's); taskkill /T still reaches it.
// Inheriting none of Orca's handles keeps a launcher's pipe or a DevTools socket from outliving Orca.
return spawnDetachedWithoutInheritance({
program: resolveWslExecutablePath(),
diff --git a/src/packages/process-host/src/isolated-detached-spawn.test.ts b/src/packages/process-host/src/isolated-detached-spawn.test.ts
index acee016744f..07fb417bf57 100644
--- a/src/packages/process-host/src/isolated-detached-spawn.test.ts
+++ b/src/packages/process-host/src/isolated-detached-spawn.test.ts
@@ -160,6 +160,24 @@ describe('spawnDetachedWithoutInheritance', () => {
expect(killed.kill()).toBe(false)
})
+ it('logs a child whose breakaway from our job was denied, and still starts it', async () => {
+ onPlatform('win32')
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ setIsolatedSpawner(() => ({ pid: 7, exitWatchError: null, breakawayDenied: true }))
+
+ const child = spawnDetachedWithoutInheritance({ program: 'C:\\wsl.exe' })
+ await once(child, 'spawn')
+
+ expect(child.pid).toBe(7)
+ expect(warn).toHaveBeenCalledWith(
+ "[process-host] pid 7 could not break away from this process's job"
+ )
+ warn.mockClear()
+ setIsolatedSpawner(() => ({ pid: 8, exitWatchError: null, breakawayDenied: false }))
+ spawnDetachedWithoutInheritance({ program: 'C:\\wsl.exe' })
+ expect(warn).not.toHaveBeenCalled()
+ })
+
it('reports a native spawn failure as an error event, like libuv', async () => {
onPlatform('win32')
setIsolatedSpawner(() => {
diff --git a/src/packages/process-host/src/isolated-detached-spawn.ts b/src/packages/process-host/src/isolated-detached-spawn.ts
index df3ad6843a8..93a2ed1ae52 100644
--- a/src/packages/process-host/src/isolated-detached-spawn.ts
+++ b/src/packages/process-host/src/isolated-detached-spawn.ts
@@ -12,7 +12,7 @@ export type IsolatedSpawner = (
cwd: string,
environmentBlock: string,
onExit: (code: number) => void
-) => { pid: number; exitWatchError: number | null }
+) => { pid: number; exitWatchError: number | null; breakawayDenied?: boolean }
export type DetachedChild = EventEmitter & {
readonly pid?: number
@@ -143,6 +143,10 @@ export function spawnDetachedWithoutInheritance(spec: DetachedSpec): DetachedChi
if (startedAt !== null) {
notifySpawnObserver(resolved.file, resolved.args, performance.now() - startedAt)
}
+ if (spawned.breakawayDenied) {
+ // The child stays in a job this process is in, and dies if that job is closed with it.
+ console.warn(`[process-host] pid ${pid} could not break away from this process's job`)
+ }
if (spawned.exitWatchError !== null) {
console.warn(
`[process-host] pid ${pid} exit is unobservable; Win32 error ${spawned.exitWatchError}`
diff --git a/src/shared/windows-security-addon.test-fixture.ts b/src/shared/windows-security-addon.test-fixture.ts
index 9367a1211d0..151a20bd998 100644
--- a/src/shared/windows-security-addon.test-fixture.ts
+++ b/src/shared/windows-security-addon.test-fixture.ts
@@ -128,6 +128,7 @@ export function createFakeWindowsSecurity(): FakeWindowsSecurity {
spawnDetachedIsolated: () => {
throw new Error('spawnDetachedIsolated is not faked')
},
+ isolatedSpawnBreaksAwayFromJob: () => true,
hasNativeExport: () => true,
getDaclAces: (addonPath) => {
const path = record('get', addonPath)
diff --git a/src/shared/windows-security-addon.ts b/src/shared/windows-security-addon.ts
index f7a0b294e25..278e0a64382 100644
--- a/src/shared/windows-security-addon.ts
+++ b/src/shared/windows-security-addon.ts
@@ -118,6 +118,7 @@ function prepare(raw: WindowsSecurityAddon): WindowsSecurity {
clearStdHandleInheritance: () => raw.clearStdHandleInheritance(),
spawnDetachedIsolated: (file, commandLine, cwd, environmentBlock, onExit) =>
raw.spawnDetachedIsolated(file, commandLine, cwd, environmentBlock, onExit),
+ isolatedSpawnBreaksAwayFromJob: () => raw.isolatedSpawnBreaksAwayFromJob(),
hasNativeExport: (name) => raw.hasNativeExport(name)
}
}