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
27 changes: 3 additions & 24 deletions src/cli/command-suggestion.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { specPaths, type CommandSpec } from './command-spec'
import { levenshtein } from '../shared/edit-distance'

export { levenshtein } from '../shared/edit-distance'

// Why: rank the live registry so typo recovery cannot drift from accepted paths.

Expand Down Expand Up @@ -46,30 +49,6 @@ export type CommandErrorData = {
nextSteps: string[]
}

export function levenshtein(a: string, b: string): number {
const m = a.length
const n = b.length
if (m === 0) {
return n
}
if (n === 0) {
return m
}
let prev = Array.from({ length: n + 1 }, (_, index) => index)
let curr = Array.from({ length: n + 1 }, () => 0)
for (let i = 1; i <= m; i += 1) {
curr[0] = i
for (let j = 1; j <= n; j += 1) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost)
}
const swap = prev
prev = curr
curr = swap
}
return prev[n]
}

// Why: one bounded near-match ranking keeps command and flag recovery consistent.
function rankByDistance(scored: { label: string; distance: number }[]): string[] {
return scored
Expand Down
51 changes: 19 additions & 32 deletions src/cli/handlers/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { CommandHandler } from '../dispatch'
import { formatCliStatus, formatStatus, printResult } from '../format'
import { RuntimeClientError, serveOrcaApp } from '../runtime-client'
import { stripElectronRunAsNode } from '../runtime/launch'
import { getServeOptionValidationError } from '../../shared/serve-option-validation'

function envRecord(): Record<string, string> {
// Why: the `orca` launcher runs Orca's Electron binary as Node, so this CLI
Expand Down Expand Up @@ -92,43 +93,29 @@ export const CORE_HANDLERS: Record<string, CommandHandler> = {
printResult(result, json, formatCliStatus)
},
serve: async ({ flags, json }) => {
if (flags.get('no-pairing') === true && flags.get('mobile-pairing') === true) {
throw new RuntimeClientError(
'invalid_argument',
'Use either --mobile-pairing or --no-pairing, not both.'
)
}
if (flags.get('recipe-json') === true && flags.get('no-pairing') === true) {
throw new RuntimeClientError(
'invalid_argument',
'Recipe JSON output requires runtime pairing; remove --no-pairing.'
)
}
if (flags.get('recipe-json') === true && flags.get('mobile-pairing') === true) {
throw new RuntimeClientError(
'invalid_argument',
'Recipe JSON output requires runtime pairing; remove --mobile-pairing.'
)
}
const projectRoot =
typeof flags.get('project-root') === 'string' ? (flags.get('project-root') as string) : null
if (flags.get('recipe-json') === true && !projectRoot) {
throw new RuntimeClientError(
'invalid_argument',
'Recipe JSON output requires --project-root.'
)
const projectRootValue = flags.get('project-root')
const projectRoot = typeof projectRootValue === 'string' ? projectRootValue : null
const noPairing = flags.get('no-pairing') === true
const mobilePairing = flags.get('mobile-pairing') === true
const recipeJson = flags.get('recipe-json') === true
const validationError = getServeOptionValidationError({
noPairing,
mobilePairing,
recipeJson,
projectRoot
})
if (validationError) {
throw new RuntimeClientError('invalid_argument', validationError)
}
const port = getOptionalServePort(flags)
const pairingAddressValue = flags.get('pairing-address')
const exitCode = await serveOrcaApp({
json,
port,
pairingAddress:
typeof flags.get('pairing-address') === 'string'
? (flags.get('pairing-address') as string)
: null,
noPairing: flags.get('no-pairing') === true,
mobilePairing: flags.get('mobile-pairing') === true,
recipeJson: flags.get('recipe-json') === true,
pairingAddress: typeof pairingAddressValue === 'string' ? pairingAddressValue : null,
noPairing,
mobilePairing,
recipeJson,
projectRoot
})
process.exitCode = exitCode
Expand Down
18 changes: 10 additions & 8 deletions src/cli/serve-electron-flag-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ describe('serve flag parity between the CLI spec and the Electron argv rewrite',

expect(normalizeServeModeArgv(argv)).toEqual(expected)
if (takesValue) {
// The equals form is the other shape `orca serve` accepts, and getServeOptions only reads the next token.
// The equals form is the other shape `orca serve` accepts; normalize it to the internal shape.
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
Expand All @@ -53,17 +53,19 @@ describe('serve flag parity between the CLI spec and the Electron argv rewrite',
})

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.
// Why source text: serveOrcaApp spawns a real process; keeping both names visible here makes
// the rewrite/parser contract fail loudly if either side drifts.
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(')
const serveOptionsSource = readFileSync(
join(process.cwd(), 'src/main/startup/serve-options.ts'),
'utf8'
)
const start = serveOptionsSource.indexOf('export 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)
const end = serveOptionsSource.indexOf('\n}', start)
expect(end).toBeGreaterThan(start)
const getServeOptionsBody = mainSource.slice(start, end)
const getServeOptionsBody = serveOptionsSource.slice(start, end)

for (const flag of translatedFlags) {
expect(launchSource).toContain(`'--serve-${flag}'`)
Expand Down
49 changes: 19 additions & 30 deletions src/main/cli/cli-command-installation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,9 @@ import {
} from './cli-command-filesystem-transaction'
import { DEV_LAUNCHER_DIR, LEGACY_LINUX_COMMAND_NAME } from './cli-install-constants'
import { buildWindowsForwarder } from './cli-dev-launcher'
import { isMissingError, isPermissionError } from './cli-install-errors'
import { isPermissionError } from './cli-install-errors'
import { isPathInsideOrEqual } from './cli-install-path-format'

const STABLE_LEGACY_INSPECTION_ATTEMPTS = 3

export class CliCommandInstallation extends CliCommandInspection {
protected async installSymlink(status: CliInstallStatus): Promise<void> {
const commandPath = status.commandPath
Expand Down Expand Up @@ -194,34 +192,25 @@ export class CliCommandInstallation extends CliCommandInspection {
})
| null
> {
for (let attempt = 0; attempt < STABLE_LEGACY_INSPECTION_ATTEMPTS; attempt += 1) {
const before = await readEntrySnapshot(commandPath)
if (!before) {
return null
}
let target: string | null = null
try {
target = before.isSymbolicLink ? await readlink(commandPath) : null
} catch (error) {
if (isMissingError(error)) {
continue
}
throw error
}
const after = await readEntrySnapshot(commandPath)
if (after && hasSameSnapshot(before, after)) {
const resolvedTarget = target ? resolve(dirname(commandPath), target) : null
return {
fileSha256: null,
rawSymlinkTarget: target,
snapshot: after,
managed: Boolean(
resolvedTarget && this.isManagedLegacyLinuxTarget(resolvedTarget, launcherPath)
)
}
}
const inspected = await inspectStableCommand(commandPath, () =>
this.inspectSymlink(commandPath, launcherPath)
)
if (!inspected.snapshot) {
return null
}
const resolvedTarget = inspected.rawSymlinkTarget
? resolve(dirname(commandPath), inspected.rawSymlinkTarget)
: inspected.status.currentTarget
return {
fileSha256: inspected.fileSha256,
rawSymlinkTarget: inspected.rawSymlinkTarget,
snapshot: inspected.snapshot,
managed: Boolean(
resolvedTarget &&
(this.isManagedLegacyLinuxTarget(resolvedTarget, launcherPath) ||
(this.appImagePath && resolve(resolvedTarget) === resolve(this.appImagePath)))
)
}
throw new Error(`The command at ${commandPath} changed while Orca inspected it.`)
}

private async restoreQuarantinedCommand(
Expand Down
50 changes: 50 additions & 0 deletions src/main/cli/cli-installer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,56 @@ describe('CliInstaller', () => {
}
)

it.skipIf(process.platform === 'win32')(
'removes a legacy AppImage wrapper only when it names the current AppImage',
async () => {
const fixture = await makeFixture()
const homePath = join(fixture.root, 'home')
const commandDir = join(homePath, '.local', 'bin')
const legacyCommandPath = join(commandDir, 'orca')
const appImagePath = join(fixture.root, 'Orca.AppImage')
const foreignAppImagePath = join(fixture.root, 'Other.AppImage')
const cacheRootPath = join(fixture.root, 'cache')
await mkdir(commandDir, { recursive: true })
await writeFile(appImagePath, '#!/usr/bin/env bash\n', {
encoding: 'utf8',
mode: 0o755
})
await writeFile(foreignAppImagePath, '#!/usr/bin/env bash\n', {
encoding: 'utf8',
mode: 0o755
})
await writeFile(legacyCommandPath, buildLegacyAppImageCliWrapper(appImagePath), {
encoding: 'utf8',
mode: 0o755
})

const installer = new CliInstaller({
platform: 'linux',
isPackaged: true,
userDataPath: fixture.userDataPath,
appPath: fixture.appPath,
appImagePath,
appImageCacheRootPath: cacheRootPath,
appImageExtractRunner: fakeAppImageExtractRunner,
homePath,
processPathEnv: commandDir
})

await installer.install()
await expect(lstat(legacyCommandPath)).rejects.toMatchObject({ code: 'ENOENT' })

await writeFile(legacyCommandPath, buildLegacyAppImageCliWrapper(foreignAppImagePath), {
encoding: 'utf8',
mode: 0o755
})
await installer.remove()
await expect(readFile(legacyCommandPath, 'utf8')).resolves.toBe(
buildLegacyAppImageCliWrapper(foreignAppImagePath)
)
}
)

// Why: the privilegedRunner is injectable so the EACCES→osascript path can be
// exercised in integration without spawning osascript in unit tests.
it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(
Expand Down
42 changes: 2 additions & 40 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ import {
} from './startup/main-process-error-guards'
import { enableRendererHeapHeadroom } from './startup/renderer-heap-headroom'
import { argvRequestsServeMode, normalizeServeModeArgv } from './startup/serve-mode-argv'
import { getServeOptions, type ServeOptions } from './startup/serve-options'
import {
ensureVirtualDisplayForHeadlessServe,
hasUsableLinuxDisplay,
Expand Down Expand Up @@ -2080,45 +2081,6 @@ const syntheticTitleSpinnerByPaneKey = new Map<
>()
let syntheticTitleSpinnerTimer: ReturnType<typeof setInterval> | null = null

type ServeOptions = {
json: boolean
wsPort?: number
pairingAddress: string | null
noPairing: boolean
mobilePairing: boolean
recipeJson: boolean
projectRoot: string | null
}

function getServeOptions(argv = process.argv): ServeOptions {
const valueAfter = (flag: string): string | null => {
const index = argv.indexOf(flag)
if (index === -1) {
return null
}
const value = argv[index + 1]
return value && !value.startsWith('--') ? value : null
}
const rawPort = valueAfter('--serve-port')
let wsPort: number | undefined
if (rawPort) {
const parsedPort = Number(rawPort)
if (!Number.isInteger(parsedPort) || parsedPort < 0 || parsedPort > 65535) {
throw new Error(`Invalid --serve-port value: ${rawPort}`)
}
wsPort = parsedPort
}
return {
json: argv.includes('--serve-json'),
...(wsPort !== undefined ? { wsPort } : {}),
pairingAddress: valueAfter('--serve-pairing-address'),
noPairing: argv.includes('--serve-no-pairing'),
mobilePairing: argv.includes('--serve-mobile-pairing'),
recipeJson: argv.includes('--serve-recipe-json'),
projectRoot: valueAfter('--serve-project-root')
}
}

function getBundledWebClientRoot(): string | undefined {
const appPath = app.getAppPath()
const roots = [
Expand Down Expand Up @@ -3376,7 +3338,7 @@ void app.whenReady().then(async () => {
const devWsPort = is.dev && !isE2E ? 6769 : undefined
let serveOptions: ServeOptions | null = null
try {
serveOptions = isServeMode ? getServeOptions() : null
serveOptions = isServeMode ? getServeOptions(process.argv) : null
} catch (error) {
console.error(error instanceof Error ? error.message : String(error))
app.exit(1)
Expand Down
8 changes: 8 additions & 0 deletions src/main/startup/serve-mode-argv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,14 @@ describe('serve-mode-argv', () => {
).toEqual(['/AppRun', '--serve', '--serve-port', '9090', '--serve-pairing-address', '0.0.0.0'])
})

it('keeps equals-form values that start with a flag marker intact', () => {
expect(normalizeServeModeArgv(['/AppRun', 'serve', '--pairing-address=--no-pairng'])).toEqual([
'/AppRun',
'--serve',
'--serve-pairing-address=--no-pairng'
])
})

it('translates serve flags in the mixed `--serve --port` form', () => {
// Why: leaving these untranslated silently kept pairing enabled despite --no-pairing.
expect(normalizeServeModeArgv(['orca', '--serve', '--port', '9090', '--no-pairing'])).toEqual([
Expand Down
12 changes: 9 additions & 3 deletions src/main/startup/serve-mode-argv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,7 @@ export function normalizeServeModeArgv(argv: readonly string[]): string[] {
next.push(...argv.slice(i))
break
}
// Why: the CLI accepts `--port=6768` as well as `--port 6768`, but
// getServeOptions only reads the next token, so `=` must be split apart.
// Why: keep the internal argv shape canonical even though getServeOptions accepts both forms.
const eq = token.indexOf('=')
const name = eq === -1 ? token : token.slice(0, eq)
// Why only the bare form: the CLI reads its serve booleans as `flags.get(name) === true`
Expand All @@ -155,7 +154,14 @@ export function normalizeServeModeArgv(argv: readonly string[]): string[] {
continue
}
if (eq !== -1) {
next.push(valueFlag, token.slice(eq + 1))
const value = token.slice(eq + 1)
// Preserve the unambiguous `=` form when its value starts with `--`; splitting
// it would make the value look like a second option to the direct parser.
if (value.startsWith('--')) {
next.push(`${valueFlag}=${value}`)
} else {
next.push(valueFlag, value)
}
continue
}
next.push(valueFlag)
Expand Down
Loading
Loading