The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): return structured error for missing-file preview reads
lesterppo2c9861f65f24
diff --git a/apps/desktop/electron/hardening.test.ts b/apps/desktop/electron/hardening.test.tsindex 5c1d9d9add0..b72ceccd5a8 100644--- a/apps/desktop/electron/hardening.test.ts+++ b/apps/desktop/electron/hardening.test.ts@@ -15,6 +15,7 @@ import {enableBasicPasswordStoreEncryption,encryptDesktopSecret,homeRelativeAttachmentCandidates,+ isMissingFileError,readFileDataUrlForIpc,resolveDirectoryForIpc,resolvePersistedRemoteToken,@@ -1049,3 +1050,29 @@ test('homeRelativeAttachmentCandidates second candidate falls back to basename opath.join('/Users/alice/.hermes', 'attachments', 'foo.xlsx')])})++test('isMissingFileError classifies ENOENT/ENOTDIR as expected preview-read outcomes', () => {+ const missing = new Error('Text preview failed: file does not exist.')+ ;(missing as NodeJS.ErrnoException).code = 'ENOENT'+ assert.equal(isMissingFileError(missing), true)++ const missingDir = new Error('Text preview failed: file does not exist.')+ ;(missingDir as NodeJS.ErrnoException).code = 'ENOTDIR'+ assert.equal(isMissingFileError(missingDir), true)++ // Everything else — permission, size, invalid path — is a real error and+ // must keep rejecting so the renderer sees it as a genuine failure.+ for (const code of ['EACCES', 'EFBIG', 'EISDIR', 'invalid-path', 'sensitive-file', undefined]) {+ const error = new Error('some read failure')+ if (code !== undefined) {+ ;(error as NodeJS.ErrnoException).code = code+ }++ assert.equal(isMissingFileError(error), false, `code ${String(code)} must not be treated as missing-file`)+ }++ assert.equal(isMissingFileError(null), false)+ assert.equal(isMissingFileError('ENOENT'), false)+ assert.equal(isMissingFileError({ code: 'ENOENT' }), true)+ assert.equal(isMissingFileError({ code: 'EACCES' }), false)+})diff --git a/apps/desktop/electron/hardening.ts b/apps/desktop/electron/hardening.tsindex 0d19ac8b356..907d869d9b5 100644--- a/apps/desktop/electron/hardening.ts+++ b/apps/desktop/electron/hardening.ts@@ -595,6 +595,24 @@ async function readFileDataUrlForIpc(return `data:${options.mimeType};base64,${data.toString('base64')}`}+/** True when a read failed because the file (or its parent) is not on disk.+ * Preview reads routinely race a file's lifecycle — a restored preview tab or+ * a transcript reference can point at something that was deleted, moved, or+ * lived in a cleared /tmp. Those are expected outcomes, not crashes: IPC+ * handlers should answer them with a structured error result instead of+ * rejecting (Electron logs every rejected handler as a stack trace even when+ * the renderer handles the rejection gracefully). Everything else still+ * throws as before. */+function isMissingFileError(error: unknown): boolean {+ if (!error || typeof error !== 'object') {+ return false+ }++ const code = (error as { code?: unknown }).code++ return code === 'ENOENT' || code === 'ENOTDIR'+}+export {assertExistingPathForOpen,ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,@@ -607,6 +625,7 @@ export {enableBasicPasswordStoreEncryption,encryptDesktopSecret,homeRelativeAttachmentCandidates,+ isMissingFileError,readFileDataUrlForIpc,rejectUnsafePathSyntax,resolveDirectoryForIpc,diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex ab7eccec0e5..f8affecd05b 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -289,6 +289,7 @@ import {enableBasicPasswordStoreEncryption,encryptDesktopSecret as encryptDesktopSecretStrict,homeRelativeAttachmentCandidates,+ isMissingFileError,readFileDataUrlForIpc,resolvePersistedRemoteToken,resolveReadableFileForIpc,@@ -17589,11 +17590,24 @@ ipcMain.handle('hermes:readFileDataUrl', async (_event, filePath) => {// Windows host bridge them to a UNC/drive form, same as directory reads.const bridgedPath = resolveIpcFileReadPath(filePath)- return readFileDataUrlForIpc(bridgedPath, {- maxBytes: dataUrlReadMaxBytesFromMb(dataUrlReadMaxMb),- mimeType: mimeTypeForPath(resolveRequestedPathForIpc(bridgedPath, { purpose: 'File preview' })),- purpose: 'File preview'- })+ try {+ return await readFileDataUrlForIpc(bridgedPath, {+ maxBytes: dataUrlReadMaxBytesFromMb(dataUrlReadMaxMb),+ mimeType: mimeTypeForPath(resolveRequestedPathForIpc(bridgedPath, { purpose: 'File preview' })),+ purpose: 'File preview'+ })+ } catch (error) {+ if (isMissingFileError(error)) {+ return {+ ok: false as const,+ error: (error as NodeJS.ErrnoException).code || 'ENOENT',+ message: error instanceof Error ? error.message : 'File does not exist.',+ path: String(filePath ?? '')+ }+ }++ throw error+ }})// Remote attachment transfer is independent of the preview / Settings path.@@ -17603,38 +17617,69 @@ ipcMain.handle('hermes:readFileDataUrl', async (_event, filePath) => {ipcMain.handle('hermes:readFileDataUrlForAttach', async (_event, filePath) => {const bridgedPath = resolveIpcFileReadPath(filePath)- return readFileDataUrlForIpc(bridgedPath, {- maxBytes: ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,- mimeType: mimeTypeForPath(resolveRequestedPathForIpc(bridgedPath, { purpose: 'Attachment upload' })),- purpose: 'Attachment upload'- })+ try {+ return await readFileDataUrlForIpc(bridgedPath, {+ maxBytes: ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,+ mimeType: mimeTypeForPath(resolveRequestedPathForIpc(bridgedPath, { purpose: 'Attachment upload' })),+ purpose: 'Attachment upload'+ })+ } catch (error) {+ if (isMissingFileError(error)) {+ return {+ ok: false as const,+ error: (error as NodeJS.ErrnoException).code || 'ENOENT',+ message: error instanceof Error ? error.message : 'File does not exist.',+ path: String(filePath ?? '')+ }+ }++ throw error+ }})ipcMain.handle('hermes:readFileText', async (_event, filePath) => {- const { resolvedPath, stat } = await resolveReadableFileForIpc(resolveIpcFileReadPath(filePath), {- maxBytes: TEXT_PREVIEW_SOURCE_MAX_BYTES,- purpose: 'Text preview'- })+ try {+ const { resolvedPath, stat } = await resolveReadableFileForIpc(resolveIpcFileReadPath(filePath), {+ maxBytes: TEXT_PREVIEW_SOURCE_MAX_BYTES,+ purpose: 'Text preview'+ })- const ext = path.extname(resolvedPath).toLowerCase()- const handle = await fs.promises.open(resolvedPath, 'r')- const bytesToRead = Math.min(stat.size, TEXT_PREVIEW_MAX_BYTES)+ const ext = path.extname(resolvedPath).toLowerCase()+ const handle = await fs.promises.open(resolvedPath, 'r')+ const bytesToRead = Math.min(stat.size, TEXT_PREVIEW_MAX_BYTES)- try {- const buffer = Buffer.alloc(bytesToRead)- const { bytesRead } = await handle.read(buffer, 0, bytesToRead, 0)+ try {+ const buffer = Buffer.alloc(bytesToRead)+ const { bytesRead } = await handle.read(buffer, 0, bytesToRead, 0)- return {- binary: looksBinary(buffer.subarray(0, Math.min(bytesRead, 4096))),- byteSize: stat.size,- language: PREVIEW_LANGUAGE_BY_EXT[ext] || 'text',- mimeType: mimeTypeForPath(resolvedPath),- path: resolvedPath,- text: buffer.subarray(0, bytesRead).toString('utf8'),- truncated: stat.size > TEXT_PREVIEW_MAX_BYTES+ return {+ binary: looksBinary(buffer.subarray(0, Math.min(bytesRead, 4096))),+ byteSize: stat.size,+ language: PREVIEW_LANGUAGE_BY_EXT[ext] || 'text',+ mimeType: mimeTypeForPath(resolvedPath),+ path: resolvedPath,+ text: buffer.subarray(0, bytesRead).toString('utf8'),+ truncated: stat.size > TEXT_PREVIEW_MAX_BYTES+ }+ } finally {+ await handle.close()}- } finally {- await handle.close()+ } catch (error) {+ // A preview probing a file that is gone (deleted, moved, or cleared from+ // /tmp since the tab/transcript reference was written) is an expected+ // outcome. Return a structured error instead of rejecting — Electron logs+ // every rejected handler with a stack trace even though the renderer shows+ // "preview unavailable" either way.+ if (isMissingFileError(error)) {+ return {+ ok: false as const,+ error: (error as NodeJS.ErrnoException).code || 'ENOENT',+ message: error instanceof Error ? error.message : 'File does not exist.',+ path: String(filePath ?? '')+ }+ }++ throw error}})diff --git a/apps/desktop/src/app/chat/right-rail/preview-file.tsx b/apps/desktop/src/app/chat/right-rail/preview-file.tsxindex c1fd8689a2f..fbda54ecd42 100644--- a/apps/desktop/src/app/chat/right-rail/preview-file.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-file.tsx@@ -25,6 +25,7 @@ import {desktopFileDiff,desktopFsCacheKey,desktopGitRoot,+ isReadFileErrorResult,readDesktopFileDataUrl,readDesktopFileText,writeDesktopFileText@@ -289,6 +290,11 @@ async function readTextPreview(filePath: string) {// Back-compat for a running Electron process whose preload hasn't been// restarted since readFileText was added. readFileDataUrl already existed.const dataUrl = await window.hermesDesktop.readFileDataUrl(filePath)++ if (isReadFileErrorResult(dataUrl)) {+ throw new Error(dataUrl.message || `File read failed: ${dataUrl.error}`)+ }+const [, metadata = '', data = ''] = dataUrl.match(/^data:([^,]*),(.*)$/) || []const base64 = metadata.includes(';base64')const mimeType = metadata.replace(/;base64$/, '') || undefineddiff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.tsindex 788a348a41c..a6b97ee7970 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts@@ -3,6 +3,7 @@ import { JsonRpcGatewayError } from '@hermes/shared'import { translateNow, type Translations } from '@/i18n'import type { ChatMessage } from '@/lib/chat-messages'+import { isReadFileErrorResult } from '@/lib/desktop-fs'import { type CommandsCatalogLike, filterDesktopCommandsCatalog } from '@/lib/desktop-slash-commands'import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'import type { ComposerAttachment } from '@/store/composer'@@ -430,6 +431,11 @@ export async function readImageForRemoteAttach(filePath: string): Promise<{ contentBase64: string; filename: string } | null> {const dataUrl = await window.hermesDesktop?.readFileDataUrl(filePath)++ if (isReadFileErrorResult(dataUrl)) {+ return null+ }+const contentBase64 = dataUrl ? base64FromDataUrl(dataUrl) : ''return contentBase64 ? { contentBase64, filename: imageFilenameFromPath(filePath) } : null@@ -448,6 +454,10 @@ export async function readFileDataUrlForAttach(filePath: string): Promise<stringconst dataUrl = await reader(filePath)+ if (isReadFileErrorResult(dataUrl)) {+ return null+ }+return dataUrl || null}diff --git a/apps/desktop/src/components/assistant-ui/directive-text.tsx b/apps/desktop/src/components/assistant-ui/directive-text.tsxindex 3b2ac91d614..3af40619b81 100644--- a/apps/desktop/src/components/assistant-ui/directive-text.tsx+++ b/apps/desktop/src/components/assistant-ui/directive-text.tsx@@ -8,6 +8,7 @@ import { Fragment, useEffect, useMemo, useState } from 'react'import { isPastedContentPath } from '@/app/chat/composer/large-paste'import { ZoomableImage } from '@/components/chat/zoomable-image'import { type I18nContextValue, useI18n } from '@/i18n'+import { isReadFileErrorResult } from '@/lib/desktop-fs'import { extractEmbeddedImages } from '@/lib/embedded-images'import { ExternalLink, openLink } from '@/lib/external-link'import { triggerHaptic } from '@/lib/haptics'@@ -432,7 +433,11 @@ const DirectiveImage: FC<{ id: string; label: string }> = ({ id, label }) => {void Promise.resolve(load).then(async url => {- if (!alive || !url) {+ if (!alive) {+ return+ }++ if (isReadFileErrorResult(url) || !url) {return}diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsxindex 0acf6e97564..16cf13559a8 100644--- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx+++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx@@ -5,7 +5,7 @@ import { requestComposerSubmit } from '@/app/chat/composer/focus'import { useSessionView } from '@/app/chat/session-view'import { PreviewAttachment } from '@/components/chat/preview-attachment'import { useThemeEpoch } from '@/hooks/use-theme-epoch'-import { readDesktopFileText } from '@/lib/desktop-fs'+import { isReadFileErrorResult, readDesktopFileText } from '@/lib/desktop-fs'import { localPreviewTarget } from '@/lib/local-preview'/**@@ -405,7 +405,12 @@ function InlineHtmlFrame({return}- if (!result || result.binary || !result.text) {+ if (!result || isReadFileErrorResult(result)) {+ setFailed(true)+ return+ }++ if (result.binary || !result.text) {setFailed(true)} else {setDoc(result.text)diff --git a/apps/desktop/src/contrib/runtime-loader.ts b/apps/desktop/src/contrib/runtime-loader.tsindex a72c12d610f..f34e6d83bda 100644--- a/apps/desktop/src/contrib/runtime-loader.ts+++ b/apps/desktop/src/contrib/runtime-loader.ts@@ -34,6 +34,7 @@import { atom } from 'nanostores'+import { isReadFileErrorResult } from '@/lib/desktop-fs'import { installPluginSdk, sdkImportMap } from '@/sdk/runtime'import { notifyError } from '@/store/notifications'@@ -669,6 +670,10 @@ async function readPluginSourceText(file: string): Promise<string> {const result = await desktop.readFileText(file)+ if (isReadFileErrorResult(result)) {+ throw new Error(result.message || `Plugin read failed: ${result.error}`)+ }+if (result.truncated) {throw new PluginSourceOversizeError("plugin.js exceeds this shell's 512 KiB read limit — update Hermes Desktop to load larger plugins"diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex dda32a9d1b0..6267efbb0b8 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -301,15 +301,15 @@ declare global {title: string} | null} | null>- readFileDataUrl: (filePath: string) => Promise<string>+ readFileDataUrl: (filePath: string) => Promise<string | HermesReadFileErrorResult>/** Remote non-image attach: higher dedicated cap than preview/Settings default. */- readFileDataUrlForAttach?: (filePath: string) => Promise<string>+ readFileDataUrlForAttach?: (filePath: string) => Promise<string | HermesReadFileErrorResult>/** Settings → Chat: max size for local files loaded as data URLs (attach/preview). */dataUrlReadMax?: {get: () => Promise<{ defaultMaxMb: number; maxBytes: number; maxMb: number }>set: (maxMb: number) => Promise<{ defaultMaxMb: number; maxBytes: number; maxMb: number }>}- readFileText: (filePath: string) => Promise<HermesReadFileTextResult>+ readFileText: (filePath: string) => Promise<HermesReadFileTextResult | HermesReadFileErrorResult>/** Full-source read for runtime desktop plugins (readFileText truncates* at the 512 KiB preview cap). Absent on older shells — callers fall* back to readFileText and must reject a `truncated` result. */@@ -1519,6 +1519,19 @@ export interface HermesReadFileTextResult {truncated?: boolean}+/** Structured failure for a preview read. The main process returns this (it+ * does NOT reject the IPC call) when the file is simply not on disk — a+ * restored preview tab or transcript reference pointing at a deleted/moved+ * file, or a path under a cleared /tmp, is an expected outcome that the+ * renderer already displays as "preview unavailable". Other errors still+ * reject as before. */+export interface HermesReadFileErrorResult {+ ok: false+ error: string+ message: string+ path?: string+}+export interface HermesPreviewWatch {id: stringpath: stringdiff --git a/apps/desktop/src/lib/desktop-fs.test.ts b/apps/desktop/src/lib/desktop-fs.test.tsindex 24e38a033bc..2314390ee7f 100644--- a/apps/desktop/src/lib/desktop-fs.test.ts+++ b/apps/desktop/src/lib/desktop-fs.test.ts@@ -18,8 +18,8 @@ import {} from './desktop-fs'const readDir = vi.fn(async () => ({ entries: [{ name: 'local', path: '/local', isDirectory: true }] }))-const readFileText = vi.fn(async () => ({ path: '/local/file.txt', text: 'local', byteSize: 5 }))-const readFileDataUrl = vi.fn(async () => 'data:text/plain;base64,bG9jYWw=')+const readFileText = vi.fn(async (): Promise<unknown> => ({ path: '/local/file.txt', text: 'local', byteSize: 5 }))+const readFileDataUrl = vi.fn(async (): Promise<unknown> => 'data:text/plain;base64,bG9jYWw=')const gitRoot = vi.fn(async () => '/local')const selectPaths = vi.fn(async () => ['/local'])@@ -336,4 +336,29 @@ describe('desktop filesystem facade', () => {expect(remoteSelect).toHaveBeenCalledWith({ directories: true, multiple: false })expect(selectPaths).not.toHaveBeenCalled()})++ it('surfaces a missing-file bridge result as a thrown error (not an object)', async () => {+ $connection.set({ mode: 'local' } as never)++ // The main process answers "file not on disk" with a structured result+ // instead of rejecting the IPC call (so a restored preview tab pointing at+ // a deleted file doesn't spam Electron's console). The facade converts it+ // back into a rejection so every existing try/catch caller keeps working.+ readFileText.mockResolvedValueOnce({+ ok: false,+ error: 'ENOENT',+ message: 'Text preview failed: file does not exist.',+ path: '/gone.txt'+ })++ await expect(readDesktopFileText('/gone.txt')).rejects.toThrow('Text preview failed: file does not exist.')++ readFileDataUrl.mockResolvedValueOnce({+ ok: false,+ error: 'ENOENT',+ message: 'Text preview failed: file does not exist.'+ })++ await expect(readDesktopFileDataUrl('/gone.png')).rejects.toThrow('Text preview failed: file does not exist.')+ })})diff --git a/apps/desktop/src/lib/desktop-fs.ts b/apps/desktop/src/lib/desktop-fs.tsindex 166054d738a..a4882dc4f9b 100644--- a/apps/desktop/src/lib/desktop-fs.ts+++ b/apps/desktop/src/lib/desktop-fs.ts@@ -2,6 +2,7 @@ import { hermesApi } from '@/api/client'import type {HermesConnection,HermesReadDirResult,+ HermesReadFileErrorResult,HermesReadFileTextResult,HermesSelectPathsOptions} from '@/global'@@ -72,6 +73,20 @@ function remoteFsApi<T>(path: string, body?: Record<string, unknown>): Promise<T)}+/** True when a bridge read returned the main process's structured "file is not+ * on disk" answer (the main process returns this instead of rejecting, so a+ * restored preview tab or transcript reference to a deleted/moved file does+ * not spam Electron's console with a stack trace per probe). Callers that+ * already try/catch their read get the same behavior as a rejection: throw+ * with the original message. */+export function isReadFileErrorResult(value: unknown): value is HermesReadFileErrorResult {+ return !!value && typeof value === 'object' && (value as { ok?: unknown }).ok === false+}++function throwForReadErrorResult(result: HermesReadFileErrorResult): never {+ throw new Error(result.message || `File read failed: ${result.error}`)+}+export async function readDesktopDir(path: string): Promise<HermesReadDirResult> {if (!isDesktopFsRemoteMode()) {return bridge().readDir(path)@@ -82,7 +97,13 @@ export async function readDesktopDir(path: string): Promise<HermesReadDirResult>export async function readDesktopFileText(path: string): Promise<HermesReadFileTextResult> {if (!isDesktopFsRemoteMode()) {- return bridge().readFileText(path)+ const result = await bridge().readFileText(path)++ if (isReadFileErrorResult(result)) {+ throwForReadErrorResult(result)+ }++ return result}return remoteFsApi<HermesReadFileTextResult>(fsPath('read-text', path))@@ -118,7 +139,13 @@ export async function createRemoteDir(path: string): Promise<string> {export async function readDesktopFileDataUrl(path: string): Promise<string> {if (!isDesktopFsRemoteMode()) {- return bridge().readFileDataUrl(path)+ const result = await bridge().readFileDataUrl(path)++ if (isReadFileErrorResult(result)) {+ throwForReadErrorResult(result)+ }++ return result}const result = await remoteFsApi<string | { dataUrl?: string }>(fsPath('read-data-url', path))@@ -135,9 +162,13 @@ export async function readDesktopFileDataUrlLocalFirst(path: string): Promise<sttry {const local = await window.hermesDesktop?.readFileDataUrl?.(path)- if (local) {+ if (local && !isReadFileErrorResult(local)) {return local}++ // A structured missing-file result from local is the same outcome as a+ // rejection: fall through to the remote fallback below (or throw in local+ // mode via readDesktopFileDataUrl's own guard).} catch (error) {if (!isDesktopFsRemoteMode()) {throw errordiff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.tsindex f54f0708b21..288c56f4670 100644--- a/apps/desktop/src/lib/media.ts+++ b/apps/desktop/src/lib/media.ts@@ -3,7 +3,7 @@ import { LOCAL_CONNECTION_ID } from '@hermes/shared'import { capabilityScoped, hermesApi, type OwnerScope } from '@/api/client'import type { HermesConnection } from '@/global'import { translateNow } from '@/i18n'-import { desktopFsCacheKey, readDesktopFileDataUrl } from '@/lib/desktop-fs'+import { desktopFsCacheKey, isReadFileErrorResult, readDesktopFileDataUrl } from '@/lib/desktop-fs'import { LruCache } from '@/lib/lru-cache'import { capitalize } from '@/lib/text'import { notify, notifyError } from '@/store/notifications'@@ -118,7 +118,13 @@ export async function resolveMediaDisplaySrc(path: string, owner?: OwnerScope):// Keep the native reader and its configured size cap; the backend preview// endpoint has a separate fixed limit.if (owner?.connectionId === LOCAL_CONNECTION_ID && window.hermesDesktop?.readFileDataUrl) {- return window.hermesDesktop.readFileDataUrl(filePathFromMediaPath(path))+ const dataUrl = await window.hermesDesktop.readFileDataUrl(filePathFromMediaPath(path))++ if (isReadFileErrorResult(dataUrl)) {+ throw new Error(dataUrl.message || `Media file read failed: ${dataUrl.error}`)+ }++ return dataUrl}// A tile can belong to a different gateway than the foreground. Pin both@@ -141,7 +147,13 @@ export async function resolveMediaDisplaySrc(path: string, owner?: OwnerScope):return mediaExternalUrl(path)}- return window.hermesDesktop.readFileDataUrl(filePathFromMediaPath(path))+ const dataUrl = await window.hermesDesktop.readFileDataUrl(filePathFromMediaPath(path))++ if (isReadFileErrorResult(dataUrl)) {+ throw new Error(dataUrl.message || `Media file read failed: ${dataUrl.error}`)+ }++ return dataUrl}export interface MediaImageDimensions {