Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions config/tsconfig.cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@
"../src/main/openclaude/hook-service.ts",
"../src/main/rolling-file-backup.ts",
"../src/main/startup/hydrate-shell-path.ts",
// Why: serve-electron-flag-parity.test.ts checks the Electron-side serve argv rewrite against this
// project's serve spec; the module has no imports, so listing it pulls in nothing else.
"../src/main/startup/serve-mode-argv.ts",
"../src/main/runtime/runtime-metadata.ts",
"../src/main/win32-utils.ts"
],
Expand Down
1 change: 1 addition & 0 deletions config/tsconfig.tc.web.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"../src/main/wsl-distro-retry.ts",
"../src/main/wsl.ts",
"../src/main/startup/serve-desktop-activation.ts",
"../src/main/startup/serve-mode-argv.ts",
"../src/main/startup/single-instance-lock.ts",
"../src/main/startup/startup-diagnostics.ts",
"../src/main/window/focus-existing-window.ts",
Expand Down
79 changes: 79 additions & 0 deletions src/cli/serve-electron-flag-parity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { normalizeServeModeArgv } from '../main/startup/serve-mode-argv'
import { BOOLEAN_FLAGS, GLOBAL_FLAGS } from './args'
import { SERVE_COMMAND_SPECS } from './specs/serve'

// Why this test lives under src/cli: the Electron rewrite duplicates the CLI's serve flag list because
// the main tsconfig cannot import the CLI project, so the parity check has to run from the CLI side.
// It fails when `orca serve` grows a flag that a direct `<binary> serve …` launch would silently drop (#12677).

// Global flags with no `--serve-*` counterpart:
// - help: a help launch is refused outright, not translated (see serve-mode-argv's HELP_FLAGS).
// - pairing-code / environment: nothing in src/main reads them, so they ride through untouched.
const UNTRANSLATED_GLOBAL_FLAGS = new Set(['help', 'pairing-code', 'environment'])

const serveSpec = SERVE_COMMAND_SPECS.find((spec) => spec.path.join(' ') === 'serve')
const translatedFlags = [...new Set(serveSpec?.allowedFlags ?? [])].filter(
(flag) => !UNTRANSLATED_GLOBAL_FLAGS.has(flag)
)

