From 07eced7636ede58d2ebf96ef7baba20cc7327a79 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:15:22 -0800 Subject: [PATCH] fix(editor): open VS Code-family editors at the clicked line on macOS (#42613) When a linked file's macOS default app is Cursor, VS Code or VS Code Insiders, hand it `--goto path:line:column` with `open -n -g -a --args`, the same LaunchServices hand-off the bundled CLI ends in, minus the CLI's Node startup and `--env` forwarding. The editor sees a desktop (non-Dock) open, so it reuses the file's window as a CLI open would. An empty env keeps Orca's variables out of the editor and lets a cold start resolve the login-shell env. `open` returns once the app has launched, like shell.openPath, so there is no timer; a non-zero exit or spawn error falls back to shell.openPath. Other platforms, other apps, links without a line, and files main reveals instead of opening are unchanged. The IPC location reuses RuntimeFileOpenPosition. Moves the positive safe-integer guard to src/shared so this and its two existing copies share one definition. Fixes #29508 Co-authored-by: Takumi Hara --- .../default-app-location-open.test.ts | 92 +++++++++++++++++++ .../default-app-location-open.ts | 71 ++++++++++++++ .../lookup/rest-stack-metadata-validation.ts | 4 +- src/main/ipc/shell.test.ts | 10 ++ src/main/ipc/shell.ts | 16 +++- .../wsl/discovery/wsl-distro-holder-record.ts | 11 +-- src/preload/api/terminal/shell-api.ts | 7 +- src/preload/api/terminal/shell-bridge.ts | 8 +- .../links/files/terminal-file-open-routing.ts | 3 +- .../terminal-link-click-fallback.test.ts | 10 +- src/shared/positive-safe-integer.ts | 3 + 11 files changed, 213 insertions(+), 22 deletions(-) create mode 100644 src/main/external-editors/default-app-location-open.test.ts create mode 100644 src/main/external-editors/default-app-location-open.ts create mode 100644 src/shared/positive-safe-integer.ts diff --git a/src/main/external-editors/default-app-location-open.test.ts b/src/main/external-editors/default-app-location-open.test.ts new file mode 100644 index 00000000000..e795b277d6c --- /dev/null +++ b/src/main/external-editors/default-app-location-open.test.ts @@ -0,0 +1,92 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { applicationInfo, openPath, runProcess } = vi.hoisted(() => ({ + applicationInfo: vi.fn(), + openPath: vi.fn(), + runProcess: vi.fn() +})) +vi.mock('electron', () => ({ + app: { getApplicationInfoForProtocol: applicationInfo }, + shell: { openPath } +})) +vi.mock('@orca/process-host', () => ({ runProcess })) + +import { openPathInDefaultApp } from './default-app-location-open' +import type { RuntimeFileOpenPosition } from '../../shared/file-access/runtime-editor-file-open' + +const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')! +const filePath = '/tmp/project with spaces/main #1.json' + +function setPlatform(value: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { configurable: true, value }) +} + +describe('openPathInDefaultApp', () => { + beforeEach(() => { + vi.resetAllMocks() + setPlatform('darwin') + applicationInfo.mockResolvedValue({ path: '/Applications/Cursor.app' }) + runProcess.mockResolvedValue({ code: 0, timedOut: false }) + openPath.mockResolvedValue('') + }) + afterEach(() => { + Object.defineProperty(process, 'platform', originalPlatform) + }) + + it.each([ + ['Cursor.app', { line: 551, column: 7 }, '551:7'], + ['Visual Studio Code.app', { line: 551 }, '551'], + ['Visual Studio Code - Insiders.app', { line: 551, column: 7 }, '551:7'] + ])( + 'hands the line to a default %s instead of the OS opener', + async (bundle, location, suffix) => { + const appPath = `/Users/ada/Applications/${bundle}` + applicationInfo.mockResolvedValue({ path: appPath }) + + await expect(openPathInDefaultApp(filePath, location)).resolves.toBe('') + + expect(applicationInfo).toHaveBeenCalledWith( + 'file:///tmp/project%20with%20spaces/main%20%231.json' + ) + expect(runProcess).toHaveBeenCalledWith( + expect.objectContaining({ + program: '/usr/bin/open', + args: ['-n', '-g', '-a', appPath, '--args', '--goto', `${filePath}:${suffix}`], + env: {}, + timeoutMs: null + }) + ) + expect(openPath).not.toHaveBeenCalled() + } + ) + + it.each<[string, () => void]>([ + ['another default app', () => applicationInfo.mockResolvedValue({ path: '/A/Zed.app' })], + ['a failed association lookup', () => applicationInfo.mockRejectedValue(new Error('none'))], + ['an open that exits non-zero', () => runProcess.mockResolvedValue({ code: 1 })], + ['an open that cannot spawn', () => runProcess.mockRejectedValue(new Error('ENOENT'))] + ])('opens once with the OS opener on %s', async (_name, arrange) => { + arrange() + openPath.mockResolvedValue('no app') + + await expect(openPathInDefaultApp(filePath, { line: 551 })).resolves.toBe('no app') + expect(openPath).toHaveBeenCalledTimes(1) + expect(openPath).toHaveBeenCalledWith(filePath) + }) + + it.each<[string, NodeJS.Platform, RuntimeFileOpenPosition | undefined]>([ + ['links without a line', 'darwin', undefined], + ['a zero line', 'darwin', { line: 0 }], + ['a fractional line', 'darwin', { line: 1.5 }], + ['a zero column', 'darwin', { line: 551, column: 0 }], + ['Linux', 'linux', { line: 551 }], + ['Windows', 'win32', { line: 551 }] + ])('leaves %s to the OS opener', async (_name, platform, location) => { + setPlatform(platform) + + await expect(openPathInDefaultApp(filePath, location)).resolves.toBe('') + expect(applicationInfo).not.toHaveBeenCalled() + expect(runProcess).not.toHaveBeenCalled() + expect(openPath).toHaveBeenCalledWith(filePath) + }) +}) diff --git a/src/main/external-editors/default-app-location-open.ts b/src/main/external-editors/default-app-location-open.ts new file mode 100644 index 00000000000..62f6ec2198a --- /dev/null +++ b/src/main/external-editors/default-app-location-open.ts @@ -0,0 +1,71 @@ +import { runProcess } from '@orca/process-host' +import { app, shell } from 'electron' +import { posix } from 'node:path' +import { pathToFileURL } from 'node:url' +import { formatFileLinkLocation } from '../../shared/file-links/file-link-location' +import { isPositiveSafeInteger } from '../../shared/positive-safe-integer' +import type { RuntimeFileOpenPosition } from '../../shared/file-access/runtime-editor-file-open' + +// Bundles whose app accepts `--goto path:line:column` on its command line. +const GOTO_CAPABLE_MAC_APPS = new Set([ + 'Cursor.app', + 'Visual Studio Code.app', + 'Visual Studio Code - Insiders.app' +]) + +// Why: the location arrives over IPC, so check its shape rather than trust the type. +function isFileLocation( + location: RuntimeFileOpenPosition | undefined +): location is RuntimeFileOpenPosition { + return ( + isPositiveSafeInteger(location?.line) && + (location?.column === undefined || isPositiveSafeInteger(location.column)) + ) +} + +async function openInMacDefaultAppAtLocation( + filePath: string, + location: RuntimeFileOpenPosition +): Promise { + try { + const { path: appPath } = await app.getApplicationInfoForProtocol(pathToFileURL(filePath).href) + if (!GOTO_CAPABLE_MAC_APPS.has(posix.basename(appPath))) { + return false + } + // Same `open -n -g` hand-off as the editor's CLI, minus its Node startup and `--env` forwarding. + // The editor sees a desktop (non-Dock) open, so it reuses the file's window like a CLI open, and + // the empty env keeps Orca's variables out while a cold start resolves the login-shell env. + const result = await runProcess({ + program: '/usr/bin/open', + args: [ + '-n', + '-g', + '-a', + appPath, + '--args', + '--goto', + formatFileLinkLocation({ pathText: filePath, line: location.line, column: location.column }) + ], + env: {}, + timeoutMs: null + }) + return result.code === 0 + } catch { + return false + } +} + +/** `shell.openPath` that keeps the line when the file's macOS default app is a VS Code-family editor. */ +export async function openPathInDefaultApp( + filePath: string, + location: RuntimeFileOpenPosition | undefined +): Promise { + if ( + process.platform === 'darwin' && + isFileLocation(location) && + (await openInMacDefaultAppAtLocation(filePath, location)) + ) { + return '' + } + return shell.openPath(filePath) +} diff --git a/src/main/github/client/lookup/rest-stack-metadata-validation.ts b/src/main/github/client/lookup/rest-stack-metadata-validation.ts index 9837e4e0d7f..42fb7acfee7 100644 --- a/src/main/github/client/lookup/rest-stack-metadata-validation.ts +++ b/src/main/github/client/lookup/rest-stack-metadata-validation.ts @@ -1,6 +1,4 @@ -export function isPositiveSafeInteger(value: unknown): value is number { - return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 -} +import { isPositiveSafeInteger } from '../../../../shared/positive-safe-integer' export function isGitObjectId(value: unknown): value is string { return typeof value === 'string' && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(value) diff --git a/src/main/ipc/shell.test.ts b/src/main/ipc/shell.test.ts index ac011959bed..f1f8f536e26 100644 --- a/src/main/ipc/shell.test.ts +++ b/src/main/ipc/shell.test.ts @@ -234,6 +234,16 @@ describe('registerShellHandlers', () => { ) }) + it('reveals scripts linked with a line instead of opening them at it', async () => { + inspectLinkedFileMock.mockResolvedValue('view-as-text') + + await expect( + getHandler('shell:openFilePath')({}, scriptPath, 'local', { line: 4 }) + ).resolves.toBe(true) + expect(openPathMock).not.toHaveBeenCalled() + expect(showItemInFolderMock).toHaveBeenCalledWith(scriptPath) + }) + it('refuses non-local owners and remote file URIs before inspecting', async () => { const handler = getHandler('shell:openFileUri') diff --git a/src/main/ipc/shell.ts b/src/main/ipc/shell.ts index ef35895263b..556c5cfe0f9 100644 --- a/src/main/ipc/shell.ts +++ b/src/main/ipc/shell.ts @@ -9,6 +9,7 @@ import type { ShellOpenFileResult, ShellOpenLocalPathResult } from '../../shared/shell/opening/shell-open-types' +import type { RuntimeFileOpenPosition } from '../../shared/file-access/runtime-editor-file-open' import { MAX_REPO_ICON_UPLOAD_BYTES } from '../../shared/repo-icon' import { repoIconPickFailure, @@ -22,6 +23,7 @@ import { } from '../external-editors/external-editor-launch' import { resolveRemoteSshEditorLaunchSpec } from '../external-editors/remote-ssh-editor-launch' import { resolveOpenInEditorCommand } from '../external-editors/open-in-editor-command' +import { openPathInDefaultApp } from '../external-editors/default-app-location-open' import { toSshExecutionHostId } from '../../shared/execution-host' import { isEditorSshHostForOwner, @@ -122,7 +124,8 @@ async function openInExternalEditor( async function openWithSystemDefault( pathValue: string, ownerHostId: unknown, - textInEditor: boolean + textInEditor: boolean, + location?: RuntimeFileOpenPosition ): Promise { if (!isLocallyOwned(ownerHostId)) { return 'failed' @@ -140,7 +143,7 @@ async function openWithSystemDefault( shell.showItemInFolder(target.path) return 'revealed' } - const errorMessage = await shell.openPath(target.path) + const errorMessage = await openPathInDefaultApp(target.path, location) return errorMessage.length === 0 ? 'opened' : 'failed' } catch { return 'failed' @@ -188,8 +191,13 @@ export function registerShellHandlers( ipcMain.handle( 'shell:openFilePath', - async (_event, filePath: string, ownerHostId: unknown): Promise => - (await openWithSystemDefault(filePath, ownerHostId, false)) !== 'failed' + async ( + _event, + filePath: string, + ownerHostId: unknown, + location?: RuntimeFileOpenPosition + ): Promise => + (await openWithSystemDefault(filePath, ownerHostId, false, location)) !== 'failed' ) ipcMain.handle( diff --git a/src/main/wsl/discovery/wsl-distro-holder-record.ts b/src/main/wsl/discovery/wsl-distro-holder-record.ts index e9bf90d8bde..29750af2725 100644 --- a/src/main/wsl/discovery/wsl-distro-holder-record.ts +++ b/src/main/wsl/discovery/wsl-distro-holder-record.ts @@ -6,6 +6,7 @@ import { writeFileDurable } from '../../filesystem/durable-file-write' import { hasErrorCode } from '../../daemon/endpoint/identity/daemon-process-inspection' +import { isPositiveSafeInteger } from '../../../shared/positive-safe-integer' /** Per-distro record intentionally survives Orca quit so the next launch can re-adopt the surviving holder. */ export type WslDistroHolderRecord = { @@ -35,10 +36,6 @@ function recordPath(userDataPath: string, distro: string): string { ) } -function isPositiveInteger(value: unknown): value is number { - return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 -} - export function parseWslDistroHolderRecord(text: string): WslDistroHolderRecord | null { let parsed: unknown try { @@ -59,9 +56,9 @@ export function parseWslDistroHolderRecord(text: string): WslDistroHolderRecord version !== 1 || typeof distro !== 'string' || wslDistroHolderKey(distro) === '' || - !isPositiveInteger(pid) || - !(creationTimeMs === null || isPositiveInteger(creationTimeMs)) || - !isPositiveInteger(startedAtMs) + !isPositiveSafeInteger(pid) || + !(creationTimeMs === null || isPositiveSafeInteger(creationTimeMs)) || + !isPositiveSafeInteger(startedAtMs) ) { return null } diff --git a/src/preload/api/terminal/shell-api.ts b/src/preload/api/terminal/shell-api.ts index 7f967b85885..dc7c3d14a8c 100644 --- a/src/preload/api/terminal/shell-api.ts +++ b/src/preload/api/terminal/shell-api.ts @@ -7,6 +7,7 @@ import type { ShellOpenFileResult, ShellOpenLocalPathResult } from '../../../shared/shell/opening/shell-open-types' +import type { RuntimeFileOpenPosition } from '../../../shared/file-access/runtime-editor-file-open' export type ShellApi = { /** Every OS open names the path's owner; main refuses anything not owned by this computer. */ @@ -19,7 +20,11 @@ export type ShellApi = { request: ShellOpenExternalEditorRequest ) => Promise openUrl: (url: string) => Promise - openFilePath: (path: string, ownerHostId: ExecutionHostId) => Promise + openFilePath: ( + path: string, + ownerHostId: ExecutionHostId, + location?: RuntimeFileOpenPosition + ) => Promise openFileUri: (uri: string, ownerHostId: ExecutionHostId) => Promise pathsExist?: (paths: string[]) => Promise /** `wakeWslDistro`: a click, a user act that may start a stopped WSL distro. */ diff --git a/src/preload/api/terminal/shell-bridge.ts b/src/preload/api/terminal/shell-bridge.ts index 852efd71561..9353b7df9ef 100644 --- a/src/preload/api/terminal/shell-bridge.ts +++ b/src/preload/api/terminal/shell-bridge.ts @@ -6,6 +6,7 @@ import type { ShellOpenFileResult, ShellOpenLocalPathResult } from '../../../shared/shell/opening/shell-open-types' +import type { RuntimeFileOpenPosition } from '../../../shared/file-access/runtime-editor-file-open' import type { ExecutionHostId } from '../../../shared/execution-host' import type { ShellPathExistence } from '../../../shared/file-access/path-existence-batch' import type { PreloadApi } from '../../api-types' @@ -27,8 +28,11 @@ export const shellApi = { openUrl: (url: string): Promise => ipcRenderer.invoke('shell:openUrl', url), - openFilePath: (path: string, ownerHostId: ExecutionHostId): Promise => - ipcRenderer.invoke('shell:openFilePath', path, ownerHostId), + openFilePath: ( + path: string, + ownerHostId: ExecutionHostId, + location?: RuntimeFileOpenPosition + ): Promise => ipcRenderer.invoke('shell:openFilePath', path, ownerHostId, location), openFileUri: (uri: string, ownerHostId: ExecutionHostId): Promise => ipcRenderer.invoke('shell:openFileUri', uri, ownerHostId), diff --git a/src/renderer/src/components/terminal-pane/links/files/terminal-file-open-routing.ts b/src/renderer/src/components/terminal-pane/links/files/terminal-file-open-routing.ts index 6ee41a67e59..ffd46282fdf 100644 --- a/src/renderer/src/components/terminal-pane/links/files/terminal-file-open-routing.ts +++ b/src/renderer/src/components/terminal-pane/links/files/terminal-file-open-routing.ts @@ -194,7 +194,8 @@ export function openDetectedFilePath( // Why folders skip this: the folder branch opens them with the OS too, and reports a failed open. if (opensWithSystemDefault && canOpenWithSystemDefault && !statResult.isDirectory) { // Shift+Cmd/Ctrl follows URL-link behavior and OS file associations without new editor settings. - if (await window.api.shell.openFilePath(mappedFilePath, LOCAL_EXECUTION_HOST_ID)) { + const location = line === null ? undefined : { line, column: column ?? undefined } + if (await window.api.shell.openFilePath(mappedFilePath, LOCAL_EXECUTION_HOST_ID, location)) { return } } diff --git a/src/renderer/src/components/terminal-pane/links/terminal-link-click-fallback.test.ts b/src/renderer/src/components/terminal-pane/links/terminal-link-click-fallback.test.ts index 183527a4a3a..05fd80af0a3 100644 --- a/src/renderer/src/components/terminal-pane/links/terminal-link-click-fallback.test.ts +++ b/src/renderer/src/components/terminal-pane/links/terminal-link-click-fallback.test.ts @@ -170,7 +170,8 @@ describe('createFilePathLinkProvider range bounds', () => { expect(openFilePathMock).toHaveBeenCalledWith( '/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5/mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/ExpoTwoWayAudioLifeCycleListener.kt', - 'local' + 'local', + undefined ) expect(preventDefault).toHaveBeenCalled() expect(stopPropagation).toHaveBeenCalled() @@ -180,7 +181,7 @@ describe('createFilePathLinkProvider range bounds', () => { expect(element.removeEventListener).toHaveBeenCalledWith('mouseup', mouseUp, { capture: true }) }) - it('opens a deeply wrapped absolute path from its final short continuation row', async () => { + it('opens a deeply wrapped absolute path at its line from its final short continuation row', async () => { setPlatform('Macintosh') const rows = [ makeBufferLine('/private/tmp/or'), @@ -194,7 +195,7 @@ describe('createFilePathLinkProvider range bounds', () => { makeBufferLine('/modules/twoway'), makeBufferLine('audio/ExpoTwoW'), makeBufferLine('ayAudioLifeCyc'), - makeBufferLine('leListener.kt') + makeBufferLine('leListener.kt:12:3') ] const opened = openFilePathLinkAtBufferPosition(makeBuffer(rows), { x: 4, y: 12 }, 15, { @@ -209,7 +210,8 @@ describe('createFilePathLinkProvider range bounds', () => { expect(opened).toBe(true) expect(openFilePathMock).toHaveBeenCalledWith( '/private/tmp/orca-setup-e2e.hOW01f/workspaces/test-wt-5/mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/ExpoTwoWayAudioLifeCycleListener.kt', - 'local' + 'local', + { line: 12, column: 3 } ) }) diff --git a/src/shared/positive-safe-integer.ts b/src/shared/positive-safe-integer.ts new file mode 100644 index 00000000000..55ad4400b85 --- /dev/null +++ b/src/shared/positive-safe-integer.ts @@ -0,0 +1,3 @@ +export function isPositiveSafeInteger(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 +}