fix(daemon): daemon cannot start in 1.4.129-rc.1 — electron require leaked into daemon-entry chunk (#7844)

This commit is contained in:
Jinwoo Hong
2026-07-08 19:41:09 -04:00
committed by GitHub
parent 4a6d12959f
commit 685418d8e4
6 changed files with 186 additions and 24 deletions
+130
View File
@@ -0,0 +1,130 @@
import { spawnSync } from 'node:child_process'
import { join } from 'node:path'
import type { NormalizedOutputOptions, OutputBundle, OutputChunk, Plugin } from 'rollup'
// Why: v1.4.129-rc.1 shipped a dead terminal daemon because a shared main
// chunk gained `require("electron")` (an import edge added in #7642), and the
// daemon is forked as a plain-Node process where electron cannot be required.
// Nothing in CI executes the built daemon-entry under plain Node, so the leak
// stayed invisible until an adopted old daemon died. This guard fails the
// build when any chunk reachable from a plain-Node fork entry requires
// electron, and smoke-loads daemon-entry under plain Node to prove its module
// graph still resolves.
// Entries executed as plain Node (ELECTRON_RUN_AS_NODE / no electron runtime):
// forked daemon, parcel-watcher and computer sidecars, and the CLI-run
// agent-hooks entry. require("electron") throws MODULE_NOT_FOUND in all of them.
const PLAIN_NODE_ENTRY_NAMES = [
'daemon-entry',
'parcel-watcher-process-entry',
'computer-sidecar',
'agent-hooks/managed-agent-hook-controls'
] as const
const ELECTRON_REQUIRE_RE = /require\(\s*["']electron["']\s*\)/
function collectReachableChunks(
entry: OutputChunk,
byFileName: Map<string, OutputChunk>
): OutputChunk[] {
const seen = new Set<string>()
const reachable: OutputChunk[] = []
const stack = [entry.fileName]
while (stack.length > 0) {
const fileName = stack.pop() as string
if (seen.has(fileName)) {
continue
}
seen.add(fileName)
const chunk = byFileName.get(fileName)
if (!chunk) {
continue
}
reachable.push(chunk)
for (const imported of [...chunk.imports, ...chunk.dynamicImports]) {
stack.push(imported)
}
}
return reachable
}
function assertNoElectronRequire(
entryName: string,
entry: OutputChunk,
byFileName: Map<string, OutputChunk>
): void {
for (const chunk of collectReachableChunks(entry, byFileName)) {
if (ELECTRON_REQUIRE_RE.test(chunk.code)) {
throw new Error(
`[plain-node-entry-guard] "${entryName}" reaches chunk "${chunk.fileName}" that ` +
`requires electron. "${entryName}" runs as a plain-Node process, where ` +
`require("electron") throws MODULE_NOT_FOUND and kills it at startup (the ` +
`v1.4.129-rc.1 daemon outage). Keep electron imports out of its module graph.`
)
}
}
}
// Why: proves the whole daemon-entry graph resolves under plain Node (no
// unresolved requires). require("electron") does not throw in a dev tree with
// node_modules present, so the static scan above — not this smoke — is the
// electron regression guard; this only catches gross load failures.
function smokeLoadDaemonEntry(outputDir: string): void {
const entryPath = join(outputDir, 'daemon-entry.js')
const result = spawnSync(process.execPath, [entryPath], {
encoding: 'utf8',
timeout: 15_000
})
if (result.error) {
throw new Error(
`[plain-node-entry-guard] could not smoke-load daemon-entry.js under plain Node: ` +
`${result.error.message}`
)
}
const stderr = result.stderr ?? ''
if (/Cannot find module|MODULE_NOT_FOUND/.test(stderr)) {
throw new Error(
`[plain-node-entry-guard] daemon-entry.js failed to load under plain Node:\n${stderr}`
)
}
if (!stderr.includes('Usage: daemon-entry')) {
throw new Error(
`[plain-node-entry-guard] daemon-entry.js did not reach argv parsing under plain Node ` +
`(expected the "Usage: daemon-entry" error). stderr:\n${stderr}`
)
}
}
export function createPlainNodeEntryGuardPlugin(): Plugin {
return {
name: 'orca-plain-node-entry-guard',
writeBundle(options: NormalizedOutputOptions, bundle: OutputBundle) {
// Why: skip in `electron-vite dev` watch mode — the smoke would respawn on
// every rebuild, and the guard only needs to gate produced builds.
if (this.meta.watchMode) {
return
}
const chunks = Object.values(bundle).filter(
(item): item is OutputChunk => item.type === 'chunk'
)
const byFileName = new Map(chunks.map((chunk) => [chunk.fileName, chunk]))
const entryByName = new Map<string, OutputChunk>()
for (const chunk of chunks) {
if (chunk.isEntry && chunk.name) {
entryByName.set(chunk.name, chunk)
}
}
for (const entryName of PLAIN_NODE_ENTRY_NAMES) {
const entry = entryByName.get(entryName)
if (entry) {
assertNoElectronRequire(entryName, entry, byFileName)
}
}
if (entryByName.has('daemon-entry') && options.dir) {
smokeLoadDaemonEntry(options.dir)
}
}
}
}
+1
View File
@@ -2,6 +2,7 @@
"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",
"include": [
"../electron.vite.config.*",
"../build-plugins/**/*",
"../src/main/**/*",
"../src/preload/**/*",
"../src/shared/**/*",
+2 -1
View File
@@ -2,6 +2,7 @@ import { resolve } from 'node:path'
import { defineConfig } from 'electron-vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { createPlainNodeEntryGuardPlugin } from './build-plugins/plain-node-entry-guard'
// Why: the telemetry transport is gated by two compile-time constants that
// only the official CI release workflow sets. Contributor / `pnpm dev` /
@@ -191,7 +192,7 @@ export default defineConfig({
'src/main/agent-hooks/managed-agent-hook-controls.ts'
)
},
plugins: [createStartupDiagnosticsBootstrapPlugin()]
plugins: [createStartupDiagnosticsBootstrapPlugin(), createPlainNodeEntryGuardPlugin()]
}
},
// Why: compile-time substitution for the telemetry gate. See the block
+10
View File
@@ -261,6 +261,7 @@ describe('registerPtyHandlers', () => {
const savedOrcaClaudeAgentStatusSettings = process.env.ORCA_CLAUDE_AGENT_STATUS_SETTINGS
const savedProcessPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
const savedDisableMacosLoginShell = process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL
const savedOrcaUserDataPath = process.env.ORCA_USER_DATA_PATH
beforeEach(() => {
// Why: most PTY spawn tests assert POSIX shell behavior; Windows-specific
@@ -333,6 +334,10 @@ describe('registerPtyHandlers', () => {
handlers.delete(channel)
})
getPathMock.mockReturnValue('/tmp/orca-user-data')
// Why: shell-ready wrapper roots resolve from ORCA_USER_DATA_PATH (main
// canonicalizes it to app.getPath('userData') at startup before any spawn);
// mirror that here so ZDOTDIR/wrapper assertions match the mocked userData.
process.env.ORCA_USER_DATA_PATH = '/tmp/orca-user-data'
existsSyncMock.mockReturnValue(true)
statSyncMock.mockReturnValue({ isDirectory: () => true, mode: 0o755 })
readFileSyncMock.mockReturnValue('')
@@ -387,6 +392,11 @@ describe('registerPtyHandlers', () => {
} else {
delete process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL
}
if (savedOrcaUserDataPath !== undefined) {
process.env.ORCA_USER_DATA_PATH = savedOrcaUserDataPath
} else {
delete process.env.ORCA_USER_DATA_PATH
}
if (savedOpenCodeConfigDir !== undefined) {
process.env.OPENCODE_CONFIG_DIR = savedOpenCodeConfigDir
} else {
@@ -14,20 +14,24 @@ import {
writeStartupCommandWhenShellReady
} from './local-pty-shell-ready'
const { getUserDataPathMock } = vi.hoisted(() => ({
getUserDataPathMock: vi.fn<() => string>()
}))
// Why: the wrapper root is resolved from ORCA_USER_DATA_PATH (main
// canonicalizes it at startup; the daemon fork sets it explicitly). This
// module must not import electron because it is bundled into the plain-node
// daemon-entry fork, so tests point the root through the env var rather than
// mocking electron's app.
function setTestUserDataPath(path: string): void {
process.env.ORCA_USER_DATA_PATH = path
}
vi.mock('electron', () => ({
app: {
getPath: (name: string) => {
if (name === 'userData') {
return getUserDataPathMock()
}
throw new Error(`unexpected app.getPath(${name})`)
}
const ORIGINAL_ORCA_USER_DATA_PATH = process.env.ORCA_USER_DATA_PATH
afterEach(() => {
if (ORIGINAL_ORCA_USER_DATA_PATH === undefined) {
delete process.env.ORCA_USER_DATA_PATH
} else {
process.env.ORCA_USER_DATA_PATH = ORIGINAL_ORCA_USER_DATA_PATH
}
}))
})
async function importFreshLocalPtyShellReady(): Promise<typeof LocalPtyShellReadyModule> {
vi.resetModules()
@@ -279,6 +283,23 @@ describe('scanForShellReady', () => {
})
})
describe('shell-ready wrapper root resolution', () => {
// Why: regression guard — the daemon-entry fork runs as plain Node and cannot
// import electron, so the wrapper root must resolve from ORCA_USER_DATA_PATH
// (set by main at startup and by the daemon fork) rather than app.getPath.
it('resolves the wrapper root from ORCA_USER_DATA_PATH', async () => {
const root = mkdtempSync(join(tmpdir(), 'orca-userdata-env-'))
try {
setTestUserDataPath(root)
const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady()
const config = getShellReadyLaunchConfig('/bin/zsh')
expect(config.env.ZDOTDIR).toBe(`${root}/shell-ready/zsh`)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})
const describePosix = process.platform === 'win32' ? describe.skip : describe
const hasBash = process.platform !== 'win32' && spawnSync('bash', ['--version']).status === 0
const itWithBash = hasBash ? it : it.skip
@@ -342,7 +363,7 @@ describePosix('local PTY shell-ready launch config', () => {
previousOrcaOrigZdotdir = process.env.ORCA_ORIG_ZDOTDIR
delete process.env.ORCA_ORIG_ZDOTDIR
userDataPath = mkdtempSync(join(tmpdir(), 'local-pty-shell-ready-test-'))
getUserDataPathMock.mockReturnValue(userDataPath)
setTestUserDataPath(userDataPath)
})
afterEach(() => {
@@ -723,7 +744,7 @@ describePosix('live zsh subprocess tests', () => {
beforeEach(async () => {
testHome = mkdtempSync(join(tmpdir(), 'orca-zsh-test-home-'))
userDataPath = mkdtempSync(join(tmpdir(), 'orca-zsh-test-userdata-'))
getUserDataPathMock.mockReturnValue(userDataPath)
setTestUserDataPath(userDataPath)
})
afterEach(() => {
@@ -957,7 +978,7 @@ export MY_VAR=foo
beforeEach(async () => {
testHome = mkdtempSync(join(tmpdir(), 'orca-zsh-edge-'))
userDataPath = mkdtempSync(join(tmpdir(), 'orca-zsh-userdata-'))
getUserDataPathMock.mockReturnValue(userDataPath)
setTestUserDataPath(userDataPath)
})
afterEach(() => {
@@ -1283,7 +1304,7 @@ export MY_VAR=foo
beforeEach(async () => {
testHome = mkdtempSync(join(tmpdir(), 'orca-term-'))
userDataPath = mkdtempSync(join(tmpdir(), 'orca-term-userdata-'))
getUserDataPathMock.mockReturnValue(userDataPath)
setTestUserDataPath(userDataPath)
})
afterEach(() => {
@@ -1516,7 +1537,7 @@ export MY_VAR=foo
beforeEach(async () => {
testHome = mkdtempSync(join(tmpdir(), 'orca-auto-'))
userDataPath = mkdtempSync(join(tmpdir(), 'orca-auto-userdata-'))
getUserDataPathMock.mockReturnValue(userDataPath)
setTestUserDataPath(userDataPath)
})
afterEach(() => {
+5 -6
View File
@@ -13,7 +13,6 @@
import { tmpdir } from 'node:os'
import { basename, win32 as pathWin32 } from 'node:path'
import { mkdirSync, writeFileSync, chmodSync, existsSync } from 'node:fs'
import { app } from 'electron'
import type * as pty from 'node-pty'
import {
encodePowerShellCommand,
@@ -50,11 +49,11 @@ export type ShellReadySignal = {
// ── Shell wrapper files ─────────────────────────────────────────────
function getShellReadyWrapperRoot(): string {
// Why: this instance's userData must win over an inherited
// ORCA_USER_DATA_PATH (Orca launched from another Orca's terminal), so the
// wrapper writer root always matches the root buildPtyHostEnv hands to
// WSL children.
const userDataPath = app?.getPath?.('userData') ?? process.env.ORCA_USER_DATA_PATH ?? tmpdir()
// Why: bundled into daemon-entry.js (a plain-node fork with no electron
// require), so this must not import electron. Main canonicalizes
// ORCA_USER_DATA_PATH to its own userData at startup (configureOrcaUserDataPathEnv)
// and the daemon fork sets it explicitly, so the env value matches this root.
const userDataPath = process.env.ORCA_USER_DATA_PATH ?? tmpdir()
return `${userDataPath}/shell-ready`
}