describe('serve flag parity between the CLI spec and the Electron argv rewrite', () => {
it('has a serve spec to compare against', () => {
expect(translatedFlags.length).toBeGreaterThan(0)
})

it.each(translatedFlags)('rewrites CLI-form --%s into the --serve-* form', (flag) => {
const takesValue = !BOOLEAN_FLAGS.has(flag)
const argv = takesValue
? ['/AppRun', 'serve', `--${flag}`, 'value']
: ['/AppRun', 'serve', `--${flag}`]
const expected = takesValue
? ['/AppRun', '--serve', `--serve-${flag}`, 'value']
: ['/AppRun', '--serve', `--serve-${flag}`]

expect(normalizeServeModeArgv(argv)).toEqual(expected)
if (takesValue) {
// The equals form is the other shape `orca serve` accepts, and getServeOptions only reads the next token.
expect(normalizeServeModeArgv(['/AppRun', 'serve', `--${flag}=value`])).toEqual(expected)
} else {
// A boolean with an attached value is not a truthy assertion: the CLI reads these as
// `flags.get(name) === true`, so `--no-pairing=false` must not disable pairing here either.
// (`--json` is the one flag the CLI reads with `.has()`; erring toward the literal value is
// the safe direction and only changes output format.)
expect(normalizeServeModeArgv(['/AppRun', 'serve', `--${flag}=false`])).toEqual([
'/AppRun',
'--serve',
`--${flag}=false`
])
}
// Idempotent: `orca serve` spawns the app already in this shape, and the rewrite runs over it too.
expect(normalizeServeModeArgv(expected)).toEqual(expected)
})

it('emits the same --serve-* names the CLI spawns with and the main process reads', () => {
// Why source text: serveOrcaApp spawns a real process and getServeOptions is not exported, so
// both ends of the contract are only readable statically. Without this leg the rewrite could
// emit a name nothing reads and every behavioural assertion above would still pass.
const launchSource = readFileSync(join(process.cwd(), 'src/cli/runtime/launch.ts'), 'utf8')
const mainSource = readFileSync(join(process.cwd(), 'src/main/index.ts'), 'utf8')
const start = mainSource.indexOf('function getServeOptions(')
// Why bound the anchor: an unresolved indexOf slices to EOF and passes vacuously.
expect(start).toBeGreaterThanOrEqual(0)
const end = mainSource.indexOf('\n}', start)
expect(end).toBeGreaterThan(start)
const getServeOptionsBody = mainSource.slice(start, end)

for (const flag of translatedFlags) {
expect(launchSource).toContain(`'--serve-${flag}'`)
expect(getServeOptionsBody).toContain(`'--serve-${flag}'`)
}
})

it('keeps the untranslated allowlist tied to real global flags', () => {
for (const flag of UNTRANSLATED_GLOBAL_FLAGS) {
expect(GLOBAL_FLAGS).toContain(flag)
}
})
})
45 changes: 28 additions & 17 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ import {
installUnhandledRejectionLogging
} from './startup/main-process-error-guards'
import { enableRendererHeapHeadroom } from './startup/renderer-heap-headroom'
import { argvRequestsServeMode, normalizeServeModeArgv } from './startup/serve-mode-argv'
import { ensureVirtualDisplayForHeadlessServe } from './startup/ensure-virtual-display'
import {
readActiveGpuFallbackMarker,
Expand Down Expand Up @@ -379,6 +380,33 @@ let gpuFeatureStatus: Electron.GPUFeatureStatus | null = null
let localPtyStartupReady: Promise<void> = Promise.resolve()
let localPtyProviderStartupReady: Promise<void> = Promise.resolve()
const AGENT_STATE_CRASH_BREADCRUMB_MIN_INTERVAL_MS = 30_000
// Why: on Windows a CLI launch that lost ELECTRON_RUN_AS_NODE would boot the GUI and exit silently; redirect to node mode before the lock gate below.
// Both redirects run before the serve-argv rewrite so they still match on the launch argv verbatim.
// It is load-bearing for the AppImage one: rewriting first replaces the `serve` positional, so its
// command-name lookup finds a port number and strands the launch in an in-process serve. The
// packaged-CLI one matches on the entry path instead, so order cannot affect it either way.
const packagedCliEntryRedirect = maybeRedirectPackagedCliEntryLaunch({
isPackaged: app.isPackaged,
resourcesPath: process.resourcesPath,
execPath: process.execPath
})
if (packagedCliEntryRedirect.redirected) {
app.exit(packagedCliEntryRedirect.status)
}
const appImageCliRedirect = maybeRedirectAppImageCliLaunch({
isPackaged: app.isPackaged,
resourcesPath: process.resourcesPath,
execPath: process.execPath
})
if (appImageCliRedirect.redirected) {
app.exit(appImageCliRedirect.status)
}
// Why: extracted AppRun / binary launches can land CLI-form `serve` args on the
// Electron process without the CLI rewrite that injects `--serve` (#12677).
// Guarded so a normal GUI launch keeps its original argv array identity.
if (argvRequestsServeMode(process.argv)) {
process.argv = normalizeServeModeArgv(process.argv)
}
const isServeMode = process.argv.includes('--serve')

function updateGpuAccelerationAboutPanel(): void {
Expand Down Expand Up @@ -412,23 +440,6 @@ const desktopActivationGate = createServeDesktopActivationGate({
},
onBlocked: (reason) => console.error(`[serve] Desktop activation blocked: ${reason}`)
})
// Why: on Windows a CLI launch that lost ELECTRON_RUN_AS_NODE would boot the GUI and exit silently; redirect to node mode before the lock gate below.
const packagedCliEntryRedirect = maybeRedirectPackagedCliEntryLaunch({
isPackaged: app.isPackaged,
resourcesPath: process.resourcesPath,
execPath: process.execPath
})
if (packagedCliEntryRedirect.redirected) {
app.exit(packagedCliEntryRedirect.status)
}
const appImageCliRedirect = maybeRedirectAppImageCliLaunch({
isPackaged: app.isPackaged,
resourcesPath: process.resourcesPath,
execPath: process.execPath
})
if (appImageCliRedirect.redirected) {
app.exit(appImageCliRedirect.status)
}

// Kill switch for the first-work on-disk folder rename; the renderer reconciles the id change (migrateWorktreeIdentity) so it isn't mistaken for a deletion.
const ENABLE_FIRST_WORK_FOLDER_RENAME = false
Expand Down
64 changes: 64 additions & 0 deletions src/main/startup/serve-mode-argv-cli-redirect-order.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { getAppImageCliArgs } from './appimage-cli-redirect'
import { argvRequestsServeMode, normalizeServeModeArgv } from './serve-mode-argv'

// Why: index.ts must run both CLI redirects before rewriting argv. Rewriting
// first replaces the `serve` positional with `--serve`, so the redirect's
// command-name lookup finds a port number instead of a command and bails —
// silently dropping AppImage serve launches out of the CLI path (#12677).

const REDIRECT_OPTIONS = {
platform: 'linux' as const,
isPackaged: true,
commandNames: ['serve', 'status']
}
// A mounted AppImage is the case where the runtime does export these.
const MOUNTED_APPIMAGE_ENV = { APPIMAGE: '/opt/orca/Orca.AppImage', APPDIR: '/tmp/.mount_ab12' }

function rewriteAsIndexDoes(argv: string[]): string[] {
return argvRequestsServeMode(argv) ? normalizeServeModeArgv(argv) : argv
}

describe('serve argv rewrite vs AppImage CLI redirect ordering', () => {
const launchArgv = ['/opt/orca/orca-ide', '--no-sandbox', 'serve', '--port', '7777', '--json']

it('hands the launch argv to the CLI when the redirect runs first', () => {
expect(getAppImageCliArgs(launchArgv, MOUNTED_APPIMAGE_ENV, REDIRECT_OPTIONS)).toEqual([
'serve',
'--port',
'7777',
'--json'
])
})

it('loses the redirect if the rewrite runs first', () => {
const rewritten = rewriteAsIndexDoes(launchArgv)
expect(rewritten).toContain('--serve')
expect(getAppImageCliArgs(rewritten, MOUNTED_APPIMAGE_ENV, REDIRECT_OPTIONS)).toBeNull()
})

it('leaves non-serve CLI commands redirectable either way', () => {
const argv = ['/opt/orca/orca-ide', 'status']
expect(rewriteAsIndexDoes(argv)).toEqual(argv)
expect(getAppImageCliArgs(argv, MOUNTED_APPIMAGE_ENV, REDIRECT_OPTIONS)).toEqual(['status'])
})

// Why source text: the ordering only exists as statement order at index.ts module scope, and the
// cases above stay green if it is reversed — nothing else would catch the regression.
it('keeps index.ts running both CLI redirects before the argv rewrite', () => {
const source = readFileSync(join(process.cwd(), 'src/main/index.ts'), 'utf8')
const packagedRedirect = source.indexOf('maybeRedirectPackagedCliEntryLaunch({')
const appImageRedirect = source.indexOf('maybeRedirectAppImageCliLaunch({')
const rewrite = source.indexOf('process.argv = normalizeServeModeArgv(process.argv)')
const serveModeCheck = source.indexOf("const isServeMode = process.argv.includes('--serve')")

expect(packagedRedirect).toBeGreaterThanOrEqual(0)
expect(appImageRedirect).toBeGreaterThanOrEqual(0)
expect(rewrite).toBeGreaterThan(packagedRedirect)
expect(rewrite).toBeGreaterThan(appImageRedirect)
// The rewrite is pointless unless it lands before the flag it exists to inject is read.
expect(serveModeCheck).toBeGreaterThan(rewrite)
})
})
Loading