The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): say "File not found" when opening a missing file
Brooklyn Nicholsonba5e3bfa31e5
diff --git a/apps/desktop/electron/external-open.test.ts b/apps/desktop/electron/external-open.test.tsindex 646ec2d365c..53acd2eb916 100644--- a/apps/desktop/electron/external-open.test.ts+++ b/apps/desktop/electron/external-open.test.ts@@ -11,7 +11,7 @@ import { EventEmitter } from 'node:events'import { test } from 'vitest'-import { type ExternalOpenDeps, openExternalUrl } from './external-open'+import { type ExternalOpenDeps, openExternalUrl, reportPreOpenStatFailure } from './external-open'function makeDeps(overrides: Partial<ExternalOpenDeps> = {}) {const calls = {@@ -134,3 +134,40 @@ test('wsl: falls back to openExternal and notifies when cmd.exe fails to spawn',assert.deepEqual(calls.opened, ['https://example.com/'])assert.deepEqual(calls.notified, [['https://example.com/', 'xdg-open missing']])})++test('guard: missing-file error is reported once and classified as a miss', () => {+ const reported: Array<[string, string]> = []+ const logged: string[] = []++ const error = Object.assign(new Error('This file does not exist: /tmp/gone.html'), { code: 'missing-file' })++ const isMiss = reportPreOpenStatFailure(error, 'file:///tmp/gone.html', {+ log: line => logged.push(line),+ reportMissing: (url, message) => reported.push([url, message])+ })++ assert.equal(isMiss, true)+ assert.deepEqual(reported, [['file:///tmp/gone.html', 'This file does not exist: /tmp/gone.html']])+ assert.equal(logged.length, 0)+})++test('guard: a non-missing stat failure is logged and classified as proceed-to-OS', () => {+ const reported: Array<[string, string]> = []+ const logged: string[] = []++ for (const code of ['EACCES', 'ELOOP', 'EPERM', 'ENAMETOOLONG']) {+ const error = Object.assign(new Error(`${code}: stat failed`), { code })++ const isMiss = reportPreOpenStatFailure(error, 'file:///srv/locked/report.html', {+ log: line => logged.push(line),+ reportMissing: (url, message) => reported.push([url, message])+ })++ assert.equal(isMiss, false, code)+ }++ // Nothing was fabricated as a miss, and every failure left a log line.+ assert.equal(reported.length, 0)+ assert.equal(logged.length, 4)+ assert.ok(logged.every(line => line.includes('[file] pre-open stat failed')))+})diff --git a/apps/desktop/electron/external-open.ts b/apps/desktop/electron/external-open.tsindex 6e1d48fb44c..25894f7157b 100644--- a/apps/desktop/electron/external-open.ts+++ b/apps/desktop/electron/external-open.ts@@ -18,6 +18,36 @@ import type { ChildProcess, SpawnOptions } from 'node:child_process'export type ExternalOpenResult ={ ok: true } | { ok: false; reason: 'invalid' } | { ok: false; reason: 'failed'; message: string }+export interface FileOpenGuardDeps {+ log: (line: string) => void+ reportMissing: (rawUrl: string, message: string) => void+}++/**+ * Decide what a pre-open stat failure means for a file open (#122027). Lives+ * here, not inline in main.ts, so the classification is unit-tested without+ * loading electron — same injected-deps shape as the rest of the module.+ *+ * Returns true when the failure was a MISS: it has been reported through+ * reportMissing and the caller must NOT hand the path to the OS (a reveal of+ * a non-existent path is silently a no-op on macOS; an open of one reads as+ * "No application found" on LaunchServices). Returns false for every other+ * stat failure (EACCES on a locked volume, ELOOP, Windows EPERM): those are+ * logged and the caller still proceeds to the OS, so an existing-but-locked+ * file keeps its real error and a stat failure never fabricates a miss.+ */+export function reportPreOpenStatFailure(error: unknown, rawUrl: string, deps: FileOpenGuardDeps): boolean {+ if (error && typeof error === 'object' && (error as { code?: string }).code === 'missing-file') {+ deps.reportMissing(rawUrl, externalOpenErrorMessage(error))++ return true+ }++ deps.log(`[file] pre-open stat failed: ${externalOpenErrorMessage(error)}`)++ return false+}+export interface ExternalOpenDeps {isWsl: booleanspawn: (cmd: string, args: readonly string[], opts: SpawnOptions) => ChildProcessdiff --git a/apps/desktop/electron/hardening.ts b/apps/desktop/electron/hardening.tsindex 3e393502b46..0d19ac8b356 100644--- a/apps/desktop/electron/hardening.ts+++ b/apps/desktop/electron/hardening.ts@@ -370,6 +370,34 @@ function rejectUnsafePathSyntax(filePath, purpose = 'File read') {return raw}+/**+ * Stat a resolved path before handing an `open` to the OS. The OS gives the+ * miss and the unclaimable file the SAME answer (macOS LaunchServices returns+ * `kLSApplicationNotFoundErr` for a non-existent path, so a deleted file is+ * reported as "No application found to open URL"; Electron's `shell.openPath`+ * resolves with an error for a miss and the caller then "reveals in folder" a+ * folder that isn't there). Only ENOENT/ENOTDIR count as missing — a path that+ * stats-fails for any other reason (EACCES on an existing file, root-owned+ * trees) must still reach the OS, so a stat failure here never fabricates a+ * miss.+ */+function assertExistingPathForOpen(resolvedPath: string, purpose = 'Open file') {+ try {+ fs.statSync(resolvedPath)+ } catch (error) {+ const code = error && typeof error === 'object' && 'code' in error ? (error as { code?: string }).code : undefined++ if (code === 'ENOENT' || code === 'ENOTDIR') {+ throw ipcPathError(+ 'missing-file',+ `${purpose} failed: the file does not exist — it may have been deleted or moved, or it lives on another machine.`+ )+ }++ throw error+ }+}+function resolveRequestedPathForIpc(filePath, options: { purpose?: string; baseDir?: fs.PathOrFileDescriptor } = {}) {const purpose = String(options.purpose || 'File read')let raw = rejectUnsafePathSyntax(filePath, purpose)@@ -568,6 +596,7 @@ async function readFileDataUrlForIpc(}export {+ assertExistingPathForOpen,ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,clampDataUrlReadMaxMb,DATA_URL_READ_DEFAULT_MAX_MB,diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 1cb0705b430..d2d333e670e 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -223,7 +223,7 @@ import { describeDevCdpDecision, resolveDevCdpPort } from './dev-cdp'import { preReadyDockLaunchSteps } from './dock-launch-order'import { installEmbedReferer } from './embed-referer'import { createAmbientClaimArbiter } from './event-dedupe'-import { openExternalUrl as externalOpen, type ExternalOpenDeps } from './external-open'+import { openExternalUrl as externalOpen, type ExternalOpenDeps, reportPreOpenStatFailure } from './external-open'import {buildTerminalScript,resolveTerminalLaunch,@@ -264,6 +264,7 @@ import { registerGitIpc } from './git-ipc'import { desktopBackendSpawnEnv, guestOnboardingEnabled, skipIntroEnabled } from './guest-onboarding'import { readAndConsumeHandoffResult } from './handoff-result'import {+ assertExistingPathForOpen,ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,clampDataUrlReadMaxMb,DATA_URL_READ_DEFAULT_MAX_MB,@@ -2065,6 +2066,14 @@ const EXTERNAL_OPEN_DEPS: ExternalOpenDeps = {log: rememberLog}+// Deps for the pre-open stat guard (see openExternalFile): a miss is+// broadcast with the 'missing-file' code so the dialog shows file-not-found+// copy; other stat failures only log.+const GUARD_REPORT_DEPS = {+ log: rememberLog,+ reportMissing: (rawUrl: string, message: string) => broadcastOpenFailed(rawUrl, message, 'missing-file')+}+// The single route every external URL open funnels through (external-open.ts).// main.ts only binds the electron deps; all open/fallback logic lives in the// module so it unit-tests without loading electron.@@ -2106,6 +2115,23 @@ async function openExternalFile(rawUrl: string) {return}+ // A missing file must never reach the reveal fallback: on macOS revealing a+ // non-existent path is silently a no-op, so the click would do nothing at+ // all. Say "missing" before the OS is asked. Only ENOENT/ENOTDIR count as+ // missing — any other stat failure (EACCES on a locked volume, ELOOP) is+ // logged and still reaches the OS below, so an existing-but-locked file+ // keeps its real error instead of a fabricated miss. Classification lives+ // in external-open.ts so it unit-tests without electron. Misses are+ // reported here and not rethrown: external-open.ts documents that openFile+ // handles its own reporting, and rethrowing would stack a second dialog.+ try {+ assertExistingPathForOpen(localPath, 'Open external file')+ } catch (error) {+ if (reportPreOpenStatFailure(error, rawUrl, GUARD_REPORT_DEPS)) {+ return+ }+ }+const now = Date.now()const lastReveal = recentFileReveals.get(localPath)@@ -2133,12 +2159,14 @@ async function openExternalFile(rawUrl: string) {// An open failure is surfaced to the renderer as a modal carrying the URL, so// a dead system-browser click (e.g. no https handler registered on Linux) is-// never silent. Broadcast to every window — the trigger has no single sender.-function broadcastOpenFailed(url: string, message: string) {+// never silent. `code` tags the failure class (e.g. 'missing-file') so the+// dialog can show accurate localized copy instead of the generic one.+// Broadcast to every window — the trigger has no single sender.+function broadcastOpenFailed(url: string, message: string, code?: 'missing-file') {rememberLog(`[open-failed] ${url}: ${message}`)for (const win of BrowserWindow.getAllWindows()) {- win.webContents.send('hermes:external-open-failed', { url, message })+ win.webContents.send('hermes:external-open-failed', { url, message, ...(code ? { code } : {}) })}}diff --git a/apps/desktop/electron/open-missing-file.test.ts b/apps/desktop/electron/open-missing-file.test.tsnew file mode 100644index 00000000000..f7eab0f1d0c--- /dev/null+++ b/apps/desktop/electron/open-missing-file.test.ts@@ -0,0 +1,95 @@+import assert from 'node:assert/strict'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { test } from 'vitest'++import { assertExistingPathForOpen } from './hardening'++// #122027: a deleted/renamed file handed to the OS comes back as+// "No application found to open URL" on the open path (LaunchServices+// kLSApplicationNotFoundErr doubles as the missing-file answer on macOS), and+// the current reveal-in-folder route silently no-ops on a missing path — the+// click does nothing at all. The guard must say "missing" before the OS is+// asked, on all platforms — fs.statSync's ENOENT/ENOTDIR are uniform across+// macOS/Windows/Linux.++test('a missing path throws a missing-file error instead of reaching the OS', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'open-missing-'))+ const ghost = path.join(dir, 'report.html')++ assert.throws(+ () => assertExistingPathForOpen(ghost, 'Open preview in browser'),+ (error: Error & { code?: string }) => {+ assert.equal(error.code, 'missing-file')+ assert.match(error.message, /does not exist/)+ assert.match(error.message, /another machine/)++ return true+ }+ )+})++test('a path under a missing directory (ENOTDIR) also reads as missing', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'open-missing-'))+ const underFile = path.join(path.join(dir, 'plain.txt'), 'nested.txt')++ fs.writeFileSync(path.join(dir, 'plain.txt'), 'not a directory')++ assert.throws(+ () => assertExistingPathForOpen(underFile),+ (error: Error & { code?: string }) => error.code === 'missing-file'+ )+})++test('an existing file passes the guard', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'open-present-'))+ const real = path.join(dir, 'report.html')++ fs.writeFileSync(real, '<html></html>')++ assert.doesNotThrow(() => assertExistingPathForOpen(real, 'Open preview in browser'))+})++test('a non-ENOENT stat failure is not converted into a fabricated miss', () => {+ // The stat itself is the seam under test: an EACCES-style failure on an+ // EXISTING file must propagate untouched so the OS still gets a chance+ // (root-owned trees are openable by their owner's other tooling, and the+ // OS error there is honest — it is not "no application").+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'open-eacces-'))+ const real = path.join(dir, 'locked.txt')++ fs.writeFileSync(real, 'x')++ const eacces = Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' })+ const original = fs.statSync+ Object.defineProperty(fs, 'statSync', {+ configurable: true,+ value: (p: fs.PathLike) => {+ if (String(p) === real) {+ throw eacces+ }++ return original(p)+ }+ })++ try {+ assert.throws(+ () => assertExistingPathForOpen(real),+ (error: Error & { code?: string }) => error.code === 'EACCES'+ )+ } finally {+ Object.defineProperty(fs, 'statSync', { configurable: true, value: original })+ }+})++test('the purpose string reaches the user-facing message', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'open-purpose-'))++ assert.throws(+ () => assertExistingPathForOpen(path.join(dir, 'gone.pdf'), 'Open external file'),+ /Open external file failed/+ )+})diff --git a/apps/desktop/electron/preload-external-open.test.ts b/apps/desktop/electron/preload-external-open.test.tsnew file mode 100644index 00000000000..eb538abe488--- /dev/null+++ b/apps/desktop/electron/preload-external-open.test.ts@@ -0,0 +1,53 @@+import { expect, it, vi } from 'vitest'++// Tripwire for the dead-wiring class: main broadcasts `hermes:external-open-+// failed` and the dialog subscribes via `onExternalOpenFailed` — with no+// preload forwarder in between the dialog never fires and the failure is+// silent in every window. The dialog guards with an optional-chain, so+// typecheck can never catch the missing listener; this does.++const host = vi.hoisted(() => ({+ exposeInMainWorld: vi.fn(),+ send: vi.fn<(channel: string, ...args: unknown[]) => void>(),+ sendSync: vi.fn((channel: string): unknown => (channel === 'hermes:feature-flags' ? {} : {})),+ on: vi.fn((channel: string, listener: (...args: unknown[]) => void) => {+ handlers.set(channel, listener)+ }),+ removeListener: vi.fn((channel: string) => {+ handlers.delete(channel)+ })+}))++const handlers = new Map<string, (...args: unknown[]) => void>()++vi.mock('electron', () => ({+ contextBridge: { exposeInMainWorld: host.exposeInMainWorld },+ ipcRenderer: { send: host.send, sendSync: host.sendSync, on: host.on, removeListener: host.removeListener },+ webFrame: {},+ webUtils: {}+}))++it('exposes onExternalOpenFailed and forwards the failure payload', async (): Promise<void> => {+ await import('./preload')+ const registration = host.exposeInMainWorld.mock.calls.find(([name]): boolean => name === 'hermesDesktop')++ expect(registration).toBeDefined()+ const bridge = registration![1] as Record<string, (callback: (payload: unknown) => void) => () => void>++ expect(typeof bridge.onExternalOpenFailed).toBe('function')++ const received: unknown[] = []+ const unsubscribe = bridge.onExternalOpenFailed(payload => received.push(payload))++ const listener = handlers.get('hermes:external-open-failed')++ expect(listener).toBeDefined()+ listener?.({}, { url: 'file:///tmp/gone.html', message: 'Open external file failed: missing.', code: 'missing-file' })++ expect(received).toEqual([+ { url: 'file:///tmp/gone.html', message: 'Open external file failed: missing.', code: 'missing-file' }+ ])++ unsubscribe()+ expect(handlers.has('hermes:external-open-failed')).toBe(false)+})diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 24aa0a19e06..04637b8e7c2 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -561,6 +561,12 @@ contextBridge.exposeInMainWorld('hermesDesktop', {return () => ipcRenderer.removeListener('hermes:notification-activate', listener)},+ onExternalOpenFailed: callback => {+ const listener = (_event, payload) => callback(payload)+ ipcRenderer.on('hermes:external-open-failed', listener)++ return () => ipcRenderer.removeListener('hermes:external-open-failed', listener)+ },onPreviewFileChanged: callback => {const listener = (_event, payload) => callback(payload)ipcRenderer.on('hermes:preview-file-changed', listener)diff --git a/apps/desktop/src/components/external-open-failed-dialog.test.tsx b/apps/desktop/src/components/external-open-failed-dialog.test.tsxindex c1e532c9fb8..513d8ab5b54 100644--- a/apps/desktop/src/components/external-open-failed-dialog.test.tsx+++ b/apps/desktop/src/components/external-open-failed-dialog.test.tsx@@ -25,9 +25,9 @@ function installBridge() {return { onExternalOpenFailed, writeClipboard }}-function fail(listener: unknown, url: string, message?: string) {+function fail(listener: unknown, url: string, message?: string, code?: 'missing-file') {act(() => {- ;(listener as (payload: { url: string; message?: string }) => void)({ url, message })+ ;(listener as (payload: { url: string; message?: string; code?: 'missing-file' }) => void)({ url, message, code })})}@@ -63,6 +63,17 @@ describe('ExternalOpenFailedDialog', () => {})})+ it('shows file-not-found copy for a missing-file failure', () => {+ const { onExternalOpenFailed }: ReturnType<typeof installBridge> = installBridge()+ render(<ExternalOpenFailedDialog />)++ const listener: (payload: { url: string; message?: string; code?: string }) => void =+ onExternalOpenFailed.mock.calls[0][0]++ fail(listener, 'file:///tmp/gone.html', undefined, 'missing-file')+ expect(screen.getByText('File not found')).toBeTruthy()+ })+it('renders nothing in a HUD window', () => {installBridge()windowsMock.isHudWindow.mockReturnValue(true)diff --git a/apps/desktop/src/components/external-open-failed-dialog.tsx b/apps/desktop/src/components/external-open-failed-dialog.tsxindex 4f24d542040..67e38c04c47 100644--- a/apps/desktop/src/components/external-open-failed-dialog.tsx+++ b/apps/desktop/src/components/external-open-failed-dialog.tsx@@ -34,14 +34,17 @@ export function ExternalOpenFailedDialog() {return null}+ // A missing file and a missing URL handler are different failures with+ // different remedies; main tags the payload so copy stays localized.const copy = t.externalOpenFailed+ const header = failure?.code === 'missing-file' ? copy.missing : copyreturn (<Dialog onOpenChange={open => (!open ? setFailure(null) : undefined)} open={Boolean(failure)}><DialogContent className="max-w-[30rem]" showCloseButton={false}><DialogHeader>- <DialogTitle>{copy.title}</DialogTitle>- <DialogDescription>{copy.message}</DialogDescription>+ <DialogTitle>{header.title}</DialogTitle>+ <DialogDescription>{header.message}</DialogDescription></DialogHeader><div className="max-h-40 overflow-auto break-all rounded-md border bg-muted p-3 select-all">{failure?.url}</div><DialogFooter>diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 7011da7f357..c9c85946b97 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -1240,6 +1240,8 @@ export interface DesktopConnectionProbeResult {export interface ExternalOpenFailedPayload {url: stringmessage?: string+ /** Machine-readable failure class; the dialog picks localized copy per code. */+ code?: 'missing-file'}export interface DesktopOauthLoginOptions {diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex ec5796fb42b..cfcfba52481 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -7,7 +7,11 @@ export const en: Translations = {title: 'Couldn’t open this link',message: 'No browser is registered to open this address. Copy the link and open it manually.',copyUrl: 'Copy link',- close: 'Close'+ close: 'Close',+ missing: {+ title: 'File not found',+ message: 'This file does not exist — it may have been deleted or moved, or it lives on another machine.'+ }},// English editorial copy stays in the shipped JSONL; other locales override it.intro: { stock: {}, custom: () => [] },diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 16dd7fb03be..2ea07d5250b 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -64,6 +64,10 @@ export interface Translations {message: stringcopyUrl: stringclose: string+ missing: {+ title: string+ message: string+ }}intro: {stock: Record<string, string[]>