diff --git a/config/scripts/orca-dev b/config/scripts/orca-dev index 47bdb1c5b..10754fe4c 100755 --- a/config/scripts/orca-dev +++ b/config/scripts/orca-dev @@ -25,4 +25,12 @@ case "$(uname -s)" in esac export ORCA_USER_DATA_PATH="${ORCA_DEV_USER_DATA_PATH:-$default_data}" +electron_executable="$REPO_ROOT/node_modules/.bin/electron" +case "$(uname -s)" in + MINGW*|MSYS*) electron_executable="$REPO_ROOT/node_modules/electron/dist/electron.exe" ;; +esac +if [ -z "${ORCA_APP_EXECUTABLE:-}" ] && [ -x "$electron_executable" ]; then + export ORCA_APP_EXECUTABLE="$electron_executable" + export ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT=1 +fi exec node "$CLI_ENTRY" "$@" diff --git a/config/scripts/run-electron-vite-dev.mjs b/config/scripts/run-electron-vite-dev.mjs index 408206b98..c3ac1b049 100644 --- a/config/scripts/run-electron-vite-dev.mjs +++ b/config/scripts/run-electron-vite-dev.mjs @@ -23,9 +23,15 @@ function getDevUserDataPath() { return path.join(process.env.HOME ?? '', 'Library', 'Application Support', 'orca-dev') } if (process.platform === 'win32') { - return path.join(process.env.APPDATA ?? path.join(process.env.USERPROFILE ?? '', 'AppData', 'Roaming'), 'orca-dev') + return path.join( + process.env.APPDATA ?? path.join(process.env.USERPROFILE ?? '', 'AppData', 'Roaming'), + 'orca-dev' + ) } - return path.join(process.env.XDG_CONFIG_HOME ?? path.join(process.env.HOME ?? '', '.config'), 'orca-dev') + return path.join( + process.env.XDG_CONFIG_HOME ?? path.join(process.env.HOME ?? '', '.config'), + 'orca-dev' + ) } function prepareDevCliWrapper() { @@ -33,18 +39,19 @@ function prepareDevCliWrapper() { mkdirSync(binDir, { recursive: true }) const userDataPath = getDevUserDataPath() const cliPath = path.join(repoRoot, 'out', 'cli', 'index.js') + const electronBin = getElectronExecutable() if (process.platform === 'win32') { writeFileSync( path.join(binDir, 'orca-dev.cmd'), - `@echo off\r\nset "ORCA_USER_DATA_PATH=${userDataPath}"\r\nnode "${cliPath}" %*\r\n`, + `@echo off\r\nset "ORCA_USER_DATA_PATH=${userDataPath}"\r\nset "ORCA_APP_EXECUTABLE=${electronBin}"\r\nset "ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT=1"\r\nnode "${cliPath}" %*\r\n`, 'utf8' ) } else { const wrapperPath = path.join(binDir, 'orca-dev') writeFileSync( wrapperPath, - `#!/usr/bin/env bash\nexport ORCA_USER_DATA_PATH=${JSON.stringify(userDataPath)}\nexec node ${JSON.stringify(cliPath)} "$@"\n`, + `#!/usr/bin/env bash\nexport ORCA_USER_DATA_PATH=${JSON.stringify(userDataPath)}\nexport ORCA_APP_EXECUTABLE=${JSON.stringify(electronBin)}\nexport ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT=1\nexec node ${JSON.stringify(cliPath)} "$@"\n`, 'utf8' ) chmodSync(wrapperPath, 0o755) @@ -54,6 +61,13 @@ function prepareDevCliWrapper() { console.log(`[orca-dev] Prepared wrapper in ${binDir}`) } +function getElectronExecutable() { + if (process.platform === 'win32') { + return path.join(repoRoot, 'node_modules', 'electron', 'dist', 'electron.exe') + } + return path.join(repoRoot, 'node_modules', '.bin', 'electron') +} + if (process.env.ORCA_SKIP_DEV_CLI_PREPARE !== '1') { prepareDevCliWrapper() } @@ -109,7 +123,10 @@ function parseDebugPortEnv(raw) { // space-separated form. `--remote-debugging-pipe` opts into pipe-based // debugging — don't fight the user's choice by injecting a port. const userPassedPort = forwardedRaw.some( - (a) => a === '--remote-debugging-port' || a.startsWith('--remote-debugging-port=') || a === '--remote-debugging-pipe' + (a) => + a === '--remote-debugging-port' || + a.startsWith('--remote-debugging-port=') || + a === '--remote-debugging-pipe' ) // Why: --help/--version exit immediately; binding a probe socket and printing // a debug-port line would be noise. @@ -136,7 +153,9 @@ if (!userPassedPort && !isHelpOrVersion) { // resolve to ::1 on IPv6-first hosts). console.error(`[orca-dev] Remote debugging on http://127.0.0.1:${port}`) } else { - console.error('[orca-dev] No free debug port found in sweep; starting without --remote-debugging-port.') + console.error( + '[orca-dev] No free debug port found in sweep; starting without --remote-debugging-port.' + ) } } const forwardedArgs = ['dev', ...forwardedRaw, ...forwardedExtras] diff --git a/config/scripts/verify-web-build.mjs b/config/scripts/verify-web-build.mjs new file mode 100644 index 000000000..cf700129a --- /dev/null +++ b/config/scripts/verify-web-build.mjs @@ -0,0 +1,14 @@ +import { readFile } from 'fs/promises' +import { resolve } from 'path' + +const indexPath = resolve('out/web/web-index.html') +const html = await readFile(indexPath, 'utf8') + +const absoluteAssetReference = /\b(?:src|href)=["']\/assets\//.exec(html) + +if (absoluteAssetReference) { + console.error( + `Web build must use relative asset URLs for reverse-proxy pairing URLs; found ${absoluteAssetReference[0]} in ${indexPath}` + ) + process.exit(1) +} diff --git a/package.json b/package.json index 2c9c6ea5f..18ce227e8 100644 --- a/package.json +++ b/package.json @@ -27,14 +27,16 @@ "typecheck": "tsc --noEmit -p config/tsconfig.node.json --composite false && tsc --noEmit -p config/tsconfig.cli.json --composite false && tsc --noEmit -p config/tsconfig.web.json --composite false", "start": "electron-vite preview", "dev": "node config/scripts/run-electron-vite-dev.mjs", + "dev:web": "vite --config vite.web.config.ts --host 127.0.0.1", "build:relay": "node config/scripts/build-relay.mjs", "build:computer-macos": "node config/scripts/build-computer-macos.mjs", "smoke:computer": "node config/scripts/computer-use-smoke.mjs", "verify:computer-native": "node config/scripts/verify-computer-native.mjs", "build:cli": "tsc -p config/tsconfig.cli.json --outDir out --composite false --incremental false && node config/scripts/install-dev-cli.mjs", "build:electron-vite": "node config/scripts/run-electron-vite-build.mjs", - "build": "pnpm run typecheck && pnpm run build:relay && pnpm run build:computer-macos && pnpm run build:electron-vite && pnpm run build:cli", - "build:release": "pnpm run build:relay && pnpm run build:computer-macos && pnpm run verify:computer-native && pnpm run build:electron-vite && pnpm run build:cli", + "build:web": "vite build --config vite.web.config.ts && node config/scripts/verify-web-build.mjs", + "build": "pnpm run typecheck && pnpm run build:relay && pnpm run build:computer-macos && pnpm run build:electron-vite && pnpm run build:web && pnpm run build:cli", + "build:release": "pnpm run build:relay && pnpm run build:computer-macos && pnpm run verify:computer-native && pnpm run build:electron-vite && pnpm run build:web && pnpm run build:cli", "postinstall": "pnpm rebuild electron && node config/scripts/rebuild-native-deps.mjs", "rebuild:electron": "node config/scripts/rebuild-native-deps.mjs", "build:unpack": "pnpm run build && electron-builder --config config/electron-builder.config.cjs --dir", diff --git a/src/cli/runtime/launch.test.ts b/src/cli/runtime/launch.test.ts index 807df9dc7..c3cf5b306 100644 --- a/src/cli/runtime/launch.test.ts +++ b/src/cli/runtime/launch.test.ts @@ -19,6 +19,7 @@ describe('serveOrcaApp', () => { afterEach(() => { delete process.env.ORCA_APP_EXECUTABLE + delete process.env.ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT }) it('pins the Electron child cwd to the app root instead of the caller cwd', async () => { @@ -85,4 +86,64 @@ describe('serveOrcaApp', () => { }) ) }) + + it('passes the app root before serve flags for dev Electron executables', async () => { + process.env.ORCA_APP_EXECUTABLE = '/repo/node_modules/.bin/electron' + process.env.ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT = '1' + const child = { + kill: vi.fn(), + once: vi.fn( + (event: string, handler: (code: number | null, signal: string | null) => void) => { + if (event === 'exit') { + queueMicrotask(() => handler(0, null)) + } + return child + } + ) + } + spawnMock.mockReturnValue(child) + + await expect(serveOrcaApp({ json: true, port: '6768' })).resolves.toBe(0) + + expect(spawnMock).toHaveBeenCalledWith( + '/repo/node_modules/.bin/electron', + [resolve(__dirname, '../../..'), '--serve', '--serve-json', '--serve-port', '6768'], + expect.objectContaining({ + cwd: resolve(__dirname, '../../..') + }) + ) + }) + + it('uses a shell when a Windows npm command shim is the Electron executable', async () => { + const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + process.env.ORCA_APP_EXECUTABLE = 'C:\\repo\\node_modules\\.bin\\electron.cmd' + const child = { + kill: vi.fn(), + once: vi.fn( + (event: string, handler: (code: number | null, signal: string | null) => void) => { + if (event === 'exit') { + queueMicrotask(() => handler(0, null)) + } + return child + } + ) + } + spawnMock.mockReturnValue(child) + + try { + await expect(serveOrcaApp({ json: true })).resolves.toBe(0) + expect(spawnMock).toHaveBeenCalledWith( + 'C:\\repo\\node_modules\\.bin\\electron.cmd', + ['--serve', '--serve-json'], + expect.objectContaining({ + shell: true + }) + ) + } finally { + if (platformDescriptor) { + Object.defineProperty(process, 'platform', platformDescriptor) + } + } + }) }) diff --git a/src/cli/runtime/launch.ts b/src/cli/runtime/launch.ts index 71de31117..6a7058c98 100644 --- a/src/cli/runtime/launch.ts +++ b/src/cli/runtime/launch.ts @@ -1,4 +1,4 @@ -import { spawn as spawnProcess } from 'child_process' +import { spawn as spawnProcess, type SpawnOptions } from 'child_process' import { dirname, resolve } from 'path' import { RuntimeClientError } from './types' @@ -15,9 +15,10 @@ export function launchOrcaApp(): void { const overrideExecutable = process.env.ORCA_APP_EXECUTABLE if (typeof overrideExecutable === 'string' && overrideExecutable.trim().length > 0) { - spawnProcess(overrideExecutable, [], { + spawnProcess(overrideExecutable, getExecutableAppArgs(), { detached: true, stdio: 'ignore', + ...getExecutableSpawnOptions(overrideExecutable), env: stripElectronRunAsNode(process.env) }).unref() return @@ -63,7 +64,7 @@ export function serveOrcaApp( } = {} ): Promise { const executable = resolveForegroundOrcaExecutable() - const childArgs = ['--serve'] + const childArgs = [...getExecutableAppArgs(), '--serve'] if (args.json) { childArgs.push('--serve-json') } @@ -83,6 +84,7 @@ export function serveOrcaApp( const child = spawnProcess(executable, childArgs, { cwd: resolveAppRoot(), stdio: 'inherit', + ...getExecutableSpawnOptions(executable), env: stripElectronRunAsNode(process.env) }) @@ -119,6 +121,14 @@ export function serveOrcaApp( }) } +function getExecutableAppArgs(): string[] { + return process.env.ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT === '1' ? [resolveAppRoot()] : [] +} + +function getExecutableSpawnOptions(executable: string): Pick { + return process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(executable) ? { shell: true } : {} +} + function resolveAppRoot(): string { // Why: dev-mode resource resolution in the Electron child may consult // process.cwd(). Pin it to the app root so `orca serve` behaves the same diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts index f8f6d8ffb..afbb9dcd9 100644 --- a/src/cli/specs/core.ts +++ b/src/cli/specs/core.ts @@ -18,7 +18,8 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ notes: [ 'Runs in the foreground and prints the runtime endpoint. Stop it with Ctrl+C.', 'Use --pairing-address when clients should connect through a LAN, Tailscale, SSH-forward, or public tunnel address.', - 'Use --mobile-pairing to print a mobile-scoped pairing QR/link instead of the default runtime-environment pairing link.' + 'Use --mobile-pairing to print a mobile-scoped pairing QR/link instead of the default runtime-environment pairing link.', + 'When the web client bundle is available, the server also prints a browser URL with the pairing data embedded.' ], examples: [ 'orca serve', diff --git a/src/main/index.ts b/src/main/index.ts index d16fdb2f1..7da6e4fa7 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -3,6 +3,8 @@ startup. Splitting by line count would fragment tightly coupled startup logic across files without a cleaner ownership seam. */ import { grantDirAcl } from './win32-utils' +import { existsSync } from 'fs' +import { join } from 'path' import { app, BrowserWindow, nativeImage, nativeTheme } from 'electron' import { electronApp, is } from '@electron-toolkit/utils' import * as QRCode from 'qrcode' @@ -449,6 +451,11 @@ function getServeOptions(argv = process.argv): ServeOptions { } } +function getBundledWebClientRoot(): string | undefined { + const root = join(app.getAppPath(), 'out', 'web') + return existsSync(join(root, 'web-index.html')) ? root : undefined +} + async function renderTerminalPairingQr(pairingUrl: string): Promise { try { return await QRCode.toString(pairingUrl, { type: 'terminal', small: true }) @@ -488,6 +495,7 @@ async function printServeReady(options: ServeOptions): Promise { url: pairing.pairingUrl, endpoint: pairing.endpoint, deviceId: pairing.deviceId, + webClientUrl: pairing.webClientUrl, scope: options.mobilePairing ? 'mobile' : 'runtime', qr: pairingQr } @@ -498,6 +506,9 @@ async function printServeReady(options: ServeOptions): Promise { } console.log(`Orca server ready: ${endpoint ?? 'websocket unavailable'}`) if (pairing.available) { + if (pairing.webClientUrl) { + console.log(`Web client URL: ${pairing.webClientUrl}`) + } if (options.mobilePairing && pairingQr) { console.log(`Mobile pairing QR:\n${pairingQr}`) } @@ -760,7 +771,8 @@ app.whenReady().then(async () => { enableWebSocket: true, ...(isE2E ? { wsPort: 0 } : {}), ...(devWsPort !== undefined ? { wsPort: devWsPort } : {}), - ...(serveOptions?.wsPort !== undefined ? { wsPort: serveOptions.wsPort } : {}) + ...(serveOptions?.wsPort !== undefined ? { wsPort: serveOptions.wsPort } : {}), + webClientRoot: getBundledWebClientRoot() }) registerMobileHandlers(runtimeRpc) diff --git a/src/main/ipc/mobile.test.ts b/src/main/ipc/mobile.test.ts index 5fb11e0b6..585b8aaf1 100644 --- a/src/main/ipc/mobile.test.ts +++ b/src/main/ipc/mobile.test.ts @@ -69,4 +69,37 @@ describe('registerMobileHandlers', () => { ] }) }) + + it('generates runtime-scoped pairing urls for web and desktop clients', async () => { + const createPairingOffer = vi.fn().mockReturnValue({ + available: true, + pairingUrl: 'orca://pair#runtime', + webClientUrl: 'http://100.64.1.20:6768/web-index.html?pairing=runtime', + endpoint: 'ws://100.64.1.20:6768', + deviceId: 'runtime-1' + }) + const rpcServer = { createPairingOffer } + + registerMobileHandlers(rpcServer as never) + + await expect( + handlers.get('mobile:getRuntimePairingUrl')?.(null, { + address: '100.64.1.20', + rotate: true + }) + ).resolves.toEqual({ + available: true, + pairingUrl: 'orca://pair#runtime', + webClientUrl: 'http://100.64.1.20:6768/web-index.html?pairing=runtime', + endpoint: 'ws://100.64.1.20:6768', + deviceId: 'runtime-1' + }) + + expect(createPairingOffer).toHaveBeenCalledWith({ + address: '100.64.1.20', + rotate: true, + name: expect.stringMatching(/^Runtime /), + scope: 'runtime' + }) + }) }) diff --git a/src/main/ipc/mobile.ts b/src/main/ipc/mobile.ts index 110f16d26..fc0315846 100644 --- a/src/main/ipc/mobile.ts +++ b/src/main/ipc/mobile.ts @@ -86,6 +86,36 @@ export function registerMobileHandlers(rpcServer: OrcaRuntimeRpcServer): void { } ) + ipcMain.handle( + 'mobile:getRuntimePairingUrl', + async (_event, args?: { address?: string; rotate?: boolean }) => { + const ip = args?.address ?? getLanAddress() + if (!ip) { + return { available: false as const } + } + + // Why: web/desktop runtime clients need full runtime access, not the + // mobile allowlist used by phone QR pairing. + const offer = rpcServer.createPairingOffer({ + address: ip, + rotate: args?.rotate, + name: `Runtime ${new Date().toLocaleDateString()}`, + scope: 'runtime' + }) + if (!offer.available) { + return { available: false as const } + } + + return { + available: true as const, + pairingUrl: offer.pairingUrl, + webClientUrl: offer.webClientUrl, + endpoint: offer.endpoint, + deviceId: offer.deviceId + } + } + ) + ipcMain.handle('mobile:listDevices', () => { const registry = rpcServer.getDeviceRegistry() if (!registry) { diff --git a/src/main/ipc/preflight.ts b/src/main/ipc/preflight.ts index 865c6d334..db3248091 100644 --- a/src/main/ipc/preflight.ts +++ b/src/main/ipc/preflight.ts @@ -114,6 +114,17 @@ export async function refreshShellPathAndDetectAgents(): Promise { + const mux = getActiveMultiplexer(args.connectionId) + if (!mux || mux.isDisposed()) { + throw new Error(`No active SSH connection for "${args.connectionId}"`) + } + const result = (await mux.request('preflight.detectAgents', { + commands: KNOWN_AGENT_COMMANDS + })) as { agents: string[] } + return result.agents +} + async function isGhAuthenticated(): Promise { try { await execFileAsync('gh', ['auth', 'status'], { @@ -199,14 +210,7 @@ export function registerPreflightHandlers(): void { ipcMain.handle( 'preflight:detectRemoteAgents', async (_event, args: { connectionId: string }): Promise => { - const mux = getActiveMultiplexer(args.connectionId) - if (!mux || mux.isDisposed()) { - throw new Error(`No active SSH connection for "${args.connectionId}"`) - } - const result = (await mux.request('preflight.detectAgents', { - commands: KNOWN_AGENT_COMMANDS - })) as { agents: string[] } - return result.agents + return detectRemoteAgents(args) } ) } diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 00767acf3..9f0277b35 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -137,6 +137,7 @@ import { import { clearProjectItemFieldValue, getProjectViewTable, + getWorkItemDetailsBySlug, listAccessibleProjects, listProjectViews, resolveProjectRef, @@ -158,6 +159,7 @@ import type { ListIssueTypesBySlugArgs, ListLabelsBySlugArgs, ListProjectViewsArgs, + ProjectWorkItemDetailsBySlugArgs, ResolveProjectRefArgs, AddIssueCommentBySlugArgs, DeleteIssueCommentBySlugArgs, @@ -4655,6 +4657,12 @@ export class OrcaRuntimeService { return getProjectViewTable(args) } + async getGitHubProjectWorkItemDetailsBySlug( + args: ProjectWorkItemDetailsBySlugArgs + ): Promise>> { + return getWorkItemDetailsBySlug(args) + } + async updateGitHubProjectItemField( args: UpdateProjectItemFieldArgs ): Promise>> { diff --git a/src/main/runtime/rpc/methods/github.test.ts b/src/main/runtime/rpc/methods/github.test.ts index bcd322350..cff285234 100644 --- a/src/main/runtime/rpc/methods/github.test.ts +++ b/src/main/runtime/rpc/methods/github.test.ts @@ -467,6 +467,37 @@ describe('github RPC methods', () => { expect(response).toMatchObject({ ok: true, result: { ok: true, data: { rows: [] } } }) }) + it('fetches GitHub project work item details by slug on the runtime server', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + getGitHubProjectWorkItemDetailsBySlug: vi.fn().mockResolvedValue({ + ok: true, + item: { number: 9, title: 'Bug' } + }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: GITHUB_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('github.project.workItemDetailsBySlug', { + owner: 'acme', + repo: 'orca', + number: 9, + type: 'issue' + }) + ) + + expect(runtime.getGitHubProjectWorkItemDetailsBySlug).toHaveBeenCalledWith({ + owner: 'acme', + repo: 'orca', + number: 9, + type: 'issue' + }) + expect(response).toMatchObject({ + ok: true, + result: { ok: true, item: { number: 9, title: 'Bug' } } + }) + }) + it('updates GitHub project item fields on the runtime server', async () => { const runtime = { getRuntimeId: () => 'test-runtime', diff --git a/src/main/runtime/rpc/methods/github.ts b/src/main/runtime/rpc/methods/github.ts index 72b32e6cd..137a1d9f6 100644 --- a/src/main/runtime/rpc/methods/github.ts +++ b/src/main/runtime/rpc/methods/github.ts @@ -142,6 +142,11 @@ const ProjectViewTable = z.object({ queryOverride: OptionalString }) +const ProjectWorkItemDetailsBySlug = SlugRepo.extend({ + number: z.number().int().positive(), + type: z.enum(['issue', 'pr']) +}) + const ProjectRef = z.object({ input: requiredString('Missing project reference') }) @@ -399,6 +404,11 @@ export const GITHUB_METHODS: RpcMethod[] = [ params: ProjectViewTable, handler: async (params, { runtime }) => runtime.getGitHubProjectViewTable(params) }), + defineMethod({ + name: 'github.project.workItemDetailsBySlug', + params: ProjectWorkItemDetailsBySlug, + handler: async (params, { runtime }) => runtime.getGitHubProjectWorkItemDetailsBySlug(params) + }), defineMethod({ name: 'github.project.updateItemField', params: ProjectItemField, diff --git a/src/main/runtime/rpc/methods/index.ts b/src/main/runtime/rpc/methods/index.ts index 9cbc55d34..868a3b503 100644 --- a/src/main/runtime/rpc/methods/index.ts +++ b/src/main/runtime/rpc/methods/index.ts @@ -9,6 +9,7 @@ import { ORCHESTRATION_METHODS } from './orchestration' import { NOTIFICATION_METHODS } from './notifications' import { STATS_METHODS } from './stats' import { ACCOUNT_METHODS } from './accounts' +import { PREFLIGHT_METHODS } from './preflight' import { COMPUTER_METHODS } from './computer' import { SESSION_TAB_METHODS } from './session-tabs' import { FILE_METHODS } from './files' @@ -33,6 +34,7 @@ export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [ ...NOTIFICATION_METHODS, ...STATS_METHODS, ...ACCOUNT_METHODS, + ...PREFLIGHT_METHODS, ...COMPUTER_METHODS, ...SESSION_TAB_METHODS, ...FILE_METHODS, diff --git a/src/main/runtime/rpc/methods/preflight.test.ts b/src/main/runtime/rpc/methods/preflight.test.ts new file mode 100644 index 000000000..51a1231ca --- /dev/null +++ b/src/main/runtime/rpc/methods/preflight.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from '../dispatcher' +import type { RpcRequest } from '../core' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { PREFLIGHT_METHODS } from './preflight' + +const { + detectInstalledAgentsMock, + detectRemoteAgentsMock, + refreshShellPathAndDetectAgentsMock, + runPreflightCheckMock +} = vi.hoisted(() => ({ + detectInstalledAgentsMock: vi.fn(), + detectRemoteAgentsMock: vi.fn(), + refreshShellPathAndDetectAgentsMock: vi.fn(), + runPreflightCheckMock: vi.fn() +})) + +vi.mock('../../../ipc/preflight', () => ({ + detectInstalledAgents: detectInstalledAgentsMock, + detectRemoteAgents: detectRemoteAgentsMock, + refreshShellPathAndDetectAgents: refreshShellPathAndDetectAgentsMock, + runPreflightCheck: runPreflightCheckMock +})) + +function makeRequest(method: string, params?: unknown): RpcRequest { + return { id: 'req-1', authToken: 'tok', method, params } +} + +describe('preflight RPC methods', () => { + it('runs the server-side preflight check through runtime RPC', async () => { + const status = { + git: { installed: true }, + gh: { installed: true, authenticated: true }, + glab: { installed: false, authenticated: false }, + bitbucket: { configured: false, authenticated: false, account: null } + } + runPreflightCheckMock.mockResolvedValueOnce(status) + const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: PREFLIGHT_METHODS }) + + const response = await dispatcher.dispatch(makeRequest('preflight.check', { force: true })) + + expect(runPreflightCheckMock).toHaveBeenCalledWith(true) + expect(response).toMatchObject({ ok: true, result: status }) + }) + + it('detects agents and refreshes PATH on the server through runtime RPC', async () => { + detectInstalledAgentsMock.mockResolvedValueOnce(['codex']) + refreshShellPathAndDetectAgentsMock.mockResolvedValueOnce({ + agents: ['codex', 'claude'], + addedPathSegments: ['/opt/bin'], + shellHydrationOk: true, + pathSource: 'shell_hydrate', + pathFailureReason: 'none' + }) + const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: PREFLIGHT_METHODS }) + + const detected = await dispatcher.dispatch(makeRequest('preflight.detectAgents')) + const refreshed = await dispatcher.dispatch(makeRequest('preflight.refreshAgents')) + + expect(detectInstalledAgentsMock).toHaveBeenCalled() + expect(refreshShellPathAndDetectAgentsMock).toHaveBeenCalled() + expect(detected).toMatchObject({ ok: true, result: ['codex'] }) + expect(refreshed).toMatchObject({ + ok: true, + result: { agents: ['codex', 'claude'], shellHydrationOk: true } + }) + }) + + it('detects agents on remote SSH connections through runtime RPC', async () => { + detectRemoteAgentsMock.mockResolvedValueOnce(['claude']) + const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: PREFLIGHT_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('preflight.detectRemoteAgents', { connectionId: 'ssh-1' }) + ) + + expect(detectRemoteAgentsMock).toHaveBeenCalledWith({ connectionId: 'ssh-1' }) + expect(response).toMatchObject({ ok: true, result: ['claude'] }) + }) +}) diff --git a/src/main/runtime/rpc/methods/preflight.ts b/src/main/runtime/rpc/methods/preflight.ts new file mode 100644 index 000000000..720a823cc --- /dev/null +++ b/src/main/runtime/rpc/methods/preflight.ts @@ -0,0 +1,38 @@ +import { z } from 'zod' +import { defineMethod, type RpcMethod } from '../core' +import { + detectRemoteAgents, + detectInstalledAgents, + refreshShellPathAndDetectAgents, + runPreflightCheck +} from '../../../ipc/preflight' + +const PreflightCheck = z.object({ + force: z.boolean().optional() +}) +const PreflightDetectRemoteAgents = z.object({ + connectionId: z.string().min(1) +}) + +export const PREFLIGHT_METHODS: RpcMethod[] = [ + defineMethod({ + name: 'preflight.check', + params: PreflightCheck, + handler: async (params) => runPreflightCheck(params.force) + }), + defineMethod({ + name: 'preflight.detectAgents', + params: null, + handler: async () => detectInstalledAgents() + }), + defineMethod({ + name: 'preflight.detectRemoteAgents', + params: PreflightDetectRemoteAgents, + handler: async (params) => detectRemoteAgents(params) + }), + defineMethod({ + name: 'preflight.refreshAgents', + params: null, + handler: async () => refreshShellPathAndDetectAgents() + }) +] diff --git a/src/main/runtime/rpc/static-web-client-handler.ts b/src/main/runtime/rpc/static-web-client-handler.ts new file mode 100644 index 000000000..650df1be7 --- /dev/null +++ b/src/main/runtime/rpc/static-web-client-handler.ts @@ -0,0 +1,139 @@ +import { createReadStream } from 'fs' +import { stat } from 'fs/promises' +import type { IncomingMessage, RequestListener, ServerResponse } from 'http' +import { extname, isAbsolute, posix, relative, resolve } from 'path' + +const STATIC_WEB_ALLOWED_PATHS = new Set(['/web-index.html']) +const STATIC_WEB_ALLOWED_PREFIXES = ['/assets/'] +const STATIC_WEB_CONTENT_TYPES = new Map([ + ['.css', 'text/css; charset=utf-8'], + ['.html', 'text/html; charset=utf-8'], + ['.js', 'text/javascript; charset=utf-8'], + ['.json', 'application/json; charset=utf-8'], + ['.png', 'image/png'], + ['.svg', 'image/svg+xml; charset=utf-8'], + ['.wasm', 'application/wasm'], + ['.webp', 'image/webp'], + ['.woff2', 'font/woff2'] +]) + +export function createStaticWebClientHandler(staticRoot: string): RequestListener { + const resolvedRoot = resolve(staticRoot) + return (request, response) => { + void handleStaticRequest(resolvedRoot, request, response) + } +} + +async function handleStaticRequest( + staticRoot: string, + request: IncomingMessage, + response: ServerResponse +): Promise { + if (request.method !== 'GET' && request.method !== 'HEAD') { + response.setHeader('Allow', 'GET, HEAD') + writeHttpStatus(response, 405) + return + } + + const pathname = parseStaticPathname(request.url) + if (!pathname) { + writeHttpStatus(response, 400) + return + } + if (!isAllowedStaticWebPath(pathname)) { + writeHttpStatus(response, 404) + return + } + + const absolutePath = resolve(staticRoot, pathname.slice(1)) + const relativePath = relative(staticRoot, absolutePath) + if (relativePath === '' || relativePath.startsWith('..') || isAbsolute(relativePath)) { + writeHttpStatus(response, 404) + return + } + + let fileStat + try { + fileStat = await stat(absolutePath) + } catch { + writeHttpStatus(response, 404) + return + } + if (!fileStat.isFile()) { + writeHttpStatus(response, 404) + return + } + + response.statusCode = 200 + response.setHeader( + 'Content-Type', + STATIC_WEB_CONTENT_TYPES.get(extname(absolutePath)) ?? 'application/octet-stream' + ) + response.setHeader('Content-Length', fileStat.size) + response.setHeader( + 'Cache-Control', + pathname.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache' + ) + if (request.method === 'HEAD') { + response.end() + return + } + + const stream = createReadStream(absolutePath) + stream.on('error', () => { + if (!response.headersSent) { + writeHttpStatus(response, 500) + return + } + response.destroy() + }) + stream.pipe(response) +} + +function parseStaticPathname(rawUrl: string | undefined): string | null { + if (!rawUrl) { + return '/web-index.html' + } + let pathname: string + try { + pathname = decodeURIComponent(new URL(rawUrl, 'http://127.0.0.1').pathname) + } catch { + return null + } + if (pathname === '/' || pathname === '/index.html') { + return '/web-index.html' + } + if (pathname.includes('\0') || pathname.includes('\\') || pathname.split('/').includes('..')) { + return null + } + if (posix.normalize(pathname) !== pathname) { + return null + } + return mapProxyPrefixedStaticPathname(pathname) +} + +function mapProxyPrefixedStaticPathname(pathname: string): string { + if (pathname === '/web-index.html' || pathname.endsWith('/web-index.html')) { + return '/web-index.html' + } + const assetMarker = '/assets/' + const assetIndex = pathname.indexOf(assetMarker) + if (assetIndex !== -1) { + // Why: reverse proxies may forward the external path prefix through to + // Orca. Only the bundled /assets subtree is served after the prefix. + return pathname.slice(assetIndex) + } + return pathname +} + +function isAllowedStaticWebPath(pathname: string): boolean { + return ( + STATIC_WEB_ALLOWED_PATHS.has(pathname) || + STATIC_WEB_ALLOWED_PREFIXES.some((prefix) => pathname.startsWith(prefix)) + ) +} + +function writeHttpStatus(response: ServerResponse, statusCode: number): void { + response.statusCode = statusCode + response.end() +} diff --git a/src/main/runtime/rpc/ws-transport-static-web.test.ts b/src/main/runtime/rpc/ws-transport-static-web.test.ts new file mode 100644 index 000000000..ed321b5c0 --- /dev/null +++ b/src/main/runtime/rpc/ws-transport-static-web.test.ts @@ -0,0 +1,91 @@ +import { mkdirSync, mkdtempSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterEach, describe, expect, it } from 'vitest' +import { WebSocketTransport } from './ws-transport' + +describe('WebSocketTransport static web client', () => { + const transports: WebSocketTransport[] = [] + + afterEach(async () => { + await Promise.all(transports.map((t) => t.stop().catch(() => {}))) + transports.length = 0 + }) + + function createStaticTransport(staticRoot: string): WebSocketTransport { + const transport = new WebSocketTransport({ + host: '127.0.0.1', + port: 0, + staticRoot + }) + transports.push(transport) + return transport + } + + it('serves the built web client from the same server', async () => { + const staticRoot = mkdtempSync(join(tmpdir(), 'ws-transport-static-')) + mkdirSync(join(staticRoot, 'assets')) + writeFileSync(join(staticRoot, 'web-index.html'), 'web') + writeFileSync(join(staticRoot, 'assets', 'app.js'), 'console.log("web")') + const transport = createStaticTransport(staticRoot) + + await transport.start() + + const indexResponse = await fetch(`http://127.0.0.1:${transport.resolvedPort}/web-index.html`) + expect(indexResponse.status).toBe(200) + expect(indexResponse.headers.get('content-type')).toContain('text/html') + await expect(indexResponse.text()).resolves.toBe('web') + + const assetResponse = await fetch(`http://127.0.0.1:${transport.resolvedPort}/assets/app.js`) + expect(assetResponse.status).toBe(200) + expect(assetResponse.headers.get('cache-control')).toContain('immutable') + await expect(assetResponse.text()).resolves.toBe('console.log("web")') + }) + + it('serves web assets when a reverse-proxy path prefix is forwarded', async () => { + const staticRoot = mkdtempSync(join(tmpdir(), 'ws-transport-static-')) + mkdirSync(join(staticRoot, 'assets')) + writeFileSync(join(staticRoot, 'web-index.html'), '') + writeFileSync(join(staticRoot, 'assets', 'app.js'), 'console.log("prefixed")') + const transport = createStaticTransport(staticRoot) + + await transport.start() + + const indexResponse = await fetch( + `http://127.0.0.1:${transport.resolvedPort}/orca/web-index.html` + ) + expect(indexResponse.status).toBe(200) + await expect(indexResponse.text()).resolves.toBe('') + + const assetResponse = await fetch( + `http://127.0.0.1:${transport.resolvedPort}/orca/assets/app.js` + ) + expect(assetResponse.status).toBe(200) + await expect(assetResponse.text()).resolves.toBe('console.log("prefixed")') + }) + + it('does not expose arbitrary files from the static root', async () => { + const staticRoot = mkdtempSync(join(tmpdir(), 'ws-transport-static-')) + writeFileSync(join(staticRoot, 'package.json'), '{}') + const transport = createStaticTransport(staticRoot) + + await transport.start() + + const response = await fetch(`http://127.0.0.1:${transport.resolvedPort}/package.json`) + expect(response.status).toBe(404) + }) + + it('rejects encoded Windows separators in static paths', async () => { + const staticRoot = mkdtempSync(join(tmpdir(), 'ws-transport-static-')) + mkdirSync(join(staticRoot, 'assets')) + writeFileSync(join(staticRoot, 'package.json'), '{}') + const transport = createStaticTransport(staticRoot) + + await transport.start() + + const response = await fetch( + `http://127.0.0.1:${transport.resolvedPort}/assets/..%5Cpackage.json` + ) + expect(response.status).toBe(400) + }) +}) diff --git a/src/main/runtime/rpc/ws-transport.test.ts b/src/main/runtime/rpc/ws-transport.test.ts index 2f3bcf6bd..72af8f185 100644 --- a/src/main/runtime/rpc/ws-transport.test.ts +++ b/src/main/runtime/rpc/ws-transport.test.ts @@ -1,3 +1,6 @@ +/* eslint-disable max-lines -- Why: these tests exercise one stateful transport + boundary across connection lifecycle, heartbeat, pre-auth timeout, and + shutdown behavior; splitting the setup would obscure the shared invariants. */ import { mkdtempSync } from 'fs' import { tmpdir } from 'os' import { join } from 'path' diff --git a/src/main/runtime/rpc/ws-transport.ts b/src/main/runtime/rpc/ws-transport.ts index 028c3f379..07ccc0952 100644 --- a/src/main/runtime/rpc/ws-transport.ts +++ b/src/main/runtime/rpc/ws-transport.ts @@ -1,3 +1,6 @@ +/* eslint-disable max-lines -- Why: the WebSocket transport owns connection + admission, heartbeat, pre-auth timeout, and client-id cleanup together; those + invariants are easier to audit in one transport boundary. */ // Why: the WebSocket transport enables mobile clients to connect to the Orca // runtime over the local network. When TLS cert/key are provided it uses wss:// // to prevent passive sniffing; otherwise it falls back to plain ws://. Per-device @@ -7,6 +10,7 @@ import { createServer as createHttpsServer, type Server as HttpsServer } from 'h import { createServer as createHttpServer, type Server as HttpServer } from 'http' import { WebSocketServer, type WebSocket } from 'ws' import type { RpcTransport } from './transport' +import { createStaticWebClientHandler } from './static-web-client-handler' const MAX_WS_MESSAGE_BYTES = 1024 * 1024 const MAX_WS_CONNECTIONS = 32 @@ -41,6 +45,9 @@ export type WebSocketTransportOptions = { heartbeatIntervalMs?: number // Why: test-only override. Production uses PRE_AUTH_TIMEOUT_MS. preAuthTimeoutMs?: number + // Why: the pairing server can also serve the browser client, so users do + // not need a second dev/static server once the web bundle is built. + staticRoot?: string } export class WebSocketTransport implements RpcTransport { @@ -50,6 +57,7 @@ export class WebSocketTransport implements RpcTransport { private readonly tlsKey: string | undefined private readonly heartbeatIntervalMs: number private readonly preAuthTimeoutMs: number + private readonly staticRoot: string | undefined private httpServer: HttpsServer | HttpServer | null = null private wss: WebSocketServer | null = null private heartbeatTimer: ReturnType | null = null @@ -72,7 +80,8 @@ export class WebSocketTransport implements RpcTransport { tlsCert, tlsKey, heartbeatIntervalMs, - preAuthTimeoutMs + preAuthTimeoutMs, + staticRoot }: WebSocketTransportOptions) { this.host = host this.port = port @@ -80,6 +89,7 @@ export class WebSocketTransport implements RpcTransport { this.tlsKey = tlsKey this.heartbeatIntervalMs = heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS this.preAuthTimeoutMs = preAuthTimeoutMs ?? PRE_AUTH_TIMEOUT_MS + this.staticRoot = staticRoot } onMessage(handler: WebSocketMessageHandler): void { @@ -150,9 +160,12 @@ export class WebSocketTransport implements RpcTransport { } private createHttpServer(): HttpServer | HttpsServer { + const requestListener = this.staticRoot + ? createStaticWebClientHandler(this.staticRoot) + : undefined return this.tlsCert && this.tlsKey - ? createHttpsServer({ cert: this.tlsCert, key: this.tlsKey }) - : createHttpServer() + ? createHttpsServer({ cert: this.tlsCert, key: this.tlsKey }, requestListener) + : createHttpServer(requestListener) } // Why: the WebSocketServer is attached only after listen succeeds. If we diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index acbbcdaa9..a67388bf1 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -255,7 +255,8 @@ describe('OrcaRuntimeRpcServer', () => { runtime, userDataPath, enableWebSocket: true, - wsPort: 0 + wsPort: 0, + webClientRoot: userDataPath }) await server.start() @@ -274,6 +275,63 @@ describe('OrcaRuntimeRpcServer', () => { await server.stop() }) + it('includes a web client URL when the web bundle is served by the runtime', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + const runtime = new OrcaRuntimeService() + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath, + enableWebSocket: true, + wsPort: 0, + webClientRoot: userDataPath + }) + + await server.start() + + try { + const offer = server.createPairingOffer({ address: '100.64.1.20', name: 'Web test' }) + expect(offer.available).toBe(true) + if (offer.available) { + expect(offer.webClientUrl).toBeTruthy() + const url = new URL(offer.webClientUrl!) + expect(url.protocol).toBe('http:') + expect(url.hostname).toBe('100.64.1.20') + expect(url.pathname).toBe('/web-index.html') + expect(url.search).toBe('') + expect(url.hash).toBe(`#pairing=${encodeURIComponent(offer.pairingUrl)}`) + } + } finally { + await server.stop() + } + }) + + it('preserves proxy path prefixes in web client URLs', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + const runtime = new OrcaRuntimeService() + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath, + enableWebSocket: true, + wsPort: 0, + webClientRoot: userDataPath + }) + + await server.start() + + try { + const offer = server.createPairingOffer({ + address: 'wss://runtime.example.com/orca', + name: 'Proxy test' + }) + expect(offer.available).toBe(true) + if (offer.available) { + expect(offer.webClientUrl).toContain('https://runtime.example.com/orca/web-index.html') + } + } finally { + await server.stop() + } + }) + it('formats pairing-address overrides for IPv6 and host-port tunnel endpoints', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const runtime = new OrcaRuntimeService() @@ -281,7 +339,8 @@ describe('OrcaRuntimeRpcServer', () => { runtime, userDataPath, enableWebSocket: true, - wsPort: 0 + wsPort: 0, + webClientRoot: userDataPath }) await server.start() @@ -323,7 +382,8 @@ describe('OrcaRuntimeRpcServer', () => { runtime, userDataPath, enableWebSocket: true, - wsPort: 0 + wsPort: 0, + webClientRoot: userDataPath }) await server.start() @@ -340,6 +400,7 @@ describe('OrcaRuntimeRpcServer', () => { } expect(server.getDeviceRegistry()?.getDevice(offer.deviceId)?.scope).toBe('mobile') + expect(offer.webClientUrl).toBeNull() const parsed = parsePairingCode(offer.pairingUrl) expect(parsed?.endpoint).toBe(offer.endpoint) expect(parsed?.endpoint).toContain('100.64.1.20') diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index da555f988..f4687e2a9 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -35,6 +35,7 @@ type OrcaRuntimeRpcServerOptions = { platform?: NodeJS.Platform enableWebSocket?: boolean wsPort?: number + webClientRoot?: string // Why: test-only overrides for the two time-bound constants below. // Production callers must not pass these — defaults are set by the design // doc (§3.1) and changing them in production would weaken the admission @@ -98,6 +99,24 @@ function formatWebSocketUrl(url: URL): string { return url.pathname === '/' && !url.search && !url.hash ? formatted.replace(/\/$/, '') : formatted } +function createWebClientUrl(endpoint: string, pairingUrl: string): string { + const url = new URL(endpoint) + url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:' + url.pathname = webClientPathForEndpoint(url.pathname) + url.search = '' + // Why: pairing URLs include full runtime credentials. Keeping them in the + // fragment avoids proxy logs and Referer headers while the web app loads. + url.hash = `pairing=${encodeURIComponent(pairingUrl)}` + return url.toString() +} + +function webClientPathForEndpoint(pathname: string): string { + if (!pathname || pathname === '/') { + return '/web-index.html' + } + return `${pathname.replace(/\/$/, '')}/web-index.html` +} + const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'accounts.list', 'accounts.selectClaude', @@ -165,6 +184,7 @@ export class OrcaRuntimeRpcServer { private readonly platform: NodeJS.Platform private readonly enableWebSocket: boolean private readonly wsPort: number + private readonly webClientRoot: string | undefined private readonly authToken = randomBytes(24).toString('hex') private readonly keepaliveIntervalMs: number private readonly longPollCap: number @@ -197,6 +217,7 @@ export class OrcaRuntimeRpcServer { platform = process.platform, enableWebSocket = false, wsPort = DEFAULT_WS_PORT, + webClientRoot, keepaliveIntervalMs = KEEPALIVE_INTERVAL_MS, longPollCap = LONG_POLL_CAP }: OrcaRuntimeRpcServerOptions) { @@ -207,6 +228,7 @@ export class OrcaRuntimeRpcServer { this.platform = platform this.enableWebSocket = enableWebSocket this.wsPort = wsPort + this.webClientRoot = webClientRoot this.keepaliveIntervalMs = keepaliveIntervalMs this.longPollCap = longPollCap } @@ -248,7 +270,13 @@ export class OrcaRuntimeRpcServer { scope?: DeviceScope }): | { available: false } - | { available: true; pairingUrl: string; endpoint: string; deviceId: string } { + | { + available: true + pairingUrl: string + endpoint: string + deviceId: string + webClientUrl: string | null + } { const rawEndpoint = this.getWebSocketEndpoint() const publicKeyB64 = this.getE2EEPublicKey() if (!rawEndpoint || !this.deviceRegistry || !publicKeyB64) { @@ -267,7 +295,14 @@ export class OrcaRuntimeRpcServer { deviceToken: device.token, publicKeyB64 }) - return { available: true, pairingUrl, endpoint, deviceId: device.deviceId } + return { + available: true, + pairingUrl, + endpoint, + deviceId: device.deviceId, + webClientUrl: + this.webClientRoot && scope === 'runtime' ? createWebClientUrl(endpoint, pairingUrl) : null + } } private registerBinaryStreamHandler( @@ -384,7 +419,8 @@ export class OrcaRuntimeRpcServer { const wsTransport = new WebSocketTransport({ host: '0.0.0.0', - port: this.wsPort + port: this.wsPort, + staticRoot: this.webClientRoot }) this.wsTransport = wsTransport diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 9eb7f202d..cecd0f29d 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1577,6 +1577,16 @@ export type PreloadApi = { deviceId: string } > + getRuntimePairingUrl: (args?: { address?: string; rotate?: boolean }) => Promise< + | { available: false } + | { + available: true + pairingUrl: string + webClientUrl: string | null + endpoint: string + deviceId: string + } + > listDevices: () => Promise<{ devices: { deviceId: string; name: string; pairedAt: number; lastSeenAt: number }[] }> diff --git a/src/preload/index.ts b/src/preload/index.ts index d26874832..d87d80f2e 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -2618,6 +2618,20 @@ const api = { } > => ipcRenderer.invoke('mobile:getPairingQR', args), + getRuntimePairingUrl: (args?: { + address?: string + rotate?: boolean + }): Promise< + | { available: false } + | { + available: true + pairingUrl: string + webClientUrl: string | null + endpoint: string + deviceId: string + } + > => ipcRenderer.invoke('mobile:getRuntimePairingUrl', args), + listDevices: (): Promise<{ devices: { deviceId: string; name: string; pairedAt: number; lastSeenAt: number }[] }> => ipcRenderer.invoke('mobile:listDevices'), diff --git a/src/renderer/src/components/LinearItemDrawer.tsx b/src/renderer/src/components/LinearItemDrawer.tsx index d4aac63d8..38fa89226 100644 --- a/src/renderer/src/components/LinearItemDrawer.tsx +++ b/src/renderer/src/components/LinearItemDrawer.tsx @@ -11,6 +11,7 @@ import { VisuallyHidden } from 'radix-ui' import CommentMarkdown from '@/components/sidebar/CommentMarkdown' import { cn } from '@/lib/utils' import { useAppStore } from '@/store' +import { createBrowserUuid } from '@/lib/browser-uuid' import { useTeamStates, useTeamLabels, @@ -447,7 +448,7 @@ function CommentFooter({ if (typed.ok) { setBody('') onCommentAdded({ - id: typed.id ?? crypto.randomUUID(), + id: typed.id ?? createBrowserUuid(), body: trimmed, createdAt: new Date().toISOString() }) diff --git a/src/renderer/src/components/editor/ipynb-parse.ts b/src/renderer/src/components/editor/ipynb-parse.ts index ffd2692b8..0415c4171 100644 --- a/src/renderer/src/components/editor/ipynb-parse.ts +++ b/src/renderer/src/components/editor/ipynb-parse.ts @@ -1,6 +1,8 @@ /* eslint-disable max-lines -- Why: keeping notebook parse and mutation helpers in one module makes nbformat preservation easier to audit while the notebook editor model is still small. */ +import { createBrowserUuid } from '@/lib/browser-uuid' + export type IpynbCellKind = 'code' | 'markdown' | 'raw' export type IpynbOutput = @@ -288,7 +290,7 @@ export function insertIpynbCell( const cells = root.cells as unknown[] const nextCell: Record = { cell_type: kind, - id: crypto.randomUUID?.() ?? `cell-${Date.now()}`, + id: createBrowserUuid(), metadata: {}, source: [] } @@ -307,7 +309,7 @@ export function deleteIpynbCell(content: string, index: number): string { if (cells.length <= 1) { cells.splice(0, cells.length, { cell_type: 'code', - id: crypto.randomUUID?.() ?? `cell-${Date.now()}`, + id: createBrowserUuid(), metadata: {}, execution_count: null, outputs: [], diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx index a83df7ae6..fa472c63e 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx @@ -17,6 +17,7 @@ import { notifyProjectNotesSelectionChanged } from '@/lib/open-project-notes-tab import { requestProjectNotesTabClose } from '@/lib/project-notes-close-request' import { linkRuntimeProjectNote, showRuntimeProjectNote } from '@/runtime/runtime-notes-client' import { useAppStore } from '@/store' +import { createBrowserUuid } from '@/lib/browser-uuid' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import type { TerminalTab } from '../../../../shared/types' import { FloatingTerminalOrchestrationDialog } from './FloatingTerminalOrchestrationDialog' @@ -237,7 +238,7 @@ export function FloatingTerminalPanel({ notifyProjectNotesSelectionChanged() } } - const id = `floating-project-notes:${globalThis.crypto.randomUUID()}` + const id = `floating-project-notes:${createBrowserUuid()}` setNotesTabs((current) => [...current, { id, label, noteId: noteId ?? null, isDirty: false }]) setActiveNotesTabId(id) setActiveSurface('notes') diff --git a/src/renderer/src/components/settings/CliSection.tsx b/src/renderer/src/components/settings/CliSection.tsx index 496f2bab6..b091665a7 100644 --- a/src/renderer/src/components/settings/CliSection.tsx +++ b/src/renderer/src/components/settings/CliSection.tsx @@ -65,6 +65,7 @@ export function CliSection({ currentPlatform }: CliSectionProps): React.JSX.Elem const isEnabled = status?.state === 'installed' const isSupported = status?.supported ?? false + const isBrowserManaged = status?.unsupportedReason === 'launch_mode_unavailable' const revealLabel = getRevealLabel(currentPlatform) const canRevealCommandPath = status?.commandPath != null && ['installed', 'stale', 'conflict'].includes(status.state) @@ -145,21 +146,23 @@ export function CliSection({ currentPlatform }: CliSectionProps): React.JSX.Elem - + {!isBrowserManaged ? ( + + ) : null} @@ -182,7 +185,7 @@ export function CliSection({ currentPlatform }: CliSectionProps): React.JSX.Elem

) : null} - {!loading && !isSupported && status?.detail ? ( + {!loading && !isSupported && !isBrowserManaged && status?.detail ? (

{status.detail}

) : null} @@ -201,44 +204,46 @@ export function CliSection({ currentPlatform }: CliSectionProps): React.JSX.Elem ) : null} -
-
- -

- Install skills so agents know how to use Orca and report status. -

-
+ {!isBrowserManaged ? ( +
+
+ +

+ Install skills so agents know how to use Orca and report status. +

+
-
-
-

CLI skill

-
- - {ORCA_CLI_SKILL_INSTALL_COMMAND} - - - - - - - - Copy - - - +
+
+

CLI skill

+
+ + {ORCA_CLI_SKILL_INSTALL_COMMAND} + + + + + + + + Copy + + + +
-
+ ) : null}
diff --git a/src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx b/src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx index b6254ba32..bad28dccb 100644 --- a/src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx +++ b/src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx @@ -1,4 +1,7 @@ -import { Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react' +/* eslint-disable max-lines -- Why: the server settings pane keeps active + server selection, saved server mutation, and confirmation dialogs together so + the state transitions stay auditable. */ +import { Loader2, Plus, RefreshCw, Share2, Trash2 } from 'lucide-react' import { useEffect, useState } from 'react' import { toast } from 'sonner' import type { GlobalSettings } from '../../../../shared/types' @@ -8,7 +11,6 @@ import { Input } from '../ui/input' import { Label } from '../ui/label' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select' import { SearchableSetting } from './SearchableSetting' -import type { SettingsSearchEntry } from './settings-search' import { Dialog, DialogContent, @@ -17,33 +19,27 @@ import { DialogHeader, DialogTitle } from '../ui/dialog' +import { RuntimePairingUrlGenerator } from './RuntimePairingUrlGenerator' +import { + RUNTIME_ENVIRONMENTS_SEARCH_ENTRY, + WEB_RUNTIME_ENVIRONMENTS_SEARCH_ENTRY +} from './runtime-environments-search' const LOCAL_RUNTIME_VALUE = '__local__' - -export const RUNTIME_ENVIRONMENTS_SEARCH_ENTRY: SettingsSearchEntry = { - title: 'Active Server', - description: 'Choose local desktop or a saved remote Orca server.', - keywords: [ - 'runtime', - 'environment', - 'server', - 'client', - 'remote', - 'pairing', - 'cloud', - 'vm', - 'dev box' - ] -} +const NO_RUNTIME_VALUE = '__none__' type RuntimeEnvironmentsPaneProps = { settings: GlobalSettings switchRuntimeEnvironment: (environmentId: string | null) => Promise + canGeneratePairingUrl?: boolean + allowLocalRuntime?: boolean } export function RuntimeEnvironmentsPane({ settings, - switchRuntimeEnvironment + switchRuntimeEnvironment, + canGeneratePairingUrl = true, + allowLocalRuntime = true }: RuntimeEnvironmentsPaneProps): React.JSX.Element { const [environments, setEnvironments] = useState([]) const [isLoading, setIsLoading] = useState(false) @@ -52,13 +48,20 @@ export function RuntimeEnvironmentsPane({ const [removingId, setRemovingId] = useState(null) const [pendingSwitchValue, setPendingSwitchValue] = useState(null) const [pendingRemove, setPendingRemove] = useState(null) + const [addServerFormOpen, setAddServerFormOpen] = useState(false) + const [shareServerFormOpen, setShareServerFormOpen] = useState(false) const [switchError, setSwitchError] = useState(null) const [removeError, setRemoveError] = useState(null) const [name, setName] = useState('') const [pairingCode, setPairingCode] = useState('') - const activeValue = settings.activeRuntimeEnvironmentId ?? LOCAL_RUNTIME_VALUE + const activeValue = + settings.activeRuntimeEnvironmentId ?? + (allowLocalRuntime ? LOCAL_RUNTIME_VALUE : NO_RUNTIME_VALUE) const isBusy = isSaving || switchingValue !== null || removingId !== null const removingActiveServer = pendingRemove?.id === settings.activeRuntimeEnvironmentId + const searchEntry = canGeneratePairingUrl + ? RUNTIME_ENVIRONMENTS_SEARCH_ENTRY + : WEB_RUNTIME_ENVIRONMENTS_SEARCH_ENTRY const loadEnvironments = async (): Promise => { setIsLoading(true) @@ -75,6 +78,15 @@ export function RuntimeEnvironmentsPane({ void loadEnvironments() }, []) + const closeAddServerForm = (): void => { + if (isSaving) { + return + } + setAddServerFormOpen(false) + setName('') + setPairingCode('') + } + const addEnvironment = async (): Promise => { const trimmedName = name.trim() const trimmedPairingCode = pairingCode.trim() @@ -91,6 +103,12 @@ export function RuntimeEnvironmentsPane({ } setIsSaving(true) try { + if (!allowLocalRuntime && settings.activeRuntimeEnvironmentId) { + const disconnected = await switchRuntimeEnvironment(null) + if (!disconnected) { + return + } + } const result = await window.api.runtimeEnvironments.addFromPairingCode({ name: trimmedName, pairingCode: trimmedPairingCode @@ -98,7 +116,18 @@ export function RuntimeEnvironmentsPane({ setName('') setPairingCode('') await loadEnvironments() - toast.success(`Saved ${result.environment.name}. Use Active Server to switch when ready.`) + if (!allowLocalRuntime) { + const switched = await switchRuntimeEnvironment(result.environment.id) + if (!switched) { + await window.api.runtimeEnvironments.remove({ selector: result.environment.id }) + await loadEnvironments() + return + } + toast.success(`Connected to ${result.environment.name}.`) + } else { + toast.success(`Saved ${result.environment.name}. Use Active Server to switch when ready.`) + } + setAddServerFormOpen(false) } catch (error) { toast.error(error instanceof Error ? error.message : 'Failed to save runtime environment.') } finally { @@ -115,9 +144,18 @@ export function RuntimeEnvironmentsPane({ if (settings.activeRuntimeEnvironmentId === environment.id) { const switched = await switchRuntimeEnvironment(null) if (!switched) { - setRemoveError('Could not switch to Local desktop. Fix the issue and try again.') + setRemoveError( + allowLocalRuntime + ? 'Could not switch to Local desktop. Fix the issue and try again.' + : 'Could not disconnect from this server. Fix the issue and try again.' + ) return false } + if (!allowLocalRuntime) { + await loadEnvironments() + toast.success(`Removed ${environment.name}.`) + return true + } } await window.api.runtimeEnvironments.remove({ selector: environment.id }) await loadEnvironments() @@ -135,10 +173,15 @@ export function RuntimeEnvironmentsPane({ } const switchToValue = async (value: string): Promise => { + if (value === NO_RUNTIME_VALUE) { + return false + } setSwitchingValue(value) setSwitchError(null) try { - const switched = await switchRuntimeEnvironment(value === LOCAL_RUNTIME_VALUE ? null : value) + const switched = await switchRuntimeEnvironment( + allowLocalRuntime && value === LOCAL_RUNTIME_VALUE ? null : value + ) if (switched) { toast.success(`Switched to ${getEnvironmentLabel(value)}.`) return true @@ -159,22 +202,26 @@ export function RuntimeEnvironmentsPane({ if (value === LOCAL_RUNTIME_VALUE) { return 'Local desktop' } + if (value === NO_RUNTIME_VALUE) { + return 'No server connected' + } return environments.find((environment) => environment.id === value)?.name ?? 'remote server' } return (

- Local keeps today's desktop behavior. Saved servers route supported client calls - through the remote runtime. + {allowLocalRuntime + ? "Local keeps today's desktop behavior. Saved servers route supported client calls through the remote runtime." + : 'Saved servers route this browser through a paired Orca runtime.'}

@@ -196,7 +243,13 @@ export function RuntimeEnvironmentsPane({ - Local desktop + {allowLocalRuntime ? ( + Local desktop + ) : environments.length === 0 ? ( + + No server connected + + ) : null} {environments.map((environment) => ( {environment.name} @@ -207,89 +260,156 @@ export function RuntimeEnvironmentsPane({
-
-
- - setName(event.target.value)} - placeholder="Dev box" - className="h-8 text-xs" - /> +
+
+
Saved Servers
+ {addServerFormOpen ? null : ( + + )}
-
- - setPairingCode(event.target.value)} - placeholder="orca://pair#..." - className="h-8 min-w-0 font-mono text-xs" - /> -

- Run orca serve --pairing-address <host> on the - server and paste the printed pairing URL. -

+ + {addServerFormOpen ? ( +
{ + event.preventDefault() + void addEnvironment() + }} + > +
+
+ + setName(event.target.value)} + placeholder="Dev box" + className="h-8 text-xs" + autoFocus + /> +
+
+ + setPairingCode(event.target.value)} + placeholder="orca://pair#..." + className="h-8 min-w-0 font-mono text-xs" + /> +

+ Run orca serve --pairing-address <host>{' '} + on the server and paste the printed pairing URL. +

+
+
+
+ + +
+
+ ) : null} + +
+ {environments.length === 0 ? ( +
No saved servers.
+ ) : ( +
+ {environments.map((environment) => ( +
+
+
{environment.name}
+
+ {environment.endpoints[0]?.endpoint ?? 'No endpoint'} +
+
+ +
+ ))} +
+ )}
-
-
- {environments.length === 0 ? ( -
No saved servers.
- ) : ( -
- {environments.map((environment) => ( -
-
-
{environment.name}
-
- {environment.endpoints[0]?.endpoint ?? 'No endpoint'} -
-
- -
- ))} + {canGeneratePairingUrl ? ( +
+
+
+
Share this desktop
+

+ Generate a pairing URL for the web client or another Orca client. +

+
+
- )} -
+ {shareServerFormOpen ? ( +
+ +
+ ) : null} +
+ ) : null} Remove Server {removingActiveServer - ? 'Removing the active server first switches Orca back to Local desktop and closes remote terminals and browser tabs for that server.' + ? allowLocalRuntime + ? 'Removing the active server first switches Orca back to Local desktop and closes remote terminals and browser tabs for that server.' + : 'Removing the active server disconnects this browser and closes remote terminals and browser tabs for that server.' : 'This removes the saved server from Orca. It does not change the active server.'} diff --git a/src/renderer/src/components/settings/RuntimePairingUrlGenerator.tsx b/src/renderer/src/components/settings/RuntimePairingUrlGenerator.tsx new file mode 100644 index 000000000..5b96398a9 --- /dev/null +++ b/src/renderer/src/components/settings/RuntimePairingUrlGenerator.tsx @@ -0,0 +1,239 @@ +import { Check, Copy, Loader2, RefreshCw } from 'lucide-react' +import { useEffect, useState } from 'react' +import { toast } from 'sonner' +import { Button } from '../ui/button' +import { Input } from '../ui/input' +import { Label } from '../ui/label' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select' + +const LOOPBACK_ADDRESS = '127.0.0.1' + +// Why: runtime pairing tokens stay valid in the main-process registry; keep the +// last displayed URL across settings collapse/navigation without less-protected storage. +const runtimePairingUrlCache: { + selectedAddress: string + customAddress: string + runtimePairingUrl: string | null + webClientUrl: string | null +} = { + selectedAddress: LOOPBACK_ADDRESS, + customAddress: '', + runtimePairingUrl: null, + webClientUrl: null +} + +function GeneratedUrlRow({ + label, + value, + copied, + onCopy +}: { + label: string + value: string + copied: boolean + onCopy: () => void +}): React.JSX.Element { + return ( +
+ +
+ + {value} + + +
+
+ ) +} + +type RuntimePairingUrlGeneratorProps = { + framed?: boolean + showHeader?: boolean +} + +export function RuntimePairingUrlGenerator({ + framed = true, + showHeader = true +}: RuntimePairingUrlGeneratorProps): React.JSX.Element { + const [networkInterfaces, setNetworkInterfaces] = useState<{ name: string; address: string }[]>( + [] + ) + const [selectedAddress, setSelectedAddress] = useState(runtimePairingUrlCache.selectedAddress) + const [customAddress, setCustomAddress] = useState(runtimePairingUrlCache.customAddress) + const [runtimePairingUrl, setRuntimePairingUrl] = useState( + runtimePairingUrlCache.runtimePairingUrl + ) + const [webClientUrl, setWebClientUrl] = useState( + runtimePairingUrlCache.webClientUrl + ) + const [copiedTarget, setCopiedTarget] = useState<'web' | 'pairing' | null>(null) + const [isGeneratingPairing, setIsGeneratingPairing] = useState(false) + + useEffect(() => { + let stale = false + + const loadNetworkInterfaces = async (): Promise => { + try { + const result = await window.api.mobile.listNetworkInterfaces() + if (!stale) { + setNetworkInterfaces(result.interfaces) + } + } catch { + // Keep the loopback option available even if interface enumeration fails. + } + } + + void loadNetworkInterfaces() + + return () => { + stale = true + } + }, []) + + const generateRuntimePairingUrl = async (): Promise => { + setIsGeneratingPairing(true) + try { + const advertiseAddress = customAddress.trim() || selectedAddress + const result = await window.api.mobile.getRuntimePairingUrl({ + address: advertiseAddress, + rotate: true + }) + if (!result.available) { + runtimePairingUrlCache.runtimePairingUrl = null + runtimePairingUrlCache.webClientUrl = null + setRuntimePairingUrl(null) + setWebClientUrl(null) + toast.error('Runtime pairing is unavailable.') + return + } + runtimePairingUrlCache.runtimePairingUrl = result.pairingUrl + runtimePairingUrlCache.webClientUrl = result.webClientUrl + setRuntimePairingUrl(result.pairingUrl) + setWebClientUrl(result.webClientUrl) + toast.success(result.webClientUrl ? 'Generated web client URL.' : 'Generated pairing URL.') + } catch (error) { + toast.error(error instanceof Error ? error.message : 'Failed to generate pairing URL.') + } finally { + setIsGeneratingPairing(false) + } + } + + const copyGeneratedUrl = async (target: 'web' | 'pairing', value: string): Promise => { + try { + await window.api.ui.writeClipboardText(value) + setCopiedTarget(target) + toast.success(target === 'web' ? 'Copied web client URL.' : 'Copied pairing URL.') + window.setTimeout(() => { + setCopiedTarget((current) => (current === target ? null : current)) + }, 1400) + } catch (error) { + toast.error(error instanceof Error ? error.message : 'Failed to copy URL.') + } + } + + const containerClassName = framed + ? 'space-y-3 rounded-lg border border-border/50 bg-muted/25 p-3' + : 'space-y-4' + + const updateSelectedAddress = (address: string): void => { + runtimePairingUrlCache.selectedAddress = address + setSelectedAddress(address) + } + + const updateCustomAddress = (address: string): void => { + runtimePairingUrlCache.customAddress = address + setCustomAddress(address) + } + + return ( +
+ {showHeader ? ( +
+ +

+ Generate a runtime pairing URL for the web client or another Orca client. +

+
+ ) : null} +
+
+
+ + +
+
+ + updateCustomAddress(event.target.value)} + placeholder="host, host:port, or wss://host/path" + className="h-8 font-mono text-xs" + /> +
+
+
+ +
+
+ + {webClientUrl ? ( + void copyGeneratedUrl('web', webClientUrl)} + /> + ) : null} + + {runtimePairingUrl ? ( + void copyGeneratedUrl('pairing', runtimePairingUrl)} + /> + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/settings/Settings.tsx b/src/renderer/src/components/settings/Settings.tsx index 1af8e8a49..53cdf9f05 100644 --- a/src/renderer/src/components/settings/Settings.tsx +++ b/src/renderer/src/components/settings/Settings.tsx @@ -62,10 +62,11 @@ import { } from './DeveloperPermissionsPane' import { ComputerUsePane, COMPUTER_USE_PANE_SEARCH_ENTRIES } from './ComputerUsePane' import { MobileSettingsPane, MOBILE_SETTINGS_PANE_SEARCH_ENTRIES } from './MobileSettingsPane' +import { RuntimeEnvironmentsPane } from './RuntimeEnvironmentsPane' import { - RuntimeEnvironmentsPane, - RUNTIME_ENVIRONMENTS_SEARCH_ENTRY -} from './RuntimeEnvironmentsPane' + RUNTIME_ENVIRONMENTS_SEARCH_ENTRY, + WEB_RUNTIME_ENVIRONMENTS_SEARCH_ENTRY +} from './runtime-environments-search' import { PrivacyPane } from './PrivacyPane' import { PRIVACY_PANE_SEARCH_ENTRIES } from './privacy-search' import { SettingsSidebar } from './SettingsSidebar' @@ -179,6 +180,13 @@ function isEditableTarget(target: EventTarget | null): boolean { return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' } +function isWebClientLocation(): boolean { + return ( + Boolean((window as unknown as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__) || + window.location.pathname.endsWith('/web-index.html') + ) +} + function Settings(): React.JSX.Element { const settings = useAppStore((s) => s.settings) const updateSettings = useAppStore((s) => s.updateSettings) @@ -199,6 +207,8 @@ function Settings(): React.JSX.Element { const systemPrefersDark = useSystemPrefersDark() const isWindows = isWindowsUserAgent() const isMac = isMacUserAgent() + const isWebClient = isWebClientLocation() + const showDesktopOnlySettings = !isWebClient const showComputerUsePreviewTooltip = !isMac const computerUsePlatform = computerUsePlatformLabel({ isWindows, isMac }) // Why: the Terminal settings section shares one search index with the @@ -399,6 +409,9 @@ function Settings(): React.JSX.Element { }, []) const displayedGitUsername = repos[0]?.gitUsername ?? '' + const runtimeEnvironmentsSearchEntry = isWebClient + ? WEB_RUNTIME_ENVIRONMENTS_SEARCH_ENTRY + : RUNTIME_ENVIRONMENTS_SEARCH_ENTRY const navSections = useMemo( () => [ @@ -447,20 +460,24 @@ function Settings(): React.JSX.Element { icon: SquareTerminal, searchEntries: terminalPaneSearchEntries }, - { - id: 'browser', - title: 'Browser', - description: 'Home page, link routing, and session cookies.', - icon: Globe, - searchEntries: BROWSER_PANE_SEARCH_ENTRIES - }, - { - id: 'notifications', - title: 'Notifications', - description: 'Native desktop notifications for agent and terminal events.', - icon: Bell, - searchEntries: NOTIFICATIONS_PANE_SEARCH_ENTRIES - }, + ...(showDesktopOnlySettings + ? [ + { + id: 'browser' as const, + title: 'Browser', + description: 'Home page, link routing, and session cookies.', + icon: Globe, + searchEntries: BROWSER_PANE_SEARCH_ENTRIES + }, + { + id: 'notifications' as const, + title: 'Notifications', + description: 'Native desktop notifications for agent and terminal events.', + icon: Bell, + searchEntries: NOTIFICATIONS_PANE_SEARCH_ENTRIES + } + ] + : []), { id: 'orchestration', title: 'Orchestration', @@ -471,36 +488,42 @@ function Settings(): React.JSX.Element { { id: 'servers', title: 'Servers', - description: 'Run this client locally or through a remote Orca server.', + description: isWebClient + ? 'Connect this browser to a saved Orca server.' + : 'Run this client locally or through a remote Orca server.', icon: Server, - searchEntries: [RUNTIME_ENVIRONMENTS_SEARCH_ENTRY], + searchEntries: [runtimeEnvironmentsSearchEntry], badge: 'Beta' }, - { - id: 'mobile', - title: 'Mobile', - description: 'Control terminals and agents from your phone.', - icon: Smartphone, - searchEntries: MOBILE_SETTINGS_PANE_SEARCH_ENTRIES, - badge: 'Beta' - }, - { - id: 'computer-use', - title: 'Computer Use', - description: 'Enable agents to control any app on your computer.', - icon: MousePointerClick, - searchEntries: COMPUTER_USE_PANE_SEARCH_ENTRIES, - badge: 'Beta' - }, - { - id: 'voice', - title: 'Voice', - description: 'Local speech-to-text dictation with on-device models.', - icon: Mic, - searchEntries: VOICE_PANE_SEARCH_ENTRIES, - badge: 'Beta' - }, - ...(isMac + ...(showDesktopOnlySettings + ? [ + { + id: 'mobile' as const, + title: 'Mobile', + description: 'Control terminals and agents from your phone.', + icon: Smartphone, + searchEntries: MOBILE_SETTINGS_PANE_SEARCH_ENTRIES, + badge: 'Beta' + }, + { + id: 'computer-use' as const, + title: 'Computer Use', + description: 'Enable agents to control any app on your computer.', + icon: MousePointerClick, + searchEntries: COMPUTER_USE_PANE_SEARCH_ENTRIES, + badge: 'Beta' + }, + { + id: 'voice' as const, + title: 'Voice', + description: 'Local speech-to-text dictation with on-device models.', + icon: Mic, + searchEntries: VOICE_PANE_SEARCH_ENTRIES, + badge: 'Beta' + } + ] + : []), + ...(showDesktopOnlySettings && isMac ? [ { id: 'developer-permissions' as const, @@ -539,13 +562,17 @@ function Settings(): React.JSX.Element { icon: BarChart3, searchEntries: STATS_PANE_SEARCH_ENTRIES }, - { - id: 'ssh', - title: 'SSH', - description: 'Remote SSH connections.', - icon: Cable, - searchEntries: SSH_PANE_SEARCH_ENTRIES - }, + ...(showDesktopOnlySettings + ? [ + { + id: 'ssh' as const, + title: 'SSH', + description: 'Remote SSH connections.', + icon: Cable, + searchEntries: SSH_PANE_SEARCH_ENTRIES + } + ] + : []), { id: 'experimental', title: 'Experimental', @@ -561,7 +588,14 @@ function Settings(): React.JSX.Element { searchEntries: getRepositoryPaneSearchEntries(repo) })) ], - [isMac, repos, terminalPaneSearchEntries] + [ + isMac, + isWebClient, + repos, + runtimeEnvironmentsSearchEntry, + showDesktopOnlySettings, + terminalPaneSearchEntries + ] ) const visibleNavSections = useMemo( @@ -824,23 +858,27 @@ function Settings(): React.JSX.Element { /> - - - + {showDesktopOnlySettings ? ( + <> + + + - - - + + + + + ) : null} - - - + {showDesktopOnlySettings ? ( + <> + + + - - - - - - - - {computerUsePlatform} Computer Use is an early preview. Some apps and - desktop environments may behave inconsistently. - - - - - ) : null - } - description="Enable agents to control any app on your computer." - searchEntries={COMPUTER_USE_PANE_SEARCH_ENTRIES} - > - - + + + + + + + + {computerUsePlatform} Computer Use is an early preview. Some apps + and desktop environments may behave inconsistently. + + + + + ) : null + } + description="Enable agents to control any app on your computer." + searchEntries={COMPUTER_USE_PANE_SEARCH_ENTRIES} + > + + - - - + + + + + ) : null} - {isMac ? ( + {showDesktopOnlySettings && isMac ? ( - - - + {showDesktopOnlySettings ? ( + + + + ) : null} { + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('uses native randomUUID when it is available', () => { + vi.stubGlobal('crypto', { + randomUUID: () => 'native-id' + }) + + expect(createBrowserUuid()).toBe('native-id') + }) + + it('falls back to getRandomValues when randomUUID is unavailable', () => { + vi.stubGlobal('crypto', { + getRandomValues: (bytes: Uint8Array) => { + for (let index = 0; index < bytes.length; index += 1) { + bytes[index] = index + } + return bytes + } + }) + + expect(createBrowserUuid()).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f') + }) +}) diff --git a/src/renderer/src/lib/browser-uuid.ts b/src/renderer/src/lib/browser-uuid.ts new file mode 100644 index 000000000..177d05f7d --- /dev/null +++ b/src/renderer/src/lib/browser-uuid.ts @@ -0,0 +1,28 @@ +export function createBrowserUuid(): string { + const cryptoApi = globalThis.crypto + if (typeof cryptoApi?.randomUUID === 'function') { + return cryptoApi.randomUUID() + } + + const bytes = new Uint8Array(16) + if (typeof cryptoApi?.getRandomValues === 'function') { + cryptoApi.getRandomValues(bytes) + } else { + // Why: LAN web clients can run in non-secure browser contexts where + // randomUUID is hidden. These are local UI IDs, not auth credentials. + for (let index = 0; index < bytes.length; index += 1) { + bytes[index] = Math.floor(Math.random() * 256) + } + } + + bytes[6] = (bytes[6] & 0x0f) | 0x40 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + return bytesToUuid(bytes) +} + +function bytesToUuid(bytes: Uint8Array): string { + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')) + return `${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-${hex + .slice(6, 8) + .join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10, 16).join('')}` +} diff --git a/src/renderer/src/lib/open-project-notes-tab.ts b/src/renderer/src/lib/open-project-notes-tab.ts index cda85c7e6..24c9fa6ca 100644 --- a/src/renderer/src/lib/open-project-notes-tab.ts +++ b/src/renderer/src/lib/open-project-notes-tab.ts @@ -1,12 +1,13 @@ import { useAppStore } from '@/store' import { NOTES_ACTIVE_CHANGED_EVENT } from '@/lib/notes-events' import { linkRuntimeProjectNote, showRuntimeProjectNote } from '@/runtime/runtime-notes-client' +import { createBrowserUuid } from '@/lib/browser-uuid' export function getProjectNotesEntityId(projectId: string, noteId?: string): string { if (noteId) { return `notes:${projectId}:note:${noteId}` } - return `notes:${projectId}:new:${globalThis.crypto.randomUUID()}` + return `notes:${projectId}:new:${createBrowserUuid()}` } export function getProjectNoteIdFromEntityId(entityId: string): string | null { diff --git a/src/renderer/src/runtime/sync-runtime-graph.ts b/src/renderer/src/runtime/sync-runtime-graph.ts index 7d8de532d..557dd1052 100644 --- a/src/renderer/src/runtime/sync-runtime-graph.ts +++ b/src/renderer/src/runtime/sync-runtime-graph.ts @@ -6,6 +6,7 @@ import { } from '@/components/terminal-pane/layout-serialization' import { warnTerminalLifecycleAnomaly } from '@/components/terminal-pane/terminal-lifecycle-diagnostics' import type { PaneManager } from '@/lib/pane-manager/pane-manager' +import { createBrowserUuid } from '@/lib/browser-uuid' import type { AppState } from '@/store/types' import type { RuntimeMobileSessionFileTab, @@ -46,10 +47,7 @@ let cachedOpenFileIndexesSource: AppState['openFiles'] | null = null let cachedOpenFileIndexes: OpenFileIndexes | null = null let cachedEditorDraftsSource: AppState['editorDrafts'] | null = null let cachedEditorDraftVersionByFileId: Map | null = null -const mobileSessionPublicationEpoch = - typeof crypto !== 'undefined' && 'randomUUID' in crypto - ? crypto.randomUUID() - : `renderer:${Date.now().toString(36)}` +const mobileSessionPublicationEpoch = `renderer:${createBrowserUuid()}` export function setRuntimeGraphStoreStateGetter(getter: (() => AppState) | null): void { getStoreState = getter diff --git a/src/renderer/src/store/slices/browser.ts b/src/renderer/src/store/slices/browser.ts index e326b7615..ab1fb6510 100644 --- a/src/renderer/src/store/slices/browser.ts +++ b/src/renderer/src/store/slices/browser.ts @@ -34,6 +34,7 @@ import type { BrowserProfileImportFromBrowserResult, BrowserProfileListResult } from '../../../../shared/runtime-types' +import { createBrowserUuid } from '@/lib/browser-uuid' type CreateBrowserTabOptions = { activate?: boolean @@ -221,7 +222,7 @@ function buildBrowserPage( ): BrowserPage { const normalizedUrl = normalizeUrl(url) return { - id: globalThis.crypto.randomUUID(), + id: createBrowserUuid(), workspaceId, worktreeId, url: normalizedUrl, @@ -355,7 +356,7 @@ export const createBrowserSlice: StateCreator = }, createBrowserTab: (worktreeId, url, options) => { - const workspaceId = globalThis.crypto.randomUUID() + const workspaceId = createBrowserUuid() const page = buildBrowserPage(workspaceId, worktreeId, url, options?.title) // Why: when no explicit profile is passed, inherit the user's chosen default // profile. This lets users set a preferred profile in Settings that all new @@ -1243,7 +1244,7 @@ export const createBrowserSlice: StateCreator = for (const tab of tabs) { const persistedPages = persistedPagesByWorkspace[tab.id] ?? [ { - id: globalThis.crypto.randomUUID(), + id: createBrowserUuid(), workspaceId: tab.id, worktreeId, url: normalizeUrl(tab.url), diff --git a/src/renderer/src/store/slices/diffComments.ts b/src/renderer/src/store/slices/diffComments.ts index 7b776d2aa..0a57741c8 100644 --- a/src/renderer/src/store/slices/diffComments.ts +++ b/src/renderer/src/store/slices/diffComments.ts @@ -3,6 +3,7 @@ import type { AppState } from '../types' import type { DiffComment, Worktree } from '../../../../shared/types' import { findWorktreeById, getRepoIdFromWorktreeId } from './worktree-helpers' import { callRuntimeRpc, getActiveRuntimeTarget } from '../../runtime/runtime-rpc-client' +import { createBrowserUuid } from '@/lib/browser-uuid' export type DiffCommentsSlice = { getDiffComments: (worktreeId: string | null | undefined) => DiffComment[] @@ -12,7 +13,7 @@ export type DiffCommentsSlice = { } function generateId(): string { - return globalThis.crypto.randomUUID() + return createBrowserUuid() } // Why: return a stable reference when no comments exist so selectors don't diff --git a/src/renderer/src/store/slices/tab-group-state.ts b/src/renderer/src/store/slices/tab-group-state.ts index 5bb4c730b..b5d634cee 100644 --- a/src/renderer/src/store/slices/tab-group-state.ts +++ b/src/renderer/src/store/slices/tab-group-state.ts @@ -1,4 +1,5 @@ import type { Tab, TabContentType, TabGroup, WorkspaceSessionState } from '../../../../shared/types' +import { createBrowserUuid } from '@/lib/browser-uuid' export function findTabAndWorktree( tabsByWorktree: Record, @@ -69,7 +70,7 @@ export function ensureGroup( if (existing) { return { group: existing, groupsByWorktree, activeGroupIdByWorktree } } - const groupId = globalThis.crypto.randomUUID() + const groupId = createBrowserUuid() const group: TabGroup = { id: groupId, worktreeId, activeTabId: null, tabOrder: [] } return { group, diff --git a/src/renderer/src/store/slices/tabs-hydration.ts b/src/renderer/src/store/slices/tabs-hydration.ts index 886fecc0b..e01b50a32 100644 --- a/src/renderer/src/store/slices/tabs-hydration.ts +++ b/src/renderer/src/store/slices/tabs-hydration.ts @@ -4,6 +4,7 @@ import type { TabGroupLayoutNode, WorkspaceSessionState } from '../../../../shared/types' +import { createBrowserUuid } from '@/lib/browser-uuid' import { dedupeTabOrder, getPersistedEditFileIdsByWorktree, @@ -164,7 +165,7 @@ function hydrateLegacyFormat( continue } - const groupId = globalThis.crypto.randomUUID() + const groupId = createBrowserUuid() const tabs: Tab[] = [] const tabOrder: string[] = [] diff --git a/src/renderer/src/store/slices/tabs.ts b/src/renderer/src/store/slices/tabs.ts index 5882d970c..428595803 100644 --- a/src/renderer/src/store/slices/tabs.ts +++ b/src/renderer/src/store/slices/tabs.ts @@ -27,6 +27,7 @@ import { } from './tab-group-state' import { buildHydratedTabState } from './tabs-hydration' import { buildOrphanTerminalCleanupPatch, getOrphanTerminalIds } from './terminal-orphan-helpers' +import { createBrowserUuid } from '@/lib/browser-uuid' export type TabSplitDirection = 'left' | 'right' | 'up' | 'down' @@ -402,7 +403,7 @@ export const createTabsSlice: StateCreator = (set, layoutByWorktree: {}, createUnifiedTab: (worktreeId, contentType, init) => { - const id = init?.id ?? globalThis.crypto.randomUUID() + const id = init?.id ?? createBrowserUuid() let created!: Tab set((state) => { const { group, groupsByWorktree, activeGroupIdByWorktree } = ensureGroup( @@ -812,7 +813,7 @@ export const createTabsSlice: StateCreator = (set, return get().activeGroupIdByWorktree[worktreeId] ?? existingGroups[0].id } - const groupId = globalThis.crypto.randomUUID() + const groupId = createBrowserUuid() set((state) => ({ // Why: a freshly selected worktree can legitimately have zero tabs, but // split-group affordances still need a canonical root group so new tabs @@ -943,7 +944,7 @@ export const createTabsSlice: StateCreator = (set, }, createEmptySplitGroup: (worktreeId, sourceGroupId, direction) => { - const newGroupId = globalThis.crypto.randomUUID() + const newGroupId = createBrowserUuid() const newGroup: TabGroup = { id: newGroupId, worktreeId, @@ -1091,7 +1092,7 @@ export const createTabsSlice: StateCreator = (set, let resolvedTargetGroupId = target.groupId if (target.splitDirection) { - const newGroupId = globalThis.crypto.randomUUID() + const newGroupId = createBrowserUuid() const newGroup: TabGroup = { id: newGroupId, worktreeId, diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index e526fd418..949eb2049 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -29,6 +29,7 @@ import { } from '@/components/terminal-pane/pty-transport' import { shutdownBufferCaptures } from '@/components/terminal-pane/shutdown-buffer-captures' import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' +import { createBrowserUuid } from '@/lib/browser-uuid' function getNextTerminalOrdinal(tabs: TerminalTab[]): number { const usedOrdinals = new Set() @@ -377,7 +378,7 @@ export const createTerminalSlice: StateCreator `[createTab] tabId hint ${hintedId} already exists; minting a fresh id (hook attribution will degrade for this terminal)` ) } - const id = hintedId !== undefined && !idCollides ? hintedId : globalThis.crypto.randomUUID() + const id = hintedId !== undefined && !idCollides ? hintedId : createBrowserUuid() const shouldActivate = options?.activate !== false const nextOrdinal = getNextTerminalOrdinal(existing) const defaultTitle = `Terminal ${nextOrdinal}` diff --git a/src/renderer/src/web/WebConnect.tsx b/src/renderer/src/web/WebConnect.tsx new file mode 100644 index 000000000..a7b9c56a9 --- /dev/null +++ b/src/renderer/src/web/WebConnect.tsx @@ -0,0 +1,143 @@ +import { useMemo, useState } from 'react' +import { Cable, Loader2, Server, Trash2 } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { + clearStoredWebRuntimeEnvironment, + createStoredWebRuntimeEnvironment, + isMixedContentWebSocket, + readStoredWebRuntimeEnvironment, + saveStoredWebRuntimeEnvironment +} from './web-runtime-environment' +import { parseWebPairingInput } from './web-pairing' +import { WebRuntimeClient } from './web-runtime-client' + +type WebConnectProps = { + initialPairingInput: string | null + onConnected: () => void +} + +export default function WebConnect({ + initialPairingInput, + onConnected +}: WebConnectProps): React.JSX.Element { + const existingEnvironment = readStoredWebRuntimeEnvironment() + const [name, setName] = useState(existingEnvironment?.name ?? 'Orca Server') + const [pairingCode, setPairingCode] = useState(initialPairingInput ?? '') + const [error, setError] = useState(null) + const [connecting, setConnecting] = useState(false) + const parsedOffer = useMemo(() => parseWebPairingInput(pairingCode), [pairingCode]) + + const connect = async (): Promise => { + setError(null) + if (!parsedOffer) { + setError('Enter a valid Orca pairing URL or pairing code.') + return + } + if (isMixedContentWebSocket(parsedOffer.endpoint)) { + setError( + 'This HTTPS page cannot connect to a plain ws:// Orca server. Open the web client over HTTP or pair with a wss:// endpoint.' + ) + return + } + setConnecting(true) + const environment = createStoredWebRuntimeEnvironment({ name, offer: parsedOffer }) + const client = new WebRuntimeClient(parsedOffer) + try { + const response = await client.call('status.get', undefined, { timeoutMs: 15_000 }) + if (!response.ok) { + throw new Error(response.error.message) + } + saveStoredWebRuntimeEnvironment({ + ...environment, + runtimeId: response._meta.runtimeId, + lastUsedAt: Date.now() + }) + onConnected() + } catch (err) { + setError(err instanceof Error ? err.message : String(err)) + } finally { + client.close() + setConnecting(false) + } + } + + const clear = (): void => { + clearStoredWebRuntimeEnvironment() + setPairingCode('') + setError(null) + } + + return ( +
+
+
+
+ +
+
+

Connect to Orca

+

+ Paste a pairing URL from an Orca server that this browser can reach. +

+
+
+ +
+ + setName(event.target.value)} + autoComplete="off" + /> +
+ +
+ + setPairingCode(event.target.value)} + placeholder="orca://pair#..." + autoComplete="off" + spellCheck={false} + /> +
+ + {parsedOffer && ( +
+ Endpoint: {parsedOffer.endpoint} +
+ )} + + {error && ( +
+ {error} +
+ )} + +
+ + +
+
+
+ ) +} diff --git a/src/renderer/src/web/main.tsx b/src/renderer/src/web/main.tsx new file mode 100644 index 000000000..6e39b36f6 --- /dev/null +++ b/src/renderer/src/web/main.tsx @@ -0,0 +1,51 @@ +import '../assets/main.css' + +import { lazy, Suspense, useMemo, useState } from 'react' +import ReactDOM from 'react-dom/client' +import WebConnect from './WebConnect' +import { + clearPairingInputFromAddressBar, + parseWebPairingInput, + readPairingInputFromLocation +} from './web-pairing' +import { + createStoredWebRuntimeEnvironment, + readStoredWebRuntimeEnvironment, + saveStoredWebRuntimeEnvironment +} from './web-runtime-environment' +import { installWebPreloadApi } from './web-preload-api' + +const App = lazy(() => import('../App')) + +function WebRoot(): React.JSX.Element { + const initialPairingInput = useMemo(() => readPairingInputFromLocation(window.location), []) + const [hasEnvironment, setHasEnvironment] = useState(() => { + const offer = initialPairingInput ? parseWebPairingInput(initialPairingInput) : null + if (offer) { + saveStoredWebRuntimeEnvironment( + createStoredWebRuntimeEnvironment({ name: 'Orca Server', offer }) + ) + clearPairingInputFromAddressBar() + return true + } + return readStoredWebRuntimeEnvironment() !== null + }) + + if (!hasEnvironment) { + return ( + setHasEnvironment(true)} + /> + ) + } + + installWebPreloadApi() + return ( + }> + + + ) +} + +ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render() diff --git a/src/renderer/src/web/web-e2ee.ts b/src/renderer/src/web/web-e2ee.ts new file mode 100644 index 000000000..933a745ee --- /dev/null +++ b/src/renderer/src/web/web-e2ee.ts @@ -0,0 +1,80 @@ +import nacl from 'tweetnacl' + +if (globalThis.crypto?.getRandomValues) { + nacl.setPRNG((bytes, count) => { + globalThis.crypto.getRandomValues(bytes.subarray(0, count) as Uint8Array) + }) +} + +export function generateKeyPair(): nacl.BoxKeyPair { + return nacl.box.keyPair() +} + +export function deriveSharedKey(ourSecretKey: Uint8Array, peerPublicKey: Uint8Array): Uint8Array { + return nacl.box.before(peerPublicKey, ourSecretKey) +} + +export function publicKeyFromBase64(b64: string): Uint8Array { + const key = base64ToBytes(b64) + if (key.length !== 32) { + throw new Error(`Invalid public key: expected 32 bytes, got ${key.length}`) + } + return key +} + +export function publicKeyToBase64(key: Uint8Array): string { + return bytesToBase64(key) +} + +export function encrypt(plaintext: string, sharedKey: Uint8Array): string { + return bytesToBase64(encryptBytes(new TextEncoder().encode(plaintext), sharedKey)) +} + +export function decrypt(encrypted: string, sharedKey: Uint8Array): string | null { + const plaintext = decryptBytes(base64ToBytes(encrypted), sharedKey) + return plaintext ? new TextDecoder().decode(plaintext) : null +} + +export function encryptBytes( + plaintext: Uint8Array, + sharedKey: Uint8Array +): Uint8Array { + const nonce = nacl.randomBytes(nacl.box.nonceLength) + const ciphertext = nacl.box.after(plaintext, nonce, sharedKey) + const bundle = new Uint8Array(nonce.length + ciphertext.length) + bundle.set(nonce) + bundle.set(ciphertext, nonce.length) + return bundle +} + +export function decryptBytes( + bundle: Uint8Array, + sharedKey: Uint8Array +): Uint8Array | null { + if (bundle.length < nacl.box.nonceLength + nacl.box.overheadLength) { + return null + } + const nonce = bundle.slice(0, nacl.box.nonceLength) + const ciphertext = bundle.slice(nacl.box.nonceLength) + const plaintext = nacl.box.open.after(ciphertext, nonce, sharedKey) + return plaintext ? new Uint8Array(plaintext) : null +} + +function base64ToBytes(value: string): Uint8Array { + const binary = window.atob(value) + const bytes = new Uint8Array(binary.length) + for (let index = 0; index < binary.length; index += 1) { + bytes[index] = binary.charCodeAt(index) + } + return bytes +} + +function bytesToBase64(bytes: Uint8Array): string { + const chunkSize = 0x8000 + let binary = '' + for (let offset = 0; offset < bytes.length; offset += chunkSize) { + const chunk = bytes.subarray(offset, offset + chunkSize) + binary += String.fromCharCode(...chunk) + } + return window.btoa(binary) +} diff --git a/src/renderer/src/web/web-pairing.ts b/src/renderer/src/web/web-pairing.ts new file mode 100644 index 000000000..cc2fc747a --- /dev/null +++ b/src/renderer/src/web/web-pairing.ts @@ -0,0 +1,107 @@ +const PAIRING_OFFER_VERSION = 2 + +export type WebPairingOffer = { + v: typeof PAIRING_OFFER_VERSION + endpoint: string + deviceToken: string + publicKeyB64: string +} + +export function parseWebPairingInput(input: string): WebPairingOffer | null { + const trimmed = input.trim() + if (!trimmed) { + return null + } + + try { + if (trimmed.startsWith('orca://pair')) { + const hashIndex = trimmed.indexOf('#') + if (hashIndex === -1) { + return null + } + return decodePairingPayload(trimmed.slice(hashIndex + 1)) + } + return decodePairingPayload(trimmed) + } catch { + return null + } +} + +export function readPairingInputFromLocation(location: Location): string | null { + const search = new URLSearchParams(location.search) + for (const key of ['pairing', 'pair', 'code', 'token']) { + const value = search.get(key) + if (value?.trim()) { + return value.trim() + } + } + + const hash = location.hash.replace(/^#/, '').trim() + if (!hash) { + return null + } + if (hash.startsWith('orca://pair')) { + return hash + } + const hashParams = new URLSearchParams(hash) + for (const key of ['pairing', 'pair', 'code', 'token']) { + const value = hashParams.get(key) + if (value?.trim()) { + return value.trim() + } + } + return hash +} + +export function clearPairingInputFromAddressBar(): void { + if (!window.location.hash && !window.location.search) { + return + } + const cleanUrl = `${window.location.origin}${window.location.pathname}` + // Why: pairing payloads include the runtime auth token. Clear them after + // import so refresh/share/browser history no longer expose the secret. + window.history.replaceState(null, document.title, cleanUrl) +} + +function decodePairingPayload(base64url: string): WebPairingOffer | null { + const json = new TextDecoder().decode(base64UrlToBytes(base64url)) + const parsed = JSON.parse(json) as Partial + if ( + parsed.v !== PAIRING_OFFER_VERSION || + typeof parsed.endpoint !== 'string' || + parsed.endpoint.length === 0 || + typeof parsed.deviceToken !== 'string' || + parsed.deviceToken.length === 0 || + typeof parsed.publicKeyB64 !== 'string' || + parsed.publicKeyB64.length === 0 + ) { + return null + } + return { + v: PAIRING_OFFER_VERSION, + endpoint: normalizeWebSocketEndpoint(parsed.endpoint), + deviceToken: parsed.deviceToken, + publicKeyB64: parsed.publicKeyB64 + } +} + +function base64UrlToBytes(value: string): Uint8Array { + const base64 = value.replace(/-/g, '+').replace(/_/g, '/') + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=') + const binary = window.atob(padded) + const bytes = new Uint8Array(binary.length) + for (let index = 0; index < binary.length; index += 1) { + bytes[index] = binary.charCodeAt(index) + } + return bytes +} + +function normalizeWebSocketEndpoint(endpoint: string): string { + if (endpoint.startsWith('http://')) { + return `ws://${endpoint.slice('http://'.length)}` + } + if (endpoint.startsWith('https://')) { + return `wss://${endpoint.slice('https://'.length)}` + } + return endpoint +} diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts new file mode 100644 index 000000000..b8bb0242a --- /dev/null +++ b/src/renderer/src/web/web-preload-api.ts @@ -0,0 +1,1332 @@ +/* eslint-disable max-lines -- Why: the web preload adapter is the browser-side + replacement for Electron preload, so the compatibility surface is necessarily + centralized at this boundary. */ +import type { PreloadApi, PreflightStatus, RefreshAgentsResult } from '../../../preload/api-types' +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import type { + DirEntry, + GlobalSettings, + MemorySnapshot, + OnboardingState, + Repo, + SearchResult, + StatsSummary, + Worktree +} from '../../../shared/types' +import { + getDefaultOnboardingState, + getDefaultSettings, + getDefaultUIState, + getDefaultWorkspaceSession +} from '../../../shared/constants' +import { createE2EConfig } from '../../../shared/e2e-config' +import { relativePathInsideRoot } from '../../../shared/cross-platform-path' +import type { RateLimitState } from '../../../shared/rate-limit-types' +import type { RuntimeStatus, RuntimeSyncWindowGraph } from '../../../shared/runtime-types' +import { + clearStoredWebRuntimeEnvironment, + createStoredWebRuntimeEnvironment, + getPreferredWebPairingOffer, + readStoredWebRuntimeEnvironment, + redactStoredWebRuntimeEnvironment, + saveStoredWebRuntimeEnvironment, + updateStoredEnvironmentRuntimeId, + type StoredWebRuntimeEnvironment +} from './web-runtime-environment' +import { parseWebPairingInput } from './web-pairing' +import { WebRuntimeClient } from './web-runtime-client' + +const SETTINGS_STORAGE_KEY = 'orca.web.settings.v1' +const UI_STORAGE_KEY = 'orca.web.ui.v1' +const SESSION_STORAGE_KEY = 'orca.web.workspaceSession.v1' +const ONBOARDING_STORAGE_KEY = 'orca.web.onboarding.v1' +const GITHUB_CACHE_STORAGE_KEY = 'orca.web.githubCache.v1' + +let activeEnvironment: StoredWebRuntimeEnvironment | null = readStoredWebRuntimeEnvironment() +let activeClient: WebRuntimeClient | null = null +let activeClientEnvironmentId: string | null = null +let cachedWorktrees: { loadedAt: number; worktrees: Worktree[] } | null = null + +type WebSettingsApi = NonNullable + +export function installWebPreloadApi(): void { + activeEnvironment = readStoredWebRuntimeEnvironment() + const webWindow = window as unknown as { __ORCA_WEB_CLIENT__?: boolean } + webWindow.__ORCA_WEB_CLIENT__ = true + window.electron = createFallbackProxy(['electron']) as Window['electron'] + window.api = withFallback(createWebPreloadApi(), []) as PreloadApi +} + +function createWebPreloadApi(): Partial { + return { + app: { + getFeatureWallAssetBaseUrl: () => Promise.resolve('/'), + relaunch: () => Promise.resolve(window.location.reload()), + getKeyboardInputSourceId: () => Promise.resolve(null), + setUnreadDockBadgeCount: () => Promise.resolve(), + getFloatingTerminalCwd: () => Promise.resolve('~') + }, + e2e: { + getConfig: () => createE2EConfig({}) + }, + settings: { + get: async () => getStoredSettings(), + set: async (updates) => { + if (updates.activeRuntimeEnvironmentId === null) { + disconnectActiveRuntimeEnvironment() + } + const next = mergeSettings(getStoredSettings(), updates) + writeJson(SETTINGS_STORAGE_KEY, next) + return next + }, + listFonts: () => Promise.resolve([]), + onChanged: () => noopUnsubscribe + } satisfies Partial as unknown as WebSettingsApi, + ui: createWebUiApi(), + session: { + get: () => Promise.resolve(readJson(SESSION_STORAGE_KEY, getDefaultWorkspaceSession())), + set: async (session) => { + writeJson(SESSION_STORAGE_KEY, session) + }, + setSync: (session) => { + writeJson(SESSION_STORAGE_KEY, session) + } + }, + onboarding: { + get: () => Promise.resolve(getStoredOnboarding()), + update: async (updates) => { + const current = getStoredOnboarding() + const next: OnboardingState = { + ...current, + ...updates, + checklist: { + ...current.checklist, + ...updates.checklist + } + } + writeJson(ONBOARDING_STORAGE_KEY, next) + return next + } + }, + cache: { + getGitHub: () => + Promise.resolve( + readJson(GITHUB_CACHE_STORAGE_KEY, { + pr: {}, + issue: {} + }) + ), + setGitHub: async ({ cache }) => { + writeJson(GITHUB_CACHE_STORAGE_KEY, cache) + } + }, + runtime: createRuntimeApi(), + runtimeEnvironments: createRuntimeEnvironmentsApi(), + repos: createReposApi(), + worktrees: createWorktreesApi(), + fs: createFileApi(), + git: createGitApi(), + browser: createBrowserApi(), + gh: createGitHubApi(), + linear: createRuntimeNamespaceApi('linear'), + notes: createNotesApi(), + hooks: createHooksApi(), + stats: { + getSummary: async () => + callRuntimeResult('stats.summary').catch(() => ({ + totalAgentsSpawned: 0, + totalPRsCreated: 0, + totalAgentTimeMs: 0, + firstEventAt: null + })) + }, + memory: { + getSnapshot: () => Promise.resolve(createEmptyMemorySnapshot()) + }, + preflight: createPreflightApi(), + notifications: createNotificationsApi(), + rateLimits: createRateLimitsApi(), + codexAccounts: createAccountsApi(), + claudeAccounts: createAccountsApi(), + cli: createCliApi(), + agentHooks: createAgentHooksApi(), + developerPermissions: createDeveloperPermissionsApi(), + computerUsePermissions: createComputerUsePermissionsApi(), + updater: createUpdaterApi(), + shell: createShellApi(), + pty: createPtyApi(), + ssh: createSshApi(), + wsl: { isAvailable: () => Promise.resolve(false) }, + pwsh: { isAvailable: () => Promise.resolve(false) }, + agentStatus: { + onSet: () => noopUnsubscribe, + getSnapshot: () => Promise.resolve([]), + drop: () => {} + }, + mobile: { + listNetworkInterfaces: () => Promise.resolve({ interfaces: [] }), + getPairingQR: () => Promise.resolve({ available: false }), + getRuntimePairingUrl: () => Promise.resolve({ available: false }), + listDevices: () => Promise.resolve({ devices: [] }), + revokeDevice: () => Promise.resolve({ revoked: false }), + isWebSocketReady: () => Promise.resolve({ ready: Boolean(activeEnvironment), endpoint: null }) + }, + telemetryTrack: () => Promise.resolve(), + telemetrySetOptIn: () => Promise.resolve(), + telemetryGetConsentState: () => + Promise.resolve({ optedIn: false, source: 'default', blockedByEnv: false } as never), + telemetryAcknowledgeBanner: () => Promise.resolve() + } +} + +function createRuntimeApi(): NonNullable['runtime']> { + return { + syncWindowGraph: async (_graph: RuntimeSyncWindowGraph) => getRemoteRuntimeStatus(), + getStatus: () => getRemoteRuntimeStatus(), + call: ({ method, params }) => callRuntimeEnvelope(method, params), + getTerminalFitOverrides: () => Promise.resolve([]), + restoreTerminalFit: () => Promise.resolve({ restored: false }), + onTerminalFitOverrideChanged: () => noopUnsubscribe, + onTerminalDriverChanged: () => noopUnsubscribe + } +} + +function createRuntimeEnvironmentsApi(): NonNullable['runtimeEnvironments']> { + return { + list: async () => { + const environment = requireActiveEnvironmentOrNull() + return environment ? [redactStoredWebRuntimeEnvironment(environment)] : [] + }, + addFromPairingCode: async ({ name, pairingCode }) => { + const offer = parseWebPairingInput(pairingCode) + if (!offer) { + throw new Error('Invalid Orca pairing code.') + } + closeActiveRuntimeClients() + activeEnvironment = createStoredWebRuntimeEnvironment({ name, offer }) + saveStoredWebRuntimeEnvironment(activeEnvironment) + return { environment: redactStoredWebRuntimeEnvironment(activeEnvironment) } + }, + resolve: async ({ selector }) => + redactStoredWebRuntimeEnvironment(resolveEnvironment(selector)), + remove: async ({ selector }) => { + const environment = resolveEnvironment(selector) + if (activeEnvironment?.id === environment.id) { + disconnectActiveRuntimeEnvironment() + } + return { removed: redactStoredWebRuntimeEnvironment(environment) } + }, + getStatus: ({ selector, timeoutMs }) => + callEnvironmentEnvelope(selector, 'status.get', undefined, timeoutMs), + call: ({ selector, method, params, timeoutMs }) => + callEnvironmentEnvelope(selector, method, params, timeoutMs), + subscribe: async ({ selector, method, params, timeoutMs }, callbacks) => { + const environment = resolveEnvironment(selector) + const client = getClientForEnvironment(environment) + return client.subscribe(method, params, callbacks, { timeoutMs }) + } + } +} + +function createReposApi(): NonNullable['repos']> { + return { + list: async () => (await callRuntimeResult<{ repos: Repo[] }>('repo.list')).repos, + add: async ({ path, kind }) => callRuntimeResult('repo.add', { path, kind }), + remove: async ({ repoId }) => { + await callRuntimeResult('repo.rm', { repo: repoId }) + cachedWorktrees = null + }, + reorder: async ({ orderedIds }) => callRuntimeResult('repo.reorder', { orderedIds }), + update: async ({ repoId, updates }) => + (await callRuntimeResult<{ repo: Repo }>('repo.update', { repo: repoId, updates })).repo, + pickFolder: () => Promise.resolve(null), + pickDirectory: () => Promise.resolve(null), + clone: async ({ url, destination }) => + (await callRuntimeResult<{ repo: Repo }>('repo.clone', { url, destination }, 10 * 60_000)) + .repo, + cloneAbort: () => Promise.resolve(), + addRemote: async ({ remotePath, displayName, kind }) => { + const result = await callRuntimeResult<{ repo: Repo }>('repo.add', { + path: remotePath, + kind + }) + return displayName + ? { + repo: await createReposApi().update({ + repoId: result.repo.id, + updates: { displayName } + }) + } + : result + }, + create: async ({ parentPath, name, kind }) => + callRuntimeResult('repo.create', { parentPath, name, kind }), + onCloneProgress: () => noopUnsubscribe, + getGitUsername: () => Promise.resolve(''), + getBaseRefDefault: async ({ repoId }) => + callRuntimeResult('repo.baseRefDefault', { repo: repoId }), + searchBaseRefs: async ({ repoId, query, limit }) => + ( + await callRuntimeResult<{ refs: string[] }>('repo.searchRefs', { + repo: repoId, + query, + limit + }) + ).refs, + onChanged: () => noopUnsubscribe + } +} + +function createWorktreesApi(): NonNullable['worktrees']> { + return { + list: async ({ repoId }) => + (await callRuntimeResult<{ worktrees: Worktree[] }>('worktree.list', { repo: repoId })) + .worktrees, + listAll: () => listAllRuntimeWorktrees(), + create: async (args) => { + cachedWorktrees = null + return callRuntimeResult('worktree.create', { + repo: args.repoId, + name: args.name, + baseBranch: args.baseBranch, + linkedIssue: args.linkedIssue, + linkedPR: args.linkedPR, + displayName: args.displayName, + sparseCheckout: args.sparseCheckout, + pushTarget: args.pushTarget, + setupDecision: args.setupDecision, + createdWithAgent: args.createdWithAgent + }) + }, + resolvePrBase: async ({ repoId, prNumber, headRefName, isCrossRepository }) => + callRuntimeResult('worktree.resolvePrBase', { + repo: repoId, + prNumber, + headRefName, + isCrossRepository + }), + resolveMrBase: async () => ({ + error: 'GitLab merge request base resolution is unavailable on web.' + }), + remove: async ({ worktreeId, force }) => { + cachedWorktrees = null + await callRuntimeResult('worktree.rm', { worktree: worktreeId, force }) + }, + updateMeta: async ({ worktreeId, updates }) => + ( + await callRuntimeResult<{ worktree: Worktree }>('worktree.set', { + worktree: worktreeId, + ...updates + }) + ).worktree, + persistSortOrder: async ({ orderedIds }) => { + await callRuntimeResult('worktree.persistSortOrder', { orderedIds }) + }, + onChanged: () => noopUnsubscribe, + onBaseStatus: () => noopUnsubscribe, + onRemoteBranchConflict: () => noopUnsubscribe + } +} + +function createFileApi(): NonNullable['fs']> { + return { + readDir: async ({ dirPath }) => { + const file = await resolveRuntimeFilePath(dirPath) + return callRuntimeResult('files.readDir', { + worktree: file.worktree.id, + relativePath: file.relativePath + }) + }, + readFile: async ({ filePath }) => { + const file = await resolveRuntimeFilePath(filePath) + return callRuntimeResult('files.readPreview', { + worktree: file.worktree.id, + relativePath: file.relativePath + }) + }, + listMarkdownDocuments: async ({ rootPath }) => { + const file = await resolveRuntimeFilePath(rootPath) + return callRuntimeResult('files.listMarkdownDocuments', { worktree: file.worktree.id }) + }, + writeFile: async ({ filePath, content }) => { + const file = await resolveRuntimeFilePath(filePath) + await callRuntimeResult('files.write', { + worktree: file.worktree.id, + relativePath: file.relativePath, + content + }) + }, + createFile: async ({ filePath }) => { + const file = await resolveRuntimeFilePath(filePath) + await callRuntimeResult('files.createFile', { + worktree: file.worktree.id, + relativePath: file.relativePath + }) + }, + createDir: async ({ dirPath }) => { + const file = await resolveRuntimeFilePath(dirPath) + await callRuntimeResult('files.createDir', { + worktree: file.worktree.id, + relativePath: file.relativePath + }) + }, + rename: async ({ oldPath, newPath }) => { + const oldFile = await resolveRuntimeFilePath(oldPath) + const newFile = await resolveRuntimeFilePath(newPath) + await callRuntimeResult('files.rename', { + worktree: oldFile.worktree.id, + oldRelativePath: oldFile.relativePath, + newRelativePath: newFile.relativePath + }) + }, + copy: async ({ sourcePath, destinationPath }) => { + const source = await resolveRuntimeFilePath(sourcePath) + const destination = await resolveRuntimeFilePath(destinationPath) + await callRuntimeResult('files.copy', { + worktree: source.worktree.id, + sourceRelativePath: source.relativePath, + destinationRelativePath: destination.relativePath + }) + }, + deletePath: async ({ targetPath, recursive }) => { + const file = await resolveRuntimeFilePath(targetPath) + await callRuntimeResult('files.delete', { + worktree: file.worktree.id, + relativePath: file.relativePath, + recursive + }) + }, + authorizeExternalPath: () => Promise.resolve(), + stat: async ({ filePath }) => { + const file = await resolveRuntimeFilePath(filePath) + return callRuntimeResult('files.stat', { + worktree: file.worktree.id, + relativePath: file.relativePath + }) + }, + listFiles: async ({ rootPath, excludePaths }) => { + const file = await resolveRuntimeFilePath(rootPath) + const result = await callRuntimeResult<{ files: { relativePath: string }[] }>( + 'files.listAll', + { + worktree: file.worktree.id, + excludePaths + } + ) + return result.files.map((entry) => entry.relativePath) + }, + search: async (args) => { + const file = await resolveRuntimeFilePath(args.rootPath) + return callRuntimeResult('files.search', { + worktree: file.worktree.id, + query: args.query, + caseSensitive: args.caseSensitive, + wholeWord: args.wholeWord, + useRegex: args.useRegex, + includePattern: args.includePattern, + excludePattern: args.excludePattern, + maxResults: args.maxResults + }) + }, + importExternalPaths: async () => ({ results: [] }), + stageExternalPathsForRuntimeUpload: async () => ({ sources: [] }), + resolveDroppedPathsForAgent: async () => ({ resolvedPaths: [], skipped: [], failed: [] }), + watchWorktree: () => Promise.resolve(), + unwatchWorktree: () => Promise.resolve(), + onFsChanged: () => noopUnsubscribe + } +} + +function createGitApi(): NonNullable['git']> { + return { + status: async ({ worktreePath }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.status', { worktree: worktree.id }) + }, + conflictOperation: async ({ worktreePath }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.conflictOperation', { worktree: worktree.id }) + }, + diff: async ({ worktreePath, filePath, staged, compareAgainstHead }) => { + const file = await resolveRuntimeFilePath(filePath, worktreePath) + return callRuntimeResult('git.diff', { + worktree: file.worktree.id, + filePath: file.relativePath, + staged, + compareAgainstHead + }) + }, + branchCompare: async ({ worktreePath, baseRef }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.branchCompare', { worktree: worktree.id, baseRef }) + }, + upstreamStatus: async ({ worktreePath }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.upstreamStatus', { worktree: worktree.id }) + }, + fetch: async ({ worktreePath }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + await callRuntimeResult('git.fetch', { worktree: worktree.id }) + }, + push: async ({ worktreePath, publish, pushTarget }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + await callRuntimeResult('git.push', { worktree: worktree.id, publish, pushTarget }) + }, + pull: async ({ worktreePath }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + await callRuntimeResult('git.pull', { worktree: worktree.id }) + }, + branchDiff: async ({ worktreePath, filePath, compare, oldPath }) => { + const file = await resolveRuntimeFilePath(filePath, worktreePath) + return callRuntimeResult('git.branchDiff', { + worktree: file.worktree.id, + filePath: file.relativePath, + compare, + oldPath + }) + }, + commit: async ({ worktreePath, message }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.commit', { worktree: worktree.id, message }) + }, + generateCommitMessage: async () => ({ + success: false, + error: 'Commit message generation is unavailable in the web client.' + }), + cancelGenerateCommitMessage: () => Promise.resolve(), + stage: async ({ worktreePath, filePath }) => mutateGitPath('git.stage', worktreePath, filePath), + bulkStage: async ({ worktreePath, filePaths }) => + mutateGitPaths('git.bulkStage', worktreePath, filePaths), + unstage: async ({ worktreePath, filePath }) => + mutateGitPath('git.unstage', worktreePath, filePath), + bulkUnstage: async ({ worktreePath, filePaths }) => + mutateGitPaths('git.bulkUnstage', worktreePath, filePaths), + discard: async ({ worktreePath, filePath }) => + mutateGitPath('git.discard', worktreePath, filePath), + bulkDiscard: async ({ worktreePath, filePaths }) => { + for (const filePath of filePaths) { + await mutateGitPath('git.discard', worktreePath, filePath) + } + }, + remoteFileUrl: async ({ worktreePath, relativePath, line }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.remoteFileUrl', { + worktree: worktree.id, + relativePath, + line + }) + } + } +} + +function createBrowserApi(): NonNullable['browser']> { + return { + registerGuest: () => Promise.resolve(), + unregisterGuest: () => Promise.resolve(), + openDevTools: () => Promise.resolve(false), + setViewportOverride: () => Promise.resolve(false), + onGuestLoadFailed: () => noopUnsubscribe, + onPermissionDenied: () => noopUnsubscribe, + onPopup: () => noopUnsubscribe, + onDownloadRequested: () => noopUnsubscribe, + onDownloadProgress: () => noopUnsubscribe, + onDownloadFinished: () => noopUnsubscribe, + onContextMenuRequested: () => noopUnsubscribe, + onContextMenuDismissed: () => noopUnsubscribe, + onNavigationUpdate: () => noopUnsubscribe, + onActivateView: () => noopUnsubscribe, + onPaneFocus: () => noopUnsubscribe, + onOpenLinkInOrcaTab: () => noopUnsubscribe, + acceptDownload: () => + Promise.resolve({ ok: false, reason: 'Downloads are handled by the server browser.' }), + cancelDownload: () => Promise.resolve(false), + setGrabMode: () => + Promise.resolve({ ok: false, error: 'Grab mode is unavailable in the web client.' }), + awaitGrabSelection: () => + Promise.resolve({ ok: false, error: 'Grab mode is unavailable in the web client.' }), + cancelGrab: () => Promise.resolve(false), + captureSelectionScreenshot: () => + Promise.resolve({ + ok: false, + error: 'Selection screenshots are unavailable in the web client.' + }), + extractHoverPayload: () => + Promise.resolve({ ok: false, error: 'Hover extraction is unavailable in the web client.' }), + onGrabModeToggle: () => noopUnsubscribe, + onGrabActionShortcut: () => noopUnsubscribe, + sessionListProfiles: () => Promise.resolve([]), + sessionCreateProfile: () => Promise.resolve(null), + sessionDeleteProfile: () => Promise.resolve(false), + sessionImportCookies: () => + Promise.resolve({ + ok: false, + summary: null, + error: 'Cookie import is unavailable in the web client.' + }), + sessionResolvePartition: () => Promise.resolve(null), + sessionDetectBrowsers: () => Promise.resolve([]), + sessionImportFromBrowser: () => + Promise.resolve({ + ok: false, + summary: null, + error: 'Cookie import is unavailable in the web client.' + }), + sessionClearDefaultCookies: () => Promise.resolve(false), + notifyActiveTabChanged: () => Promise.resolve(false) + } as unknown as NonNullable['browser']> +} + +function createGitHubApi(): NonNullable['gh']> { + const direct = (method: string) => (args?: unknown) => + callRuntimeResult(method, mapRepoPathArg(args)) + return { + viewer: () => Promise.resolve(null), + repoSlug: direct('github.repoSlug'), + prForBranch: direct('github.prForBranch'), + issue: direct('github.issue'), + workItem: direct('github.workItem'), + workItemByOwnerRepo: direct('github.workItemByOwnerRepo'), + workItemDetails: direct('github.workItemDetails'), + prFileContents: direct('github.prFileContents'), + listIssues: async () => [], + createIssue: direct('github.createIssue'), + countWorkItems: direct('github.countWorkItems'), + listWorkItems: direct('github.listWorkItems'), + prChecks: direct('github.prChecks'), + prComments: direct('github.prComments'), + resolveReviewThread: direct('github.resolveReviewThread'), + updatePRTitle: direct('github.updatePRTitle'), + mergePR: direct('github.mergePR'), + updateIssue: direct('github.updateIssue'), + addIssueComment: direct('github.addIssueComment'), + addPRReviewCommentReply: direct('github.addPRReviewCommentReply'), + addPRReviewComment: direct('github.addPRReviewComment'), + listLabels: direct('github.listLabels'), + listAssignableUsers: direct('github.listAssignableUsers'), + onWorkItemMutated: () => noopUnsubscribe, + checkOrcaStarred: () => Promise.resolve(null), + starOrca: () => Promise.resolve(false), + rateLimit: direct('github.rateLimit'), + diagnoseAuth: () => + Promise.resolve({ ok: false, message: 'Unavailable in the web client.' } as never), + listAccessibleProjects: direct('github.project.listAccessible'), + resolveProjectRef: direct('github.project.resolveRef'), + listProjectViews: direct('github.project.listViews'), + getProjectViewTable: direct('github.project.viewTable'), + projectWorkItemDetailsBySlug: direct('github.project.workItemDetailsBySlug'), + updateProjectItemField: direct('github.project.updateItemField'), + clearProjectItemField: direct('github.project.clearItemField'), + updateIssueBySlug: direct('github.project.updateIssueBySlug'), + updatePullRequestBySlug: direct('github.project.updatePullRequestBySlug'), + addIssueCommentBySlug: direct('github.project.addIssueCommentBySlug'), + updateIssueCommentBySlug: direct('github.project.updateIssueCommentBySlug'), + deleteIssueCommentBySlug: direct('github.project.deleteIssueCommentBySlug'), + listLabelsBySlug: direct('github.project.listLabelsBySlug'), + listAssignableUsersBySlug: direct('github.project.listAssignableUsersBySlug'), + listIssueTypesBySlug: direct('github.project.listIssueTypesBySlug'), + updateIssueTypeBySlug: direct('github.project.updateIssueTypeBySlug') + } as NonNullable['gh']> +} + +function createRuntimeNamespaceApi(prefix: string): never { + return createFallbackProxy([prefix], (path, args) => { + const method = `${prefix}.${path.at(-1) ?? ''}` + return callRuntimeResult(method, args[0]) + }) as never +} + +function createNotesApi(): NonNullable['notes']> { + const noteCall = (method: string) => (args: Record) => + callRuntimeResult(method, { ...args, worktree: args.worktreeId }) + return { + list: noteCall('note.list'), + show: noteCall('note.show'), + create: noteCall('note.create'), + save: noteCall('note.save'), + rename: noteCall('note.rename'), + delete: noteCall('note.delete'), + append: noteCall('note.append'), + search: noteCall('note.search'), + link: noteCall('note.link'), + panelState: noteCall('note.panelState') + } as NonNullable['notes']> +} + +function createHooksApi(): NonNullable['hooks']> { + return { + check: async ({ repoId }) => callRuntimeResult('repo.hooksCheck', { repo: repoId }), + createIssueCommandRunner: async () => ({ launched: false }) as never, + readIssueCommand: async ({ repoId }) => + callRuntimeResult('repo.issueCommandRead', { repo: repoId }), + writeIssueCommand: async ({ repoId, content }) => { + await callRuntimeResult('repo.issueCommandWrite', { repo: repoId, content }) + } + } +} + +function createWebUiApi(): NonNullable['ui']> { + let zoomLevel = readJson(UI_STORAGE_KEY, getDefaultUIState()).uiZoomLevel + return { + get: () => Promise.resolve(readJson(UI_STORAGE_KEY, getDefaultUIState())), + set: async (updates) => { + const next = { ...readJson(UI_STORAGE_KEY, getDefaultUIState()), ...updates } + writeJson(UI_STORAGE_KEY, next) + }, + readClipboardText: () => navigator.clipboard?.readText?.() ?? Promise.resolve(''), + saveClipboardImageAsTempFile: () => Promise.resolve(null), + writeClipboardText: (text) => navigator.clipboard?.writeText?.(text) ?? Promise.resolve(), + writeClipboardImage: () => Promise.resolve(), + getZoomLevel: () => zoomLevel, + setZoomLevel: (level) => { + zoomLevel = level + }, + isMaximized: () => Promise.resolve(false), + onOpenSettings: () => noopUnsubscribe, + onOpenFeatureTour: () => noopUnsubscribe, + onShowFeatureTourNudge: () => noopUnsubscribe, + onToggleLeftSidebar: () => noopUnsubscribe, + onToggleRightSidebar: () => noopUnsubscribe, + onToggleWorktreePalette: () => noopUnsubscribe, + onToggleFloatingTerminal: () => noopUnsubscribe, + onOpenQuickOpen: () => noopUnsubscribe, + onOpenNewWorkspace: () => noopUnsubscribe, + onJumpToWorktreeIndex: () => noopUnsubscribe, + onWorktreeHistoryNavigate: () => noopUnsubscribe, + onNewBrowserTab: () => noopUnsubscribe, + onRequestTabCreate: () => noopUnsubscribe, + replyTabCreate: () => {}, + onRequestTabSetProfile: () => noopUnsubscribe, + replyTabSetProfile: () => {}, + onRequestTabClose: () => noopUnsubscribe, + replyTabClose: () => {}, + onNewTerminalTab: () => noopUnsubscribe, + onFocusBrowserAddressBar: () => noopUnsubscribe, + onFindInBrowserPage: () => noopUnsubscribe, + onReloadBrowserPage: () => noopUnsubscribe, + onHardReloadBrowserPage: () => noopUnsubscribe, + onCloseActiveTab: () => noopUnsubscribe, + onSwitchTab: () => noopUnsubscribe, + onSwitchTabAcrossAllTypes: () => noopUnsubscribe, + onSwitchTerminalTab: () => noopUnsubscribe, + onToggleStatusBar: () => noopUnsubscribe, + onDictationKeyDown: () => noopUnsubscribe, + onExportPdfRequested: () => noopUnsubscribe, + onActivateWorktree: () => noopUnsubscribe, + onCreateTerminal: () => noopUnsubscribe, + onRequestTerminalCreate: () => noopUnsubscribe, + replyTerminalCreate: () => {}, + onSplitTerminal: () => noopUnsubscribe, + onRenameTerminal: () => noopUnsubscribe, + onFocusTerminal: () => noopUnsubscribe, + onFocusEditorTab: () => noopUnsubscribe, + onCloseSessionTab: () => noopUnsubscribe, + onOpenFileFromMobile: () => noopUnsubscribe, + onMobileMarkdownRequest: () => noopUnsubscribe, + respondMobileMarkdownRequest: () => {}, + onCloseTerminal: () => noopUnsubscribe, + onSleepWorktree: () => noopUnsubscribe, + onTerminalZoom: () => noopUnsubscribe, + onFileDrop: () => noopUnsubscribe, + syncTrafficLights: () => {}, + setMarkdownEditorFocused: () => {}, + onRichMarkdownContextCommand: () => noopUnsubscribe, + onFullscreenChanged: () => noopUnsubscribe, + minimize: () => {}, + maximize: () => {}, + onMaximizeChanged: () => noopUnsubscribe, + requestClose: () => {}, + popupMenu: () => {}, + onWindowCloseRequested: () => noopUnsubscribe, + confirmWindowClose: () => {} + } +} + +function createPreflightApi(): NonNullable['preflight']> { + const fallbackStatus: PreflightStatus = { + git: { installed: false }, + gh: { installed: false, authenticated: false }, + glab: { installed: false, authenticated: false }, + bitbucket: { configured: false, authenticated: false, account: null } + } + const fallbackRefreshAgents: RefreshAgentsResult = { + agents: [], + addedPathSegments: [], + shellHydrationOk: false, + pathSource: 'sync_seed_only', + pathFailureReason: 'spawn_error' + } + return { + check: async (args) => { + if (!requireActiveEnvironmentOrNull()) { + return fallbackStatus + } + return callRuntimeResult('preflight.check', args) + }, + detectAgents: async () => { + if (!requireActiveEnvironmentOrNull()) { + return [] + } + return callRuntimeResult('preflight.detectAgents').catch(() => []) + }, + refreshAgents: () => + requireActiveEnvironmentOrNull() + ? callRuntimeResult('preflight.refreshAgents') + .then((result) => result as RefreshAgentsResult) + .catch(() => fallbackRefreshAgents) + : Promise.resolve(fallbackRefreshAgents), + detectRemoteAgents: async (args) => + requireActiveEnvironmentOrNull() + ? callRuntimeResult('preflight.detectRemoteAgents', args).catch(() => []) + : [] + } +} + +function createCliApi(): NonNullable['cli']> { + const status = { + platform: getBrowserPlatform(), + commandName: 'orca', + commandPath: null, + pathDirectory: null, + pathConfigured: false, + launcherPath: null, + installMethod: null, + supported: false, + state: 'unsupported', + currentTarget: null, + unsupportedReason: 'launch_mode_unavailable', + detail: 'CLI registration is managed on the Orca server, not in the web browser.' + } as const + return { + getInstallStatus: () => Promise.resolve(status), + install: () => Promise.resolve(status), + remove: () => Promise.resolve(status) + } as NonNullable['cli']> +} + +function createAgentHooksApi(): NonNullable['agentHooks']> { + const status = (agent: 'claude' | 'codex' | 'gemini' | 'cursor' | 'droid') => + Promise.resolve({ + agent, + state: 'not_installed', + configPath: '', + managedHooksPresent: false, + detail: 'Agent hook status is only available on the Orca server.' + } as const) + return { + claudeStatus: () => status('claude'), + codexStatus: () => status('codex'), + geminiStatus: () => status('gemini'), + cursorStatus: () => status('cursor'), + droidStatus: () => status('droid') + } +} + +function createDeveloperPermissionsApi(): NonNullable['developerPermissions']> { + return { + getStatus: () => Promise.resolve([]), + request: ({ id }) => + Promise.resolve({ id, status: 'unsupported', openedSystemSettings: false } as const), + openSettings: () => Promise.resolve() + } +} + +function createComputerUsePermissionsApi(): NonNullable< + Partial['computerUsePermissions'] +> { + return { + getStatus: () => + Promise.resolve({ + platform: getBrowserPlatform(), + helperAppPath: null, + helperUnavailableReason: 'web_client', + permissions: [] + }), + openSetup: () => + Promise.resolve({ + platform: getBrowserPlatform(), + helperAppPath: null, + openedSettings: false, + launchedHelper: false, + nextStep: 'Computer-use permissions are managed on the Orca server.' + }) + } +} + +function createNotificationsApi(): NonNullable['notifications']> { + return { + dispatch: () => Promise.resolve({ delivered: false, reason: 'not-supported' }), + openSystemSettings: () => Promise.resolve(), + getPermissionStatus: () => + Promise.resolve({ supported: false, platform: getBrowserPlatform(), requested: false }), + requestPermission: () => + Promise.resolve({ supported: false, platform: getBrowserPlatform(), requested: false }), + playSound: () => Promise.resolve({ played: false, reason: 'missing-path' }) + } +} + +function createRateLimitsApi(): NonNullable['rateLimits']> { + const empty: RateLimitState = { + claude: null, + codex: null, + gemini: null, + opencodeGo: null, + inactiveClaudeAccounts: [], + inactiveCodexAccounts: [] + } + return { + get: () => Promise.resolve(empty), + refresh: () => Promise.resolve(empty), + setPollingInterval: () => Promise.resolve(), + fetchInactiveClaudeAccounts: () => Promise.resolve(), + fetchInactiveCodexAccounts: () => Promise.resolve(), + onUpdate: () => noopUnsubscribe + } +} + +function createAccountsApi(): never { + const empty = { accounts: [], activeAccountId: null } + return { + list: () => Promise.resolve(empty), + add: () => Promise.resolve(empty), + reauthenticate: () => Promise.resolve(empty), + remove: () => Promise.resolve(empty), + select: () => Promise.resolve(empty) + } as never +} + +function createUpdaterApi(): NonNullable['updater']> { + return { + getVersion: () => Promise.resolve('web'), + getStatus: () => Promise.resolve({ state: 'idle' } as never), + check: () => Promise.resolve(), + download: () => Promise.resolve(), + quitAndInstall: () => Promise.resolve(), + dismissNudge: () => Promise.resolve(), + onStatus: () => noopUnsubscribe, + onClearDismissal: () => noopUnsubscribe + } +} + +function createShellApi(): NonNullable['shell']> { + return { + openPath: (path) => + Promise.resolve(window.open(path, '_blank', 'noopener,noreferrer') as never), + openUrl: (url) => Promise.resolve(window.open(url, '_blank', 'noopener,noreferrer') as never), + openFilePath: () => Promise.resolve(), + openFileUri: (uri) => + Promise.resolve(window.open(uri, '_blank', 'noopener,noreferrer') as never), + pathExists: async (path) => { + try { + await resolveRuntimeFilePath(path) + return true + } catch { + return false + } + }, + pickAttachment: () => Promise.resolve(null), + pickImage: () => Promise.resolve(null), + pickAudio: () => Promise.resolve(null), + pickDirectory: () => Promise.resolve(null), + copyFile: () => Promise.resolve() + } +} + +function createPtyApi(): NonNullable['pty']> { + return { + spawn: () => Promise.reject(new Error('Local PTYs are unavailable in the web client.')), + write: () => {}, + resize: () => {}, + reportGeometry: () => {}, + signal: () => {}, + kill: () => Promise.resolve(), + ackColdRestore: () => {}, + hasChildProcesses: () => Promise.resolve(false), + getForegroundProcess: () => Promise.resolve(null), + getCwd: () => Promise.resolve('~'), + listSessions: () => Promise.resolve([]), + onData: () => noopUnsubscribe, + onReplay: () => noopUnsubscribe, + onExit: () => noopUnsubscribe, + onSerializeBufferRequest: () => noopUnsubscribe, + onClearBufferRequest: () => noopUnsubscribe, + sendSerializedBuffer: () => {}, + declarePendingPaneSerializer: () => Promise.resolve(0), + settlePaneSerializer: () => Promise.resolve(), + clearPendingPaneSerializer: () => Promise.resolve(), + management: { + listSessions: () => Promise.resolve({ sessions: [] }), + killAll: () => Promise.resolve({ killedCount: 0, remainingCount: 0 }), + killOne: () => Promise.resolve({ success: false }), + restart: () => Promise.resolve({ success: false }) + } + } +} + +function createSshApi(): NonNullable['ssh']> { + return { + listTargets: () => Promise.resolve([]), + addTarget: () => + Promise.reject(new Error('SSH target management is unavailable in the web client.')), + updateTarget: () => + Promise.reject(new Error('SSH target management is unavailable in the web client.')), + removeTarget: () => Promise.resolve(), + importConfig: () => Promise.resolve([]), + connect: () => Promise.resolve(null), + disconnect: () => Promise.resolve(), + terminateSessions: () => Promise.resolve(), + getState: () => Promise.resolve(null), + needsPassphrasePrompt: () => Promise.resolve(false), + testConnection: () => + Promise.resolve({ success: false, error: 'Unavailable in the web client.' }), + onStateChanged: () => noopUnsubscribe, + addPortForward: () => + Promise.reject(new Error('SSH port forwarding is unavailable in the web client.')), + updatePortForward: () => + Promise.reject(new Error('SSH port forwarding is unavailable in the web client.')), + removePortForward: () => Promise.resolve(null), + listPortForwards: () => Promise.resolve([]), + listDetectedPorts: () => Promise.resolve([]), + onPortForwardsChanged: () => noopUnsubscribe, + onDetectedPortsChanged: () => noopUnsubscribe, + browseDir: () => Promise.resolve({ entries: [], resolvedPath: '' }), + onCredentialRequest: () => noopUnsubscribe, + onCredentialResolved: () => noopUnsubscribe, + submitCredential: () => Promise.resolve() + } +} + +async function callRuntimeEnvelope( + method: string, + params?: unknown, + timeoutMs?: number +): Promise> { + const environment = requireActiveEnvironment() + const response = await getClientForEnvironment(environment).call(method, params, { timeoutMs }) + updateEnvironmentFromResponse(environment, response) + return response as RuntimeRpcResponse +} + +async function callEnvironmentEnvelope( + selector: string, + method: string, + params?: unknown, + timeoutMs?: number +): Promise> { + const environment = resolveEnvironment(selector) + const response = await getClientForEnvironment(environment).call(method, params, { timeoutMs }) + updateEnvironmentFromResponse(environment, response) + return response as RuntimeRpcResponse +} + +async function callRuntimeResult( + method: string, + params?: unknown, + timeoutMs?: number +): Promise { + const response = await callRuntimeEnvelope(method, params, timeoutMs) + if (!response.ok) { + throw new Error(response.error.message) + } + return response.result as TResult +} + +async function getRemoteRuntimeStatus(): Promise { + return callRuntimeResult('status.get', undefined, 15_000) +} + +function getClientForEnvironment(environment: StoredWebRuntimeEnvironment): WebRuntimeClient { + if (!activeClient || activeClientEnvironmentId !== environment.id) { + activeClient?.close() + activeClient = new WebRuntimeClient(getPreferredWebPairingOffer(environment)) + activeClientEnvironmentId = environment.id + } + return activeClient +} + +function closeActiveRuntimeClients(): void { + activeClient?.close() + activeClient = null + activeClientEnvironmentId = null + cachedWorktrees = null +} + +function disconnectActiveRuntimeEnvironment(): void { + closeActiveRuntimeClients() + clearStoredWebRuntimeEnvironment() + activeEnvironment = null +} + +function resolveEnvironment(selector: string): StoredWebRuntimeEnvironment { + const environment = requireActiveEnvironment() + if (selector === environment.id || selector === environment.name || selector === 'active') { + return environment + } + throw new Error(`Unknown Orca runtime environment: ${selector}`) +} + +function requireActiveEnvironment(): StoredWebRuntimeEnvironment { + activeEnvironment = activeEnvironment ?? readStoredWebRuntimeEnvironment() + if (!activeEnvironment) { + throw new Error('Pair this web client with an Orca server first.') + } + return activeEnvironment +} + +function requireActiveEnvironmentOrNull(): StoredWebRuntimeEnvironment | null { + activeEnvironment = activeEnvironment ?? readStoredWebRuntimeEnvironment() + return activeEnvironment +} + +function updateEnvironmentFromResponse( + environment: StoredWebRuntimeEnvironment, + response: RuntimeRpcResponse +): void { + const runtimeId = response.ok ? response._meta.runtimeId : (response._meta?.runtimeId ?? null) + activeEnvironment = updateStoredEnvironmentRuntimeId(environment, runtimeId) +} + +function getStoredSettings(): GlobalSettings { + const environment = (activeEnvironment = activeEnvironment ?? readStoredWebRuntimeEnvironment()) + const defaults = getDefaultSettings('~') + const stored = readJson>(SETTINGS_STORAGE_KEY, {}) + return mergeSettings( + { + ...defaults, + floatingTerminalEnabled: false, + rightSidebarOpenByDefault: false, + activeRuntimeEnvironmentId: environment?.id ?? null + }, + stored + ) +} + +function getStoredOnboarding(): OnboardingState { + const storedRaw = window.localStorage.getItem(ONBOARDING_STORAGE_KEY) + if (storedRaw) { + const stored = readJson(ONBOARDING_STORAGE_KEY, getDefaultOnboardingState()) + if (stored.checklist.dismissed) { + return stored + } + const closed = closeWebOnboarding(stored) + writeJson(ONBOARDING_STORAGE_KEY, closed) + return closed + } + const closed = closeWebOnboarding(getDefaultOnboardingState()) + // Why: pairing already means the user has an Orca server. Desktop first-run + // onboarding would incorrectly probe browser-local tools and block the client. + writeJson(ONBOARDING_STORAGE_KEY, closed) + return closed +} + +function closeWebOnboarding(base: OnboardingState): OnboardingState { + return { + ...base, + closedAt: Date.now(), + outcome: 'dismissed', + checklist: { + ...base.checklist, + dismissed: true + } + } +} + +function mergeSettings(base: GlobalSettings, updates: Partial): GlobalSettings { + const defaults = getDefaultSettings('~') + return { + ...base, + ...updates, + notifications: { + ...base.notifications, + ...updates.notifications + }, + githubProjects: { + ...(base.githubProjects ?? defaults.githubProjects), + ...updates.githubProjects + } as GlobalSettings['githubProjects'], + voice: { + ...(base.voice ?? defaults.voice), + ...updates.voice + } as NonNullable, + activeRuntimeEnvironmentId: activeEnvironment?.id ?? updates.activeRuntimeEnvironmentId ?? null + } +} + +async function listAllRuntimeWorktrees(): Promise { + if (cachedWorktrees && Date.now() - cachedWorktrees.loadedAt < 5_000) { + return cachedWorktrees.worktrees + } + const result = await callRuntimeResult<{ worktrees: Worktree[] }>('worktree.list', {}) + cachedWorktrees = { loadedAt: Date.now(), worktrees: result.worktrees } + return result.worktrees +} + +async function resolveRuntimeWorktreeByPath(worktreePath: string): Promise { + const worktrees = await listAllRuntimeWorktrees() + const match = worktrees + .map((worktree) => ({ + worktree, + relativePath: relativePathInsideRoot(worktree.path, worktreePath) + })) + .filter((entry) => entry.relativePath !== null) + .sort((a, b) => b.worktree.path.length - a.worktree.path.length)[0] + if (!match) { + throw new Error(`No runtime worktree owns ${worktreePath}`) + } + return match.worktree +} + +async function resolveRuntimeFilePath( + filePath: string, + preferredWorktreePath?: string +): Promise<{ worktree: Worktree; relativePath: string }> { + const worktree = preferredWorktreePath + ? await resolveRuntimeWorktreeByPath(preferredWorktreePath) + : await resolveRuntimeWorktreeByPath(filePath) + const relativePath = relativePathInsideRoot(worktree.path, filePath) + if (relativePath === null) { + throw new Error(`File is outside runtime worktree: ${filePath}`) + } + return { worktree, relativePath } +} + +async function mutateGitPath( + method: string, + worktreePath: string, + filePath: string +): Promise { + const file = await resolveRuntimeFilePath(filePath, worktreePath) + await callRuntimeResult(method, { worktree: file.worktree.id, filePath: file.relativePath }) +} + +async function mutateGitPaths( + method: string, + worktreePath: string, + filePaths: string[] +): Promise { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + await callRuntimeResult(method, { worktree: worktree.id, filePaths }) +} + +function mapRepoPathArg(args: unknown): unknown { + if (!args || typeof args !== 'object' || !('repoPath' in args)) { + return args + } + const record = args as Record + return { + ...record, + repo: record.repoPath + } +} + +function createEmptyMemorySnapshot(): MemorySnapshot { + const emptyUsage = { cpu: 0, memory: 0 } + return { + app: { ...emptyUsage, main: emptyUsage, renderer: emptyUsage, other: emptyUsage, history: [] }, + worktrees: [], + host: { + totalMemory: 0, + freeMemory: 0, + usedMemory: 0, + memoryUsagePercent: 0, + cpuCoreCount: navigator.hardwareConcurrency || 1, + loadAverage1m: 0 + }, + totalCpu: 0, + totalMemory: 0, + collectedAt: Date.now() + } +} + +function getBrowserPlatform(): NodeJS.Platform { + if (navigator.userAgent.includes('Windows')) { + return 'win32' + } + if (navigator.userAgent.includes('Linux')) { + return 'linux' + } + return 'darwin' +} + +function readJson(key: string, fallback: T): T { + const raw = window.localStorage.getItem(key) + if (!raw) { + return cloneJson(fallback) + } + try { + return { ...cloneJson(fallback), ...JSON.parse(raw) } as T + } catch { + return cloneJson(fallback) + } +} + +function writeJson(key: string, value: T): void { + window.localStorage.setItem(key, JSON.stringify(value)) +} + +function cloneJson(value: T): T { + return JSON.parse(JSON.stringify(value)) as T +} + +function withFallback(target: T, path: string[]): T { + return new Proxy(target, { + get(current, property, receiver) { + if (property in current) { + const value = Reflect.get(current, property, receiver) as unknown + if (value && typeof value === 'object' && !Array.isArray(value)) { + return withFallback(value as object, [...path, String(property)]) + } + return value + } + return createFallbackProxy([...path, String(property)]) + } + }) +} + +function createFallbackProxy( + path: string[], + applyOverride?: (path: string[], args: unknown[]) => unknown +): never { + const fn = () => undefined + return new Proxy(fn, { + get(_target, property) { + if (property === 'then') { + return undefined + } + return createFallbackProxy([...path, String(property)], applyOverride) + }, + apply(_target, _thisArg, args) { + if (applyOverride) { + return applyOverride(path, args) + } + return getFallbackResult(path, args) + } + }) as never +} + +function getFallbackResult(path: string[], args: unknown[]): unknown { + const name = path.at(-1) ?? '' + if (name.startsWith('on')) { + return noopUnsubscribe + } + if (name.startsWith('is') || name.startsWith('has') || name === 'pathExists') { + return Promise.resolve(false) + } + if (name.startsWith('list') || name.startsWith('detect')) { + return Promise.resolve([]) + } + if (name.startsWith('preview')) { + return Promise.resolve({ found: false, diff: {}, unsupportedKeys: [] }) + } + if (name.startsWith('get') && name.endsWith('Status')) { + return Promise.resolve([]) + } + if (name === 'write' || name === 'resize' || name === 'reportGeometry') { + return undefined + } + if (args.length === 0 && (name === 'getZoomLevel' || name === 'declarePendingPaneSerializer')) { + return 0 + } + return Promise.resolve(undefined) +} + +function noopUnsubscribe(): void {} diff --git a/src/renderer/src/web/web-runtime-client.test.ts b/src/renderer/src/web/web-runtime-client.test.ts new file mode 100644 index 000000000..58e1a2f3d --- /dev/null +++ b/src/renderer/src/web/web-runtime-client.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi, afterEach, beforeEach } from 'vitest' +import { WebRuntimeClient } from './web-runtime-client' + +class FakeWebSocket { + static readonly CONNECTING = 0 + static readonly OPEN = 1 + readonly readyState = FakeWebSocket.CONNECTING + binaryType = 'arraybuffer' + close = vi.fn() + send = vi.fn() + + constructor(readonly _url: string) {} +} + +describe('WebRuntimeClient', () => { + beforeEach(() => { + vi.stubGlobal('window', { + setTimeout, + clearTimeout, + atob: (value: string) => Buffer.from(value, 'base64').toString('binary') + }) + vi.stubGlobal('WebSocket', FakeWebSocket) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('closes child subscription clients when the owning client closes', () => { + const client = new WebRuntimeClient({ + v: 2, + endpoint: 'ws://127.0.0.1:6768', + deviceToken: 'token', + publicKeyB64: Buffer.alloc(32).toString('base64') + }) + const child = { close: vi.fn() } + + ;( + client as unknown as { + childClients: Set<{ close: () => void }> + } + ).childClients.add(child) + + client.close() + + expect(child.close).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/web/web-runtime-client.ts b/src/renderer/src/web/web-runtime-client.ts new file mode 100644 index 000000000..93e48598f --- /dev/null +++ b/src/renderer/src/web/web-runtime-client.ts @@ -0,0 +1,548 @@ +/* eslint-disable max-lines -- Why: this browser runtime client owns the E2EE + WebSocket state machine, JSON-RPC request routing, streaming callbacks, and + binary frame forwarding as one transport boundary. */ +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import { isKeepaliveFrame } from '../../../shared/runtime-rpc-envelope' +import type { WebPairingOffer } from './web-pairing' +import { + decrypt, + decryptBytes, + deriveSharedKey, + encrypt, + encryptBytes, + generateKeyPair, + publicKeyFromBase64, + publicKeyToBase64 +} from './web-e2ee' + +type WebRuntimeConnectionState = + | 'disconnected' + | 'connecting' + | 'handshaking' + | 'connected' + | 'auth-failed' + +type PendingRequest = { + method: string + resolve: (response: RuntimeRpcResponse) => void + reject: (error: Error) => void + timeout: number +} + +type SubscriptionCallbacks = { + onResponse: (response: RuntimeRpcResponse) => void + onBinary?: (bytes: Uint8Array) => void + onError?: (error: { code: string; message: string }) => void + onClose?: () => void +} + +type RuntimeSubscription = { + method: string + params: unknown + callbacks: SubscriptionCallbacks +} + +export type WebRuntimeSubscriptionHandle = { + unsubscribe: () => void + sendBinary: (bytes: Uint8Array) => void +} + +const REQUEST_TIMEOUT_MS = 30_000 +const CONNECT_TIMEOUT_MS = 12_000 +const HANDSHAKE_TIMEOUT_MS = 10_000 +const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000, 15_000] + +export class WebRuntimeClient { + private ws: WebSocket | null = null + private sharedKey: Uint8Array | null = null + private state: WebRuntimeConnectionState = 'disconnected' + private requestCounter = 0 + private reconnectAttempt = 0 + private intentionallyClosed = false + private connectTimer: number | null = null + private handshakeTimer: number | null = null + private reconnectTimer: number | null = null + private readonly pending = new Map() + private readonly subscriptions = new Map() + private readonly childClients = new Set() + private readonly waiters: { resolve: () => void; reject: (error: Error) => void }[] = [] + private readonly serverPublicKey: Uint8Array + + constructor(private readonly pairing: WebPairingOffer) { + this.serverPublicKey = publicKeyFromBase64(pairing.publicKeyB64) + this.openConnection() + } + + async call( + method: string, + params?: unknown, + options?: { timeoutMs?: number } + ): Promise> { + await this.waitForConnected(options?.timeoutMs) + return new Promise((resolve, reject) => { + const id = this.nextId() + const timeoutMs = options?.timeoutMs ?? REQUEST_TIMEOUT_MS + const timeout = window.setTimeout(() => { + this.pending.delete(id) + reject(new Error(`Request timed out: ${method}`)) + }, timeoutMs) + this.pending.set(id, { method, resolve, reject, timeout }) + if (!this.sendEncrypted({ id, deviceToken: this.pairing.deviceToken, method, params })) { + this.pending.delete(id) + window.clearTimeout(timeout) + reject(new Error('Remote Orca runtime is not connected.')) + } + }) + } + + async subscribe( + method: string, + params: unknown, + callbacks: SubscriptionCallbacks, + options?: { timeoutMs?: number } + ): Promise { + const client = new WebRuntimeClient(this.pairing) + this.childClients.add(client) + const closeChild = (): void => { + this.childClients.delete(client) + client.close() + } + try { + const wrappedCallbacks: SubscriptionCallbacks = { + ...callbacks, + onError: (error) => { + callbacks.onError?.(error) + closeChild() + }, + onClose: () => { + callbacks.onClose?.() + closeChild() + } + } + const handle = await client.subscribeOnCurrentConnection( + method, + params, + wrappedCallbacks, + options + ) + return { + unsubscribe: () => { + handle.unsubscribe() + closeChild() + }, + sendBinary: (bytes) => handle.sendBinary(bytes) + } + } catch (error) { + closeChild() + throw error + } + } + + private async subscribeOnCurrentConnection( + method: string, + params: unknown, + callbacks: SubscriptionCallbacks, + options?: { timeoutMs?: number } + ): Promise { + await this.waitForConnected(options?.timeoutMs) + const id = this.nextId() + this.subscriptions.set(id, { method, params, callbacks }) + if (!this.sendEncrypted({ id, deviceToken: this.pairing.deviceToken, method, params })) { + this.subscriptions.delete(id) + throw new Error('Remote Orca runtime is not connected.') + } + return { + unsubscribe: () => { + this.subscriptions.delete(id) + }, + sendBinary: (bytes) => { + this.sendEncryptedBinary(bytes) + } + } + } + + close(): void { + this.intentionallyClosed = true + for (const child of Array.from(this.childClients)) { + child.close() + } + this.childClients.clear() + this.clearTimers() + this.rejectAllPending('Remote Orca runtime connection closed.') + this.notifySubscriptionsClosed() + if (this.ws) { + this.ws.close() + this.ws = null + } + this.sharedKey = null + this.setState('disconnected') + } + + private openConnection(): void { + if (this.intentionallyClosed) { + return + } + let ws: WebSocket + try { + ws = new WebSocket(this.pairing.endpoint) + } catch (error) { + this.rejectAllPending(error instanceof Error ? error.message : String(error)) + this.scheduleReconnect() + return + } + + ws.binaryType = 'arraybuffer' + this.ws = ws + this.sharedKey = null + this.setState('connecting') + + this.connectTimer = window.setTimeout(() => { + if (this.ws === ws && ws.readyState === WebSocket.CONNECTING) { + ws.close() + this.handleSocketClosed(ws) + } + }, CONNECT_TIMEOUT_MS) + + ws.onopen = () => { + if (this.ws !== ws) { + return + } + this.clearConnectTimer() + this.setState('handshaking') + const keyPair = generateKeyPair() + this.sharedKey = deriveSharedKey(keyPair.secretKey, this.serverPublicKey) + ws.send( + JSON.stringify({ + type: 'e2ee_hello', + publicKeyB64: publicKeyToBase64(keyPair.publicKey) + }) + ) + this.handshakeTimer = window.setTimeout(() => { + if (this.ws === ws && this.state === 'handshaking') { + ws.close() + } + }, HANDSHAKE_TIMEOUT_MS) + } + + ws.onmessage = (event) => { + void this.handleSocketMessage(event.data) + } + + ws.onclose = () => this.handleSocketClosed(ws) + ws.onerror = () => { + if (this.state === 'connecting') { + this.rejectAllWaiters(new Error('Could not connect to the remote Orca runtime.')) + } + } + } + + private async handleSocketMessage(rawData: unknown): Promise { + const raw = typeof rawData === 'string' ? rawData : null + if (this.state === 'handshaking') { + if (raw === null || !this.sharedKey) { + return + } + try { + const control = JSON.parse(raw) as { type?: unknown } + if (control.type === 'e2ee_ready') { + this.sendEncrypted({ type: 'e2ee_auth', deviceToken: this.pairing.deviceToken }) + return + } + } catch { + // The authenticated control frame is encrypted, so non-JSON is normal here. + } + + const plaintext = decrypt(raw, this.sharedKey) + if (plaintext === null) { + return + } + try { + const control = JSON.parse(plaintext) as { + type?: unknown + error?: { code?: string; message?: string } + } + if (control.type === 'e2ee_authenticated') { + this.clearHandshakeTimer() + this.reconnectAttempt = 0 + this.setState('connected') + } else if (control.type === 'e2ee_error' || control.error?.code === 'unauthorized') { + this.intentionallyClosed = true + this.setState('auth-failed') + this.rejectAllPending('Unauthorized. Pair this web client again.') + this.notifySubscriptionsError('unauthorized', 'Unauthorized. Pair this web client again.') + this.ws?.close() + } + } catch { + // Ignore malformed handshake payloads; the server will close on timeout. + } + return + } + + if (this.state !== 'connected' || !this.sharedKey) { + return + } + + if (raw === null) { + const encrypted = await websocketPayloadToUint8(rawData) + if (!encrypted) { + return + } + const plaintext = decryptBytes(encrypted, this.sharedKey) + if (!plaintext) { + return + } + for (const subscription of this.subscriptions.values()) { + subscription.callbacks.onBinary?.(plaintext) + } + return + } + + const plaintext = decrypt(raw, this.sharedKey) + if (plaintext === null) { + return + } + + let response: RuntimeRpcResponse | Record + try { + response = JSON.parse(plaintext) as RuntimeRpcResponse | Record + } catch { + return + } + if (isKeepaliveFrame(response)) { + return + } + if (!('id' in response) || typeof response.id !== 'string') { + return + } + if (isRuntimeFailureResponse(response) && response.error.code === 'unauthorized') { + this.intentionallyClosed = true + this.setState('auth-failed') + this.rejectAllPending('Unauthorized. Pair this web client again.') + this.notifySubscriptionsError('unauthorized', 'Unauthorized. Pair this web client again.') + this.ws?.close() + return + } + + const subscription = this.subscriptions.get(response.id) + if (subscription && isSubscriptionResponse(response)) { + subscription.callbacks.onResponse(response) + if (response.ok && isEndResult(response.result)) { + this.subscriptions.delete(response.id) + subscription.callbacks.onClose?.() + } + return + } + + const pending = this.pending.get(response.id) + if (!pending) { + return + } + this.pending.delete(response.id) + window.clearTimeout(pending.timeout) + pending.resolve(response as RuntimeRpcResponse) + } + + private sendEncrypted(message: unknown): boolean { + const ws = this.ws + if (!ws || ws.readyState !== WebSocket.OPEN || !this.sharedKey) { + return false + } + ws.send(encrypt(JSON.stringify(message), this.sharedKey)) + return true + } + + private sendEncryptedBinary(bytes: Uint8Array): boolean { + const ws = this.ws + if (!ws || ws.readyState !== WebSocket.OPEN || !this.sharedKey) { + return false + } + ws.send(encryptBytes(bytes, this.sharedKey)) + return true + } + + private waitForConnected(timeoutMs = REQUEST_TIMEOUT_MS): Promise { + if (this.state === 'connected') { + return Promise.resolve() + } + if (this.state === 'auth-failed') { + return Promise.reject(new Error('Unauthorized. Pair this web client again.')) + } + if (this.intentionallyClosed) { + return Promise.reject(new Error('Remote Orca runtime connection closed.')) + } + return new Promise((resolve, reject) => { + const timeout = window.setTimeout(() => { + const index = this.waiters.findIndex((waiter) => waiter.resolve === resolve) + if (index !== -1) { + this.waiters.splice(index, 1) + } + reject(new Error('Timed out while connecting to the remote Orca runtime.')) + }, timeoutMs) + this.waiters.push({ + resolve: () => { + window.clearTimeout(timeout) + resolve() + }, + reject: (error) => { + window.clearTimeout(timeout) + reject(error) + } + }) + }) + } + + private handleSocketClosed(closedWs: WebSocket): void { + if (this.ws !== closedWs) { + return + } + this.ws = null + this.sharedKey = null + this.clearConnectTimer() + this.clearHandshakeTimer() + this.rejectAllPending('Remote Orca runtime connection interrupted.') + this.notifySubscriptionsClosed() + if (this.intentionallyClosed || this.state === 'auth-failed') { + this.setState(this.state === 'auth-failed' ? 'auth-failed' : 'disconnected') + return + } + this.setState('disconnected') + this.scheduleReconnect() + } + + private scheduleReconnect(): void { + if (this.reconnectTimer || this.intentionallyClosed) { + return + } + const delay = + RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] + this.reconnectAttempt += 1 + this.reconnectTimer = window.setTimeout(() => { + this.reconnectTimer = null + this.openConnection() + }, delay) + } + + private setState(next: WebRuntimeConnectionState): void { + this.state = next + if (next === 'connected') { + for (const waiter of this.waiters.splice(0)) { + waiter.resolve() + } + } else if (next === 'auth-failed') { + this.rejectAllWaiters(new Error('Unauthorized. Pair this web client again.')) + } + } + + private nextId(): string { + this.requestCounter += 1 + return `web-rpc-${this.requestCounter}-${Date.now()}` + } + + private rejectAllPending(reason: string): void { + const error = new Error(reason) + for (const [id, pending] of this.pending) { + this.pending.delete(id) + window.clearTimeout(pending.timeout) + pending.reject(error) + } + } + + private rejectAllWaiters(error: Error): void { + for (const waiter of this.waiters.splice(0)) { + waiter.reject(error) + } + } + + private notifySubscriptionsClosed(): void { + const subscriptions = Array.from(this.subscriptions.values()) + this.subscriptions.clear() + for (const subscription of subscriptions) { + subscription.callbacks.onClose?.() + } + } + + private notifySubscriptionsError(code: string, message: string): void { + const subscriptions = Array.from(this.subscriptions.values()) + this.subscriptions.clear() + for (const subscription of subscriptions) { + subscription.callbacks.onError?.({ code, message }) + } + } + + private clearTimers(): void { + this.clearConnectTimer() + this.clearHandshakeTimer() + if (this.reconnectTimer) { + window.clearTimeout(this.reconnectTimer) + this.reconnectTimer = null + } + } + + private clearConnectTimer(): void { + if (this.connectTimer) { + window.clearTimeout(this.connectTimer) + this.connectTimer = null + } + } + + private clearHandshakeTimer(): void { + if (this.handshakeTimer) { + window.clearTimeout(this.handshakeTimer) + this.handshakeTimer = null + } + } +} + +function isSubscriptionResponse( + response: RuntimeRpcResponse | Record +): response is RuntimeRpcResponse { + if (!('ok' in response)) { + return false + } + if (response.ok === false) { + return true + } + if (response.ok === false) { + return true + } + const success = response as RuntimeRpcResponse & { ok: true; streaming?: true } + return ( + success.streaming === true || isEndResult(success.result) || isScrollbackResult(success.result) + ) +} + +function isRuntimeFailureResponse( + response: RuntimeRpcResponse | Record +): response is RuntimeRpcResponse & { ok: false } { + return ( + 'ok' in response && + response.ok === false && + 'error' in response && + !!response.error && + typeof response.error === 'object' && + 'code' in response.error + ) +} + +function isEndResult(value: unknown): value is { type: 'end' } { + return !!value && typeof value === 'object' && (value as { type?: unknown }).type === 'end' +} + +function isScrollbackResult(value: unknown): value is { type: 'scrollback' } { + return !!value && typeof value === 'object' && (value as { type?: unknown }).type === 'scrollback' +} + +async function websocketPayloadToUint8( + value: unknown +): Promise | null> { + if (value instanceof Uint8Array) { + return value + } + if (value instanceof ArrayBuffer) { + return new Uint8Array(value) + } + if (value instanceof Blob) { + return new Uint8Array(await value.arrayBuffer()) + } + return null +} diff --git a/src/renderer/src/web/web-runtime-environment.ts b/src/renderer/src/web/web-runtime-environment.ts new file mode 100644 index 000000000..57769a1a6 --- /dev/null +++ b/src/renderer/src/web/web-runtime-environment.ts @@ -0,0 +1,115 @@ +import type { PublicKnownRuntimeEnvironment } from '../../../shared/runtime-environments' +import type { WebPairingOffer } from './web-pairing' +import { createBrowserUuid } from '@/lib/browser-uuid' + +export type StoredWebRuntimeEnvironment = Omit & { + endpoints: { + id: string + kind: 'websocket' + label: string + endpoint: string + deviceToken: string + publicKeyB64: string + }[] +} + +const ENVIRONMENT_STORAGE_KEY = 'orca.web.runtimeEnvironment.v1' + +export function readStoredWebRuntimeEnvironment(): StoredWebRuntimeEnvironment | null { + const raw = window.localStorage.getItem(ENVIRONMENT_STORAGE_KEY) + if (!raw) { + return null + } + try { + const parsed = JSON.parse(raw) as StoredWebRuntimeEnvironment + if (!parsed.id || !parsed.name || parsed.endpoints.length === 0) { + return null + } + return parsed + } catch { + return null + } +} + +export function saveStoredWebRuntimeEnvironment(environment: StoredWebRuntimeEnvironment): void { + window.localStorage.setItem(ENVIRONMENT_STORAGE_KEY, JSON.stringify(environment)) +} + +export function clearStoredWebRuntimeEnvironment(): void { + window.localStorage.removeItem(ENVIRONMENT_STORAGE_KEY) +} + +export function createStoredWebRuntimeEnvironment(args: { + name: string + offer: WebPairingOffer +}): StoredWebRuntimeEnvironment { + const id = `web-${createBrowserUuid()}` + const now = Date.now() + return { + id, + name: args.name.trim() || 'Orca Server', + createdAt: now, + updatedAt: now, + lastUsedAt: null, + runtimeId: null, + preferredEndpointId: `ws-${id}`, + endpoints: [ + { + id: `ws-${id}`, + kind: 'websocket', + label: 'WebSocket', + endpoint: args.offer.endpoint, + deviceToken: args.offer.deviceToken, + publicKeyB64: args.offer.publicKeyB64 + } + ] + } +} + +export function redactStoredWebRuntimeEnvironment( + environment: StoredWebRuntimeEnvironment +): PublicKnownRuntimeEnvironment { + return { + ...environment, + endpoints: environment.endpoints.map( + ({ deviceToken: _token, publicKeyB64: _key, ...rest }) => ({ + ...rest + }) + ) + } +} + +export function getPreferredWebPairingOffer( + environment: StoredWebRuntimeEnvironment +): WebPairingOffer { + const endpoint = + environment.endpoints.find((entry) => entry.id === environment.preferredEndpointId) ?? + environment.endpoints[0] + if (!endpoint) { + throw new Error('No runtime endpoint is stored for this web client.') + } + return { + v: 2, + endpoint: endpoint.endpoint, + deviceToken: endpoint.deviceToken, + publicKeyB64: endpoint.publicKeyB64 + } +} + +export function updateStoredEnvironmentRuntimeId( + environment: StoredWebRuntimeEnvironment, + runtimeId: string | null +): StoredWebRuntimeEnvironment { + const next = { + ...environment, + runtimeId, + updatedAt: Date.now(), + lastUsedAt: Date.now() + } + saveStoredWebRuntimeEnvironment(next) + return next +} + +export function isMixedContentWebSocket(endpoint: string): boolean { + return window.location.protocol === 'https:' && endpoint.startsWith('ws://') +} diff --git a/src/renderer/web-index.html b/src/renderer/web-index.html new file mode 100644 index 000000000..09fbbfa76 --- /dev/null +++ b/src/renderer/web-index.html @@ -0,0 +1,15 @@ + + + + + + Orca Web + + +
+ + + diff --git a/vite.web.config.ts b/vite.web.config.ts new file mode 100644 index 000000000..db107e103 --- /dev/null +++ b/vite.web.config.ts @@ -0,0 +1,28 @@ +import { resolve } from 'path' +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' + +export default defineConfig({ + root: resolve('src/renderer'), + // Why: pairing URLs may live under a reverse-proxy path prefix like + // /orca/web-index.html, so built assets must resolve relative to the page. + base: './', + plugins: [react(), tailwindcss()], + resolve: { + alias: { + '@renderer': resolve('src/renderer/src'), + '@': resolve('src/renderer/src') + } + }, + build: { + outDir: resolve('out/web'), + emptyOutDir: true, + rollupOptions: { + input: resolve('src/renderer/web-index.html') + } + }, + worker: { + format: 'es' + } +})