diff --git a/src/main/cli/appimage-cli-wrapper.ts b/src/main/cli/appimage-cli-wrapper.ts new file mode 100644 index 000000000..b80125811 --- /dev/null +++ b/src/main/cli/appimage-cli-wrapper.ts @@ -0,0 +1,37 @@ +const APPIMAGE_CLI_SCRIPT = [ + '(async()=>{', + 'try{', + 'const path=require("path");', + 'const appDir=process.env.APPDIR;', + 'if(!appDir){console.error("Orca AppImage runtime did not set APPDIR.");process.exit(1);}', + 'const cli=path.join(appDir,"resources","app.asar.unpacked","out","cli","index.js");', + 'await Promise.resolve(require(cli).main(process.argv.slice(1)));', + '}catch(error){', + 'console.error(error&&error.stack?error.stack:String(error));process.exit(1);', + '}', + '})();' +].join('') + +export function buildAppImageCliWrapper(appImagePath: string): string { + // Why: AppImage mounts resources under a fresh FUSE path per launch, so the + // installed command must call the stable outer AppImage and resolve APPDIR. + return `#!/usr/bin/env bash +set -euo pipefail +APPIMAGE=${quoteShell(appImagePath)} +if [ ! -f "$APPIMAGE" ]; then + echo "Orca AppImage not found at $APPIMAGE" >&2 + echo "If you moved the AppImage, re-run CLI registration from Orca Settings." >&2 + exit 1 +fi +export ORCA_NODE_OPTIONS="\${NODE_OPTIONS-}" +export ORCA_NODE_REPL_EXTERNAL_MODULE="\${NODE_REPL_EXTERNAL_MODULE-}" +unset NODE_OPTIONS +unset NODE_REPL_EXTERNAL_MODULE +# Why: AppImage mount paths change on each launch; $APPDIR is the runtime mount. +ELECTRON_RUN_AS_NODE=1 exec "$APPIMAGE" -e ${quoteShell(APPIMAGE_CLI_SCRIPT)} -- "$@" +` +} + +function quoteShell(value: string): string { + return `'${value.replaceAll("'", `'"'"'`)}'` +} diff --git a/src/main/cli/cli-installer.test.ts b/src/main/cli/cli-installer.test.ts index bbbd5f8f4..1f5ce3dab 100644 --- a/src/main/cli/cli-installer.test.ts +++ b/src/main/cli/cli-installer.test.ts @@ -28,6 +28,7 @@ vi.mock('node:child_process', () => ({ })) import { CliInstaller } from './cli-installer' +import { buildAppImageCliWrapper } from './appimage-cli-wrapper' async function makeFixture(): Promise<{ root: string @@ -116,6 +117,97 @@ describe('CliInstaller', () => { } ) + // Why: AppImage resources live under a per-launch FUSE mount, so the + // installed shell command must be a stable wrapper rather than a symlink. + it.skipIf(process.platform === 'win32')( + 'creates an AppImage wrapper under the linux command path', + async () => { + const fixture = await makeFixture() + const commandDir = join(fixture.root, '.local', 'bin') + const installPath = join(commandDir, 'orca-ide') + const appImagePath = join(fixture.root, 'Orca.AppImage') + await writeFile(appImagePath, '#!/usr/bin/env bash\n', { + encoding: 'utf8', + mode: 0o755 + }) + + const installer = new CliInstaller({ + platform: 'linux', + isPackaged: true, + appImagePath, + commandPathOverride: installPath, + processPathEnv: commandDir + }) + + const initial = await installer.getStatus() + expect(initial).toMatchObject({ + state: 'not_installed', + installMethod: 'wrapper', + launcherPath: appImagePath + }) + + const installed = await installer.install() + expect(installed).toMatchObject({ + state: 'installed', + commandName: 'orca-ide', + installMethod: 'wrapper', + launcherPath: appImagePath, + currentTarget: appImagePath, + pathConfigured: true + }) + + const commandStats = await lstat(installPath) + expect(commandStats.isFile()).toBe(true) + expect(commandStats.mode & 0o111).not.toBe(0) + await expect(readlink(installPath)).rejects.toMatchObject({ code: 'EINVAL' }) + await expect(readFile(installPath, 'utf8')).resolves.toBe( + buildAppImageCliWrapper(appImagePath) + ) + + const removed = await installer.remove() + expect(removed.state).toBe('not_installed') + } + ) + + it.skipIf(process.platform === 'win32')( + 'reports a stale AppImage wrapper when the AppImage path changes', + async () => { + const fixture = await makeFixture() + const commandDir = join(fixture.root, '.local', 'bin') + const installPath = join(commandDir, 'orca-ide') + const oldAppImagePath = join(fixture.root, 'Old-Orca.AppImage') + const newAppImagePath = join(fixture.root, 'Orca.AppImage') + await mkdir(commandDir, { recursive: true }) + await writeFile(installPath, buildAppImageCliWrapper(oldAppImagePath), { + encoding: 'utf8', + mode: 0o755 + }) + await writeFile(newAppImagePath, '#!/usr/bin/env bash\n', { + encoding: 'utf8', + mode: 0o755 + }) + + const installer = new CliInstaller({ + platform: 'linux', + isPackaged: true, + appImagePath: newAppImagePath, + commandPathOverride: installPath, + processPathEnv: commandDir + }) + + await expect(installer.getStatus()).resolves.toMatchObject({ + state: 'stale', + installMethod: 'wrapper', + currentTarget: newAppImagePath + }) + + await expect(installer.install()).resolves.toMatchObject({ state: 'installed' }) + await expect(readFile(installPath, 'utf8')).resolves.toBe( + buildAppImageCliWrapper(newAppImagePath) + ) + } + ) + // Why: Linux renamed the public command to avoid shadowing GNOME Orca, so // upgrading must clean up only the old symlink owned by prior Orca installs. it.skipIf(process.platform === 'win32')( @@ -147,6 +239,35 @@ describe('CliInstaller', () => { } ) + it.skipIf(process.platform === 'win32')( + 'removes a legacy linux orca symlink when installing an AppImage wrapper', + 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') + await mkdir(commandDir, { recursive: true }) + await writeFile(appImagePath, '#!/usr/bin/env bash\n', { + encoding: 'utf8', + mode: 0o755 + }) + await symlink(join('/tmp', '.mount_Orca1234', 'resources', 'bin', 'orca'), legacyCommandPath) + + const installer = new CliInstaller({ + platform: 'linux', + isPackaged: true, + appImagePath, + homePath, + processPathEnv: commandDir + }) + + const installed = await installer.install() + expect(installed.commandPath).toBe(join(commandDir, 'orca-ide')) + await expect(lstat(legacyCommandPath)).rejects.toMatchObject({ code: 'ENOENT' }) + } + ) + it('creates a windows wrapper and updates the user PATH', async () => { const fixture = await makeFixture() const installPath = join(fixture.root, 'Programs', 'Orca', 'bin', 'orca.cmd') diff --git a/src/main/cli/cli-installer.ts b/src/main/cli/cli-installer.ts index edb543b84..46e3aa2a0 100644 --- a/src/main/cli/cli-installer.ts +++ b/src/main/cli/cli-installer.ts @@ -7,6 +7,7 @@ import { homedir } from 'node:os' import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path' import { promisify } from 'node:util' import type { CliInstallMethod, CliInstallStatus } from '../../shared/cli-install-types' +import { buildAppImageCliWrapper } from './appimage-cli-wrapper' const execFileAsync = promisify(execFile) const DEFAULT_MAC_COMMAND_PATH = '/usr/local/bin/orca' @@ -31,6 +32,8 @@ type CliInstallerOptions = { privilegedRunner?: (command: string) => Promise userPathReader?: () => Promise userPathWriter?: (value: string) => Promise + /** Why: AppImage reports a stable outer file path via $APPIMAGE while bundled resources live in an ephemeral FUSE mount. */ + appImagePath?: string | null } type InstallSpec = { @@ -53,6 +56,7 @@ export class CliInstaller { private readonly privilegedRunner: (command: string) => Promise private readonly userPathReader: () => Promise private readonly userPathWriter: (value: string) => Promise + private readonly appImagePath: string | null // Why: Linux uses `orca-ide` to avoid shadowing GNOME Orca's /usr/bin/orca. private get commandName(): string { @@ -88,6 +92,10 @@ export class CliInstaller { this.privilegedRunner = options.privilegedRunner ?? runMacPrivilegedCommand this.userPathReader = options.userPathReader ?? (() => readWindowsUserPath()) this.userPathWriter = options.userPathWriter ?? ((value) => writeWindowsUserPath(value)) + this.appImagePath = + this.platform === 'linux' && this.isPackaged + ? (options.appImagePath ?? process.env.APPIMAGE ?? null) + : null } async getStatus(): Promise { @@ -111,6 +119,12 @@ export class CliInstaller { const launcherPath = await this.resolveLauncherPath() if (!launcherPath) { + const detail = + this.isLinuxAppImage() && this.appImagePath + ? `The AppImage file at ${this.appImagePath} is missing. Move it back or re-run CLI registration from the current AppImage location.` + : this.isPackaged + ? 'The bundled CLI launcher is missing from this Orca build.' + : 'Development mode uses a generated launcher for validation only.' return { platform: this.platform, commandName: this.commandName, @@ -123,16 +137,16 @@ export class CliInstaller { state: 'unsupported', currentTarget: null, unsupportedReason: this.isPackaged ? 'launcher_missing' : 'launch_mode_unavailable', - detail: this.isPackaged - ? 'The bundled CLI launcher is missing from this Orca build.' - : 'Development mode uses a generated launcher for validation only.' + detail } } const baseStatus = spec.installMethod === 'symlink' ? await this.inspectSymlink(spec.commandPath, launcherPath) - : await this.inspectWindowsWrapper(spec.commandPath, launcherPath) + : this.isLinuxAppImage() + ? await this.inspectAppImageWrapper(spec.commandPath, launcherPath) + : await this.inspectWindowsWrapper(spec.commandPath, launcherPath) const pathDirectory = dirname(spec.commandPath) const pathConfigured = await this.isPathConfigured(pathDirectory) return this.withPathInfo(baseStatus, pathDirectory, pathConfigured) @@ -151,6 +165,9 @@ export class CliInstaller { if (status.installMethod === 'symlink') { await this.installSymlink(status) await this.removeLegacyLinuxCommandIfManaged(status.launcherPath) + } else if (this.isLinuxAppImage()) { + await this.installAppImageWrapper(status.commandPath, status.launcherPath) + await this.removeLegacyLinuxCommandIfManaged(status.launcherPath) } else { // Why: mkdir stays here for the Windows wrapper path — the target dir is // user-writable (%LOCALAPPDATA%) so EACCES cannot occur. The symlink path @@ -210,7 +227,7 @@ export class CliInstaller { if (this.platform === 'darwin' || this.platform === 'linux') { return { commandPath, - installMethod: 'symlink' + installMethod: this.isLinuxAppImage() ? 'wrapper' : 'symlink' } } @@ -255,6 +272,10 @@ export class CliInstaller { return null } + if (this.isLinuxAppImage()) { + return this.appImagePath && existsSync(this.appImagePath) ? this.appImagePath : null + } + if (this.isPackaged) { const bundledPath = getBundledLauncherPath(this.platform, this.resourcesPath) return bundledPath && existsSync(bundledPath) ? bundledPath : null @@ -325,8 +346,7 @@ export class CliInstaller { const currentTarget = await readlink(legacyCommandPath) const resolvedCurrentTarget = resolve(dirname(legacyCommandPath), currentTarget) - const legacyLauncherPath = resolve(dirname(launcherPath), LEGACY_LINUX_COMMAND_NAME) - if (resolvedCurrentTarget !== legacyLauncherPath) { + if (!this.isManagedLegacyLinuxTarget(resolvedCurrentTarget, launcherPath)) { return } @@ -341,10 +361,89 @@ export class CliInstaller { } } + private isManagedLegacyLinuxTarget(resolvedTarget: string, launcherPath: string): boolean { + const legacyLauncherPath = resolve(dirname(launcherPath), LEGACY_LINUX_COMMAND_NAME) + if (resolvedTarget === legacyLauncherPath) { + return true + } + + if (basename(resolvedTarget) !== LEGACY_LINUX_COMMAND_NAME) { + return false + } + + const devLauncherDir = resolve(this.userDataPath, ...DEV_LAUNCHER_DIR) + const devRelative = relative(devLauncherDir, resolvedTarget) + if (devRelative && !devRelative.startsWith('..') && !isAbsolute(devRelative)) { + return true + } + + // Why: AppImage upgrades can leave a legacy symlink into a now-gone FUSE + // mount; the stable AppImage path is not a sibling of that old target. + return /(?:^|[/\\])resources[/\\]bin[/\\]orca$/.test(resolvedTarget) + } + private async installWindowsWrapper(commandPath: string, launcherPath: string): Promise { await writeFile(commandPath, buildWindowsForwarder(launcherPath), 'utf8') } + private async installAppImageWrapper(commandPath: string, appImagePath: string): Promise { + // Why: unlike macOS symlink install, AppImage uses the user-writable Linux + // command dir and must create it before writing the wrapper file. + await mkdir(dirname(commandPath), { recursive: true }) + await writeFile(commandPath, buildAppImageCliWrapper(appImagePath), { + encoding: 'utf8', + mode: 0o755 + }) + } + + private async inspectAppImageWrapper( + commandPath: string, + appImagePath: string + ): Promise { + try { + const stats = await lstat(commandPath) + if (!stats.isFile()) { + return this.buildStatus({ + commandPath, + launcherPath: appImagePath, + installMethod: 'wrapper', + supported: true, + state: 'conflict', + currentTarget: null, + detail: `${commandPath} exists but is not an Orca launcher script.` + }) + } + + const currentContent = await readFile(commandPath, 'utf8') + const expectedContent = buildAppImageCliWrapper(appImagePath) + return this.buildStatus({ + commandPath, + launcherPath: appImagePath, + installMethod: 'wrapper', + supported: true, + state: currentContent === expectedContent ? 'installed' : 'stale', + currentTarget: appImagePath, + detail: + currentContent === expectedContent + ? `Registered at ${commandPath}.` + : `${commandPath} points to a different launcher.` + }) + } catch (error) { + if (isMissingError(error)) { + return this.buildStatus({ + commandPath, + launcherPath: appImagePath, + installMethod: 'wrapper', + supported: true, + state: 'not_installed', + currentTarget: null, + detail: `Register ${commandPath} to use Orca from the terminal.` + }) + } + throw error + } + } + private async inspectSymlink( commandPath: string, launcherPath: string @@ -425,6 +524,10 @@ export class CliInstaller { return false } + private isLinuxAppImage(): boolean { + return this.platform === 'linux' && Boolean(this.appImagePath) + } + private async inspectWindowsWrapper( commandPath: string, launcherPath: string diff --git a/src/main/cli/packaged-cli-assets.test.ts b/src/main/cli/packaged-cli-assets.test.ts index ce36cf518..63f5f1b78 100644 --- a/src/main/cli/packaged-cli-assets.test.ts +++ b/src/main/cli/packaged-cli-assets.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' import { describe, expect, it } from 'vitest' +import { buildAppImageCliWrapper } from './appimage-cli-wrapper' const require = createRequire(import.meta.url) const execFileAsync = promisify(execFile) @@ -98,4 +99,72 @@ printf 'arg=%s\\n' "$@" } } ) + + itRunsUnixShell('runs the AppImage CLI wrapper through APPDIR at runtime', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-appimage-cli-')) + try { + const appDir = join(root, 'Orca.AppDir') + const cliDir = join(appDir, 'resources', 'app.asar.unpacked', 'out', 'cli') + const cliPath = join(cliDir, 'index.js') + const appImagePath = join(root, "Orca's AppImage.AppImage") + const commandPath = join(root, 'orca-ide') + await mkdir(cliDir, { recursive: true }) + await writeFile( + cliPath, + `exports.main = (argv) => { + console.log(JSON.stringify({ + argv, + appDir: process.env.APPDIR, + runAsNode: process.env.ELECTRON_RUN_AS_NODE, + nodeOptions: process.env.NODE_OPTIONS ?? null, + orcaNodeOptions: process.env.ORCA_NODE_OPTIONS ?? null, + nodeReplExternalModule: process.env.NODE_REPL_EXTERNAL_MODULE ?? null, + orcaNodeReplExternalModule: process.env.ORCA_NODE_REPL_EXTERNAL_MODULE ?? null + })) +} +`, + 'utf8' + ) + await writeFile( + appImagePath, + `#!/usr/bin/env bash +export APPDIR="$FAKE_APPDIR" +exec node "$@" +`, + { encoding: 'utf8', mode: 0o755 } + ) + await writeFile(commandPath, buildAppImageCliWrapper(appImagePath), { + encoding: 'utf8', + mode: 0o755 + }) + + const result = await execFileAsync(commandPath, ['--help', 'two words'], { + env: { + ...process.env, + FAKE_APPDIR: appDir, + NODE_OPTIONS: '--trace-warnings', + NODE_REPL_EXTERNAL_MODULE: 'external-loader' + } + }) + const payload = JSON.parse(result.stdout) as { + argv: string[] + appDir: string + runAsNode: string + nodeOptions: string | null + orcaNodeOptions: string | null + nodeReplExternalModule: string | null + orcaNodeReplExternalModule: string | null + } + + expect(payload.argv).toEqual(['--help', 'two words']) + expect(payload.appDir).toBe(appDir) + expect(payload.runAsNode).toBe('1') + expect(payload.nodeOptions).toBeNull() + expect(payload.orcaNodeOptions).toBe('--trace-warnings') + expect(payload.nodeReplExternalModule).toBeNull() + expect(payload.orcaNodeReplExternalModule).toBe('external-loader') + } finally { + await rm(root, { recursive: true, force: true }) + } + }) })