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 <app> --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 <takumihara1226@gmail.com>
This commit is contained in:
Neil
2026-11-14 21:15:22 -08:00
committed by GitHub
co-authored by Takumi Hara
parent d5a90c0da0
commit 07eced7636
11 changed files with 213 additions and 22 deletions
@@ -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)
})
})
@@ -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<boolean> {
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<string> {
if (
process.platform === 'darwin' &&
isFileLocation(location) &&
(await openInMacDefaultAppAtLocation(filePath, location))
) {
return ''
}
return shell.openPath(filePath)
}
@@ -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)
+10
View File
@@ -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')
+12 -4
View File
@@ -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<ShellOpenFileResult> {
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<boolean> =>
(await openWithSystemDefault(filePath, ownerHostId, false)) !== 'failed'
async (
_event,
filePath: string,
ownerHostId: unknown,
location?: RuntimeFileOpenPosition
): Promise<boolean> =>
(await openWithSystemDefault(filePath, ownerHostId, false, location)) !== 'failed'
)
ipcMain.handle(
@@ -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
}
+6 -1
View File
@@ -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<ShellOpenExternalEditorResult>
openUrl: (url: string) => Promise<void>
openFilePath: (path: string, ownerHostId: ExecutionHostId) => Promise<boolean>
openFilePath: (
path: string,
ownerHostId: ExecutionHostId,
location?: RuntimeFileOpenPosition
) => Promise<boolean>
openFileUri: (uri: string, ownerHostId: ExecutionHostId) => Promise<ShellOpenFileResult>
pathsExist?: (paths: string[]) => Promise<ShellPathExistence[]>
/** `wakeWslDistro`: a click, a user act that may start a stopped WSL distro. */
+6 -2
View File
@@ -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<void> => ipcRenderer.invoke('shell:openUrl', url),
openFilePath: (path: string, ownerHostId: ExecutionHostId): Promise<boolean> =>
ipcRenderer.invoke('shell:openFilePath', path, ownerHostId),
openFilePath: (
path: string,
ownerHostId: ExecutionHostId,
location?: RuntimeFileOpenPosition
): Promise<boolean> => ipcRenderer.invoke('shell:openFilePath', path, ownerHostId, location),
openFileUri: (uri: string, ownerHostId: ExecutionHostId): Promise<ShellOpenFileResult> =>
ipcRenderer.invoke('shell:openFileUri', uri, ownerHostId),
@@ -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
}
}
@@ -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 }
)
})
+3
View File
@@ -0,0 +1,3 @@
export function isPositiveSafeInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0
}