Skip to content

The agent that grows with you

fix(desktop): branch transcript path cards on local filesystem state

Brooklyn Nicholson1fb569aa238c
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 6c1d7f349cb..855f9f3d4c0 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -6131,16 +6131,36 @@ async function previewFileTarget(rawTarget, baseDir) {
}
}
+ // A directory is not a preview (#101683). Overloading it as
+ // `<dir>/index.html` made a directory without one classify as missing, and
+ // the renderer's blind fallback then fabricated a broken text-preview tab.
+ // Answer with a typed non-previewable result so the card can offer the
+ // native folder action, and a typed `missing` result so a dead link reports
+ // instead of previewing.
if (directoryExists(resolved)) {
- resolved = path.join(resolved, 'index.html')
+ return {
+ kind: 'file',
+ label: path.basename(resolved) || resolved,
+ path: resolved,
+ previewKind: 'directory',
+ source: raw,
+ url: pathToFileURL(resolved).toString()
+ }
}
- const ext = path.extname(resolved).toLowerCase()
-
if (!fileExists(resolved)) {
- return null
+ return {
+ kind: 'file',
+ label: path.basename(resolved) || raw,
+ path: resolved,
+ previewKind: 'missing',
+ source: raw,
+ url: pathToFileURL(resolved).toString()
+ }
}
+ const ext = path.extname(resolved).toLowerCase()
+
;({ resolvedPath: resolved } = await resolveReadableFileForIpc(resolved, { purpose: 'Preview target' }))
const mimeType = mimeTypeForPath(resolved)
diff --git a/apps/desktop/src/components/chat/preview-attachment.test.tsx b/apps/desktop/src/components/chat/preview-attachment.test.tsx
new file mode 100644
index 00000000000..e5ccedc0cd6
--- /dev/null
+++ b/apps/desktop/src/components/chat/preview-attachment.test.tsx
@@ -0,0 +1,158 @@
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { atom } from 'nanostores'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { PreviewAttachment } from '@/components/chat/preview-attachment'
+import type * as PreviewStore from '@/store/preview'
+
+// #101683 regression coverage: the delivered-file card must branch on the
+// target's LOCAL filesystem state — an existing directory opens natively with
+// no Download and no broken preview, an existing local file reveals instead of
+// re-downloading, a remote-backend file keeps the gateway-backed actions, and a
+// missing path reports instead of fabricating a preview tab.
+
+const { isDesktopFsRemoteMode, notifyError, openPreview } = vi.hoisted(() => ({
+ isDesktopFsRemoteMode: vi.fn(() => false),
+ notifyError: vi.fn(),
+ openPreview: vi.fn()
+}))
+
+vi.mock('@/lib/desktop-fs', () => ({
+ isDesktopFsRemoteMode,
+ readDesktopDir: vi.fn(),
+ readDesktopFileDataUrl: vi.fn(),
+ readDesktopFileText: vi.fn()
+}))
+
+vi.mock('@/store/notifications', () => ({ notifyError }))
+
+vi.mock('@/store/preview', async importOriginal => ({
+ ...(await importOriginal<typeof PreviewStore>()),
+ $previewTabSources: atom<string[]>([]),
+ closePreviewForSource: vi.fn(),
+ openPreview
+}))
+
+const previousDesktop = window.hermesDesktop
+
+function fileTarget(path: string, previewKind = 'text') {
+ return {
+ kind: 'file' as const,
+ label: path.split('/').filter(Boolean).pop() || path,
+ path,
+ previewKind,
+ source: `file://${path}`,
+ url: `file://${path}`
+ }
+}
+
+function mountDesktopStub(normalizePreviewTarget: (target: string, baseDir?: string) => unknown) {
+ const openDir = vi.fn(async () => ({ ok: true }))
+ const revealPath = vi.fn(async () => true)
+
+ window.hermesDesktop = {
+ normalizePreviewTarget: vi.fn(normalizePreviewTarget),
+ openDir,
+ revealPath
+ } as never
+
+ return { openDir, revealPath }
+}
+
+async function buttons() {
+ return (await screen.findAllByRole('button')).map(button => button.textContent)
+}
+
+describe('PreviewAttachment local target classification (#101683)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ isDesktopFsRemoteMode.mockReturnValue(false)
+ })
+
+ afterEach(() => {
+ cleanup()
+ window.hermesDesktop = previousDesktop
+ })
+
+ it('opens a Windows file:///C:/... directory link natively with no Download or preview action', async () => {
+ const { openDir, revealPath } = mountDesktopStub(() =>
+ fileTarget('C:/Users/E/reports/historical', 'directory')
+ )
+
+ render(<PreviewAttachment target="file:///C:/Users/E/reports/historical" />)
+
+ const open = await screen.findByRole('button', { name: 'Open containing folder' })
+ expect(await buttons()).toEqual(['Open containing folder'])
+
+ await act(async () => {
+ fireEvent.click(open)
+ })
+
+ expect(openDir).toHaveBeenCalledWith('C:/Users/E/reports/historical')
+ expect(revealPath).not.toHaveBeenCalled()
+ expect(openPreview).not.toHaveBeenCalled()
+ })
+
+ it('opens a POSIX directory link through the native folder action', async () => {
+ const { openDir } = mountDesktopStub(() => fileTarget('/work/reports/historical', 'directory'))
+
+ render(<PreviewAttachment target="/work/reports/historical" />)
+
+ const open = await screen.findByRole('button', { name: 'Open containing folder' })
+
+ await act(async () => {
+ fireEvent.click(open)
+ })
+
+ expect(openDir).toHaveBeenCalledWith('/work/reports/historical')
+ expect(openPreview).not.toHaveBeenCalled()
+ })
+
+ it('reveals an existing local file in the file manager instead of offering Download', async () => {
+ const { openDir, revealPath } = mountDesktopStub(() => fileTarget('/work/report.md'))
+
+ render(<PreviewAttachment target="/work/report.md" />)
+
+ await screen.findByRole('button', { name: 'Open containing folder' })
+ expect(await buttons()).toEqual(['Open containing folder', 'Open preview'])
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Open containing folder' }))
+ })
+
+ expect(revealPath).toHaveBeenCalledWith('/work/report.md')
+ expect(openDir).not.toHaveBeenCalled()
+ })
+
+ it('keeps Download and the preview action for a remote-backend file', async () => {
+ isDesktopFsRemoteMode.mockReturnValue(true)
+ const { openDir, revealPath } = mountDesktopStub(() => fileTarget('/srv/report.md'))
+
+ render(<PreviewAttachment target="/srv/report.md" />)
+
+ expect(await buttons()).toEqual(['Download', 'Open preview'])
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Open preview' }))
+ })
+
+ // The remote path is not on this machine: no native folder action fires.
+ expect(openDir).not.toHaveBeenCalled()
+ expect(revealPath).not.toHaveBeenCalled()
+ })
+
+ it('reports a missing path instead of opening a broken preview tab', async () => {
+ mountDesktopStub(() => fileTarget('/work/gone.md', 'missing'))
+
+ render(<PreviewAttachment target="/work/gone.md" />)
+
+ const preview = await screen.findByRole('button', { name: 'Preview unavailable' })
+
+ await act(async () => {
+ fireEvent.click(preview)
+ })
+
+ expect(notifyError).toHaveBeenCalled()
+ expect(openPreview).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/components/chat/preview-attachment.tsx b/apps/desktop/src/components/chat/preview-attachment.tsx
index 0146982c24f..feb42eb0190 100644
--- a/apps/desktop/src/components/chat/preview-attachment.tsx
+++ b/apps/desktop/src/components/chat/preview-attachment.tsx
@@ -3,13 +3,52 @@ import { useEffect, useRef, useState } from 'react'
import { useSessionView } from '@/app/chat/session-view'
import { useI18n } from '@/i18n'
-import { Download, MonitorPlay } from '@/lib/icons'
+import { isDesktopFsRemoteMode } from '@/lib/desktop-fs'
+import { Download, FolderOpen, MonitorPlay } from '@/lib/icons'
import { normalizeOrLocalPreviewTarget } from '@/lib/local-preview'
import { downloadGatewayMediaFile } from '@/lib/media'
import { previewName } from '@/lib/preview-targets'
import { notifyError } from '@/store/notifications'
import { $previewTabSources, closePreviewForSource, openPreview } from '@/store/preview'
+/** What the Electron main process said about this target's LOCAL filesystem
+ * state (#101683). `null` keeps the stock card — remote-backend targets keep
+ * Download, and a bridge-less dev server can't classify. */
+type LocalTargetState =
+ | { path: string; type: 'directory' | 'file' }
+ | { type: 'missing' }
+ | null
+
+async function classifyLocalTarget(rawTarget: string, cwd?: string | null): Promise<LocalTargetState> {
+ const bridge = window.hermesDesktop
+
+ // Only the Electron host's filesystem is knowable here; a remote backend's
+ // paths are not on this machine, so they keep the gateway-backed actions.
+ if (!bridge?.normalizePreviewTarget || isDesktopFsRemoteMode()) {
+ return null
+ }
+
+ try {
+ const resolved = await bridge.normalizePreviewTarget(rawTarget, cwd || undefined)
+
+ if (!resolved || resolved.previewKind === 'missing') {
+ return { type: 'missing' }
+ }
+
+ if (resolved.previewKind === 'directory' && resolved.path) {
+ return { path: resolved.path, type: 'directory' }
+ }
+
+ if (resolved.kind === 'file' && resolved.path) {
+ return { path: resolved.path, type: 'file' }
+ }
+ } catch {
+ // An old Electron build without the normalizer keeps the stock card.
+ }
+
+ return null
+}
+
export function PreviewAttachment({ target }: { target: string }) {
const { t } = useI18n()
// This link lives in one session's transcript; resolve it against THAT
@@ -19,6 +58,7 @@ export function PreviewAttachment({ target }: { target: string }) {
const [opening, setOpening] = useState(false)
const [downloading, setDownloading] = useState(false)
const [downloaded, setDownloaded] = useState(false)
+ const [localTarget, setLocalTarget] = useState<LocalTargetState>(null)
const cwdRef = useRef(cwd)
const mountedRef = useRef(false)
const requestTokenRef = useRef(0)
@@ -45,6 +85,55 @@ export function PreviewAttachment({ target }: { target: string }) {
setOpening(false)
}, [cwd, target])
+ // Classify the target against the local filesystem so the card offers the
+ // native action instead of a Download this machine already has (#101683).
+ useEffect(() => {
+ let current = true
+ setLocalTarget(null)
+
+ void classifyLocalTarget(target, cwd).then(state => {
+ if (current) {
+ setLocalTarget(state)
+ }
+ })
+
+ return () => {
+ current = false
+ }
+ }, [cwd, target])
+
+ async function openInFileManager(path: string, directory: boolean) {
+ if (opening) {
+ return
+ }
+
+ setOpening(true)
+
+ try {
+ if (directory) {
+ const result = await window.hermesDesktop?.openDir?.(path)
+
+ if (!result?.ok) {
+ throw new Error(result?.error || `Could not open directory: ${path}`)
+ }
+ } else {
+ const revealed = await window.hermesDesktop?.revealPath?.(path)
+
+ if (revealed === false) {
+ throw new Error(`${path} — ${t.fileMenu.revealMissing}`)
+ }
+ }
+ } catch (error) {
+ if (mountedRef.current) {
+ notifyError(error, t.preview.unavailable)
+ }
+ } finally {
+ if (mountedRef.current) {
+ setOpening(false)
+ }
+ }
+ }
+
async function togglePreview() {
if (opening) {
return
@@ -56,6 +145,14 @@ export function PreviewAttachment({ target }: { target: string }) {
return
}
+ // The classifier already knows this path is not on this computer: report
+ // instead of running a pipeline that would fabricate a broken tab.
+ if (localTarget?.type === 'missing') {
+ notifyError(new Error(`${target} — ${t.preview.missingTarget}`), t.preview.unavailable)
+
+ return
+ }
+
const requestToken = ++requestTokenRef.current
const requestTarget = target
const requestCwd = cwd
@@ -125,6 +222,30 @@ export function PreviewAttachment({ target }: { target: string }) {
}
}
+ // A local directory is not previewable: one native folder action — no
+ // Download, no preview button that used to open a broken text tab (#101683).
+ if (localTarget?.type === 'directory') {
+ return (
+ <div className="flex w-full max-w-160 items-center gap-2 rounded-lg border border-(--ui-stroke-tertiary) bg-card/55 px-2.5 py-1.5 text-sm">
+ <span className="grid size-6 shrink-0 place-items-center rounded-md bg-muted/55 text-muted-foreground/85">
+ <MonitorPlay className="size-3.5" />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-[0.78rem] font-medium text-foreground/90" title={target}>
+ {name}
+ </span>
+ <button
+ className="flex shrink-0 items-center gap-1 rounded-md border border-(--ui-stroke-tertiary) bg-background/40 px-2 py-1 text-[0.7rem] font-medium text-muted-foreground transition-colors hover:bg-accent/55 hover:text-foreground disabled:opacity-50"
+ disabled={opening}
+ onClick={() => void openInFileManager(localTarget.path, true)}
+ type="button"
+ >
+ <FolderOpen className="size-3" />
+ {t.fileMenu.revealFileManager}
+ </button>
+ </div>
+ )
+ }
+
return (
<div className="flex w-full max-w-160 items-center gap-2 rounded-lg border border-(--ui-stroke-tertiary) bg-card/55 px-2.5 py-1.5 text-sm">
<span className="grid size-6 shrink-0 place-items-center rounded-md bg-muted/55 text-muted-foreground/85">
@@ -133,23 +254,43 @@ export function PreviewAttachment({ target }: { target: string }) {
<span className="min-w-0 flex-1 truncate text-[0.78rem] font-medium text-foreground/90" title={target}>
{name}
</span>
- <button
- aria-label={t.fileMenu.download}
- className="flex shrink-0 items-center gap-1 rounded-md border border-(--ui-stroke-tertiary) bg-background/40 px-2 py-1 text-[0.7rem] font-medium text-muted-foreground transition-colors hover:bg-accent/55 hover:text-foreground disabled:opacity-50"
- disabled={downloading}
- onClick={() => void downloadFile()}
- type="button"
- >
- <Download className="size-3" />
- {downloaded ? t.fileMenu.downloadSaved : t.fileMenu.download}
- </button>
+ {localTarget?.type === 'file' ? (
+ // The file already exists on this machine: reveal it in the OS file
+ // manager instead of offering to download it again (#101683).
+ <button
+ className="flex shrink-0 items-center gap-1 rounded-md border border-(--ui-stroke-tertiary) bg-background/40 px-2 py-1 text-[0.7rem] font-medium text-muted-foreground transition-colors hover:bg-accent/55 hover:text-foreground disabled:opacity-50"
+ disabled={opening}
+ onClick={() => void openInFileManager(localTarget.path, false)}
+ type="button"
+ >
+ <FolderOpen className="size-3" />
+ {t.fileMenu.revealFileManager}
+ </button>
+ ) : (
+ <button
+ aria-label={t.fileMenu.download}
+ className="flex shrink-0 items-center gap-1 rounded-md border border-(--ui-stroke-tertiary) bg-background/40 px-2 py-1 text-[0.7rem] font-medium text-muted-foreground transition-colors hover:bg-accent/55 hover:text-foreground disabled:opacity-50"
+ disabled={downloading}
+ onClick={() => void downloadFile()}
+ type="button"
+ >
+ <Download className="size-3" />
+ {downloaded ? t.fileMenu.downloadSaved : t.fileMenu.download}
+ </button>
+ )}
<button
className="shrink-0 rounded-md border border-(--ui-stroke-tertiary) bg-background/40 px-2 py-1 text-[0.7rem] font-medium text-muted-foreground transition-colors hover:bg-accent/55 hover:text-foreground disabled:opacity-50"
disabled={opening}
onClick={() => void togglePreview()}
type="button"
>
- {opening ? t.preview.opening : isActive ? t.preview.hide : t.preview.openPreview}
+ {opening
+ ? t.preview.opening
+ : localTarget?.type === 'missing'
+ ? t.preview.unavailable
+ : isActive
+ ? t.preview.hide
+ : t.preview.openPreview}
</button>
</div>
)
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 0ef2f3d9afb..3f5f96c6c5c 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -1480,7 +1480,7 @@ export interface HermesPreviewTarget {
language?: string
mimeType?: string
path?: string
- previewKind?: 'binary' | 'html' | 'image' | 'pdf' | 'text'
+ previewKind?: 'binary' | 'directory' | 'html' | 'image' | 'missing' | 'pdf' | 'text'
renderMode?: 'preview' | 'source'
source: string
url: string
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 8d530bc10a1..f3439698267 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -4846,6 +4846,7 @@ export const en: Translations = {
closePane: 'Close preview pane',
loading: 'Loading preview',
unavailable: 'Preview unavailable',
+ missingTarget: 'That path does not exist on this computer',
opening: 'Opening...',
hide: 'Hide',
openPreview: 'Open preview',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index d15be99951f..b613caa65cf 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -4099,6 +4099,7 @@ export interface Translations {
closePane: string
loading: string
unavailable: string
+ missingTarget: string
opening: string
hide: string
openPreview: string
diff --git a/apps/desktop/src/lib/local-preview.local-target.test.ts b/apps/desktop/src/lib/local-preview.local-target.test.ts
new file mode 100644
index 00000000000..429ca522695
--- /dev/null
+++ b/apps/desktop/src/lib/local-preview.local-target.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// #101683 pipeline invariant: a typed non-previewable normalization result
+// (directory / missing) must NOT fall through to the renderer's blind local
+// classification, which fabricates a text-preview tab for a path that cannot
+// be previewed. A remote backend's paths are not on this machine, so remote
+// mode keeps the fabricated fallback the gateway read resolves later.
+
+const { isDesktopFsRemoteMode } = vi.hoisted(() => ({
+ isDesktopFsRemoteMode: vi.fn(() => false)
+}))
+
+vi.mock('@/lib/desktop-fs', () => ({
+ isDesktopFsRemoteMode,
+ readDesktopDir: vi.fn(),
+ readDesktopFileDataUrl: vi.fn(),
+ readDesktopFileText: vi.fn()
+}))
+
+import { normalizeOrLocalPreviewTarget } from './local-preview'
+
+const previousDesktop = window.hermesDesktop
+
+function stubNormalization(result: unknown) {
+ window.hermesDesktop = {
+ normalizePreviewTarget: vi.fn(async () => result)
+ } as never
+}
+
+describe('normalizeOrLocalPreviewTarget non-previewable results', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ isDesktopFsRemoteMode.mockReturnValue(false)
+ })
+
+ afterEach(() => {
+ window.hermesDesktop = previousDesktop
+ })
+
+ it('returns null for a directory in local mode instead of fabricating a text tab', async () => {
+ stubNormalization({
+ kind: 'file',
+ label: 'historical',
+ path: '/work/reports/historical',
+ previewKind: 'directory',
+ source: '/work/reports/historical',
+ url: 'file:///work/reports/historical'
+ })
+
+ await expect(normalizeOrLocalPreviewTarget('/work/reports/historical')).resolves.toBeNull()
+ })
+
+ it('returns null for a missing path in local mode', async () => {
+ stubNormalization({
+ kind: 'file',
+ label: 'gone.md',
+ path: '/work/gone.md',
+ previewKind: 'missing',
+ source: '/work/gone.md',
+ url: 'file:///work/gone.md'
+ })
+
+ await expect(normalizeOrLocalPreviewTarget('/work/gone.md')).resolves.toBeNull()
+ })
+
+ it('treats a null main-process result as authoritative in local mode', async () => {
+ stubNormalization(null)
+
+ await expect(normalizeOrLocalPreviewTarget('/work/nope.md')).resolves.toBeNull()
+ })
+
+ it('keeps the gateway-backed fallback for remote-backend directories', async () => {
+ isDesktopFsRemoteMode.mockReturnValue(true)
+ stubNormalization({
+ kind: 'file',
+ label: 'srv',
+ path: '/srv/reports',
+ previewKind: 'directory',
+ source: '/srv/reports',
+ url: 'file:///srv/reports'
+ })
+
+ const fabricated = await normalizeOrLocalPreviewTarget('/srv/reports')
+
+ expect(fabricated?.kind).toBe('file')
+ expect(fabricated?.path).toBe('/srv/reports')
+ })
+})
diff --git a/apps/desktop/src/lib/local-preview.ts b/apps/desktop/src/lib/local-preview.ts
index 9c3c598ce35..99e9875c8e2 100644
--- a/apps/desktop/src/lib/local-preview.ts
+++ b/apps/desktop/src/lib/local-preview.ts
@@ -310,8 +310,28 @@ export async function normalizeOrLocalPreviewTarget(
const normalized = await window.hermesDesktop?.normalizePreviewTarget?.(rawTarget, cwd || undefined)
if (normalized) {
+ // Directories and dead links arrive as typed non-previewable results
+ // (#101683). Locally they must not fall through to the renderer's blind
+ // classification below, which would fabricate a text tab for a path
+ // that cannot be previewed. A remote backend's paths are not on this
+ // machine, so remote mode keeps the fabricated fallback the gateway
+ // read resolves later.
+ if (normalized.previewKind === 'directory' || normalized.previewKind === 'missing') {
+ return isDesktopFsRemoteMode() ? enrichPreviewTarget(localPreviewTarget(rawTarget, cwd)) : null
+ }
+
return enrichPreviewTarget(normalized)
}
+
+ // The main process resolved the target against the real filesystem and
+ // found nothing openable (`null`); an absent bridge yields `undefined` from
+ // the optional call above instead. In local mode the main process's answer
+ // is authoritative — the fallback below can only fabricate a broken
+ // preview tab (#101683). Remote-backend paths, and a dev server without
+ // the bridge, keep it.
+ if (!isDesktopFsRemoteMode() && normalized === null) {
+ return null
+ }
} catch {
// Running Electron may still have the old HTML-only preview IPC. Fall
// through to renderer-side local classification so text/images still open.
diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.ts
index b4e30dcf8d7..bd8ef32fce1 100644
--- a/apps/desktop/src/store/preview.ts
+++ b/apps/desktop/src/store/preview.ts
@@ -43,7 +43,10 @@ export interface PreviewTarget {
language?: string
mimeType?: string
path?: string
- previewKind?: 'binary' | 'html' | 'image' | 'pdf' | 'text'
+ /** `directory`/`missing` are typed non-previewable results from main-process
+ * normalization (#101683): they never reach `openPreview` — callers branch on
+ * them for the native folder action / not-found reporting instead. */
+ previewKind?: 'binary' | 'directory' | 'html' | 'image' | 'missing' | 'pdf' | 'text'
renderMode?: PreviewRenderMode
source: string
/** Runtime-only target that cannot be restored from persisted state. */
diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.json
index 28f9767d591..0d92186e54b 100644
--- a/locales/_keys.desktop.json
+++ b/locales/_keys.desktop.json
@@ -2134,6 +2134,7 @@
"preview.largeTitle",
"preview.linkHint",
"preview.loading",
+ "preview.missingTarget",
"preview.noInlineBody",
"preview.noInlineTitle",
"preview.openInBrowser",