The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): silent missing-file watch probes + tombstoned preview tabs
lesterppo33d768d08639
diff --git a/apps/desktop/electron/hardening.test.ts b/apps/desktop/electron/hardening.test.tsindex b72ceccd5a8..7aae6b7c2fc 100644--- a/apps/desktop/electron/hardening.test.ts+++ b/apps/desktop/electron/hardening.test.ts@@ -16,6 +16,7 @@ import {encryptDesktopSecret,homeRelativeAttachmentCandidates,isMissingFileError,+ missingFileResult,readFileDataUrlForIpc,resolveDirectoryForIpc,resolvePersistedRemoteToken,@@ -1053,10 +1054,12 @@ test('homeRelativeAttachmentCandidates second candidate falls back to basename otest('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)@@ -1064,6 +1067,7 @@ test('isMissingFileError classifies ENOENT/ENOTDIR as expected preview-read outc// 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}@@ -1076,3 +1080,30 @@ test('isMissingFileError classifies ENOENT/ENOTDIR as expected preview-read outcassert.equal(isMissingFileError({ code: 'ENOENT' }), true)assert.equal(isMissingFileError({ code: 'EACCES' }), false)})++test('missingFileResult builds the structured missing-file IPC answer', () => {+ const error = new Error('ENOENT: no such file or directory, open \'/tmp/gone.txt\'')++ ;(error as NodeJS.ErrnoException).code = 'ENOENT'++ assert.deepEqual(missingFileResult('/tmp/gone.txt', error), {+ ok: false,+ error: 'ENOENT',+ message: "ENOENT: no such file or directory, open '/tmp/gone.txt'",+ path: '/tmp/gone.txt'+ })++ // A non-Error throw (e.g. a string from a lower layer) still yields the+ // same shape with a fallback message and code.+ assert.deepEqual(missingFileResult(null, 'boom'), {+ ok: false,+ error: 'ENOENT',+ message: 'File does not exist.',+ path: ''+ })++ // The path echoes what was REQUESTED (not resolved) so the renderer can+ // match it back to the tab that probed it.+ const url = 'file:///tmp/gone.txt'+ assert.equal(missingFileResult(url, { code: 'ENOTDIR' }).path, url)+})diff --git a/apps/desktop/electron/hardening.ts b/apps/desktop/electron/hardening.tsindex 907d869d9b5..cd23f658186 100644--- a/apps/desktop/electron/hardening.ts+++ b/apps/desktop/electron/hardening.ts@@ -613,6 +613,19 @@ function isMissingFileError(error: unknown): boolean {return code === 'ENOENT' || code === 'ENOTDIR'}+/** The structured "file is not on disk" IPC answer built from a caught read+ * error. Shared by every handler that converts expected absence into data+ * (preview text/image reads, attachment reads, file watches) so all of them+ * answer with the same shape. */+function missingFileResult(requestedPath: unknown, error: unknown) {+ return {+ ok: false as const,+ error: (error as NodeJS.ErrnoException).code || 'ENOENT',+ message: error instanceof Error ? error.message : 'File does not exist.',+ path: String(requestedPath ?? '')+ }+}+export {assertExistingPathForOpen,ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,@@ -626,6 +639,7 @@ export {encryptDesktopSecret,homeRelativeAttachmentCandidates,isMissingFileError,+ missingFileResult,readFileDataUrlForIpc,rejectUnsafePathSyntax,resolveDirectoryForIpc,diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex f8affecd05b..8306c12625d 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -290,6 +290,7 @@ import {encryptDesktopSecret as encryptDesktopSecretStrict,homeRelativeAttachmentCandidates,isMissingFileError,+ missingFileResult,readFileDataUrlForIpc,resolvePersistedRemoteToken,resolveReadableFileForIpc,@@ -6065,7 +6066,21 @@ async function filePathFromPreviewUrl(rawUrl) {}async function watchPreviewFile(owner, rawUrl) {- const filePath = await filePathFromPreviewUrl(rawUrl)+ let filePath++ try {+ filePath = await filePathFromPreviewUrl(rawUrl)+ } catch (error) {+ // A restored tab probing a file that is gone is an expected outcome —+ // answer it like the read handlers do instead of rejecting (Electron logs+ // every rejected handler as a stack trace at startup).+ if (isMissingFileError(error)) {+ return missingFileResult(rawUrl, error)+ }++ throw error+ }+const watchDir = path.dirname(filePath)const targetName = path.basename(filePath)const id = crypto.randomBytes(12).toString('base64url')@@ -17598,12 +17613,7 @@ ipcMain.handle('hermes:readFileDataUrl', async (_event, filePath) => {})} 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 ?? '')- }+ return missingFileResult(filePath, error)}throw error@@ -17625,12 +17635,7 @@ ipcMain.handle('hermes:readFileDataUrlForAttach', async (_event, filePath) => {})} 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 ?? '')- }+ return missingFileResult(filePath, error)}throw error@@ -17671,12 +17676,7 @@ ipcMain.handle('hermes:readFileText', async (_event, filePath) => {// 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 ?? '')- }+ return missingFileResult(filePath, error)}throw errordiff --git a/apps/desktop/src/app/chat/right-rail/preview-file.tsx b/apps/desktop/src/app/chat/right-rail/preview-file.tsxindex fbda54ecd42..98ba270485b 100644--- a/apps/desktop/src/app/chat/right-rail/preview-file.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-file.tsx@@ -23,6 +23,7 @@ import { Tip } from '@/components/ui/tooltip'import { translateNow, useI18n } from '@/i18n'import {desktopFileDiff,+ DesktopFileMissingError,desktopFsCacheKey,desktopGitRoot,isReadFileErrorResult,@@ -46,7 +47,7 @@ import {} from '@/lib/preview-markdown-links'import { previewTargetFromMarkdownHref } from '@/lib/preview-targets'import { cn } from '@/lib/utils'-import { openPreview, type PreviewTarget } from '@/store/preview'+import { markPreviewTabMissing, openPreview, type PreviewTarget } from '@/store/preview'import { setPreviewDirty } from '@/store/preview-edit'import { $connection, $currentCwd } from '@/store/session'import { notifyWorkspaceChanged } from '@/store/workspace-events'@@ -168,8 +169,11 @@ interface LocalPreviewState {diff?: stringerror?: stringlanguage?: string- loading: boolean+ /** The read confirmed the file is gone (not a transient failure) — renders+ * the explicit tombstone and prunes the tab from future restores. */+ missing?: booleantext?: string+ loading: booleantruncated?: boolean}@@ -862,9 +866,19 @@ export function LocalFilePreview({}} catch (error) {if (active) {+ // Expected absence (deleted / moved / cleared /tmp): tombstone the+ // tab so the next launch drops it instead of re-probing the dead+ // path, and show the explicit "file no longer exists" state.+ const missing = error instanceof DesktopFileMissingError++ if (missing) {+ markPreviewTabMissing(target.url)+ }+setState({error: error instanceof Error ? error.message : String(error),- loading: false+ loading: false,+ missing})}}@@ -886,7 +900,8 @@ export function LocalFilePreview({reloadKey,selfReload,target.dataUrl,- target.language+ target.language,+ target.url])useEffect(() => {@@ -1104,10 +1119,15 @@ export function LocalFilePreview({return <PageLoader label={t.preview.loading} />}+ if (state.missing) {+ return <PreviewEmptyState body={t.preview.missingBody(target.label)} title={t.preview.missingTitle} tone="warning" />+ }+// A preview that can't load (the file was moved or deleted) is a dead end,// so it carries its own way out rather than leaving it to the tab strip.const closeAction = onClose ? { label: t.common.close, onClick: onClose } : undefined+if (state.error) {return <PreviewEmptyState body={state.error} primaryAction={closeAction} title={t.preview.unavailable} />}diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsxindex f16d0618a77..1c4dc0ad9bf 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx@@ -12,7 +12,7 @@ import { PanelEmpty } from '@/app/overlays/panel'import { isElementInHiddenPane } from '@/components/pane-shell/pane-visibility'import { Tip } from '@/components/ui/tooltip'import { type Translations, useI18n } from '@/i18n'-import { isDesktopFsRemoteMode } from '@/lib/desktop-fs'+import { isDesktopFsRemoteMode, isReadFileErrorResult } from '@/lib/desktop-fs'import { guardGuestPointers } from '@/lib/guest-pointer-guard'import { isLoopbackPreviewUrl, openPreviewTargetInBrowser, remoteHtmlPreviewDocument } from '@/lib/local-preview'import { isRemoteGateway } from '@/lib/media'@@ -1066,6 +1066,13 @@ export function PreviewPane({void window.hermesDesktop.watchPreviewFile(target.url).then(watch => {+ // The file was already gone when the watch was requested (a restored+ // tab probing a deleted path): structured data, not a rejection. The+ // read below surfaces the tombstone; nothing to watch.+ if (isReadFileErrorResult(watch)) {+ return+ }+if (!active) {void window.hermesDesktop?.stopPreviewFileWatch?.(watch.id)diff --git a/apps/desktop/src/contrib/runtime-loader.ts b/apps/desktop/src/contrib/runtime-loader.tsindex f34e6d83bda..a350b6d69fa 100644--- a/apps/desktop/src/contrib/runtime-loader.ts+++ b/apps/desktop/src/contrib/runtime-loader.ts@@ -785,7 +785,11 @@ async function watchDiskPluginFile(desktop: NonNullable<Window['hermesDesktop']>}try {- record.watchId = (await desktop.watchPreviewFile(record.file)).id+ const watch = await desktop.watchPreviewFile(record.file)++ // Structured "folder gone" answer — nothing to watch; the poll still+ // reconciles new folders and edits need a manual reload.+ record.watchId = isReadFileErrorResult(watch) ? null : watch.id} catch {// Unwatchable — the poll still reconciles new folders; edits need a// manual "Reload desktop plugins".diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 6267efbb0b8..e278bcbef99 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -362,7 +362,10 @@ declare global {saveClipboardImage: () => Promise<string>getPathForFile: (file: File) => stringnormalizePreviewTarget: (target: string, baseDir?: string) => Promise<HermesPreviewTarget | null>- watchPreviewFile: (url: string) => Promise<HermesPreviewWatch>+ /** Resolves to `HermesReadFileErrorResult` when the watched file was+ * already gone at call time (a restored tab probing a deleted path) —+ * structured data instead of a rejection, matching the read handlers. */+ watchPreviewFile: (url: string) => Promise<HermesPreviewWatch | HermesReadFileErrorResult>/** Watch a directory for entry churn (disk-plugin door); same watcher* registry + onPreviewFileChanged channel as watchPreviewFile. Optional:* older Electron shells predate it and fall back to the readdir poll. */diff --git a/apps/desktop/src/i18n/ar_artifacts.ts b/apps/desktop/src/i18n/ar_artifacts.tsindex 98ed304a309..acf39b0a5fe 100644--- a/apps/desktop/src/i18n/ar_artifacts.ts+++ b/apps/desktop/src/i18n/ar_artifacts.ts@@ -58,6 +58,8 @@ export const arArtifacts = {closePane: 'إغلاق جزء المعاينة',loading: 'جار تحميل المعاينة',unavailable: 'المعاينة غير متاحة',+ missingTitle: 'الملف لم يعد موجودا',+ missingBody: label => `تم حذف ${label} أو نقله، أو أُفرغ موقعه المؤقت. لن تتم استعادة علامة التبويب هذه عند الإطلاق التالي.`,opening: 'جار الفتح...',hide: 'إخفاء',openPreview: 'فتح المعاينة',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 8b6b514b8e2..c1a7901a9cc 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -4859,6 +4859,8 @@ export const en: Translations = {loading: 'Loading preview',unavailable: 'Preview unavailable',missingTarget: 'That path does not exist on this computer',+ missingTitle: 'File no longer exists',+ missingBody: label => `${label} was deleted, moved, or its temporary location was cleared. This tab will not be restored on the next launch.`,opening: 'Opening...',hide: 'Hide',openPreview: 'Open preview',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 0ece6d564a3..884fedeacf7 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -3580,6 +3580,8 @@ export const ja = defineLocale({closePane: 'プレビューペインを閉じる',loading: 'プレビューを読み込み中',unavailable: 'プレビューは利用できません',+ missingTitle: 'ファイルは存在しません',+ missingBody: label => `${label} は削除・移動されたか、一時的な場所が消去されました。このタブは次回の起動時には復元されません。`,opening: '開いています...',hide: '非表示',openPreview: 'プレビューを開く',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex aa3b04df59e..e22396430e1 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -4110,6 +4110,8 @@ export interface Translations {loading: stringunavailable: stringmissingTarget: string+ missingTitle: string+ missingBody: (label: string) => stringopening: stringhide: stringopenPreview: stringdiff --git a/apps/desktop/src/i18n/zh-hant_artifacts.ts b/apps/desktop/src/i18n/zh-hant_artifacts.tsindex 9a113d19d70..1e61c422a3b 100644--- a/apps/desktop/src/i18n/zh-hant_artifacts.ts+++ b/apps/desktop/src/i18n/zh-hant_artifacts.ts@@ -61,6 +61,8 @@ export const zhHantArtifacts = {closePane: '關閉預覽窗格',loading: '正在載入預覽',unavailable: '預覽不可用',+ missingTitle: '檔案已不存在',+ missingBody: label => `${label} 已被刪除、移動,或其暫存位置已被清除。此分頁不會在下一次啟動時還原。`,opening: '開啟中...',hide: '隱藏',openPreview: '開啟預覽',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 2ee20a25730..f15efba3ac9 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -4556,6 +4556,8 @@ export const zh = defineLocale({closePane: '关闭预览面板',loading: '正在加载预览',unavailable: '预览不可用',+ missingTitle: '文件已不存在',+ missingBody: label => `${label} 已被删除、移动,或其临时位置已被清除。此标签页不会在下次启动时恢复。`,opening: '正在打开...',hide: '隐藏',openPreview: '打开预览',diff --git a/apps/desktop/src/lib/desktop-fs.test.ts b/apps/desktop/src/lib/desktop-fs.test.tsindex 2314390ee7f..edccb471591 100644--- a/apps/desktop/src/lib/desktop-fs.test.ts+++ b/apps/desktop/src/lib/desktop-fs.test.ts@@ -7,6 +7,7 @@ import {createRemoteDir,desktopDefaultCwd,desktopFileDiff,+ DesktopFileMissingError,desktopFsCacheKey,desktopGitRoot,readDesktopDir,@@ -360,5 +361,16 @@ describe('desktop filesystem facade', () => {})await expect(readDesktopFileDataUrl('/gone.png')).rejects.toThrow('Text preview failed: file does not exist.')++ // The rejection is the typed missing-file error, so callers can tell+ // expected absence apart from real failures without string matching.+ readFileText.mockResolvedValueOnce({+ ok: false,+ error: 'ENOENT',+ message: 'gone',+ path: '/gone.txt'+ })++ await expect(readDesktopFileText('/gone.txt')).rejects.toBeInstanceOf(DesktopFileMissingError)})})diff --git a/apps/desktop/src/lib/desktop-fs.ts b/apps/desktop/src/lib/desktop-fs.tsindex a4882dc4f9b..82620029f7c 100644--- a/apps/desktop/src/lib/desktop-fs.ts+++ b/apps/desktop/src/lib/desktop-fs.ts@@ -84,7 +84,21 @@ export function isReadFileErrorResult(value: unknown): value is HermesReadFileEr}function throwForReadErrorResult(result: HermesReadFileErrorResult): never {- throw new Error(result.message || `File read failed: ${result.error}`)+ throw new DesktopFileMissingError(result)+}++/** Thrown by the facade when the main process answered that the file is simply+ * not on disk (the structured `{ ok:false }` result). Callers that need to+ * tell expected absence apart from real failures check `instanceof`; everyone+ * else sees an ordinary error whose message matches the old rejection. */+export class DesktopFileMissingError extends Error {+ readonly code: string++ constructor(result: HermesReadFileErrorResult) {+ super(result.message || `File read failed: ${result.error}`)+ this.name = 'DesktopFileMissingError'+ this.code = result.error+ }}export async function readDesktopDir(path: string): Promise<HermesReadDirResult> {diff --git a/apps/desktop/src/store/preview.test.ts b/apps/desktop/src/store/preview.test.tsindex ab2289ab98d..6cfa1a99887 100644--- a/apps/desktop/src/store/preview.test.ts+++ b/apps/desktop/src/store/preview.test.ts@@ -14,6 +14,8 @@ import {closeRightRail,closeRightRailTab,commitBrowserTabLocation,+ decodePreviewTabs,+ markPreviewTabMissing,newBrowserTab,noteBrowserPage,openPreview,@@ -348,4 +350,40 @@ describe('preview store', () => {// removed rather than stored as an empty list (matching the tiles store).expect(window.localStorage.getItem('hermes.desktop.previewTabs.v2')).toBeNull()})++ it('tombstones a confirmed-missing tab in place without closing it', () => {+ openPreview(fileTarget('/work/demo.html'))+ openPreview(fileTarget('/work/keep.html'))+ const demoId = 'file:file:///work/demo.html'++ markPreviewTabMissing(demoId)++ const tabs = $previewTabs.get()++ expect(tabs).toHaveLength(2)+ expect(tabs.find(tab => tab.id === demoId)?.target.missing).toBe(true)+ expect(tabs.find(tab => tab.id !== demoId)?.target.missing).toBeFalsy()++ // Idempotent: a second tombstone must not rewrite the list.+ const before = JSON.stringify($previewTabs.get())+ markPreviewTabMissing(demoId)+ expect(JSON.stringify($previewTabs.get())).toBe(before)+ })++ it('ignores a tombstone for a tab that is not open', () => {+ markPreviewTabMissing('file:file:///nowhere.html')++ expect($previewTabs.get()).toHaveLength(0)+ })++ it('drops tombstoned file tabs at restore so dead paths are not re-probed next boot', () => {+ const raw = JSON.stringify([+ { id: 'file:file:///work/gone.html', target: { ...fileTarget('/work/gone.html'), missing: true } },+ { id: 'file:file:///work/alive.html', target: fileTarget('/work/alive.html') }+ ])++ const restored = decodePreviewTabs(raw)++ expect(restored.map(tab => tab.target.path)).toEqual(['/work/alive.html'])+ })})diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.tsindex 5377eb529a6..4d8f6bc9627 100644--- a/apps/desktop/src/store/preview.ts+++ b/apps/desktop/src/store/preview.ts@@ -53,6 +53,10 @@ export interface PreviewTarget {* them for the native folder action / not-found reporting instead. */previewKind?: 'binary' | 'directory' | 'html' | 'image' | 'missing' | 'pdf' | 'text'renderMode?: PreviewRenderMode+ /** Tombstone set when a read/watch confirmed the file is gone. The tab stays+ * open for the session showing an explicit "file no longer exists" state,+ * but is dropped at the next restore so day-2 boots stop re-probing it. */+ missing?: booleansource: string/** Runtime-only target that cannot be restored from persisted state. */transient?: boolean@@ -131,11 +135,15 @@ export function decodePreviewTabs(raw: string): PreviewTab[] {}function parseTabList(parsed: unknown): PreviewTab[] {- return (Array.isArray(parsed) ? parsed.filter(isPreviewTab) : []).map(tab =>- isPdfFileTarget(tab.target) && tab.target.previewKind === 'binary'- ? { ...tab, target: { ...tab.target, previewKind: 'pdf' as const } }- : tab- )+ return (Array.isArray(parsed) ? parsed.filter(isPreviewTab) : [])+ .map(tab =>+ isPdfFileTarget(tab.target) && tab.target.previewKind === 'binary'+ ? { ...tab, target: { ...tab.target, previewKind: 'pdf' as const } }+ : tab+ )+ // Drop tombstoned file tabs (a previous session confirmed the file is+ // gone). Keeping them would re-probe a known-dead path on every boot.+ .filter(tab => !tab.target.missing)}/** The tabs a profile's rail is showing, keyed by profile. */@@ -628,6 +636,23 @@ export function openPreview(target: PreviewTarget) {const blankPage = (): PreviewTarget => ({ kind: 'url', label: 'Browser', source: 'about:blank', url: 'about:blank' })+/** Tombstone the tab for a confirmed-missing file: keep it open this session+ * (the pane shows "file no longer exists"), but flag the target so the next+ * restore drops it instead of re-probing the dead path on every boot. */+export function markPreviewTabMissing(targetUrl: string) {+ const current = $previewTabs.get()+ const id = targetUrl.startsWith('file:') ? targetUrl : `file:${targetUrl}`+ const index = current.findIndex(tab => tab.id === id)++ if (index === -1 || current[index]!.target.missing) {+ return+ }++ $previewTabs.set(+ current.map((tab, i) => (i === index ? { ...tab, target: { ...tab.target, missing: true } } : tab))+ )+}+/** Show the Browser — the surface, not a page. Keeps whatever it was last* showing so the hotkey re-fronts your page instead of wiping it; with no* browser open it lands on `about:blank`, where the pane's empty state