diff --git a/src/main/ai-vault-search/session-search-store.ts b/src/main/ai-vault-search/session-search-store.ts index 71215bb71746..435fa16ce8af 100644 --- a/src/main/ai-vault-search/session-search-store.ts +++ b/src/main/ai-vault-search/session-search-store.ts @@ -199,30 +199,32 @@ export class SessionSearchStore { files(): SessionSearchFileRow[] { return ( // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The files schema and SELECT aliases define this row; REAL casts return numeric IDs or null. - this.db - .prepare( - // Numeric stat IDs may exceed SQLite's safe INTEGER-to-number read range. - `SELECT path, CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, + ( + this.db + .prepare( + // Numeric stat IDs may exceed SQLite's safe INTEGER-to-number read range. + `SELECT path, CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, mtime_ms AS mtimeMs, size_bytes AS sizeBytes, state, fail_count AS failCount, failed_mtime_ms AS failedMtimeMs FROM files` - ) - .all() as (Omit & { - dev: number | null - ino: number | null - })[] - ).map((row) => ({ - path: row.path, - identity: - typeof row.dev === 'number' && typeof row.ino === 'number' - ? { dev: row.dev, ino: row.ino } - : null, - mtimeMs: row.mtimeMs, - sizeBytes: row.sizeBytes, - state: row.state, - failCount: row.failCount, - failedMtimeMs: row.failedMtimeMs - })) + ) + .all() as (Omit & { + dev: number | null + ino: number | null + })[] + ).map((row) => ({ + path: row.path, + identity: + typeof row.dev === 'number' && typeof row.ino === 'number' + ? { dev: row.dev, ino: row.ino } + : null, + mtimeMs: row.mtimeMs, + sizeBytes: row.sizeBytes, + state: row.state, + failCount: row.failCount, + failedMtimeMs: row.failedMtimeMs + })) + ) } /** diff --git a/src/main/external-editor-launch.ts b/src/main/external-editor-launch.ts index 6fa0e8675085..fa8a6a1e9c75 100644 --- a/src/main/external-editor-launch.ts +++ b/src/main/external-editor-launch.ts @@ -27,6 +27,12 @@ export type ExternalEditorExecutableLaunchSpec = { * `/B`. Left unset elsewhere because `start` re-parses quoted argv. */ detachedGui?: boolean + /** + * Hand the argv to CreateProcess unquoted. Only for launchers such as + * rundll32's OpenAs_RunDLL that read their raw command-line tail and never + * strip the quotes Node would add around a spaced path. + */ + windowsVerbatimArguments?: boolean spawnCmd: string spawnArgs: string[] } @@ -250,6 +256,7 @@ function resolveExternalEditorSpawn(launchSpec: ExternalEditorLaunchSpec): { spawnCmd: string spawnArgs: string[] windowsHide: boolean + windowsVerbatimArguments?: boolean } { // Why: only shims flagged during resolution (JetBrains) take the start /B // detach; every other launcher keeps the waiting form so its argv survives. @@ -257,7 +264,11 @@ function resolveExternalEditorSpawn(launchSpec: ExternalEditorLaunchSpec): { const spawned = getSpawnArgsForWindows(launchSpec.spawnCmd, launchSpec.spawnArgs, { detachedGui: launchSpec.detachedGui === true }) - return { ...spawned, windowsHide: launchSpec.hideWindowsConsole } + return { + ...spawned, + windowsHide: launchSpec.hideWindowsConsole, + ...(launchSpec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}) + } } return { spawnCmd: launchSpec.spawnCmd, @@ -267,9 +278,15 @@ function resolveExternalEditorSpawn(launchSpec: ExternalEditorLaunchSpec): { } export async function launchExternalEditor(launchSpec: ExternalEditorLaunchSpec): Promise { - const { spawnCmd, spawnArgs, windowsHide } = resolveExternalEditorSpawn(launchSpec) + const { spawnCmd, spawnArgs, windowsHide, windowsVerbatimArguments } = + resolveExternalEditorSpawn(launchSpec) await new Promise((resolvePromise, rejectPromise) => { - const child = spawn(spawnCmd, spawnArgs, { detached: true, stdio: 'ignore', windowsHide }) + const child = spawn(spawnCmd, spawnArgs, { + detached: true, + stdio: 'ignore', + windowsHide, + ...(windowsVerbatimArguments ? { windowsVerbatimArguments } : {}) + }) let settled = false function cleanup(): void { child.off('error', onError) diff --git a/src/main/ipc/local-path-target-guard.ts b/src/main/ipc/local-path-target-guard.ts new file mode 100644 index 000000000000..0ead4d32f85f --- /dev/null +++ b/src/main/ipc/local-path-target-guard.ts @@ -0,0 +1,32 @@ +import { stat } from 'node:fs/promises' +import { isAbsolute, normalize } from 'node:path' +import type { Store } from '../persistence' + +/** True when the path exists on this machine's filesystem. */ +export async function pathExists(pathValue: string): Promise { + try { + await stat(pathValue) + return true + } catch { + return false + } +} + +/** Normalizes a caller-supplied path, refusing anything not absolute or not present on disk. */ +export async function validateLocalPathTarget( + pathValue: string +): Promise<{ ok: true; path: string } | { ok: false; reason: 'not-absolute' | 'not-found' }> { + const normalizedPath = normalize(pathValue) + if (!isAbsolute(normalizedPath)) { + return { ok: false, reason: 'not-absolute' } + } + if (!(await pathExists(normalizedPath))) { + return { ok: false, reason: 'not-found' } + } + return { ok: true, path: normalizedPath } +} + +/** True when a remote runtime owns the session, so local-machine shell actions must refuse. */ +export function hasActiveRuntime(store: Store): boolean { + return Boolean(store.getSettings().activeRuntimeEnvironmentId?.trim()) +} diff --git a/src/main/ipc/shell-open-with-handlers.ts b/src/main/ipc/shell-open-with-handlers.ts new file mode 100644 index 000000000000..7a9e655890ba --- /dev/null +++ b/src/main/ipc/shell-open-with-handlers.ts @@ -0,0 +1,60 @@ +import { ipcMain } from 'electron' +import { extname } from 'node:path' +import { + OPEN_WITH_CHOOSER_APPLICATION_ID, + type ShellListOpenWithApplicationsResult, + type ShellOpenLocalPathResult, + type ShellOpenPathWithApplicationRequest +} from '../../shared/shell-open-types' +import type { Store } from '../persistence' +import { + launchOpenWithApplication, + listOpenWithApplications +} from '../open-with/open-with-applications' +import { hasActiveRuntime, validateLocalPathTarget } from './local-path-target-guard' + +/** Registers the Open With listing and launch IPC handlers. */ +export function registerShellOpenWithHandlers(store: Store): void { + ipcMain.handle( + 'shell:listOpenWithApplications', + async (_event, filePath: string): Promise => { + if (hasActiveRuntime(store)) { + return { ok: false, reason: 'remote-runtime-unsupported' } + } + const target = await validateLocalPathTarget(filePath) + if (!target.ok) { + return target + } + const listing = await listOpenWithApplications(target.path, { + recentApplicationIds: store.getOpenWithRecentApplicationIds(extname(target.path)) + }) + return { ok: true, ...listing } + } + ) + + ipcMain.handle( + 'shell:openPathWithApplication', + async ( + _event, + request: ShellOpenPathWithApplicationRequest + ): Promise => { + if (hasActiveRuntime(store)) { + return { ok: false, reason: 'remote-runtime-unsupported' } + } + const target = await validateLocalPathTarget(request.path) + if (!target.ok) { + return target + } + const launched = await launchOpenWithApplication(request.applicationId, target.path) + if (!launched) { + return { ok: false, reason: 'launch-failed' } + } + // Why: the Windows chooser dialog is not an application choice; Windows + // keeps its own MRU for it. + if (request.applicationId !== OPEN_WITH_CHOOSER_APPLICATION_ID) { + store.recordOpenWithApplicationLaunch(extname(target.path), request.applicationId) + } + return { ok: true } + } + ) +} diff --git a/src/main/ipc/shell.test.ts b/src/main/ipc/shell.test.ts index 9671eb7a09cb..0ecd7085a3c5 100644 --- a/src/main/ipc/shell.test.ts +++ b/src/main/ipc/shell.test.ts @@ -5,6 +5,8 @@ import { pathToFileURL } from 'node:url' const { getSpawnArgsForWindowsMock, handleMock, + launchOpenWithApplicationMock, + listOpenWithApplicationsMock, openPathMock, resolveCliCommandMock, showItemInFolderMock, @@ -14,6 +16,8 @@ const { } = vi.hoisted(() => ({ getSpawnArgsForWindowsMock: vi.fn(), handleMock: vi.fn(), + launchOpenWithApplicationMock: vi.fn(), + listOpenWithApplicationsMock: vi.fn(), openPathMock: vi.fn(), resolveCliCommandMock: vi.fn(), showItemInFolderMock: vi.fn(), @@ -55,6 +59,11 @@ vi.mock('../win32-utils', () => ({ getSpawnArgsForWindows: getSpawnArgsForWindowsMock })) +vi.mock('../open-with/open-with-applications', () => ({ + launchOpenWithApplication: launchOpenWithApplicationMock, + listOpenWithApplications: listOpenWithApplicationsMock +})) + import { EXTERNAL_EDITOR_CLI_COMMAND, registerShellHandlers } from './shell' import { resolveExternalEditorLaunchSpec } from '../external-editor-launch' import type { SshTarget } from '../../shared/ssh-types' @@ -95,9 +104,13 @@ function createSshTarget(overrides: Partial = {}): SshTarget { describe('registerShellHandlers', () => { const settings = { activeRuntimeEnvironmentId: null as string | null } const sshTargets = new Map() + const getOpenWithRecentApplicationIdsMock = vi.fn() + const recordOpenWithApplicationLaunchMock = vi.fn() const store = { getSettings: () => settings, - getSshTarget: (id: string) => sshTargets.get(id) + getSshTarget: (id: string) => sshTargets.get(id), + getOpenWithRecentApplicationIds: getOpenWithRecentApplicationIdsMock, + recordOpenWithApplicationLaunch: recordOpenWithApplicationLaunchMock } beforeEach(() => { @@ -119,6 +132,11 @@ describe('registerShellHandlers', () => { })) spawnMock.mockReturnValue(createSpawnedProcess()) statMock.mockResolvedValue({ isDirectory: () => true }) + launchOpenWithApplicationMock.mockReset() + listOpenWithApplicationsMock.mockReset() + getOpenWithRecentApplicationIdsMock.mockReset() + getOpenWithRecentApplicationIdsMock.mockReturnValue([]) + recordOpenWithApplicationLaunchMock.mockReset() }) function getHandler(channel: string): (event: unknown, ...args: unknown[]) => Promise { @@ -257,6 +275,100 @@ describe('registerShellHandlers', () => { }) }) + describe('shell:listOpenWithApplications', () => { + it('blocks discovery while a remote runtime is active', async () => { + settings.activeRuntimeEnvironmentId = 'runtime-1' + const handler = getHandler('shell:listOpenWithApplications') + + await expect(handler({}, resolve('notes.md'))).resolves.toEqual({ + ok: false, + reason: 'remote-runtime-unsupported' + }) + expect(listOpenWithApplicationsMock).not.toHaveBeenCalled() + }) + + it('rejects relative paths', async () => { + const handler = getHandler('shell:listOpenWithApplications') + + await expect(handler({}, 'relative/notes.md')).resolves.toEqual({ + ok: false, + reason: 'not-absolute' + }) + expect(listOpenWithApplicationsMock).not.toHaveBeenCalled() + }) + + it('returns the discovered applications for existing files', async () => { + const filePath = resolve('notes.md') + getOpenWithRecentApplicationIdsMock.mockReturnValue(['windows:c:\\recent.exe']) + listOpenWithApplicationsMock.mockResolvedValue({ + applications: [{ id: 'windows:c:\\app.exe', name: 'App', isDefault: true }], + supportsChooserDialog: true + }) + const handler = getHandler('shell:listOpenWithApplications') + + await expect(handler({}, filePath)).resolves.toEqual({ + ok: true, + applications: [{ id: 'windows:c:\\app.exe', name: 'App', isDefault: true }], + supportsChooserDialog: true + }) + expect(getOpenWithRecentApplicationIdsMock).toHaveBeenCalledWith('.md') + expect(listOpenWithApplicationsMock).toHaveBeenCalledWith(normalize(filePath), { + recentApplicationIds: ['windows:c:\\recent.exe'] + }) + }) + }) + + describe('shell:openPathWithApplication', () => { + it('blocks launches while a remote runtime is active', async () => { + settings.activeRuntimeEnvironmentId = 'runtime-1' + const handler = getHandler('shell:openPathWithApplication') + + await expect( + handler({}, { path: resolve('notes.md'), applicationId: 'windows:c:\\app.exe' }) + ).resolves.toEqual({ ok: false, reason: 'remote-runtime-unsupported' }) + expect(launchOpenWithApplicationMock).not.toHaveBeenCalled() + }) + + it('maps unknown applications and spawn errors to launch-failed', async () => { + launchOpenWithApplicationMock.mockResolvedValue(false) + const handler = getHandler('shell:openPathWithApplication') + + await expect( + handler({}, { path: resolve('notes.md'), applicationId: 'windows:c:\\missing.exe' }) + ).resolves.toEqual({ ok: false, reason: 'launch-failed' }) + }) + + it('launches the selected application and records the recency choice', async () => { + const filePath = resolve('notes.md') + launchOpenWithApplicationMock.mockResolvedValue(true) + const handler = getHandler('shell:openPathWithApplication') + + await expect( + handler({}, { path: filePath, applicationId: 'windows:c:\\app.exe' }) + ).resolves.toEqual({ ok: true }) + expect(launchOpenWithApplicationMock).toHaveBeenCalledWith( + 'windows:c:\\app.exe', + normalize(filePath) + ) + expect(recordOpenWithApplicationLaunchMock).toHaveBeenCalledWith('.md', 'windows:c:\\app.exe') + }) + + it('does not record recency for failed launches or the chooser dialog', async () => { + const filePath = resolve('notes.md') + const handler = getHandler('shell:openPathWithApplication') + + launchOpenWithApplicationMock.mockResolvedValue(false) + await handler({}, { path: filePath, applicationId: 'windows:c:\\app.exe' }) + expect(recordOpenWithApplicationLaunchMock).not.toHaveBeenCalled() + + launchOpenWithApplicationMock.mockResolvedValue(true) + await expect( + handler({}, { path: filePath, applicationId: 'system:open-with-chooser' }) + ).resolves.toEqual({ ok: true }) + expect(recordOpenWithApplicationLaunchMock).not.toHaveBeenCalled() + }) + }) + describe('shell:openInExternalEditor', () => { it('rejects relative paths', async () => { const handler = getHandler('shell:openInExternalEditor') diff --git a/src/main/ipc/shell.ts b/src/main/ipc/shell.ts index 7ed49c4af7c0..68c5465729c1 100644 --- a/src/main/ipc/shell.ts +++ b/src/main/ipc/shell.ts @@ -8,6 +8,8 @@ import type { ShellOpenExternalEditorResult, ShellOpenLocalPathResult } from '../../shared/shell-open-types' +import { hasActiveRuntime, pathExists, validateLocalPathTarget } from './local-path-target-guard' +import { registerShellOpenWithHandlers } from './shell-open-with-handlers' import { MAX_REPO_ICON_UPLOAD_BYTES } from '../../shared/repo-icon' import type { Store } from '../persistence' import { @@ -24,32 +26,6 @@ const REPO_ICON_IMAGE_MIME_TYPES: Record = { '.png': 'image/png' } -async function pathExists(pathValue: string): Promise { - try { - await stat(pathValue) - return true - } catch { - return false - } -} - -async function validateLocalPathTarget( - pathValue: string -): Promise<{ ok: true; path: string } | { ok: false; reason: 'not-absolute' | 'not-found' }> { - const normalizedPath = normalize(pathValue) - if (!isAbsolute(normalizedPath)) { - return { ok: false, reason: 'not-absolute' } - } - if (!(await pathExists(normalizedPath))) { - return { ok: false, reason: 'not-found' } - } - return { ok: true, path: normalizedPath } -} - -function hasActiveRuntime(store: Store): boolean { - return Boolean(store.getSettings().activeRuntimeEnvironmentId?.trim()) -} - async function openInFileManager( store: Store, pathValue: string @@ -173,6 +149,8 @@ export function registerShellHandlers(store: Store): void { return openWithSystemDefault(filePath) }) + registerShellOpenWithHandlers(store) + ipcMain.handle('shell:openFileUri', async (_event, rawUri: string) => { let parsed: URL try { diff --git a/src/main/open-with/linux-open-with-applications.test.ts b/src/main/open-with/linux-open-with-applications.test.ts new file mode 100644 index 000000000000..7e2edc2a60a6 --- /dev/null +++ b/src/main/open-with/linux-open-with-applications.test.ts @@ -0,0 +1,129 @@ +import { pathToFileURL } from 'node:url' +import { describe, expect, it } from 'vitest' +import { + buildLinuxLaunchInvocation, + parseDesktopEntry, + parseGioMimeApplications, + parseLinuxExecTokens +} from './linux-open-with-applications' + +describe('parseGioMimeApplications', () => { + it('extracts the default and registered desktop ids', () => { + const output = [ + 'Default application for “text/markdown”: org.gnome.gedit.desktop', + 'Registered applications:', + '\tcode.desktop', + '\torg.gnome.gedit.desktop', + 'Recommended applications:', + '\torg.gnome.gedit.desktop', + '' + ].join('\n') + + expect(parseGioMimeApplications(output)).toEqual({ + defaultDesktopId: 'org.gnome.gedit.desktop', + desktopIds: ['code.desktop', 'org.gnome.gedit.desktop', 'org.gnome.gedit.desktop'] + }) + }) + + it('handles output without a default application line', () => { + const output = ['Registered applications:', '\tcode.desktop'].join('\n') + expect(parseGioMimeApplications(output)).toEqual({ + defaultDesktopId: null, + desktopIds: ['code.desktop'] + }) + }) +}) + +describe('parseDesktopEntry', () => { + it('reads keys from the Desktop Entry group only', () => { + const content = [ + '[Desktop Entry]', + 'Name=Text Editor', + 'NoDisplay=false', + 'Exec=gedit %U', + '[Desktop Action new-window]', + 'Name=New Window', + 'Exec=gedit --new-window %U' + ].join('\n') + + expect(parseDesktopEntry(content)).toEqual({ + name: 'Text Editor', + noDisplay: false, + hidden: false, + exec: 'gedit %U', + terminal: false + }) + }) + + it('flags NoDisplay, Hidden and Terminal entries', () => { + const content = [ + '[Desktop Entry]', + 'Name=Vim', + 'NoDisplay=true', + 'Hidden=true', + 'Terminal=true' + ].join('\n') + expect(parseDesktopEntry(content)).toEqual({ + name: 'Vim', + noDisplay: true, + hidden: true, + exec: null, + terminal: true + }) + }) +}) + +describe('parseLinuxExecTokens', () => { + it('splits on unquoted whitespace', () => { + expect(parseLinuxExecTokens('code --new-window %F')).toEqual(['code', '--new-window', '%F']) + }) + + it('keeps double-quoted sections as one token and unescapes inside quotes', () => { + expect(parseLinuxExecTokens('"/opt/My Editor/editor" --file=%f')).toEqual([ + '/opt/My Editor/editor', + '--file=%f' + ]) + expect(parseLinuxExecTokens('app "a \\"b\\" \\$c"')).toEqual(['app', 'a "b" $c']) + }) + + it('returns null for empty or whitespace-only Exec lines', () => { + expect(parseLinuxExecTokens('')).toBeNull() + expect(parseLinuxExecTokens(' ')).toBeNull() + }) +}) + +describe('buildLinuxLaunchInvocation', () => { + it('substitutes %f with the plain path as its own argv element', () => { + expect(buildLinuxLaunchInvocation(['gedit', '%f'], '/tmp/a & b.md')).toEqual({ + spawnCmd: 'gedit', + spawnArgs: ['/tmp/a & b.md'] + }) + }) + + it('substitutes %u with a file URI and handles embedded field codes', () => { + // Computed, not hardcoded: pathToFileURL prefixes the drive on Windows dev machines. + const expectedUri = pathToFileURL('/tmp/x.html').href + expect(buildLinuxLaunchInvocation(['browser', '--open=%u'], '/tmp/x.html')).toEqual({ + spawnCmd: 'browser', + spawnArgs: [`--open=${expectedUri}`] + }) + }) + + it('drops bare %i/%c/%k tokens and keeps %% literal', () => { + expect(buildLinuxLaunchInvocation(['app', '%i', '%c', '--pct=100%%', '%F'], '/tmp/x')).toEqual({ + spawnCmd: 'app', + spawnArgs: ['--pct=100%', '/tmp/x'] + }) + }) + + it('appends the file path when the Exec line has no file field code', () => { + expect(buildLinuxLaunchInvocation(['xdg-open'], '/tmp/x')).toEqual({ + spawnCmd: 'xdg-open', + spawnArgs: ['/tmp/x'] + }) + }) + + it('returns null when every token drops away', () => { + expect(buildLinuxLaunchInvocation(['%i'], '/tmp/x')).toBeNull() + }) +}) diff --git a/src/main/open-with/linux-open-with-applications.ts b/src/main/open-with/linux-open-with-applications.ts new file mode 100644 index 000000000000..2137f9355974 --- /dev/null +++ b/src/main/open-with/linux-open-with-applications.ts @@ -0,0 +1,259 @@ +import { existsSync } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import type { OpenWithApplicationCandidate } from './open-with-candidate' +import { readOpenWithCommandOutput } from './open-with-command-output' + +/** Discovers the applications registered for a file's MIME type via xdg-mime and gio. */ +export async function listLinuxOpenWithApplications( + filePath: string +): Promise { + const mimeType = ( + await readOpenWithCommandOutput('xdg-mime', ['query', 'filetype', filePath]) + ).trim() + if (!mimeType) { + return [] + } + const gioOutput = await readOpenWithCommandOutput('gio', ['mime', mimeType]) + const { defaultDesktopId, desktopIds } = parseGioMimeApplications(gioOutput) + + const candidates: OpenWithApplicationCandidate[] = [] + const seenDesktopIds = new Set() + const orderedIds = defaultDesktopId ? [defaultDesktopId, ...desktopIds] : desktopIds + for (const desktopId of orderedIds) { + if (seenDesktopIds.has(desktopId)) { + continue + } + seenDesktopIds.add(desktopId) + const desktopFilePath = findDesktopFilePath(desktopId) + if (!desktopFilePath) { + continue + } + let entry: ReturnType + try { + entry = parseDesktopEntry(await readFile(desktopFilePath, 'utf8')) + } catch { + continue + } + // Why: Terminal=true entries need a terminal emulator we cannot attach; + // Hidden means the user deleted the entry at their level. + if (entry.noDisplay || entry.hidden || entry.terminal) { + continue + } + const execTokens = entry.exec ? parseLinuxExecTokens(entry.exec) : null + if (!execTokens) { + continue + } + candidates.push({ + id: `linux:${desktopId}`, + name: entry.name ?? desktopId.replace(/\.desktop$/, ''), + isDefault: desktopId === defaultDesktopId, + launch: { kind: 'linux-desktop-entry', execTokens } + }) + } + return candidates +} + +/** Extracts the default and registered desktop ids from `gio mime` output. */ +export function parseGioMimeApplications(output: string): { + defaultDesktopId: string | null + desktopIds: string[] +} { + let defaultDesktopId: string | null = null + const desktopIds: string[] = [] + for (const rawLine of output.split('\n')) { + const line = rawLine.trim() + if (!line || line.endsWith(':')) { + continue + } + const defaultMatch = /^Default application for .*:\s*(\S+\.desktop)$/.exec(line) + if (defaultMatch) { + defaultDesktopId = defaultMatch[1] + continue + } + if (line.endsWith('.desktop')) { + desktopIds.push(line) + } + } + return { defaultDesktopId, desktopIds } +} + +/** XDG application directories, user data home first. */ +function getLinuxApplicationDirectories(env: NodeJS.ProcessEnv = process.env): string[] { + const home = env.HOME ?? '' + const dataHome = env.XDG_DATA_HOME?.trim() || (home ? join(home, '.local', 'share') : '') + const dataDirs = (env.XDG_DATA_DIRS?.trim() || '/usr/local/share:/usr/share').split(':') + return [dataHome, ...dataDirs] + .map((dir) => dir.trim()) + .filter(Boolean) + .map((dir) => join(dir, 'applications')) +} + +/** Locates a desktop id's file, or null when no XDG directory holds it. */ +function findDesktopFilePath(desktopId: string): string | null { + for (const directory of getLinuxApplicationDirectories()) { + const directPath = join(directory, desktopId) + if (existsSync(directPath)) { + return directPath + } + // Why: desktop ids encode subdirectories as dashes (kde4-kate.desktop can + // live at applications/kde4/kate.desktop). + const dashIndex = desktopId.indexOf('-') + if (dashIndex > 0) { + const nestedPath = join( + directory, + desktopId.slice(0, dashIndex), + desktopId.slice(dashIndex + 1) + ) + if (existsSync(nestedPath)) { + return nestedPath + } + } + } + return null +} + +/** Reads Name, NoDisplay, Hidden, Exec and Terminal from the [Desktop Entry] group. */ +export function parseDesktopEntry(content: string): { + name: string | null + noDisplay: boolean + hidden: boolean + exec: string | null + terminal: boolean +} { + let inDesktopEntryGroup = false + let name: string | null = null + let noDisplay = false + let hidden = false + let exec: string | null = null + let terminal = false + for (const rawLine of content.split('\n')) { + const line = rawLine.trim() + if (line.startsWith('[')) { + inDesktopEntryGroup = line === '[Desktop Entry]' + continue + } + if (!inDesktopEntryGroup) { + continue + } + if (name === null && line.startsWith('Name=')) { + name = line.slice('Name='.length).trim() || null + } + if (line.startsWith('NoDisplay=')) { + noDisplay = line.slice('NoDisplay='.length).trim() === 'true' + } + if (line.startsWith('Hidden=')) { + hidden = line.slice('Hidden='.length).trim() === 'true' + } + if (exec === null && line.startsWith('Exec=')) { + exec = line.slice('Exec='.length).trim() || null + } + if (line.startsWith('Terminal=')) { + terminal = line.slice('Terminal='.length).trim() === 'true' + } + } + return { name, noDisplay, hidden, exec, terminal } +} + +/** + * Splits a desktop entry's Exec line into argv tokens using freedesktop quoting + * rules. Orca runs the Exec line itself because `gio launch` needs GLib 2.67.2+, + * newer than the Ubuntu 20.04 floor. + */ +export function parseLinuxExecTokens(exec: string): string[] | null { + const tokens: string[] = [] + let current: string | null = null + let inQuotes = false + for (let index = 0; index < exec.length; index++) { + const char = exec[index] + if (inQuotes) { + if (char === '"') { + inQuotes = false + } else if (char === '\\' && index + 1 < exec.length) { + current = (current ?? '') + exec[++index] + } else { + current = (current ?? '') + char + } + continue + } + if (char === '"') { + inQuotes = true + current ??= '' + continue + } + if (char === ' ' || char === '\t') { + if (current !== null) { + tokens.push(current) + current = null + } + continue + } + current = (current ?? '') + char + } + if (current !== null) { + tokens.push(current) + } + return tokens.length > 0 ? tokens : null +} + +/** Turns Exec tokens plus a target path into a spawn command, or null when nothing executable remains. */ +export function buildLinuxLaunchInvocation( + execTokens: string[], + filePath: string +): { spawnCmd: string; spawnArgs: string[] } | null { + const args: string[] = [] + let usedFilePath = false + for (const token of execTokens) { + const substituted = substituteExecFieldCodes(token, filePath) + if (substituted === null) { + continue + } + usedFilePath ||= substituted.usedFilePath + args.push(substituted.value) + } + if (args.length === 0) { + return null + } + // Why: entries without a file field code still receive the file, matching + // gio/gtk-launch behavior. + if (!usedFilePath) { + args.push(filePath) + } + return { spawnCmd: args[0], spawnArgs: args.slice(1) } +} + +/** Substitutes one token's field codes; null when the token expands to nothing. */ +function substituteExecFieldCodes( + token: string, + filePath: string +): { value: string; usedFilePath: boolean } | null { + let value = '' + let usedFilePath = false + let droppedFieldCode = false + for (let index = 0; index < token.length; index++) { + const char = token[index] + if (char !== '%' || index + 1 >= token.length) { + value += char + continue + } + const code = token[++index] + if (code === '%') { + value += '%' + } else if (code === 'f' || code === 'F') { + value += filePath + usedFilePath = true + } else if (code === 'u' || code === 'U') { + // Why: %u/%U handlers declare URI support; %f handlers get a plain path. + value += pathToFileURL(filePath).href + usedFilePath = true + } else { + // Why: %i/%c/%k and the deprecated codes expand to nothing here. + droppedFieldCode = true + } + } + if (value === '' && droppedFieldCode) { + return null + } + return { value, usedFilePath } +} diff --git a/src/main/open-with/macos-open-with-applications.test.ts b/src/main/open-with/macos-open-with-applications.test.ts new file mode 100644 index 000000000000..bda2ed4475e8 --- /dev/null +++ b/src/main/open-with/macos-open-with-applications.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { parseMacApplicationList } from './macos-open-with-applications' + +describe('parseMacApplicationList', () => { + it('marks the default handler and strips .app from names', () => { + const output = JSON.stringify({ + defaultPath: '/Applications/TextEdit.app', + applicationPaths: ['/Applications/TextEdit.app', '/Applications/Visual Studio Code.app'] + }) + + expect(parseMacApplicationList(output)).toEqual([ + { + id: 'macos:/Applications/TextEdit.app', + name: 'TextEdit', + isDefault: true, + launch: { kind: 'macos-application', applicationPath: '/Applications/TextEdit.app' } + }, + { + id: 'macos:/Applications/Visual Studio Code.app', + name: 'Visual Studio Code', + isDefault: false, + launch: { + kind: 'macos-application', + applicationPath: '/Applications/Visual Studio Code.app' + } + } + ]) + }) + + it('includes a default handler missing from the candidate list', () => { + const output = JSON.stringify({ + defaultPath: '/Applications/Preview.app', + applicationPaths: [] + }) + + const parsed = parseMacApplicationList(output) + expect(parsed).toHaveLength(1) + expect(parsed[0]).toMatchObject({ name: 'Preview', isDefault: true }) + }) + + it('deduplicates repeated application paths', () => { + const output = JSON.stringify({ + defaultPath: null, + applicationPaths: ['/Applications/A.app', '/Applications/A.app'] + }) + expect(parseMacApplicationList(output)).toHaveLength(1) + }) +}) diff --git a/src/main/open-with/macos-open-with-applications.ts b/src/main/open-with/macos-open-with-applications.ts new file mode 100644 index 000000000000..b043d7ad6646 --- /dev/null +++ b/src/main/open-with/macos-open-with-applications.ts @@ -0,0 +1,63 @@ +import { basename } from 'node:path' +import type { OpenWithApplicationCandidate } from './open-with-candidate' +import { readOpenWithCommandOutput } from './open-with-command-output' + +// Why: LaunchServices has no CLI; the JXA ObjC bridge is the only way to ask +// NSWorkspace for per-file handlers without shipping a native helper. +const LIST_APPLICATIONS_JXA = ` +function run(argv) { + ObjC.import('AppKit') + const fileUrl = $.NSURL.fileURLWithPath(argv[0]) + const workspace = $.NSWorkspace.sharedWorkspace + const applicationUrls = workspace.URLsForApplicationsToOpenURL(fileUrl) + const defaultUrl = workspace.URLForApplicationToOpenURL(fileUrl) + const applicationPaths = [] + for (let index = 0; index < applicationUrls.count; index += 1) { + applicationPaths.push(ObjC.unwrap(applicationUrls.objectAtIndex(index).path)) + } + const defaultPath = defaultUrl.isNil() ? null : ObjC.unwrap(defaultUrl.path) + return JSON.stringify({ defaultPath: defaultPath, applicationPaths: applicationPaths }) +} +` + +/** Discovers the applications LaunchServices registers for a file. */ +export async function listMacOpenWithApplications( + filePath: string +): Promise { + const output = await readOpenWithCommandOutput('osascript', [ + '-l', + 'JavaScript', + '-e', + LIST_APPLICATIONS_JXA, + filePath + ]) + return parseMacApplicationList(output) +} + +/** Turns the JXA payload into candidates with the default handler marked. */ +export function parseMacApplicationList(output: string): OpenWithApplicationCandidate[] { + const parsed = JSON.parse(output) as { + defaultPath?: string | null + applicationPaths?: unknown[] + } + const defaultPath = typeof parsed.defaultPath === 'string' ? parsed.defaultPath : null + const candidatesByPath = new Map() + const applicationPaths = (parsed.applicationPaths ?? []).filter( + (value): value is string => typeof value === 'string' && value.length > 0 + ) + if (defaultPath && !applicationPaths.includes(defaultPath)) { + applicationPaths.unshift(defaultPath) + } + for (const applicationPath of applicationPaths) { + if (candidatesByPath.has(applicationPath)) { + continue + } + candidatesByPath.set(applicationPath, { + id: `macos:${applicationPath}`, + name: basename(applicationPath).replace(/\.app$/i, ''), + isDefault: applicationPath === defaultPath, + launch: { kind: 'macos-application', applicationPath } + }) + } + return [...candidatesByPath.values()] +} diff --git a/src/main/open-with/open-with-applications.test.ts b/src/main/open-with/open-with-applications.test.ts new file mode 100644 index 000000000000..46ce4ef88cee --- /dev/null +++ b/src/main/open-with/open-with-applications.test.ts @@ -0,0 +1,133 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { OPEN_WITH_CHOOSER_APPLICATION_ID } from '../../shared/shell-open-types' +import { launchOpenWithApplication, sortOpenWithApplications } from './open-with-applications' + +const APPS = [ + { id: 'windows:c:\\code.exe', name: 'Visual Studio Code' }, + { id: 'windows:c:\\notepad++.exe', name: 'Notepad++' }, + { id: 'windows:c:\\powerpnt.exe', name: 'Microsoft PowerPoint', isDefault: true }, + { id: 'windows:c:\\cursor.exe', name: 'Cursor' } +] + +describe('sortOpenWithApplications', () => { + it('puts the default first, then sorts by name, when nothing is recent', () => { + expect(sortOpenWithApplications(APPS, []).map((a) => a.name)).toEqual([ + 'Microsoft PowerPoint', + 'Cursor', + 'Notepad++', + 'Visual Studio Code' + ]) + }) + + it('ranks recently used applications ahead of the default', () => { + const sorted = sortOpenWithApplications(APPS, [ + 'windows:c:\\notepad++.exe', + 'windows:c:\\code.exe' + ]) + expect(sorted.map((a) => a.name)).toEqual([ + 'Notepad++', + 'Visual Studio Code', + 'Microsoft PowerPoint', + 'Cursor' + ]) + }) + + it('ignores recent ids that are no longer discovered', () => { + const sorted = sortOpenWithApplications(APPS, ['windows:c:\\uninstalled.exe']) + expect(sorted[0].name).toBe('Microsoft PowerPoint') + }) + + it('does not mutate the input array', () => { + const input = [...APPS] + sortOpenWithApplications(input, ['windows:c:\\cursor.exe']) + expect(input).toEqual(APPS) + }) +}) + +describe('launchOpenWithApplication', () => { + // Why: the renderer only echoes ids; anything discovery never produced must + // resolve to no launch spec and spawn nothing. + it('refuses ids that were never produced by discovery', async () => { + await expect(launchOpenWithApplication('linux:forged.desktop', '/tmp/x')).resolves.toBe(false) + }) + + it('refuses the chooser id on non-Windows platforms', async () => { + await expect( + launchOpenWithApplication(OPEN_WITH_CHOOSER_APPLICATION_ID, '/tmp/x', { platform: 'linux' }) + ).resolves.toBe(false) + }) +}) + +vi.mock('./linux-open-with-applications', () => ({ + listLinuxOpenWithApplications: vi.fn(async () => []), + buildLinuxLaunchInvocation: vi.fn(() => null) +})) + +describe('listOpenWithApplications caching', () => { + const CANDIDATE = { + id: 'linux:editor.desktop', + name: 'Editor', + isDefault: true, + launch: { kind: 'linux-desktop-entry' as const, execTokens: ['editor', '%f'] } + } + + beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + async function loadModules() { + const linux = await import('./linux-open-with-applications') + const applications = await import('./open-with-applications') + return { discover: vi.mocked(linux.listLinuxOpenWithApplications), applications } + } + + it('deduplicates concurrent listings for the same extension', async () => { + const { discover, applications } = await loadModules() + let settle: (candidates: (typeof CANDIDATE)[]) => void = () => {} + discover.mockImplementation(() => new Promise((resolve) => (settle = resolve))) + + const first = applications.listOpenWithApplications('/tmp/a.md', { platform: 'linux' }) + const second = applications.listOpenWithApplications('/tmp/b.md', { platform: 'linux' }) + settle([CANDIDATE]) + + expect((await first).applications).toEqual([ + { id: CANDIDATE.id, name: 'Editor', isDefault: true } + ]) + expect((await second).applications).toHaveLength(1) + expect(discover).toHaveBeenCalledTimes(1) + }) + + it('serves the cache inside the TTL and rediscovers after it expires', async () => { + vi.useFakeTimers() + const { discover, applications } = await loadModules() + discover.mockResolvedValue([CANDIDATE]) + + await applications.listOpenWithApplications('/tmp/a.md', { platform: 'linux' }) + await applications.listOpenWithApplications('/tmp/b.md', { platform: 'linux' }) + expect(discover).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(5 * 60_000 + 1) + await applications.listOpenWithApplications('/tmp/c.md', { platform: 'linux' }) + expect(discover).toHaveBeenCalledTimes(2) + }) + + it('does not cache a failed discovery', async () => { + const { discover, applications } = await loadModules() + discover.mockRejectedValueOnce(new Error('xdg-mime missing')) + + expect( + (await applications.listOpenWithApplications('/tmp/a.md', { platform: 'linux' })).applications + ).toEqual([]) + + discover.mockResolvedValue([CANDIDATE]) + expect( + (await applications.listOpenWithApplications('/tmp/b.md', { platform: 'linux' })).applications + ).toHaveLength(1) + expect(discover).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/main/open-with/open-with-applications.ts b/src/main/open-with/open-with-applications.ts new file mode 100644 index 000000000000..e81487c187d2 --- /dev/null +++ b/src/main/open-with/open-with-applications.ts @@ -0,0 +1,178 @@ +import { extname } from 'node:path' +import { + OPEN_WITH_CHOOSER_APPLICATION_ID, + type ShellOpenWithApplication +} from '../../shared/shell-open-types' +import { launchExternalEditor } from '../external-editor-launch' +import { getRundll32ExePath } from '../win32-utils' +import type { OpenWithApplicationCandidate, OpenWithLaunchSpec } from './open-with-candidate' +import { + buildLinuxLaunchInvocation, + listLinuxOpenWithApplications +} from './linux-open-with-applications' +import { listMacOpenWithApplications } from './macos-open-with-applications' +import { + buildWindowsLaunchInvocation, + listWindowsOpenWithApplications +} from './windows-open-with-applications' + +export type OpenWithApplicationListing = { + applications: ShellOpenWithApplication[] + supportsChooserDialog: boolean +} + +// Why: listings hit the registry / external discovery commands; keep results +// briefly so reopening the context menu stays instant, but expire so newly +// installed applications appear without an app restart. +const LISTING_CACHE_TTL_MS = 5 * 60_000 +const listingCache = new Map< + string, + { expiresAt: number; candidates: OpenWithApplicationCandidate[] } +>() +const inFlightListings = new Map>() +// Why: launch specs never leave the main process; the renderer only echoes an +// opaque id back, so arbitrary commands cannot be injected over IPC. +const launchSpecsByApplicationId = new Map() + +/** Lists the applications that can open a file, ranked by recency, then OS default, then name. */ +export async function listOpenWithApplications( + filePath: string, + options: { platform?: NodeJS.Platform; recentApplicationIds?: string[] } = {} +): Promise { + const platform = options.platform ?? process.platform + const candidates = await listCachedCandidates(filePath, platform) + for (const candidate of candidates) { + launchSpecsByApplicationId.set(candidate.id, candidate.launch) + } + return { + applications: sortOpenWithApplications(candidates, options.recentApplicationIds ?? []).map( + ({ id, name, isDefault }) => (isDefault ? { id, name, isDefault } : { id, name }) + ), + supportsChooserDialog: platform === 'win32' + } +} + +/** Launches a discovered application id against a file; false when the id is unknown or the spawn fails. */ +export async function launchOpenWithApplication( + applicationId: string, + filePath: string, + options: { platform?: NodeJS.Platform } = {} +): Promise { + const platform = options.platform ?? process.platform + const launch = + applicationId === OPEN_WITH_CHOOSER_APPLICATION_ID + ? platform === 'win32' + ? ({ kind: 'windows-chooser' } as const) + : null + : (launchSpecsByApplicationId.get(applicationId) ?? null) + if (!launch) { + return false + } + const invocation = resolveLaunchInvocation(launch, filePath) + if (!invocation) { + return false + } + try { + // Why: windowsHide sets STARTUPINFO SW_HIDE, which Office and other Win32 + // apps (and anything the Open With dialog launches) honor for their first + // window — the launched app must be visible, so never hide here. + await launchExternalEditor({ + kind: 'executable', + hideWindowsConsole: false, + // Why: rundll32's OpenAs_RunDLL reads its raw tail and keeps Node's quotes, + // so a spawn-quoted spaced path never resolves. + ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), + spawnCmd: invocation.spawnCmd, + spawnArgs: invocation.spawnArgs + }) + return true + } catch { + return false + } +} + +/** Serves discovery from a per-extension cache, deduping concurrent calls and never caching a failure. */ +async function listCachedCandidates( + filePath: string, + platform: NodeJS.Platform +): Promise { + // Why: every discovery backend resolves handlers by file type, so one file + // per extension is representative and cheap to cache. + const cacheKey = `${platform}:${extname(filePath).toLowerCase()}` + const cached = listingCache.get(cacheKey) + if (cached && cached.expiresAt > Date.now()) { + return cached.candidates + } + const inFlight = inFlightListings.get(cacheKey) + if (inFlight) { + return inFlight + } + const listing = loadCandidates(filePath, platform) + .then((candidates) => { + listingCache.set(cacheKey, { expiresAt: Date.now() + LISTING_CACHE_TTL_MS, candidates }) + return candidates + }) + .catch(() => [] as OpenWithApplicationCandidate[]) + .finally(() => { + inFlightListings.delete(cacheKey) + }) + inFlightListings.set(cacheKey, listing) + return listing +} + +/** Dispatches discovery to the platform backend. */ +function loadCandidates( + filePath: string, + platform: NodeJS.Platform +): Promise { + if (platform === 'win32') { + return listWindowsOpenWithApplications(filePath) + } + if (platform === 'darwin') { + return listMacOpenWithApplications(filePath) + } + return listLinuxOpenWithApplications(filePath) +} + +/** Turns a launch spec into the exact command and argv for the target path. */ +function resolveLaunchInvocation( + launch: OpenWithLaunchSpec, + filePath: string +): { spawnCmd: string; spawnArgs: string[]; windowsVerbatimArguments?: boolean } | null { + if (launch.kind === 'windows-command') { + return buildWindowsLaunchInvocation(launch.command, filePath) + } + if (launch.kind === 'windows-chooser') { + return { + spawnCmd: getRundll32ExePath(), + spawnArgs: [`shell32.dll,OpenAs_RunDLL ${filePath}`], + windowsVerbatimArguments: true + } + } + if (launch.kind === 'macos-application') { + // Why: absolute path — a shadowing `open` earlier on PATH must not win. + return { spawnCmd: '/usr/bin/open', spawnArgs: ['-a', launch.applicationPath, filePath] } + } + return buildLinuxLaunchInvocation(launch.execTokens, filePath) +} + +/** Orders candidates by recency, then the OS default, then name. */ +export function sortOpenWithApplications( + candidates: T[], + recentApplicationIds: string[] +): T[] { + // Why: recently launched apps outrank the OS default — the user's own last + // choice is the strongest signal for what they want next time. + const recencyRank = new Map(recentApplicationIds.map((id, index) => [id, index])) + return [...candidates].sort((a, b) => { + const aRecency = recencyRank.get(a.id) ?? Number.POSITIVE_INFINITY + const bRecency = recencyRank.get(b.id) ?? Number.POSITIVE_INFINITY + if (aRecency !== bRecency) { + return aRecency - bRecency + } + if (Boolean(a.isDefault) !== Boolean(b.isDefault)) { + return a.isDefault ? -1 : 1 + } + return a.name.localeCompare(b.name) + }) +} diff --git a/src/main/open-with/open-with-candidate.ts b/src/main/open-with/open-with-candidate.ts new file mode 100644 index 000000000000..8ca860c0cc9a --- /dev/null +++ b/src/main/open-with/open-with-candidate.ts @@ -0,0 +1,11 @@ +import type { ShellOpenWithApplication } from '../../shared/shell-open-types' + +export type OpenWithLaunchSpec = + | { kind: 'windows-command'; command: string } + | { kind: 'windows-chooser' } + | { kind: 'macos-application'; applicationPath: string } + | { kind: 'linux-desktop-entry'; execTokens: string[] } + +export type OpenWithApplicationCandidate = ShellOpenWithApplication & { + launch: OpenWithLaunchSpec +} diff --git a/src/main/open-with/open-with-command-output.ts b/src/main/open-with/open-with-command-output.ts new file mode 100644 index 000000000000..d3a113dda861 --- /dev/null +++ b/src/main/open-with/open-with-command-output.ts @@ -0,0 +1,32 @@ +import { runProcess } from '../../shared/child-process/run-process' + +export const OPEN_WITH_COMMAND_TIMEOUT_MS = 10_000 +const OPEN_WITH_COMMAND_MAX_OUTPUT_BYTES = 4 * 1024 * 1024 + +/** Runs a discovery command and resolves its stdout, rejecting on failure or timeout. */ +export async function readOpenWithCommandOutput( + command: string, + args: string[], + timeoutMs = OPEN_WITH_COMMAND_TIMEOUT_MS +): Promise { + const result = await runProcess({ + program: command, + args, + // Why: app discovery is a context-menu convenience; a stuck OS tool must + // fall back to an empty list instead of keeping the menu IPC pending. + timeoutMs, + maxOutputBytes: OPEN_WITH_COMMAND_MAX_OUTPUT_BYTES, + // Why: gio/xdg-mime localize their output and the parsers key on the + // English text; force the C locale (inert for the other commands). + env: { ...process.env, LC_ALL: 'C' } + }) + if (result.timedOut) { + throw new Error(`Timed out running ${command}`) + } + if (result.code !== 0) { + throw new Error( + `${command} exited with ${result.code ?? result.signal}: ${result.stderr.trim()}` + ) + } + return result.stdout +} diff --git a/src/main/open-with/windows-open-with-applications.test.ts b/src/main/open-with/windows-open-with-applications.test.ts new file mode 100644 index 000000000000..7dda0f0e949a --- /dev/null +++ b/src/main/open-with/windows-open-with-applications.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'vitest' +import { + buildWindowsLaunchInvocation, + expandWindowsEnvironmentVariables, + extractWindowsExecutablePath, + fallbackWindowsApplicationName +} from './windows-open-with-applications' + +describe('extractWindowsExecutablePath', () => { + it('reads a quoted executable path', () => { + expect( + extractWindowsExecutablePath('"C:\\Program Files\\App\\app.exe" "%1"', () => false) + ).toBe('C:\\Program Files\\App\\app.exe') + }) + + it('probes unquoted spaced paths against the filesystem', () => { + const existing = new Set(['C:\\Program Files\\My App\\app.exe']) + expect( + extractWindowsExecutablePath('C:\\Program Files\\My App\\app.exe %1', (path) => + existing.has(path) + ) + ).toBe('C:\\Program Files\\My App\\app.exe') + }) + + it('falls back to the first token when nothing on disk matches', () => { + expect(extractWindowsExecutablePath('C:\\App\\app.exe --flag', () => false)).toBe( + 'C:\\App\\app.exe' + ) + }) + + it('rejects commands without a closing quote', () => { + expect(extractWindowsExecutablePath('"C:\\App\\app.exe', () => true)).toBeNull() + }) +}) + +describe('buildWindowsLaunchInvocation', () => { + it('substitutes %1 placeholders with the file path', () => { + expect( + buildWindowsLaunchInvocation('"C:\\App\\app.exe" "%1"', 'D:\\notes\\todo.md', () => false) + ).toEqual({ spawnCmd: 'C:\\App\\app.exe', spawnArgs: ['D:\\notes\\todo.md'] }) + }) + + it('keeps flags and drops unfillable %2+/%* placeholders', () => { + expect( + buildWindowsLaunchInvocation( + '"C:\\App\\app.exe" --reuse-window "%1" %*', + 'D:\\a.txt', + () => false + ) + ).toEqual({ spawnCmd: 'C:\\App\\app.exe', spawnArgs: ['--reuse-window', 'D:\\a.txt'] }) + }) + + it('substitutes placeholders embedded inside a token', () => { + expect( + buildWindowsLaunchInvocation('"C:\\App\\app.exe" --file=%1', 'D:\\a.txt', () => false) + ).toEqual({ spawnCmd: 'C:\\App\\app.exe', spawnArgs: ['--file=D:\\a.txt'] }) + }) + + it('appends the file path when the command has no placeholder', () => { + expect(buildWindowsLaunchInvocation('"C:\\App\\app.exe"', 'D:\\a.txt', () => false)).toEqual({ + spawnCmd: 'C:\\App\\app.exe', + spawnArgs: ['D:\\a.txt'] + }) + }) + + // Why: pins the injection guarantee — a hostile filename stays one argv + // element and never reaches a shell. + it('keeps a filename full of shell metacharacters as a single argv element', () => { + const hostile = 'D:\\docs\\a & calc.exe %TEMP% $(x) "q".txt' + expect(buildWindowsLaunchInvocation('"C:\\App\\app.exe" "%1"', hostile, () => false)).toEqual({ + spawnCmd: 'C:\\App\\app.exe', + spawnArgs: [hostile] + }) + }) + + it('fills Office-style %u placeholders with the file path', () => { + expect( + buildWindowsLaunchInvocation( + '"C:\\Office\\POWERPNT.EXE" "%1" /ou "%u"', + 'D:\\paper survey\\deck.pptx', + () => false + ) + ).toEqual({ + spawnCmd: 'C:\\Office\\POWERPNT.EXE', + spawnArgs: ['D:\\paper survey\\deck.pptx', '/ou', 'D:\\paper survey\\deck.pptx'] + }) + }) + + it('leaves unexpanded environment-style tokens alone', () => { + expect( + buildWindowsLaunchInvocation( + '"C:\\App\\app.exe" %USERPROFILE% "%1"', + 'D:\\a.txt', + () => false + ) + ).toEqual({ + spawnCmd: 'C:\\App\\app.exe', + spawnArgs: ['%USERPROFILE%', 'D:\\a.txt'] + }) + }) +}) + +describe('expandWindowsEnvironmentVariables', () => { + it('expands known variables and preserves launch placeholders', () => { + expect( + expandWindowsEnvironmentVariables('%SystemRoot%\\notepad.exe %1', { + SystemRoot: 'C:\\Windows' + } as NodeJS.ProcessEnv) + ).toBe('C:\\Windows\\notepad.exe %1') + }) +}) + +describe('fallbackWindowsApplicationName', () => { + it('prettifies the executable base name', () => { + expect(fallbackWindowsApplicationName('C:\\Windows\\notepad.exe')).toBe('Notepad') + }) +}) diff --git a/src/main/open-with/windows-open-with-applications.ts b/src/main/open-with/windows-open-with-applications.ts new file mode 100644 index 000000000000..ab2b6afe7728 --- /dev/null +++ b/src/main/open-with/windows-open-with-applications.ts @@ -0,0 +1,341 @@ +import { existsSync } from 'node:fs' +import { win32 } from 'node:path' +import { + loadWindowsNativeRegistry, + WINDOWS_REG_EXPAND_SZ, + type WindowsNativeRegistryModule +} from '../windows-native-registry' +import { getWindowsPowerShellExePath } from '../win32-utils' +import type { OpenWithApplicationCandidate } from './open-with-candidate' +import { readOpenWithCommandOutput } from './open-with-command-output' + +const FILE_EXTS_KEY_PREFIX = 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts' +const CLASSES_KEY_PREFIX = 'Software\\Classes' +const DESCRIPTION_LOOKUP_TIMEOUT_MS = 5_000 + +type WindowsOpenCommand = { + command: string + isDefault: boolean +} + +/** Discovers the applications registered for a file extension in the Windows registry. */ +export async function listWindowsOpenWithApplications( + filePath: string +): Promise { + const extension = win32.extname(filePath).toLowerCase() + if (!extension) { + return [] + } + let registry: WindowsNativeRegistryModule + try { + registry = loadWindowsNativeRegistry() + } catch { + return [] + } + + const candidatesByExecutable = new Map< + string, + OpenWithApplicationCandidate & { executablePath: string } + >() + for (const openCommand of collectWindowsOpenCommands(registry, extension)) { + const executablePath = extractWindowsExecutablePath(openCommand.command) + if (!executablePath || !existsSync(executablePath)) { + continue + } + const executableKey = executablePath.toLowerCase() + const existing = candidatesByExecutable.get(executableKey) + if (existing) { + // Why: two ProgIds can share an exe with different command lines; the + // default handler's line wins so the launch matches the Default label. + if (openCommand.isDefault && !existing.isDefault) { + existing.isDefault = true + existing.launch = { kind: 'windows-command', command: openCommand.command } + } + continue + } + candidatesByExecutable.set(executableKey, { + id: `windows:${executableKey}`, + name: fallbackWindowsApplicationName(executablePath), + isDefault: openCommand.isDefault, + executablePath, + launch: { kind: 'windows-command', command: openCommand.command } + }) + } + + const candidates = [...candidatesByExecutable.values()] + await applyWindowsFileDescriptions(candidates) + return candidates.map(({ executablePath: _executablePath, ...candidate }) => candidate) +} + +/** Collects an extension's open command lines from UserChoice, OpenWithProgids and OpenWithList. */ +function collectWindowsOpenCommands( + registry: WindowsNativeRegistryModule, + extension: string +): WindowsOpenCommand[] { + const { HK } = registry + const fileExtsKey = `${FILE_EXTS_KEY_PREFIX}\\${extension}` + const userChoiceProgid = readRegistryString( + registry, + HK.CU, + `${fileExtsKey}\\UserChoice`, + 'ProgId' + ) + + // Why: HKCR is the merged view of these two hives; the native module only + // exposes HKCU/HKLM roots, so read both Software\Classes branches directly. + const progids = new Set() + for (const root of [HK.CU, HK.LM]) { + const defaultProgid = readRegistryString( + registry, + root, + `${CLASSES_KEY_PREFIX}\\${extension}`, + '' + ) + if (defaultProgid) { + progids.add(defaultProgid) + } + for (const name of readRegistryValueNames( + registry, + root, + `${CLASSES_KEY_PREFIX}\\${extension}\\OpenWithProgids` + )) { + progids.add(name) + } + } + for (const name of readRegistryValueNames(registry, HK.CU, `${fileExtsKey}\\OpenWithProgids`)) { + progids.add(name) + } + if (userChoiceProgid) { + progids.add(userChoiceProgid) + } + + const commands: WindowsOpenCommand[] = [] + for (const progid of progids) { + const command = readClassOpenCommand(registry, `${progid}\\shell\\open\\command`) + if (command) { + commands.push({ command, isDefault: progid === userChoiceProgid }) + } + } + for (const executableName of readWindowsOpenWithListExecutables(registry, fileExtsKey)) { + const command = readClassOpenCommand( + registry, + `Applications\\${executableName}\\shell\\open\\command` + ) + if (command) { + commands.push({ command, isDefault: false }) + } + } + return commands +} + +/** Reads the OpenWithList executable names, ignoring the MRU ordering value. */ +function readWindowsOpenWithListExecutables( + registry: WindowsNativeRegistryModule, + fileExtsKey: string +): string[] { + const openWithList = registry.getRegistryKey(registry.HK.CU, `${fileExtsKey}\\OpenWithList`) + const executableNames: string[] = [] + for (const [valueName, entry] of Object.entries(openWithList ?? {})) { + if (valueName.toLowerCase() === 'mrulist' || typeof entry?.value !== 'string') { + continue + } + executableNames.push(entry.value) + } + return executableNames +} + +/** Reads a ProgId's shell\open\command line from one hive. */ +function readClassOpenCommand( + registry: WindowsNativeRegistryModule, + classSubkeyPath: string +): string | null { + for (const root of [registry.HK.CU, registry.HK.LM]) { + const command = readRegistryString( + registry, + root, + `${CLASSES_KEY_PREFIX}\\${classSubkeyPath}`, + '' + ) + if (command?.trim()) { + return command.trim() + } + } + return null +} + +/** Reads one registry string value, or null when the key, value or type does not match. */ +function readRegistryString( + registry: WindowsNativeRegistryModule, + root: number, + keyPath: string, + valueName: string +): string | null { + let key: ReturnType + try { + key = registry.getRegistryKey(root, keyPath) + } catch { + return null + } + const entry = key?.[valueName] + if (typeof entry?.value !== 'string') { + return null + } + return entry.type === WINDOWS_REG_EXPAND_SZ + ? expandWindowsEnvironmentVariables(entry.value) + : entry.value +} + +/** Lists a registry key's value names; empty when the key is missing. */ +function readRegistryValueNames( + registry: WindowsNativeRegistryModule, + root: number, + keyPath: string +): string[] { + try { + return Object.keys(registry.getRegistryKey(root, keyPath) ?? {}).filter(Boolean) + } catch { + return [] + } +} + +/** Expands %VAR% references while leaving argument placeholders such as %1 intact. */ +export function expandWindowsEnvironmentVariables( + value: string, + env: NodeJS.ProcessEnv = process.env +): string { + // Why: %1-style launch placeholders never resolve as env vars, so unknown + // names must survive expansion untouched. + return value.replace(/%([^%]+)%/g, (match, name: string) => env[name] ?? match) +} + +/** Extracts the executable path from a registry command line. */ +export function extractWindowsExecutablePath( + command: string, + fileExists: (path: string) => boolean = existsSync +): string | null { + const trimmed = command.trim() + if (!trimmed) { + return null + } + if (trimmed.startsWith('"')) { + const closingQuote = trimmed.indexOf('"', 1) + return closingQuote > 1 ? trimmed.slice(1, closingQuote) : null + } + // Why: registry commands may leave a spaced executable path unquoted + // (`C:\Program Files\App\app.exe "%1"`); probe progressively longer prefixes. + const tokens = trimmed.split(/\s+/) + let prefix = '' + for (const token of tokens) { + prefix = prefix ? `${prefix} ${token}` : token + if (/\.exe$/i.test(prefix) && fileExists(prefix)) { + return prefix + } + } + return /\.exe$/i.test(tokens[0] ?? '') ? tokens[0] : null +} + +/** Builds the spawn command and argv for a registry command line and target path. */ +export function buildWindowsLaunchInvocation( + command: string, + filePath: string, + fileExists: (path: string) => boolean = existsSync +): { spawnCmd: string; spawnArgs: string[] } | null { + const executablePath = extractWindowsExecutablePath(command, fileExists) + if (!executablePath) { + return null + } + const trimmed = command.trim() + const argsText = trimmed.startsWith('"') + ? trimmed.slice(trimmed.indexOf('"', 1) + 1) + : trimmed.slice(executablePath.length) + + const spawnArgs: string[] = [] + let placeholderUsed = false + for (const token of tokenizeWindowsCommandArguments(argsText)) { + // Why: shell verbs substitute the target into %1/%l (path) and %u/%v (URL + // or path) alike — Office registers `"%1" /ou "%u"` and expects both filled. + if (/^%[1lLuUvV]$/.test(token)) { + spawnArgs.push(filePath) + placeholderUsed = true + continue + } + if (/^%(\*|\d+)$/.test(token)) { + continue + } + if (/%[1lLuUvV](?![A-Za-z0-9_%])/.test(token)) { + spawnArgs.push(token.replace(/%[1lLuUvV](?![A-Za-z0-9_%])/g, () => filePath)) + placeholderUsed = true + continue + } + spawnArgs.push(token) + } + if (!placeholderUsed) { + spawnArgs.push(filePath) + } + return { spawnCmd: executablePath, spawnArgs } +} + +/** Splits a command line's argument tail, honoring double-quoted spans. */ +function tokenizeWindowsCommandArguments(argsText: string): string[] { + const tokens: string[] = [] + const tokenPattern = /"([^"]*)"|(\S+)/g + let match: RegExpExecArray | null + while ((match = tokenPattern.exec(argsText)) !== null) { + tokens.push(match[1] ?? match[2]) + } + return tokens +} + +/** Display name derived from the executable file name, used when FileDescription is unavailable. */ +export function fallbackWindowsApplicationName(executablePath: string): string { + const baseName = win32.basename(executablePath).replace(/\.exe$/i, '') + return baseName ? baseName.charAt(0).toUpperCase() + baseName.slice(1) : executablePath +} + +/** Replaces candidate names with each executable's FileDescription where one is available. */ +async function applyWindowsFileDescriptions( + candidates: (OpenWithApplicationCandidate & { executablePath: string })[] +): Promise { + if (candidates.length === 0) { + return + } + const quotedPaths = candidates + .map((candidate) => `'${candidate.executablePath.replace(/'/g, "''")}'`) + .join(', ') + // Why: PowerShell 5.1 emits redirected stdout in the OEM code page; pin UTF-8 + // or localized app descriptions arrive as mojibake. + const script = ` +[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) +$results = foreach ($p in @(${quotedPaths})) { + try { + $d = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($p).FileDescription + if ($d) { [PSCustomObject]@{ path = $p; description = $d.Trim() } } + } catch {} +} +ConvertTo-Json -InputObject @($results) -Compress +` + let entries: { path?: unknown; description?: unknown }[] + try { + const output = await readOpenWithCommandOutput( + getWindowsPowerShellExePath(), + ['-NoProfile', '-NonInteractive', '-Command', script], + DESCRIPTION_LOOKUP_TIMEOUT_MS + ) + const parsed: unknown = JSON.parse(output) + entries = Array.isArray(parsed) ? parsed : [] + } catch { + return + } + const descriptionsByPath = new Map() + for (const entry of entries) { + if (typeof entry?.path === 'string' && typeof entry.description === 'string') { + descriptionsByPath.set(entry.path.toLowerCase(), entry.description) + } + } + for (const candidate of candidates) { + const description = descriptionsByPath.get(candidate.executablePath.toLowerCase()) + if (description) { + candidate.name = description + } + } +} diff --git a/src/main/persistence-open-with-recent-applications.test.ts b/src/main/persistence-open-with-recent-applications.test.ts new file mode 100644 index 000000000000..1427b08d6186 --- /dev/null +++ b/src/main/persistence-open-with-recent-applications.test.ts @@ -0,0 +1,106 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { rmSync, mkdtempSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import type { PersistedState } from '../shared/persisted-state-types' +import { testState, createStore, readDataFile } from './persistence-test-harness' + +// Stub the ~/.ssh/config parser so the real Store boots with deterministic hosts, not the operator's actual ~/.ssh/config. +const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ + loadUserSshConfigMock: vi.fn(), + sshConfigHostsToTargetsMock: vi.fn() +})) + +vi.mock('./ssh/ssh-config-parser', () => ({ + loadUserSshConfig: loadUserSshConfigMock, + sshConfigHostsToTargets: sshConfigHostsToTargetsMock +})) +const { trackMock, getCohortAtEmitMock } = vi.hoisted(() => ({ + trackMock: vi.fn(), + getCohortAtEmitMock: vi.fn() +})) + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.dir + }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), + decryptString: (ciphertext: Buffer) => { + const decoded = ciphertext.toString('utf-8') + if (!decoded.startsWith('encrypted:')) { + throw new Error('invalid ciphertext') + } + return decoded.slice('encrypted:'.length) + } + } +})) + +vi.mock('./telemetry/client', () => ({ + track: trackMock +})) + +vi.mock('./telemetry/cohort-classifier', () => ({ + getCohortAtEmit: getCohortAtEmitMock +})) + +describe('open-with recent applications', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) + trackMock.mockReset() + getCohortAtEmitMock.mockReset() + getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 }) + }) + + afterEach(() => { + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it('records launches most-recent-first, dedupes to front, caps at 5, lowercases the key', () => { + const store = createStore() + + store.recordOpenWithApplicationLaunch('.MD', 'app-a') + store.recordOpenWithApplicationLaunch('.md', 'app-b') + store.recordOpenWithApplicationLaunch('.md', 'app-a') + expect(store.getOpenWithRecentApplicationIds('.md')).toEqual(['app-a', 'app-b']) + + for (const id of ['app-c', 'app-d', 'app-e', 'app-f']) { + store.recordOpenWithApplicationLaunch('.md', id) + } + expect(store.getOpenWithRecentApplicationIds('.MD')).toEqual([ + 'app-f', + 'app-e', + 'app-d', + 'app-c', + 'app-a' + ]) + + store.flush() + const persisted = readDataFile() as PersistedState + expect(persisted.openWithRecentApplicationsByExtension).toEqual({ + '.md': ['app-f', 'app-e', 'app-d', 'app-c', 'app-a'] + }) + + // Why: the field has no default in getDefaultPersistedState, so the load path must keep it. + const reloaded = createStore() + expect(reloaded.getOpenWithRecentApplicationIds('.md')).toEqual([ + 'app-f', + 'app-e', + 'app-d', + 'app-c', + 'app-a' + ]) + }) + + it('ignores empty extensions and records nothing after writes freeze', () => { + const store = createStore() + + store.recordOpenWithApplicationLaunch(' ', 'app-a') + expect(store.getOpenWithRecentApplicationIds('')).toEqual([]) + + store.freezeWrites() + store.recordOpenWithApplicationLaunch('.md', 'app-a') + expect(store.getOpenWithRecentApplicationIds('.md')).toEqual([]) + }) +}) diff --git a/src/main/persistence/loading-store/open-with-recent-application-persistence.ts b/src/main/persistence/loading-store/open-with-recent-application-persistence.ts new file mode 100644 index 000000000000..280364ce5e88 --- /dev/null +++ b/src/main/persistence/loading-store/open-with-recent-application-persistence.ts @@ -0,0 +1,56 @@ +import type { StoreRuntimeState } from './store-runtime-state' +import type { WriteSchedulingOperations } from './write-scheduling' +import { scheduleSave } from './write-scheduling' + +const OPEN_WITH_RECENT_APPLICATIONS_LIMIT = 5 + +type OpenWithRecentApplicationRuntime = Pick + +const openWithRecentApplicationPersistenceContext = Symbol('OpenWithRecentApplicationPersistence') +type OpenWithRecentApplicationPersistenceContext = { + runtime: OpenWithRecentApplicationRuntime + scheduling: WriteSchedulingOperations +} + +/** Per-extension Open With recency; ids only affect ranking, never what launches. */ +export class OpenWithRecentApplicationPersistence { + readonly [openWithRecentApplicationPersistenceContext]: OpenWithRecentApplicationPersistenceContext + + constructor(runtime: OpenWithRecentApplicationRuntime, scheduling: WriteSchedulingOperations) { + this[openWithRecentApplicationPersistenceContext] = { runtime, scheduling } + } + + getOpenWithRecentApplicationIds(extension: string): string[] { + const key = extension.trim().toLowerCase() + if (!key) { + return [] + } + const byExtension = + this[openWithRecentApplicationPersistenceContext].runtime.state + .openWithRecentApplicationsByExtension + return [...(byExtension?.[key] ?? [])] + } + + recordOpenWithApplicationLaunch(extension: string, applicationId: string): void { + const { runtime, scheduling } = this[openWithRecentApplicationPersistenceContext] + const key = extension.trim().toLowerCase() + if (!key || !applicationId || runtime.writesFrozen) { + return + } + const byExtension = (runtime.state.openWithRecentApplicationsByExtension ??= {}) + byExtension[key] = [ + applicationId, + ...(byExtension[key] ?? []).filter((id) => id !== applicationId) + ].slice(0, OPEN_WITH_RECENT_APPLICATIONS_LIMIT) + scheduleSave(scheduling) + } +} + +export function installOpenWithRecentApplicationPersistenceContext( + target: object, + source: OpenWithRecentApplicationPersistence +): void { + Object.defineProperty(target, openWithRecentApplicationPersistenceContext, { + value: source[openWithRecentApplicationPersistenceContext] + }) +} diff --git a/src/main/persistence/loading-store/store-domain-composition.ts b/src/main/persistence/loading-store/store-domain-composition.ts index 2bbe91a1a2ef..eec78187f8e9 100644 --- a/src/main/persistence/loading-store/store-domain-composition.ts +++ b/src/main/persistence/loading-store/store-domain-composition.ts @@ -63,6 +63,10 @@ import { SshLeaseRecoveryOperations, installSshLeaseRecoveryOperationsContext } from './ssh-lease-recovery-operations' +import { + OpenWithRecentApplicationPersistence, + installOpenWithRecentApplicationPersistenceContext +} from './open-with-recent-application-persistence' export type StoreDomains = { adaptation: LoadedStateAdaptationOperations @@ -87,6 +91,7 @@ export type StoreDomains = { sshProfiles: SshProfileOperations retiredWorktreeNames: RetiredWorktreeNamePersistence sshLeases: SshLeaseRecoveryOperations + openWithRecentApplications: OpenWithRecentApplicationPersistence } export const STORE_DOMAIN_OPERATION_CLASSES = [ @@ -105,6 +110,7 @@ export const STORE_DOMAIN_OPERATION_CLASSES = [ SshProfileOperations, RetiredWorktreeNamePersistence, SshLeaseRecoveryOperations, + OpenWithRecentApplicationPersistence, WriteFlushBarrierOperations ] as const @@ -124,6 +130,7 @@ export function installStoreDomainContexts(target: object, domains: StoreDomains installSshProfileOperationsContext(target, domains.sshProfiles) installRetiredWorktreeNamePersistenceContext(target, domains.retiredWorktreeNames) installSshLeaseRecoveryOperationsContext(target, domains.sshLeases) + installOpenWithRecentApplicationPersistenceContext(target, domains.openWithRecentApplications) installWriteFlushBarrierOperationsContext(target, domains.flushBarriers) } @@ -160,6 +167,7 @@ export function createStoreDomains(runtime: StoreRuntimeState): StoreDomains { bindingRecovery, scheduling ) + const openWithRecentApplications = new OpenWithRecentApplicationPersistence(runtime, scheduling) return { adaptation, backups, @@ -182,6 +190,7 @@ export function createStoreDomains(runtime: StoreRuntimeState): StoreDomains { ptyBindings, sshProfiles, retiredWorktreeNames, - sshLeases + sshLeases, + openWithRecentApplications } } diff --git a/src/main/persistence/loading-store/store.ts b/src/main/persistence/loading-store/store.ts index 017583e8f863..0b5ada294182 100644 --- a/src/main/persistence/loading-store/store.ts +++ b/src/main/persistence/loading-store/store.ts @@ -31,6 +31,7 @@ import type { PtyBindingPersistenceOperations } from './pty-binding-persistence' import type { SshProfileOperations } from './ssh-profile-operations' import type { RetiredWorktreeNamePersistence } from './retired-worktree-name-persistence' import type { SshLeaseRecoveryOperations } from './ssh-lease-recovery-operations' +import type { OpenWithRecentApplicationPersistence } from './open-with-recent-application-persistence' import type { WriteFlushBarrierOperations } from './write-flush-barriers' export type StoreOptions = StoreRuntimeOptions @@ -122,6 +123,7 @@ export interface Store SshProfileOperations, RetiredWorktreeNamePersistence, SshLeaseRecoveryOperations, + OpenWithRecentApplicationPersistence, WriteFlushBarrierOperations {} for (const OperationClass of STORE_DOMAIN_OPERATION_CLASSES) { diff --git a/src/main/win32-utils.ts b/src/main/win32-utils.ts index 5798f22be5a3..b0d700113b36 100644 --- a/src/main/win32-utils.ts +++ b/src/main/win32-utils.ts @@ -42,11 +42,30 @@ export function getWhoamiExePath(): string { return `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\whoami.exe` } +function resolveSystemRoot(env: NodeJS.ProcessEnv): string { + const systemRoot = env.SystemRoot?.trim() + return systemRoot && /^[a-z]:[\\/]/i.test(systemRoot) ? systemRoot : 'C:\\Windows' +} + /** Absolute path because service-launched Electron can omit System32 from PATH. */ export function getRegExePath(env: NodeJS.ProcessEnv = process.env): string { - const systemRoot = env.SystemRoot?.trim() - const root = systemRoot && /^[a-z]:[\\/]/i.test(systemRoot) ? systemRoot : 'C:\\Windows' - return win32.join(root, 'System32', 'reg.exe') + return win32.join(resolveSystemRoot(env), 'System32', 'reg.exe') +} + +/** Absolute path because service-launched Electron can omit System32 from PATH. */ +export function getWindowsPowerShellExePath(env: NodeJS.ProcessEnv = process.env): string { + return win32.join( + resolveSystemRoot(env), + 'System32', + 'WindowsPowerShell', + 'v1.0', + 'powershell.exe' + ) +} + +/** Absolute path because service-launched Electron can omit System32 from PATH. */ +export function getRundll32ExePath(env: NodeJS.ProcessEnv = process.env): string { + return win32.join(resolveSystemRoot(env), 'System32', 'rundll32.exe') } export function resolveWindowsCommand( diff --git a/src/preload/api/shell-api.ts b/src/preload/api/shell-api.ts index 49e811aeb659..e51dcc63d000 100644 --- a/src/preload/api/shell-api.ts +++ b/src/preload/api/shell-api.ts @@ -1,13 +1,17 @@ import type { + ShellListOpenWithApplicationsResult, ShellOpenExternalEditorRequest, ShellOpenExternalEditorResult, - ShellOpenLocalPathResult + ShellOpenLocalPathResult, + ShellOpenPathWithApplicationRequest } from '../../shared/shell-open-types' export type { + ShellListOpenWithApplicationsResult, ShellOpenExternalEditorRequest, ShellOpenExternalEditorResult, - ShellOpenLocalPathResult + ShellOpenLocalPathResult, + ShellOpenPathWithApplicationRequest } from '../../shared/shell-open-types' export type ShellApi = { @@ -18,6 +22,10 @@ export type ShellApi = { ) => Promise openUrl: (url: string) => Promise openFilePath: (path: string) => Promise + listOpenWithApplications: (path: string) => Promise + openPathWithApplication: ( + request: ShellOpenPathWithApplicationRequest + ) => Promise openFileUri: (uri: string) => Promise pathsExist?: (paths: string[]) => Promise pathExists: (path: string) => Promise diff --git a/src/preload/api/shell-bridge.ts b/src/preload/api/shell-bridge.ts index 6cd250042a69..159def8cb6e5 100644 --- a/src/preload/api/shell-bridge.ts +++ b/src/preload/api/shell-bridge.ts @@ -1,8 +1,10 @@ import { ipcRenderer } from 'electron' import type { + ShellListOpenWithApplicationsResult, ShellOpenExternalEditorRequest, ShellOpenExternalEditorResult, - ShellOpenLocalPathResult + ShellOpenLocalPathResult, + ShellOpenPathWithApplicationRequest } from '../../shared/shell-open-types' import type { PreloadApi } from '../api-types' @@ -21,6 +23,14 @@ export const shellApi = { openFilePath: (path: string): Promise => ipcRenderer.invoke('shell:openFilePath', path), + listOpenWithApplications: (path: string): Promise => + ipcRenderer.invoke('shell:listOpenWithApplications', path), + + openPathWithApplication: ( + request: ShellOpenPathWithApplicationRequest + ): Promise => + ipcRenderer.invoke('shell:openPathWithApplication', request), + openFileUri: (uri: string): Promise => ipcRenderer.invoke('shell:openFileUri', uri), pathsExist: (paths: string[]): Promise => diff --git a/src/renderer/src/components/right-sidebar/file-explorer-open-with-submenu.test.ts b/src/renderer/src/components/right-sidebar/file-explorer-open-with-submenu.test.ts new file mode 100644 index 000000000000..db3f7585dc41 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer-open-with-submenu.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { shouldShowOpenWithSubmenu } from './file-explorer-open-with-submenu' + +const fileNode = { isDirectory: false } +const directoryNode = { isDirectory: true } + +describe('shouldShowOpenWithSubmenu', () => { + it('shows only for local file rows on the desktop client', () => { + const previous = (globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ + try { + expect(shouldShowOpenWithSubmenu(fileNode, null, null)).toBe(true) + expect(shouldShowOpenWithSubmenu(fileNode, undefined, undefined)).toBe(true) + expect(shouldShowOpenWithSubmenu(directoryNode, null, null)).toBe(false) + expect(shouldShowOpenWithSubmenu(fileNode, 'ssh-1', null)).toBe(false) + expect(shouldShowOpenWithSubmenu(fileNode, null, { activeRuntimeEnvironmentId: 'rt-1' })).toBe( + false + ) + // Whitespace-only ids mean no active remote target. + expect(shouldShowOpenWithSubmenu(fileNode, ' ', { activeRuntimeEnvironmentId: ' ' })).toBe( + true + ) + + ;(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = true + expect(shouldShowOpenWithSubmenu(fileNode, null, null)).toBe(false) + } finally { + ;(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = previous + } + }) +}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer-open-with-submenu.tsx b/src/renderer/src/components/right-sidebar/file-explorer-open-with-submenu.tsx new file mode 100644 index 000000000000..2f0dbdcb3e0e --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer-open-with-submenu.tsx @@ -0,0 +1,180 @@ +import React, { useCallback, useEffect, useState } from 'react' +import { AppWindow } from 'lucide-react' +import { toast } from 'sonner' +import { + OPEN_WITH_CHOOSER_APPLICATION_ID, + type ShellOpenWithApplication +} from '../../../../shared/shell-open-types' +import { + ContextMenuItem, + ContextMenuSeparator, + ContextMenuSub, + ContextMenuSubContent, + ContextMenuSubTrigger +} from '@/components/ui/context-menu' +import { translate } from '@/i18n/i18n' +import { isLocalPathOpenBlocked } from '@/lib/local-path-open-guard' + +type OpenWithListingState = + | { status: 'idle' } + | { status: 'loading' } + | { status: 'ready'; applications: ShellOpenWithApplication[]; supportsChooserDialog: boolean } + | { status: 'unavailable' } + +/** True only for local file rows on the desktop client, the one case where OS handlers apply. */ +export function shouldShowOpenWithSubmenu( + node: { isDirectory: boolean }, + connectionId: string | null | undefined, + settings: { activeRuntimeEnvironmentId?: string | null } | null | undefined +): boolean { + if (node.isDirectory) { + return false + } + // Why: OS handler discovery and launching both run on this client's machine; + // web clients and remote (SSH / on-demand runtime) files have no local path. + if ((globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ === true) { + return false + } + return !isLocalPathOpenBlocked(settings, { connectionId }) +} + +/** Open With submenu; discovery starts the first time it opens. */ +export function FileExplorerOpenWithSubmenu({ filePath }: { filePath: string }): React.JSX.Element { + const [listing, setListing] = useState({ status: 'idle' }) + // Why: discovery spawns OS tools — only pay for it once the user opens the + // submenu, not on every context-menu open. + const [discoveryRequested, setDiscoveryRequested] = useState(false) + + useEffect(() => { + setListing({ status: 'idle' }) + setDiscoveryRequested(false) + }, [filePath]) + + useEffect(() => { + if (!discoveryRequested) { + return + } + let disposed = false + setListing({ status: 'loading' }) + window.api.shell + .listOpenWithApplications(filePath) + .then((result) => { + if (disposed) { + return + } + setListing( + result.ok + ? { + status: 'ready', + applications: result.applications, + supportsChooserDialog: result.supportsChooserDialog + } + : { status: 'unavailable' } + ) + }) + .catch(() => { + if (!disposed) { + setListing({ status: 'unavailable' }) + } + }) + return () => { + disposed = true + } + }, [filePath, discoveryRequested]) + + const handleOpenWithApplication = useCallback( + (applicationId: string) => { + const showOpenFailedToast = (): void => { + toast.error( + translate( + 'auto.components.right.sidebar.FileExplorerOpenWithSubmenu.openFailed', + 'Could not open the file with the selected application.' + ) + ) + } + void window.api.shell + .openPathWithApplication({ path: filePath, applicationId }) + .then((result) => { + if (!result.ok) { + showOpenFailedToast() + } + }) + .catch(showOpenFailedToast) + }, + [filePath] + ) + + return ( + { + if (open) { + setDiscoveryRequested(true) + } + }} + > + + + {translate( + 'auto.components.right.sidebar.FileExplorerOpenWithSubmenu.openWith', + 'Open With' + )} + + + {(listing.status === 'idle' || listing.status === 'loading') && ( + + {translate( + 'auto.components.right.sidebar.FileExplorerOpenWithSubmenu.loading', + 'Looking for applications...' + )} + + )} + {listing.status === 'unavailable' && ( + + {translate( + 'auto.components.right.sidebar.FileExplorerOpenWithSubmenu.unavailable', + 'Applications are unavailable for this file.' + )} + + )} + {listing.status === 'ready' && listing.applications.length === 0 && ( + + {translate( + 'auto.components.right.sidebar.FileExplorerOpenWithSubmenu.noApplications', + 'No applications found' + )} + + )} + {listing.status === 'ready' && + listing.applications.map((application) => ( + handleOpenWithApplication(application.id)} + > + {application.name} + {application.isDefault ? ( + + {translate( + 'auto.components.right.sidebar.FileExplorerOpenWithSubmenu.defaultBadge', + 'Default' + )} + + ) : null} + + ))} + {listing.status === 'ready' && listing.supportsChooserDialog && ( + <> + + handleOpenWithApplication(OPEN_WITH_CHOOSER_APPLICATION_ID)} + > + {translate( + 'auto.components.right.sidebar.FileExplorerOpenWithSubmenu.chooseAnotherApp', + 'Choose another app...' + )} + + + )} + + + ) +} diff --git a/src/renderer/src/components/right-sidebar/file-explorer-row-context-menu.tsx b/src/renderer/src/components/right-sidebar/file-explorer-row-context-menu.tsx index a9be313a4367..5b3458bbe8a1 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer-row-context-menu.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer-row-context-menu.tsx @@ -38,6 +38,10 @@ import { shouldShowViewFileAction } from './file-explorer-row-action-visibility' import { copyFileToOsClipboard, downloadRemoteFile } from './file-explorer-row-file-transfer' +import { + FileExplorerOpenWithSubmenu, + shouldShowOpenWithSubmenu +} from './file-explorer-open-with-submenu' const isMac = navigator.userAgent.includes('Mac') const isLinux = navigator.userAgent.includes('Linux') @@ -119,6 +123,9 @@ export function FileExplorerRowContextMenu({ }: FileExplorerRowContextMenuProps): React.JSX.Element { const openMarkdownPreview = useAppStore((s) => s.openMarkdownPreview) const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) + const activeRuntimeEnvironmentId = useAppStore( + (s) => s.settings?.activeRuntimeEnvironmentId ?? null + ) const copyPathShortcutLabel = useShortcutLabel('fileExplorer.copyPath') const copyRelativePathShortcutLabel = useShortcutLabel('fileExplorer.copyRelativePath') const findInFolderShortcutLabel = useShortcutLabel('sidebar.search.toggle') @@ -233,6 +240,9 @@ export function FileExplorerRowContextMenu({ )} )} + {shouldShowOpenWithSubmenu(node, connectionId, { activeRuntimeEnvironmentId }) && ( + + )} {!node.isDirectory && activeWorktreeId && detectLanguage(node.path) === 'markdown' && ( diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 81700b22ff3a..defd22124cb6 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -13349,6 +13349,15 @@ "90cabf6cfc": "Stack this PR above #{{value0}}", "ff81473a57": "Creates a GitHub Stack or extends the parent's existing stack.", "29732f2fb0": "new PR" + }, + "FileExplorerOpenWithSubmenu": { + "openFailed": "Could not open the file with the selected application.", + "openWith": "Open With", + "loading": "Looking for applications...", + "unavailable": "Applications are unavailable for this file.", + "noApplications": "No applications found", + "defaultBadge": "Default", + "chooseAnotherApp": "Choose another app..." } } }, diff --git a/src/renderer/src/web/preload-api/web-shell-api.ts b/src/renderer/src/web/preload-api/web-shell-api.ts index 138ebe9abb46..defd9cf32160 100644 --- a/src/renderer/src/web/preload-api/web-shell-api.ts +++ b/src/renderer/src/web/preload-api/web-shell-api.ts @@ -19,6 +19,12 @@ export function createShellApi(): NonNullable['shell']> { openInExternalEditor: () => Promise.resolve(openResult), openUrl: (url) => Promise.resolve(window.open(url, '_blank', 'noopener,noreferrer') as never), openFilePath: () => Promise.resolve(false), + // Why: OS handler discovery needs the desktop main process; the web client + // hides the Open With menu, so these stubs only satisfy the API surface. + listOpenWithApplications: () => + Promise.resolve({ ok: false, reason: 'remote-runtime-unsupported' as const }), + openPathWithApplication: () => + Promise.resolve({ ok: false, reason: 'remote-runtime-unsupported' as const }), openFileUri: (uri) => Promise.resolve(window.open(uri, '_blank', 'noopener,noreferrer') as never), pathExists: async (path) => pathExistsOnRuntime(path), diff --git a/src/shared/persisted-state-types.ts b/src/shared/persisted-state-types.ts index a081eee76ab3..f325d78a0971 100644 --- a/src/shared/persisted-state-types.ts +++ b/src/shared/persisted-state-types.ts @@ -114,4 +114,6 @@ export type PersistedState = { featureInteractionTelemetryBuckets?: FeatureInteractionTelemetryBucketState /** Main-owned reset mutation journal. Never expose this through renderer settings APIs. */ codexResetCreditAttemptLedger?: CodexResetCreditAttemptLedger + /** Main-owned Open With recency (extension → application ids, most recent first); never expose through renderer settings APIs. */ + openWithRecentApplicationsByExtension?: Record } diff --git a/src/shared/shell-open-types.ts b/src/shared/shell-open-types.ts index f898ee210696..b7ecfd6f8918 100644 --- a/src/shared/shell-open-types.ts +++ b/src/shared/shell-open-types.ts @@ -27,3 +27,27 @@ export type ShellOpenExternalEditorResult = | { ok: true } | { ok: false; reason: Exclude } | { ok: false; reason: 'ssh-alias-required'; host: string; port: number } + +export type ShellOpenWithApplication = { + id: string + name: string + isDefault?: boolean +} + +export type ShellListOpenWithApplicationsResult = + | { + ok: true + applications: ShellOpenWithApplication[] + supportsChooserDialog: boolean + } + | { ok: false; reason: ShellOpenLocalPathFailureReason } + +export type ShellOpenPathWithApplicationRequest = { + path: string + applicationId: string +} + +// Why: the Windows "How do you want to open this file?" dialog is offered as a +// synthetic entry so the renderer needs a stable id that can never collide +// with a discovered application id (those are prefixed by platform). +export const OPEN_WITH_CHOOSER_APPLICATION_ID = 'system:open-with-chooser'