Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(desktop-app): open GFS file previews in a workspace tab

Diego Zacarias7858b9822d39
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index e12c2d97e..6e0509cfb 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -80,6 +80,7 @@ import type { WorkspaceTab } from '@lib/workspaceTabs.types'
import { AgentsPage } from '@pages/AgentsPage'
import { AuthPage } from '@pages/AuthPage'
import { ChatPage } from '@pages/ChatPage'
+import { FilePreviewPage } from '@pages/FilePreviewPage'
import { FilesPage } from '@pages/FilesPage'
import { McpServersPage } from '@pages/McpServersPage'
import { OnboardingPage } from '@pages/OnboardingPage'
@@ -386,7 +387,7 @@ export function App() {
// this only tears down any lingering app embed.
const revealWorkspaceTab = React.useCallback(
(tab: WorkspaceTab | undefined, inDrawer = chatDrawerVisibleRef.current) => {
- if (!tab || tab.kind === 'files' || tab.kind === 'settings') {
+ if (!tab || tab.kind === 'files' || tab.kind === 'settings' || tab.kind === 'preview') {
if (!inDrawer) leaveSandboxForChat()
return
}
@@ -865,6 +866,15 @@ export function App() {
[setWorkspaceTabs]
)
+ // Preview tab render seam (spec 18 §3.B.1). Only the ACTIVE preview tab mounts
+ // a FilePreviewPage, keyed by that tab's id so switching preview tabs remounts
+ // with the incoming file's payload. Unlike an app tab, a preview tab is a plain
+ // DOM page — revealing it does not relaunch a native embed.
+ const activePreviewTab =
+ vm.activeWorkspaceTab?.kind === 'preview' ? vm.activeWorkspaceTab : undefined
+ const activePreviewTabId = activePreviewTab?.id ?? null
+ const activePreviewPayload = activePreviewTab?.preview ?? null
+
const closePluginGfsPreview = React.useCallback(() => {
setPluginGfsPreview(null)
void window.clerum.sandboxUi.setVisible(true).catch(() => undefined)
@@ -2532,6 +2542,17 @@ export function App() {
pushToast={vm.pushToast}
pendingGfsUri={filesSeedPath}
onLocationChange={handleFilesLocationChange}
+ onOpenPreview={vm.openPreviewSection}
+ />
+ )}
+ {vm.navItem === DESKTOP_ROUTES.preview && activePreviewPayload && (
+ <FilePreviewPage
+ key={activePreviewTabId ?? 'preview'}
+ gfsUri={activePreviewPayload.gfsUri}
+ fileName={activePreviewTab?.title ?? 'Preview'}
+ fileKind={activePreviewPayload.fileKind}
+ mimeType={activePreviewPayload.mimeType}
+ byteLength={activePreviewPayload.byteLength}
/>
)}
{vm.navItem === DESKTOP_ROUTES.connectors && <McpServersPage />}
diff --git a/desktop-app/ui/src/components/GfsImagePreview/Body.tsx b/desktop-app/ui/src/components/GfsImagePreview/Body.tsx
new file mode 100644
index 000000000..36a334cb1
--- /dev/null
+++ b/desktop-app/ui/src/components/GfsImagePreview/Body.tsx
@@ -0,0 +1,185 @@
+import { useEffect, useId, useRef, useState } from 'react'
+import { Button, StatusBanner } from '@components/Common'
+import { IconCopy } from '@components/SidebarNav/icons'
+import { assertGfsImagePreviewSize } from '@lib/gfsImagePreview'
+import type { GfsImagePreviewBodyProps } from './types'
+
+/**
+ * De-modalized image preview body (spec 18 §3.B.2). Owns the byte fetch (by
+ * `gfsUri`), the size-guard, the copy-to-clipboard, and the rendered `<img>` +
+ * loading/error states. It renders NO portal, backdrop, `aria-modal`, or Escape
+ * handling — that chrome belongs to the caller. Fails closed: any download error
+ * both surfaces the reason in the body and is routed to `onDownloadError`.
+ */
+export function GfsImagePreviewBody({
+ byteLength,
+ fileName,
+ gfsUri,
+ mimeType,
+ onDownloadError,
+ titleId,
+ headerActions,
+ headingLevel = 3,
+}: GfsImagePreviewBodyProps) {
+ const generatedTitleId = useId()
+ const headingId = titleId ?? generatedTitleId
+ const [previewUrl, setPreviewUrl] = useState<string | null>(null)
+ const [sourceBlob, setSourceBlob] = useState<Blob | null>(null)
+ const [previewError, setPreviewError] = useState<string | null>(null)
+ const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle')
+ const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const mountedRef = useRef(true)
+ const onDownloadErrorRef = useRef(onDownloadError)
+ const HeadingTag = `h${headingLevel}` as const
+
+ useEffect(() => {
+ onDownloadErrorRef.current = onDownloadError
+ }, [onDownloadError])
+
+ useEffect(() => {
+ let active = true
+ let objectUrl: string | null = null
+
+ const loadPreview = async () => {
+ try {
+ assertGfsImagePreviewSize(byteLength)
+ const { bytes } = await window.clerum.gfs.download(gfsUri)
+ assertGfsImagePreviewSize(bytes.byteLength)
+ if (!active) return
+ const blob = new Blob([bytes], { type: mimeType })
+ setSourceBlob(blob)
+ objectUrl = URL.createObjectURL(blob)
+ setPreviewUrl(objectUrl)
+ } catch (error) {
+ if (!active) return
+ onDownloadErrorRef.current?.(error)
+ setPreviewError(error instanceof Error ? error.message : 'Could not load the image preview')
+ }
+ }
+
+ void loadPreview()
+ return () => {
+ active = false
+ if (objectUrl) URL.revokeObjectURL(objectUrl)
+ }
+ }, [byteLength, gfsUri, mimeType])
+
+ useEffect(() => {
+ mountedRef.current = true
+ return () => {
+ mountedRef.current = false
+ if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)
+ }
+ }, [])
+
+ function markCopyState(state: 'copied' | 'error'): boolean {
+ if (!mountedRef.current) return false
+ setCopyState(state)
+ if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)
+ copyResetTimeoutRef.current = setTimeout(() => {
+ if (mountedRef.current) setCopyState('idle')
+ }, 2000)
+ return true
+ }
+
+ async function copyImageToClipboard(): Promise<void> {
+ if (!sourceBlob || !mountedRef.current) return
+ try {
+ if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
+ let clipboardBlob: Blob | null = sourceBlob
+ if (!sourceBlob.type.includes('png')) {
+ clipboardBlob = await convertBlobToPng(sourceBlob)
+ }
+ if (!mountedRef.current) return
+ if (clipboardBlob) {
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': clipboardBlob })])
+ if (!mountedRef.current) return
+ markCopyState('copied')
+ return
+ }
+ }
+ if (navigator.clipboard?.writeText) {
+ const dataUrl = await blobToDataUrl(sourceBlob)
+ if (!mountedRef.current) return
+ await navigator.clipboard.writeText(dataUrl)
+ if (!mountedRef.current) return
+ markCopyState('copied')
+ } else {
+ markCopyState('error')
+ }
+ } catch {
+ markCopyState('error')
+ }
+ }
+
+ return (
+ <>
+ <header className="da-gfs-image-preview-dialog__header">
+ <HeadingTag className="da-gfs-preview-title" id={headingId}>
+ {fileName}
+ </HeadingTag>
+ <div className="da-gfs-image-preview-dialog__header-actions">
+ <Button
+ className="da-gfs-image-preview-dialog__copy"
+ aria-label={
+ copyState === 'copied' ? 'Copied image to clipboard' : 'Copy image to clipboard'
+ }
+ color="neutral"
+ disabled={!sourceBlob}
+ onClick={() => void copyImageToClipboard()}
+ variant="ghost"
+ >
+ <IconCopy width={18} height={18} />
+ <span className="da-gfs-preview-button__label">
+ {copyState === 'copied' ? 'Copied' : 'Copy'}
+ </span>
+ </Button>
+ {headerActions}
+ </div>
+ </header>
+ <div className="da-gfs-image-preview-dialog__body">
+ {previewError ? <StatusBanner tone="error" text={previewError} /> : null}
+ {!previewError && !previewUrl ? (
+ <div className="da-gfs-image-preview-dialog__loading" role="status">
+ Loading image preview…
+ </div>
+ ) : null}
+ {previewUrl && !previewError ? (
+ <img
+ alt={`Preview of ${fileName}`}
+ className="da-gfs-image-preview-dialog__image"
+ onError={() => setPreviewError('This image could not be displayed')}
+ src={previewUrl}
+ />
+ ) : null}
+ </div>
+ </>
+ )
+}
+
+async function convertBlobToPng(blob: Blob): Promise<Blob | null> {
+ if (typeof createImageBitmap === 'undefined') return null
+ try {
+ const bitmap = await createImageBitmap(blob)
+ const canvas = document.createElement('canvas')
+ canvas.width = bitmap.width
+ canvas.height = bitmap.height
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return null
+ ctx.drawImage(bitmap, 0, 0)
+ return await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, 'image/png'))
+ } catch {
+ return null
+ }
+}
+
+async function blobToDataUrl(blob: Blob): Promise<string> {
+ const result = await new Promise<string | ArrayBuffer | null>((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => resolve(reader.result)
+ reader.onerror = () => reject(reader.error ?? new Error('Could not read the image'))
+ reader.readAsDataURL(blob)
+ })
+ if (typeof result !== 'string') throw new Error('Could not read the image')
+ return result
+}
diff --git a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx
new file mode 100644
index 000000000..4460e80ad
--- /dev/null
+++ b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx
@@ -0,0 +1,119 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { GFS_IMAGE_PREVIEW_MAX_BYTES } from '@constants/gfsImagePreview'
+import { GfsImagePreviewBody } from './Body'
+
+// The producer (`window.clerum.gfs.download`) returns `{ bytes: ArrayBuffer }`
+// (renderer.d.ts); the body reads only `.bytes`, so the mock mirrors that shape.
+function stubDownload(bytes: ArrayBuffer) {
+ const download = vi.fn(async () => ({ bytes }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { download } },
+ })
+ return download
+}
+
+describe('GfsImagePreviewBody', () => {
+ beforeEach(() => {
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ value: vi.fn(() => 'blob:gfs-image-preview'),
+ })
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ it('downloads by gfsUri and renders the image without a modal', async () => {
+ const download = stubDownload(new Uint8Array([1, 2, 3]).buffer)
+
+ render(
+ <GfsImagePreviewBody
+ byteLength={3}
+ fileName="diagram.PNG"
+ gfsUri="gfs://main/image-1"
+ mimeType="image/png"
+ />
+ )
+
+ const img = await screen.findByAltText('Preview of diagram.PNG')
+ expect(img.tagName).toBe('IMG')
+ expect(img.getAttribute('src')).toBe('blob:gfs-image-preview')
+ expect(download).toHaveBeenCalledWith('gfs://main/image-1')
+ // No portal/backdrop/dialog chrome — this is the de-modalized body.
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(screen.queryByRole('presentation')).toBeNull()
+ })
+
+ it('renders the heading at the requested level (a page uses h2)', async () => {
+ stubDownload(new Uint8Array([1, 2, 3]).buffer)
+ render(
+ <GfsImagePreviewBody
+ byteLength={3}
+ fileName="diagram.PNG"
+ gfsUri="gfs://main/image-1"
+ mimeType="image/png"
+ headingLevel={2}
+ />
+ )
+ expect(await screen.findByRole('heading', { name: 'diagram.PNG', level: 2 })).toBeTruthy()
+ })
+
+ it('rejects an oversized image from metadata before downloading', async () => {
+ const download = stubDownload(new Uint8Array([1]).buffer)
+ render(
+ <GfsImagePreviewBody
+ byteLength={GFS_IMAGE_PREVIEW_MAX_BYTES + 1}
+ fileName="oversized.png"
+ gfsUri="gfs://main/oversized"
+ mimeType="image/png"
+ />
+ )
+ expect(await screen.findByText(/Image previews are limited to 10 MB/)).toBeTruthy()
+ expect(download).not.toHaveBeenCalled()
+ })
+
+ it('fails closed on a download error: shows the reason and notifies onDownloadError', async () => {
+ const onDownloadError = vi.fn()
+ const download = vi.fn(async () => {
+ throw new Error('403 Forbidden')
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { download } },
+ })
+
+ render(
+ <GfsImagePreviewBody
+ byteLength={3}
+ fileName="secret.png"
+ gfsUri="gfs://main/secret"
+ mimeType="image/png"
+ onDownloadError={onDownloadError}
+ />
+ )
+
+ expect(await screen.findByText('403 Forbidden')).toBeTruthy()
+ expect(screen.queryByAltText('Preview of secret.png')).toBeNull()
+ await waitFor(() => expect(onDownloadError).toHaveBeenCalled())
+ })
+
+ it('renders the copy affordance in the header', async () => {
+ stubDownload(new Uint8Array([1, 2, 3]).buffer)
+ render(
+ <GfsImagePreviewBody
+ byteLength={3}
+ fileName="diagram.PNG"
+ gfsUri="gfs://main/image-1"
+ mimeType="image/png"
+ />
+ )
+ const copyButton = await screen.findByRole('button', { name: /Copy image to clipboard/i })
+ expect(copyButton.textContent).toContain('Copy')
+ })
+})
diff --git a/desktop-app/ui/src/components/GfsImagePreview/index.tsx b/desktop-app/ui/src/components/GfsImagePreview/index.tsx
index c7e92e858..610b1446c 100644
--- a/desktop-app/ui/src/components/GfsImagePreview/index.tsx
+++ b/desktop-app/ui/src/components/GfsImagePreview/index.tsx
@@ -1,11 +1,17 @@
-import { useEffect, useId, useRef, useState } from 'react'
+import { useEffect, useId, useRef } from 'react'
import { createPortal } from 'react-dom'
-import { Button, StatusBanner } from '@components/Common'
-import { IconClose, IconCopy } from '@components/SidebarNav/icons'
+import { Button } from '@components/Common'
+import { IconClose } from '@components/SidebarNav/icons'
import { useWorkspaceModalStyle } from '@hooks/useWorkspaceModalStyle'
-import { assertGfsImagePreviewSize } from '@lib/gfsImagePreview'
+import { GfsImagePreviewBody } from './Body'
import type { GfsImagePreviewProps } from './types'
+/**
+ * Modal chrome around {@link GfsImagePreviewBody} (spec 18 §3.B.2): portal,
+ * backdrop, `role="dialog"`, focus-on-open, Escape-to-close, and the workspace
+ * backdrop positioning. The body owns the fetch/copy/size-guard so both this
+ * modal and `FilePreviewPage` share one implementation.
+ */
export function GfsImagePreview({
byteLength,
fileName,
@@ -16,18 +22,7 @@ export function GfsImagePreview({
}: GfsImagePreviewProps) {
const titleId = useId()
const closeButtonRef = useRef<HTMLButtonElement | null>(null)
- const [previewUrl, setPreviewUrl] = useState<string | null>(null)
- const [sourceBlob, setSourceBlob] = useState<Blob | null>(null)
- const [previewError, setPreviewError] = useState<string | null>(null)
- const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle')
const backdropStyle = useWorkspaceModalStyle()
- const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- const mountedRef = useRef(true)
- const onDownloadErrorRef = useRef(onDownloadError)
-
- useEffect(() => {
- onDownloadErrorRef.current = onDownloadError
- }, [onDownloadError])
useEffect(() => {
closeButtonRef.current?.focus()
@@ -38,82 +33,6 @@ export function GfsImagePreview({
return () => window.removeEventListener('keydown', handleKeyDown)
}, [onClose])
- useEffect(() => {
- let active = true
- let objectUrl: string | null = null
-
- const loadPreview = async () => {
- try {
- assertGfsImagePreviewSize(byteLength)
- const { bytes } = await window.clerum.gfs.download(gfsUri)
- assertGfsImagePreviewSize(bytes.byteLength)
- if (!active) return
- const blob = new Blob([bytes], { type: mimeType })
- setSourceBlob(blob)
- objectUrl = URL.createObjectURL(blob)
- setPreviewUrl(objectUrl)
- } catch (error) {
- if (!active) return
- onDownloadErrorRef.current?.(error)
- setPreviewError(error instanceof Error ? error.message : 'Could not load the image preview')
- }
- }
-
- void loadPreview()
- return () => {
- active = false
- if (objectUrl) URL.revokeObjectURL(objectUrl)
- }
- }, [byteLength, gfsUri, mimeType])
-
- useEffect(() => {
- mountedRef.current = true
- return () => {
- mountedRef.current = false
- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)
- }
- }, [])
-
- function markCopyState(state: 'copied' | 'error'): boolean {
- if (!mountedRef.current) return false
- setCopyState(state)
- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)
- copyResetTimeoutRef.current = setTimeout(() => {
- if (mountedRef.current) setCopyState('idle')
- }, 2000)
- return true
- }
-
- async function copyImageToClipboard(): Promise<void> {
- if (!sourceBlob || !mountedRef.current) return
- try {
- if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
- let clipboardBlob: Blob | null = sourceBlob
- if (!sourceBlob.type.includes('png')) {
- clipboardBlob = await convertBlobToPng(sourceBlob)
- }
- if (!mountedRef.current) return
- if (clipboardBlob) {
- await navigator.clipboard.write([new ClipboardItem({ 'image/png': clipboardBlob })])
- if (!mountedRef.current) return
- markCopyState('copied')
- return
- }
- }
- if (navigator.clipboard?.writeText) {
- const dataUrl = await blobToDataUrl(sourceBlob)
- if (!mountedRef.current) return
- await navigator.clipboard.writeText(dataUrl)
- if (!mountedRef.current) return
- markCopyState('copied')
- } else {
- markCopyState('error')
- }
- } catch {
- markCopyState('error')
- }
- }
-
return createPortal(
<div
className="da-gfs-image-preview-modal"
@@ -129,24 +48,14 @@ export function GfsImagePreview({
aria-modal="true"
aria-labelledby={titleId}
>
- <header className="da-gfs-image-preview-dialog__header">
- <h3 id={titleId}>{fileName}</h3>
- <div className="da-gfs-image-preview-dialog__header-actions">
- <Button
- className="da-gfs-image-preview-dialog__copy"
- aria-label={
- copyState === 'copied' ? 'Copied image to clipboard' : 'Copy image to clipboard'
- }
- color="neutral"
- disabled={!sourceBlob}
- onClick={() => void copyImageToClipboard()}
- variant="ghost"
- >
- <IconCopy width={18} height={18} />
- <span className="da-gfs-preview-button__label">
- {copyState === 'copied' ? 'Copied' : 'Copy'}
- </span>
- </Button>
+ <GfsImagePreviewBody
+ byteLength={byteLength}
+ fileName={fileName}
+ gfsUri={gfsUri}
+ mimeType={mimeType}
+ onDownloadError={onDownloadError}
+ titleId={titleId}
+ headerActions={
<Button
className="da-gfs-image-preview-dialog__close"
data-preview-close
@@ -158,55 +67,13 @@ export function GfsImagePreview({
>
<IconClose width={18} height={18} />
</Button>
- </div>
- </header>
- <div className="da-gfs-image-preview-dialog__body">
- {previewError ? <StatusBanner tone="error" text={previewError} /> : null}
- {!previewError && !previewUrl ? (
- <div className="da-gfs-image-preview-dialog__loading" role="status">
- Loading image preview…
- </div>
- ) : null}
- {previewUrl && !previewError ? (
- <img
- alt={`Preview of ${fileName}`}
- className="da-gfs-image-preview-dialog__image"
- onError={() => setPreviewError('This image could not be displayed')}
- src={previewUrl}
- />
- ) : null}
- </div>
+ }
+ />
</section>
</div>,
document.body
)
}
-async function convertBlobToPng(blob: Blob): Promise<Blob | null> {
- if (typeof createImageBitmap === 'undefined') return null
- try {
- const bitmap = await createImageBitmap(blob)
- const canvas = document.createElement('canvas')
- canvas.width = bitmap.width
- canvas.height = bitmap.height
- const ctx = canvas.getContext('2d')
- if (!ctx) return null
- ctx.drawImage(bitmap, 0, 0)
- return await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, 'image/png'))
- } catch {
- return null
- }
-}
-
-async function blobToDataUrl(blob: Blob): Promise<string> {
- const result = await new Promise<string | ArrayBuffer | null>((resolve, reject) => {
- const reader = new FileReader()
- reader.onload = () => resolve(reader.result)
- reader.onerror = () => reject(reader.error ?? new Error('Could not read the image'))
- reader.readAsDataURL(blob)
- })
- if (typeof result !== 'string') throw new Error('Could not read the image')
- return result
-}
-
+export { GfsImagePreviewBody } from './Body'
export type { GfsImagePreviewProps } from './types'
diff --git a/desktop-app/ui/src/components/GfsImagePreview/types.ts b/desktop-app/ui/src/components/GfsImagePreview/types.ts
index bac51aef6..03226508d 100644
--- a/desktop-app/ui/src/components/GfsImagePreview/types.ts
+++ b/desktop-app/ui/src/components/GfsImagePreview/types.ts
@@ -1,3 +1,5 @@
+import type { ReactNode } from 'react'
+
export type GfsImagePreviewProps = {
byteLength: number
fileName: string
@@ -6,3 +8,21 @@ export type GfsImagePreviewProps = {
onClose: () => void
onDownloadError?: (error: unknown) => void
}
+
+/**
+ * The de-modalized image preview (spec 18 §3.B.2): the `<img>` + its fetch,
+ * copy, and size-guard, WITHOUT the portal/backdrop/close/Escape chrome. Both
+ * the surviving modal and `FilePreviewPage` mount it. `headerActions` is a slot
+ * for chrome-owned controls (the modal's close button); `headingLevel` lets a
+ * page use `h2` while the modal keeps `h3`.
+ */
+export type GfsImagePreviewBodyProps = {
+ byteLength: number
+ fileName: string
+ gfsUri: string
+ mimeType: string
+ onDownloadError?: (error: unknown) => void
+ titleId?: string
+ headerActions?: ReactNode
+ headingLevel?: 2 | 3
+}
diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx
new file mode 100644
index 000000000..6abe2eab3
--- /dev/null
+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx
@@ -0,0 +1,214 @@
+import { Fragment, useEffect, useId, useMemo, useRef, useState } from 'react'
+import type { ReactNode } from 'react'
+import { Button, StatusBanner } from '@components/Common'
+import { IconCopy } from '@components/SidebarNav/icons'
+import { assertGfsMarkdownPreviewSize } from '@lib/gfsMarkdownPreview'
+import { parseVanillaMarkdown } from '@lib/vanillaMarkdown'
+import type { MarkdownBlock, MarkdownInlineNode } from '@lib/vanillaMarkdown.types'
+import type { GfsMarkdownPreviewBodyProps } from './types'
+
+function isPlainTextName(fileName: string): boolean {
+ return fileName.toLowerCase().endsWith('.txt')
+}
+
+function renderInlineNodes(nodes: MarkdownInlineNode[]): ReactNode[] {
+ return nodes.map(node => {
+ if (node.kind === 'text') return <Fragment key={node.id}>{node.value}</Fragment>
+ if (node.kind === 'code') return <code key={node.id}>{node.value}</code>
+ const children = renderInlineNodes(node.children)
+ if (node.kind === 'strong') return <strong key={node.id}>{children}</strong>
+ if (node.kind === 'emphasis') return <em key={node.id}>{children}</em>
+ if (node.kind === 'strikethrough') return <s key={node.id}>{children}</s>
+ return node.href ? (
+ <a href={node.href} key={node.id} rel="noreferrer" target="_blank">
+ {children}
+ </a>
+ ) : (
+ <span key={node.id}>{children}</span>
+ )
+ })
+}
+
+function renderHeading(block: Extract<MarkdownBlock, { kind: 'heading' }>): ReactNode {
+ const children = renderInlineNodes(block.children)
+ if (block.level === 1) return <h1 key={block.id}>{children}</h1>
+ if (block.level === 2) return <h2 key={block.id}>{children}</h2>
+ if (block.level === 3) return <h3 key={block.id}>{children}</h3>
+ if (block.level === 4) return <h4 key={block.id}>{children}</h4>
+ if (block.level === 5) return <h5 key={block.id}>{children}</h5>
+ return <h6 key={block.id}>{children}</h6>
+}
+
+function renderBlock(block: MarkdownBlock): ReactNode {
+ if (block.kind === 'heading') return renderHeading(block)
+ if (block.kind === 'paragraph') {
+ return <p key={block.id}>{renderInlineNodes(block.children)}</p>
+ }
+ if (block.kind === 'blockquote') {
+ return <blockquote key={block.id}>{renderInlineNodes(block.children)}</blockquote>
+ }
+ if (block.kind === 'divider') return <hr key={block.id} />
+ if (block.kind === 'code') {
+ return (
+ <pre key={block.id}>
+ <code data-language={block.language ?? undefined}>{block.value}</code>
+ </pre>
+ )
+ }
+ const items = block.items.map(item => <li key={item.id}>{renderInlineNodes(item.children)}</li>)
+ return block.ordered ? <ol key={block.id}>{items}</ol> : <ul key={block.id}>{items}</ul>
+}
+
+/**
+ * De-modalized markdown/text preview body (spec 18 §3.B.2). Owns the byte fetch
+ * (by `gfsUri`), the size-guard, copy-source-to-clipboard, and the rendered
+ * markdown/plain-text `<article>` + loading/error states. Renders no modal
+ * chrome. Fails closed: a download error both shows the reason and is routed to
+ * `onDownloadError`.
+ */
+export function GfsMarkdownPreviewBody({
+ byteLength,
+ fileName,
+ gfsUri,
+ onDownloadError,
+ titleId,
+ headerActions,
+ headingLevel = 3,
+}: GfsMarkdownPreviewBodyProps) {
+ const generatedTitleId = useId()
+ const headingId = titleId ?? generatedTitleId
+ const [source, setSource] = useState<string | null>(null)
+ const [previewError, setPreviewError] = useState<string | null>(null)
+ const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle')
+ const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const mountedRef = useRef(true)
+ const onDownloadErrorRef = useRef(onDownloadError)
+ const blocks = useMemo(() => (source === null ? [] : parseVanillaMarkdown(source)), [source])
+ const isPlainText = isPlainTextName(fileName)
+ const HeadingTag = `h${headingLevel}` as const
+
+ useEffect(() => {
+ onDownloadErrorRef.current = onDownloadError
+ }, [onDownloadError])
+
+ useEffect(() => {
+ mountedRef.current = true
+ return () => {
+ mountedRef.current = false
+ if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)
+ }
+ }, [])
+
+ useEffect(() => {
+ let active = true
+
+ const loadPreview = async () => {
+ try {
+ assertGfsMarkdownPreviewSize(byteLength)
+ const { bytes } = await window.clerum.gfs.download(gfsUri)
+ assertGfsMarkdownPreviewSize(bytes.byteLength)
+ const markdown = new TextDecoder().decode(bytes)
+ if (active) setSource(markdown)
+ } catch (error) {
+ if (!active) return
+ onDownloadErrorRef.current?.(error)
+ setPreviewError(
+ error instanceof Error ? error.message : 'Could not load the Markdown preview'
+ )
+ }
+ }
+
+ void loadPreview()
+ return () => {
+ active = false
+ }
+ }, [byteLength, gfsUri])
+
+ function markCopyState(state: 'copied' | 'error'): boolean {
+ if (!mountedRef.current) return false
+ setCopyState(state)
+ if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)
+ copyResetTimeoutRef.current = setTimeout(() => {
+ if (mountedRef.current) setCopyState('idle')
+ }, 2000)
+ return true
+ }
+
+ async function copySourceToClipboard(): Promise<void> {
+ if (source === null || !mountedRef.current) return
+ try {
+ if (navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(source)
+ if (!mountedRef.current) return
+ markCopyState('copied')
+ } else {
+ markCopyState('error')
+ }
+ } catch {
+ markCopyState('error')
+ }
+ }
+
+ return (
+ <>
+ <header className="da-gfs-markdown-preview-dialog__header">
+ <HeadingTag className="da-gfs-preview-title" id={headingId}>
+ {fileName}
+ </HeadingTag>
+ <div className="da-gfs-markdown-preview-dialog__header-actions">
+ <Button
+ className="da-gfs-markdown-preview-dialog__copy"
+ aria-label={
+ copyState === 'copied'
+ ? 'Copied preview contents to clipboard'
+ : 'Copy preview contents to clipboard'
+ }
+ color="neutral"
+ disabled={source === null}
+ onClick={() => void copySourceToClipboard()}
+ variant="ghost"
+ >
+ <IconCopy width={18} height={18} />
+ <span className="da-gfs-preview-button__label">
+ {copyState === 'copied' ? 'Copied' : 'Copy'}
+ </span>
+ </Button>
+ {headerActions}
+ </div>
+ </header>
+ <div className="da-gfs-markdown-preview-dialog__body">
+ {previewError ? <StatusBanner tone="error" text={previewError} /> : null}
+ {!previewError && source === null ? (
+ <div className="da-gfs-markdown-preview-dialog__loading" role="status">
+ Loading preview…
+ </div>
+ ) : null}
+ {source !== null && !previewError ? (
+ isPlainText ? (
+ <article
+ aria-label={`Text preview of ${fileName}`}
+ className="da-gfs-text-preview__content"
+ >
+ {source.length > 0 ? (
+ <pre className="da-gfs-text-preview__body">{source}</pre>
+ ) : (
+ <p className="da-gfs-markdown-preview__empty">This text file is empty.</p>
+ )}
+ </article>
+ ) : (
+ <article
+ aria-label={`Markdown preview of ${fileName}`}
+ className="da-gfs-markdown-preview__content markdown-content"
+ >
+ {blocks.length > 0 ? (
+ blocks.map(renderBlock)
+ ) : (
+ <p className="da-gfs-markdown-preview__empty">This Markdown file is empty.</p>
+ )}
+ </article>
+ )
+ ) : null}
+ </div>
+ </>
+ )
+}
diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.test.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.test.tsx
new file mode 100644
index 000000000..af8c1743b
--- /dev/null
+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.test.tsx
@@ -0,0 +1,111 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { GFS_MARKDOWN_PREVIEW_MAX_BYTES } from '@constants/gfsMarkdownPreview'
+import { GfsMarkdownPreviewBody } from './Body'
+
+// Mirror the producer shape: `window.clerum.gfs.download` → `{ bytes: ArrayBuffer }`.
+function stubDownload(text: string) {
+ const download = vi.fn(async () => ({ bytes: new TextEncoder().encode(text).buffer }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { download } },
+ })
+ return download
+}
+
+describe('GfsMarkdownPreviewBody', () => {
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ it('renders markdown with safe vanilla rendering (no modal, no unsafe links or scripts)', async () => {
+ const markdown =
+ '# Project guide\n\nUse **safe rendering**.\n\n1. First\n2. Second\n\n[Unsafe](javascript:alert)\n\n<script>alert("no")</script>'
+ const download = stubDownload(markdown)
+
+ const { container } = render(
+ <GfsMarkdownPreviewBody
+ byteLength={markdown.length}
+ fileName="README.md"
+ gfsUri="gfs://main/markdown-1"
+ />
+ )
+
+ expect(await screen.findByRole('heading', { name: 'Project guide', level: 1 })).toBeTruthy()
+ expect(screen.getByText('safe rendering').tagName).toBe('STRONG')
+ expect(screen.getAllByRole('listitem')).toHaveLength(2)
+ expect(screen.getByText('Unsafe').closest('a')).toBeNull()
+ expect(container.querySelector('script')).toBeNull()
+ expect(download).toHaveBeenCalledWith('gfs://main/markdown-1')
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+
+ it('renders a .txt file as plain text', async () => {
+ stubDownload('line one\nline two\twith tab')
+ render(
+ <GfsMarkdownPreviewBody byteLength={26} fileName="notes.txt" gfsUri="gfs://main/text-1" />
+ )
+ const pre = await screen.findByText(/line one/)
+ expect(pre.tagName).toBe('PRE')
+ expect(pre.textContent).toContain('line two\twith tab')
+ })
+
+ it('copies the source to the clipboard from the header button', async () => {
+ const writeText = vi.fn(async () => undefined)
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { ...(navigator.clipboard ?? {}), writeText },
+ })
+ const markdown = '# Hello\n\nGreetings.'
+ stubDownload(markdown)
+
+ render(
+ <GfsMarkdownPreviewBody
+ byteLength={markdown.length}
+ fileName="README.md"
+ gfsUri="gfs://main/markdown-2"
+ />
+ )
+ const copyButton = await screen.findByRole('button', {
+ name: /Copy preview contents to clipboard/i,
+ })
+ fireEvent.click(copyButton)
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith(markdown))
+ })
+
+ it('rejects an oversized markdown file from metadata before downloading', async () => {
+ const download = stubDownload('x')
+ render(
+ <GfsMarkdownPreviewBody
+ byteLength={GFS_MARKDOWN_PREVIEW_MAX_BYTES + 1}
+ fileName="oversized.md"
+ gfsUri="gfs://main/oversized"
+ />
+ )
+ expect(await screen.findByText(/Markdown previews are limited to 2 MB/)).toBeTruthy()
+ expect(download).not.toHaveBeenCalled()
+ })
+
+ it('fails closed on a download error and notifies onDownloadError', async () => {
+ const onDownloadError = vi.fn()
+ const download = vi.fn(async () => {
+ throw new Error('401 not authenticated')
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { download } },
+ })
+ render(
+ <GfsMarkdownPreviewBody
+ byteLength={5}
+ fileName="README.md"
+ gfsUri="gfs://main/markdown-3"
+ onDownloadError={onDownloadError}
+ />
+ )
+ expect(await screen.findByText('401 not authenticated')).toBeTruthy()
+ await waitFor(() => expect(onDownloadError).toHaveBeenCalled())
+ })
+})
diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx
index 9c4ad8c75..51755f303 100644
--- a/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx
+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx
@@ -1,241 +1,6 @@
-import { Fragment, useEffect, useId, useMemo, useRef, useState } from 'react'
-import type { ReactNode } from 'react'
-import { createPortal } from 'react-dom'
-import { Button, StatusBanner } from '@components/Common'
-import { IconClose, IconCopy } from '@components/SidebarNav/icons'
-import { useWorkspaceModalStyle } from '@hooks/useWorkspaceModalStyle'
-import { assertGfsMarkdownPreviewSize } from '@lib/gfsMarkdownPreview'
-import { parseVanillaMarkdown } from '@lib/vanillaMarkdown'
-import type { MarkdownBlock, MarkdownInlineNode } from '@lib/vanillaMarkdown.types'
-import type { GfsMarkdownPreviewProps } from './types'
-
-function isPlainTextName(fileName: string): boolean {
- return fileName.toLowerCase().endsWith('.txt')
-}
-
-function renderInlineNodes(nodes: MarkdownInlineNode[]): ReactNode[] {
- return nodes.map(node => {
- if (node.kind === 'text') return <Fragment key={node.id}>{node.value}</Fragment>
- if (node.kind === 'code') return <code key={node.id}>{node.value}</code>
- const children = renderInlineNodes(node.children)
- if (node.kind === 'strong') return <strong key={node.id}>{children}</strong>
- if (node.kind === 'emphasis') return <em key={node.id}>{children}</em>
- if (node.kind === 'strikethrough') return <s key={node.id}>{children}</s>
- return node.href ? (
- <a href={node.href} key={node.id} rel="noreferrer" target="_blank">
- {children}
- </a>
- ) : (
- <span key={node.id}>{children}</span>
- )
- })
-}
-
-function renderHeading(block: Extract<MarkdownBlock, { kind: 'heading' }>): ReactNode {
- const children = renderInlineNodes(block.children)
- if (block.level === 1) return <h1 key={block.id}>{children}</h1>
- if (block.level === 2) return <h2 key={block.id}>{children}</h2>
- if (block.level === 3) return <h3 key={block.id}>{children}</h3>
- if (block.level === 4) return <h4 key={block.id}>{children}</h4>
- if (block.level === 5) return <h5 key={block.id}>{children}</h5>
- return <h6 key={block.id}>{children}</h6>
-}
-
-function renderBlock(block: MarkdownBlock): ReactNode {
- if (block.kind === 'heading') return renderHeading(block)
- if (block.kind === 'paragraph') {
- return <p key={block.id}>{renderInlineNodes(block.children)}</p>
- }
- if (block.kind === 'blockquote') {
- return <blockquote key={block.id}>{renderInlineNodes(block.children)}</blockquote>
- }
- if (block.kind === 'divider') return <hr key={block.id} />
- if (block.kind === 'code') {
- return (
- <pre key={block.id}>
- <code data-language={block.language ?? undefined}>{block.value}</code>
- </pre>
- )
- }
- const items = block.items.map(item => <li key={item.id}>{renderInlineNodes(item.children)}</li>)
- return block.ordered ? <ol key={block.id}>{items}</ol> : <ul key={block.id}>{items}</ul>
-}
-
-export function GfsMarkdownPreview({
- byteLength,
- fileName,
- gfsUri,
- onClose,
- onDownloadError,
-}: GfsMarkdownPreviewProps) {
- const titleId = useId()
- const closeButtonRef = useRef<HTMLButtonElement | null>(null)
- const [source, setSource] = useState<string | null>(null)
- const [previewError, setPreviewError] = useState<string | null>(null)
- const [copyState, setCopyState] = useState<'idle' | 'copied' | 'error'>('idle')
- const backdropStyle = useWorkspaceModalStyle()
- const copyResetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
- const mountedRef = useRef(true)
- const onDownloadErrorRef = useRef(onDownloadError)
- const blocks = useMemo(() => (source === null ? [] : parseVanillaMarkdown(source)), [source])
- const isPlainText = isPlainTextName(fileName)
-
- useEffect(() => {
- onDownloadErrorRef.current = onDownloadError
- }, [onDownloadError])
-
- useEffect(() => {
- mountedRef.current = true
- return () => {
- mountedRef.current = false
- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)
- }
- }, [])
-
- useEffect(() => {
- closeButtonRef.current?.focus()
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.key === 'Escape') onClose()
- }
- window.addEventListener('keydown', handleKeyDown)
- return () => window.removeEventListener('keydown', handleKeyDown)
- }, [onClose])
-
- useEffect(() => {
- let active = true
-
- const loadPreview = async () => {
- try {
- assertGfsMarkdownPreviewSize(byteLength)
- const { bytes } = await window.clerum.gfs.download(gfsUri)
- assertGfsMarkdownPreviewSize(bytes.byteLength)
- const markdown = new TextDecoder().decode(bytes)
- if (active) setSource(markdown)
- } catch (error) {
- if (!active) return
- onDownloadErrorRef.current?.(error)
- setPreviewError(
- error instanceof Error ? error.message : 'Could not load the Markdown preview'
- )
- }
- }
-
- void loadPreview()
- return () => {
- active = false
- }
- }, [byteLength, gfsUri])
-
- function markCopyState(state: 'copied' | 'error'): boolean {
- if (!mountedRef.current) return false
- setCopyState(state)
- if (copyResetTimeoutRef.current) clearTimeout(copyResetTimeoutRef.current)
- copyResetTimeoutRef.current = setTimeout(() => {
- if (mountedRef.current) setCopyState('idle')
- }, 2000)
- return true
- }
-
- async function copySourceToClipboard(): Promise<void> {
- if (source === null || !mountedRef.current) return
- try {
- if (navigator.clipboard?.writeText) {
- await navigator.clipboard.writeText(source)
- if (!mountedRef.current) return
- markCopyState('copied')
- } else {
- markCopyState('error')
- }
- } catch {
- markCopyState('error')
- }
- }
-
- return createPortal(
- <div
- className="da-gfs-markdown-preview-modal"
- role="presentation"
- style={backdropStyle}
- onMouseDown={event => {
- if (event.target === event.currentTarget) onClose()
- }}
- >
- <section
- className="da-gfs-markdown-preview-dialog"
- role="dialog"
- aria-modal="true"
- aria-labelledby={titleId}
- >
- <header className="da-gfs-markdown-preview-dialog__header">
- <h3 id={titleId}>{fileName}</h3>
- <div className="da-gfs-markdown-preview-dialog__header-actions">
- <Button
- className="da-gfs-markdown-preview-dialog__copy"
- aria-label={
- copyState === 'copied'
- ? 'Copied preview contents to clipboard'
- : 'Copy preview contents to clipboard'
- }
- color="neutral"
- disabled={source === null}
- onClick={() => void copySourceToClipboard()}
- variant="ghost"
- >
- <IconCopy width={18} height={18} />
- <span className="da-gfs-preview-button__label">
- {copyState === 'copied' ? 'Copied' : 'Copy'}
- </span>
- </Button>
- <Button
- className="da-gfs-markdown-preview-dialog__close"
- data-preview-close
- ref={closeButtonRef}
- aria-label="Close preview"
- color="neutral"
- onClick={onClose}
- variant="ghost"
- >
- <IconClose width={18} height={18} />
- </Button>
- </div>
- </header>
- <div className="da-gfs-markdown-preview-dialog__body">
- {previewError ? <StatusBanner tone="error" text={previewError} /> : null}
- {!previewError && source === null ? (
- <div className="da-gfs-markdown-preview-dialog__loading" role="status">
- Loading preview…
- </div>
- ) : null}
- {source !== null && !previewError ? (
- isPlainText ? (
- <article
- aria-label={`Text preview of ${fileName}`}
- className="da-gfs-text-preview__content"
- >
- {source.length > 0 ? (
- <pre className="da-gfs-text-preview__body">{source}</pre>
- ) : (
- <p className="da-gfs-markdown-preview__empty">This text file is empty.</p>
- )}
- </article>
- ) : (
- <article
- aria-label={`Markdown preview of ${fileName}`}
- className="da-gfs-markdown-preview__content markdown-content"
- >
- {blocks.length > 0 ? (
- blocks.map(renderBlock)
- ) : (
- <p className="da-gfs-markdown-preview__empty">This Markdown file is empty.</p>
- )}
- </article>
- )
- ) : null}
- </div>
- </section>
- </div>,
- document.body
- )
-}
-
-export type { GfsMarkdownPreviewProps } from './types'
+// The markdown/text preview no longer has a modal wrapper (spec 18 §3.B.2/§3.B.4):
+// FilesPage opens previews in a workspace tab via FilePreviewPage, which mounts
+// the de-modalized body directly. This module stays as the public barrel so
+// `@components/GfsMarkdownPreview` keeps resolving to the body.
+export { GfsMarkdownPreviewBody } from './Body'
+export type { GfsMarkdownPreviewBodyProps } from './types'
diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/types.ts b/desktop-app/ui/src/components/GfsMarkdownPreview/types.ts
index a35970ca1..d3fd297f4 100644
--- a/desktop-app/ui/src/components/GfsMarkdownPreview/types.ts
+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/types.ts
@@ -1,7 +1,16 @@
-export type GfsMarkdownPreviewProps = {
+import type { ReactNode } from 'react'
+
+/**
+ * De-modalized markdown/text preview body (spec 18 §3.B.2): the rendered
+ * `<article>` + its fetch, copy, and size-guard, without modal chrome. Shared by
+ * the surviving modal and `FilePreviewPage`.
+ */
+export type GfsMarkdownPreviewBodyProps = {
byteLength: number
fileName: string
gfsUri: string
- onClose: () => void
onDownloadError?: (error: unknown) => void
+ titleId?: string
+ headerActions?: ReactNode
+ headingLevel?: 2 | 3
}
diff --git a/desktop-app/ui/src/components/GfsPreviewWorkspaceLayout.test.tsx b/desktop-app/ui/src/components/GfsPreviewWorkspaceLayout.test.tsx
deleted file mode 100644
index a22768024..000000000
--- a/desktop-app/ui/src/components/GfsPreviewWorkspaceLayout.test.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, render, screen, waitFor } from '@testing-library/react'
-import { GfsMarkdownPreview } from '@components/GfsMarkdownPreview'
-import { GfsVideoPreview } from '@components/GfsVideoPreview'
-
-describe('GFS workspace-aware preview layout', () => {
- let sidebar: HTMLElement
- let sidebarRight = 74
- let resizeObserverCallback: (() => void) | null = null
-
- beforeEach(() => {
- Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 })
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: {
- gfs: {
- download: vi.fn(async () => ({
- bytes: new TextEncoder().encode('# Preview\nBody').buffer,
- })),
- },
- },
- })
- Object.defineProperty(URL, 'createObjectURL', {
- configurable: true,
- value: vi.fn(() => 'blob:gfs-video-preview'),
- })
- Object.defineProperty(URL, 'revokeObjectURL', {
- configurable: true,
- value: vi.fn(),
- })
-
- sidebar = document.createElement('aside')
- sidebar.className = 'left-nav collapsed'
- vi.spyOn(sidebar, 'getBoundingClientRect').mockImplementation(
- () =>
- ({
- right: sidebarRight,
- width: sidebarRight,
- height: 800,
- }) as DOMRect
- )
- document.body.appendChild(sidebar)
-
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- constructor(callback: () => void) {
- resizeObserverCallback = callback
- }
-
- observe() {}
-
- disconnect() {}
- }
- )
- })
-
- afterEach(() => {
- cleanup()
- sidebar.remove()
- sidebarRight = 74
- resizeObserverCallback = null
- vi.unstubAllGlobals()
- vi.restoreAllMocks()
- })
-
- it.each([
- ['plain text', 'notes.txt'],
- ['Markdown', 'readme.md'],
- ['video', 'demo.mp4'],
- ])('keeps the %s preview clear of an expanding sidebar', async (kind, fileName) => {
- if (kind === 'video') {
- render(
- <GfsVideoPreview
- byteLength={14}
- fileName={fileName}
- gfsUri="gfs://main/file-1"
- mimeType="video/mp4"
- onClose={vi.fn()}
- />
- )
- } else {
- render(
- <GfsMarkdownPreview
- byteLength={14}
- fileName={fileName}
- gfsUri="gfs://main/file-1"
- onClose={vi.fn()}
- />
- )
- }
-
- const modal = screen.getByRole('presentation') as HTMLElement
- expect(modal.style.left).toBe('74px')
- expect(modal.style.right).toBe('0px')
-
- sidebarRight = 328
- sidebar.classList.remove('collapsed')
- resizeObserverCallback?.()
-
- await waitFor(() => {
- expect(modal.style.left).toBe('328px')
- expect(modal.style.right).toBe('0px')
- })
- })
-})
diff --git a/desktop-app/ui/src/components/GfsVideoPreview/Body.tsx b/desktop-app/ui/src/components/GfsVideoPreview/Body.tsx
new file mode 100644
index 000000000..6ed221f75
--- /dev/null
+++ b/desktop-app/ui/src/components/GfsVideoPreview/Body.tsx
@@ -0,0 +1,87 @@
+import { useEffect, useId, useRef, useState } from 'react'
+import { StatusBanner } from '@components/Common'
+import { assertGfsVideoPreviewSize } from '@lib/gfsVideoPreview'
+import type { GfsVideoPreviewBodyProps } from './types'
+
+/**
+ * De-modalized video preview body (spec 18 §3.B.2). Owns the byte fetch (by
+ * `gfsUri`), the size-guard, and the rendered `<video>` + loading/error states.
+ * Renders no modal chrome. Fails closed: a download error both shows the reason
+ * and is routed to `onDownloadError`.
+ */
+export function GfsVideoPreviewBody({
+ byteLength,
+ fileName,
+ gfsUri,
+ mimeType,
+ onDownloadError,
+ titleId,
+ headerActions,
+ headingLevel = 3,
+}: GfsVideoPreviewBodyProps) {
+ const generatedTitleId = useId()
+ const headingId = titleId ?? generatedTitleId
+ const [previewUrl, setPreviewUrl] = useState<string | null>(null)
+ const [previewError, setPreviewError] = useState<string | null>(null)
+ const onDownloadErrorRef = useRef(onDownloadError)
+ const HeadingTag = `h${headingLevel}` as const
+
+ useEffect(() => {
+ onDownloadErrorRef.current = onDownloadError
+ }, [onDownloadError])
+
+ useEffect(() => {
+ let active = true
+ let objectUrl: string | null = null
+
+ const loadPreview = async () => {
+ try {
+ assertGfsVideoPreviewSize(byteLength)
+ const { bytes } = await window.clerum.gfs.download(gfsUri)
+ assertGfsVideoPreviewSize(bytes.byteLength)
+ if (!active) return
+ objectUrl = URL.createObjectURL(new Blob([bytes], { type: mimeType }))
+ setPreviewUrl(objectUrl)
+ } catch (error) {
+ if (!active) return
+ onDownloadErrorRef.current?.(error)
+ setPreviewError(error instanceof Error ? error.message : 'Could not load the video preview')
+ }
+ }
+
+ void loadPreview()
+ return () => {
+ active = false
+ if (objectUrl) URL.revokeObjectURL(objectUrl)
+ }
+ }, [byteLength, gfsUri, mimeType])
+
+ return (
+ <>
+ <header className="da-gfs-video-preview-dialog__header">
+ <HeadingTag className="da-gfs-preview-title" id={headingId}>
+ {fileName}
+ </HeadingTag>
+ {headerActions}
+ </header>
+ <div className="da-gfs-video-preview-dialog__body">
+ {previewError ? <StatusBanner tone="error" text={previewError} /> : null}
+ {!previewError && !previewUrl ? (
+ <div className="da-gfs-video-preview-dialog__loading" role="status">
+ Loading video preview…
+ </div>
+ ) : null}
+ {previewUrl && !previewError ? (
+ <video
+ aria-label={`Video preview of ${fileName}`}
+ className="da-gfs-video-preview-dialog__video"
+ controls
+ onError={() => setPreviewError('This video could not be played by your browser')}
+ preload="metadata"
+ src={previewUrl}
+ />
+ ) : null}
+ </div>
+ </>
+ )
+}
diff --git a/desktop-app/ui/src/components/GfsVideoPreview/GfsVideoPreviewBody.test.tsx b/desktop-app/ui/src/components/GfsVideoPreview/GfsVideoPreviewBody.test.tsx
new file mode 100644
index 000000000..3670ca63b
--- /dev/null
+++ b/desktop-app/ui/src/components/GfsVideoPreview/GfsVideoPreviewBody.test.tsx
@@ -0,0 +1,88 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { GFS_VIDEO_PREVIEW_MAX_BYTES } from '@constants/gfsVideoPreview'
+import { GfsVideoPreviewBody } from './Body'
+
+function stubDownload(bytes: ArrayBuffer) {
+ const download = vi.fn(async () => ({ bytes }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { download } },
+ })
+ return download
+}
+
+describe('GfsVideoPreviewBody', () => {
+ beforeEach(() => {
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ value: vi.fn(() => 'blob:gfs-video-preview'),
+ })
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ it('downloads by gfsUri and renders an HTML5 video without a modal', async () => {
+ const createObjectURL = vi.fn(() => 'blob:gfs-video-preview')
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL })
+ const download = stubDownload(new Uint8Array([1, 2, 3]).buffer)
+
+ render(
+ <GfsVideoPreviewBody
+ byteLength={3}
+ fileName="demo.mp4"
+ gfsUri="gfs://main/video-1"
+ mimeType="video/mp4"
+ />
+ )
+
+ const video = await screen.findByLabelText('Video preview of demo.mp4')
+ expect(video.tagName).toBe('VIDEO')
+ expect(video.getAttribute('controls')).not.toBeNull()
+ expect(video.getAttribute('src')).toBe('blob:gfs-video-preview')
+ expect(createObjectURL).toHaveBeenCalledWith(expect.objectContaining({ type: 'video/mp4' }))
+ expect(download).toHaveBeenCalledWith('gfs://main/video-1')
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+
+ it('rejects an oversized video from metadata before downloading', async () => {
+ const download = stubDownload(new Uint8Array([1]).buffer)
+ render(
+ <GfsVideoPreviewBody
+ byteLength={GFS_VIDEO_PREVIEW_MAX_BYTES + 1}
+ fileName="oversized.mp4"
+ gfsUri="gfs://main/oversized"
+ mimeType="video/mp4"
+ />
+ )
+ expect(await screen.findByText(/Video previews are limited to 100 MB/)).toBeTruthy()
+ expect(download).not.toHaveBeenCalled()
+ })
+
+ it('fails closed on a download error and notifies onDownloadError', async () => {
+ const onDownloadError = vi.fn()
+ const download = vi.fn(async () => {
+ throw new Error('403 Forbidden')
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { download } },
+ })
+ render(
+ <GfsVideoPreviewBody
+ byteLength={3}
+ fileName="secret.mp4"
+ gfsUri="gfs://main/secret"
+ mimeType="video/mp4"
+ onDownloadError={onDownloadError}
+ />
+ )
+ expect(await screen.findByText('403 Forbidden')).toBeTruthy()
+ await waitFor(() => expect(onDownloadError).toHaveBeenCalled())
+ })
+})
diff --git a/desktop-app/ui/src/components/GfsVideoPreview/index.tsx b/desktop-app/ui/src/components/GfsVideoPreview/index.tsx
index 51cd9fe86..f9991f41d 100644
--- a/desktop-app/ui/src/components/GfsVideoPreview/index.tsx
+++ b/desktop-app/ui/src/components/GfsVideoPreview/index.tsx
@@ -1,116 +1,6 @@
-import { useEffect, useId, useRef, useState } from 'react'
-import { createPortal } from 'react-dom'
-import { Button, StatusBanner } from '@components/Common'
-import { IconClose } from '@components/SidebarNav/icons'
-import { useWorkspaceModalStyle } from '@hooks/useWorkspaceModalStyle'
-import { assertGfsVideoPreviewSize } from '@lib/gfsVideoPreview'
-import type { GfsVideoPreviewProps } from './types'
-
-export function GfsVideoPreview({
- byteLength,
- fileName,
- gfsUri,
- mimeType,
- onClose,
- onDownloadError,
-}: GfsVideoPreviewProps) {
- const titleId = useId()
- const closeButtonRef = useRef<HTMLButtonElement | null>(null)
- const [previewUrl, setPreviewUrl] = useState<string | null>(null)
- const [previewError, setPreviewError] = useState<string | null>(null)
- const backdropStyle = useWorkspaceModalStyle()
- const onDownloadErrorRef = useRef(onDownloadError)
-
- useEffect(() => {
- onDownloadErrorRef.current = onDownloadError
- }, [onDownloadError])
-
- useEffect(() => {
- closeButtonRef.current?.focus()
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.key === 'Escape') onClose()
- }
- window.addEventListener('keydown', handleKeyDown)
- return () => window.removeEventListener('keydown', handleKeyDown)
- }, [onClose])
-
- useEffect(() => {
- let active = true
- let objectUrl: string | null = null
-
- const loadPreview = async () => {
- try {
- assertGfsVideoPreviewSize(byteLength)
- const { bytes } = await window.clerum.gfs.download(gfsUri)
- assertGfsVideoPreviewSize(bytes.byteLength)
- if (!active) return
- objectUrl = URL.createObjectURL(new Blob([bytes], { type: mimeType }))
- setPreviewUrl(objectUrl)
- } catch (error) {
- if (!active) return
- onDownloadErrorRef.current?.(error)
- setPreviewError(error instanceof Error ? error.message : 'Could not load the video preview')
- }
- }
-
- void loadPreview()
- return () => {
- active = false
- if (objectUrl) URL.revokeObjectURL(objectUrl)
- }
- }, [byteLength, gfsUri, mimeType])
-
- return createPortal(
- <div
- className="da-gfs-video-preview-modal"
- role="presentation"
- style={backdropStyle}
- onMouseDown={event => {
- if (event.target === event.currentTarget) onClose()
- }}
- >
- <section
- className="da-gfs-video-preview-dialog"
- role="dialog"
- aria-modal="true"
- aria-labelledby={titleId}
- >
- <header className="da-gfs-video-preview-dialog__header">
- <h3 id={titleId}>{fileName}</h3>
- <Button
- className="da-gfs-video-preview-dialog__close"
- data-preview-close
- ref={closeButtonRef}
- aria-label="Close video preview"
- color="neutral"
- onClick={onClose}
- variant="ghost"
- >
- <IconClose width={18} height={18} />
- </Button>
- </header>
- <div className="da-gfs-video-preview-dialog__body">
- {previewError ? <StatusBanner tone="error" text={previewError} /> : null}
- {!previewError && !previewUrl ? (
- <div className="da-gfs-video-preview-dialog__loading" role="status">
- Loading video preview…
- </div>
- ) : null}
- {previewUrl && !previewError ? (
- <video
- aria-label={`Video preview of ${fileName}`}
- className="da-gfs-video-preview-dialog__video"
- controls
- onError={() => setPreviewError('This video could not be played by your browser')}
- preload="metadata"
- src={previewUrl}
- />
- ) : null}
- </div>
- </section>
- </div>,
- document.body
- )
-}
-
-export type { GfsVideoPreviewProps } from './types'
+// The video preview no longer has a modal wrapper (spec 18 §3.B.2/§3.B.4):
+// FilesPage opens previews in a workspace tab via FilePreviewPage, which mounts
+// the de-modalized body directly. This module stays as the public barrel so
+// `@components/GfsVideoPreview` keeps resolving to the body.
+export { GfsVideoPreviewBody } from './Body'
+export type { GfsVideoPreviewBodyProps } from './types'
diff --git a/desktop-app/ui/src/components/GfsVideoPreview/types.ts b/desktop-app/ui/src/components/GfsVideoPreview/types.ts
index 2b7b5e105..f7efd8923 100644
--- a/desktop-app/ui/src/components/GfsVideoPreview/types.ts
+++ b/desktop-app/ui/src/components/GfsVideoPreview/types.ts
@@ -1,8 +1,17 @@
-export type GfsVideoPreviewProps = {
+import type { ReactNode } from 'react'
+
+/**
+ * De-modalized video preview body (spec 18 §3.B.2): the `<video>` + its fetch
+ * and size-guard, without modal chrome. Shared by the surviving modal and
+ * `FilePreviewPage`. Video has no copy affordance.
+ */
+export type GfsVideoPreviewBodyProps = {
byteLength: number
fileName: string
gfsUri: string
mimeType: string
- onClose: () => void
onDownloadError?: (error: unknown) => void
+ titleId?: string
+ headerActions?: ReactNode
+ headingLevel?: 2 | 3
}
diff --git a/desktop-app/ui/src/constants/navigation.ts b/desktop-app/ui/src/constants/navigation.ts
index 4c45d46b4..5d99a81ff 100644
--- a/desktop-app/ui/src/constants/navigation.ts
+++ b/desktop-app/ui/src/constants/navigation.ts
@@ -8,6 +8,7 @@ export const DESKTOP_ROUTES = {
agents: 'agents',
connectors: 'mcp-servers',
files: 'files',
+ preview: 'preview',
settings: 'settings',
} as const
diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.workspaceTabs.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.workspaceTabs.test.tsx
index f1812314c..f1d7ff557 100644
--- a/desktop-app/ui/src/hooks/__tests__/useAppController.workspaceTabs.test.tsx
+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.workspaceTabs.test.tsx
@@ -141,4 +141,32 @@ describe('useAppController — universal tab store ports', () => {
await waitFor(() => expect(app.result.current.chatMessagesLoading).toBe(false))
expect(app.result.current.activeChatId).toBe('chat-1')
})
+
+ // (c) openPreviewSection is re-exported through the controller (spec 18): it
+ // opens a preview tab and the derived navItem flips to the preview route in the
+ // same commit — the seam the App render uses to mount FilePreviewPage.
+ it('opens a preview tab and derives the preview route via openPreviewSection', async () => {
+ installAppControllerClerum({ agentNames: ['agent-x'] })
+ const app = renderAppController()
+ unmount = app.unmount
+
+ await waitFor(() => expect(app.result.current.isAuthenticated).toBe(true))
+ await waitFor(() => expect(app.result.current.initialExperienceLoading).toBe(false))
+
+ act(() => {
+ app.result.current.openPreviewSection({
+ gfsUri: 'gfs://main/image-1',
+ kind: 'image',
+ mimeType: 'image/png',
+ name: 'diagram.png',
+ bytes: 3,
+ })
+ })
+
+ expect(app.result.current.navItem).toBe(DESKTOP_ROUTES.preview)
+ const active = activeWorkspaceTab(app.result.current.workspaceTabs)
+ expect(active?.kind).toBe('preview')
+ expect(active?.title).toBe('diagram.png')
+ expect(active?.preview?.gfsUri).toBe('gfs://main/image-1')
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useNavigationController.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/useNavigationController.test.ts
index d9489d12c..b36f3cddc 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useNavigationController.test.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useNavigationController.test.ts
@@ -60,6 +60,55 @@ describe('useNavigationController — agent-centric navigation (Fase 2)', () =>
expect(result.current.lastActiveChatTabId).toBeNull()
})
+ it('openPreviewSection opens a preview tab and derives the preview route (spec 18)', () => {
+ const { result } = renderHook(() => useNavigationController())
+ act(() =>
+ result.current.openPreviewSection({
+ gfsUri: 'gfs://main/image-1',
+ kind: 'image',
+ mimeType: 'image/png',
+ name: 'diagram.png',
+ bytes: 3,
+ })
+ )
+ expect(result.current.activeTab?.kind).toBe('preview')
+ expect(result.current.activeTab?.title).toBe('diagram.png')
+ expect(result.current.activeTab?.preview).toEqual({
+ gfsUri: 'gfs://main/image-1',
+ fileKind: 'image',
+ mimeType: 'image/png',
+ byteLength: 3,
+ })
+ expect(result.current.navItem).toBe(DESKTOP_ROUTES.preview)
+ })
+
+ it('openPreviewSection dedupes by gfsUri: re-opening the same file focuses its tab', () => {
+ const { result } = renderHook(() => useNavigationController())
+ act(() =>
+ result.current.openPreviewSection({
+ gfsUri: 'gfs://main/image-1',
+ kind: 'image',
+ mimeType: 'image/png',
+ name: 'diagram.png',
+ bytes: 3,
+ })
+ )
+ const firstId = result.current.activeTab?.id
+ // Navigate away, then re-open the same file: it focuses the existing tab.
+ act(() => result.current.handleNavSelect(DESKTOP_ROUTES.files))
+ act(() =>
+ result.current.openPreviewSection({
+ gfsUri: 'gfs://main/image-1',
+ kind: 'image',
+ mimeType: 'image/png',
+ name: 'diagram.png',
+ bytes: 3,
+ })
+ )
+ expect(result.current.activeTab?.id).toBe(firstId)
+ expect(result.current.workspaceTabs.tabs.filter(t => t.kind === 'preview')).toHaveLength(1)
+ })
+
it('no longer exposes the removed context/teams handlers or state', () => {
const { result } = renderHook(() => useNavigationController())
const controller = result.current as Record<string, unknown>
diff --git a/desktop-app/ui/src/hooks/domain/useNavigationController.ts b/desktop-app/ui/src/hooks/domain/useNavigationController.ts
index 1fae40d43..5b533f427 100644
--- a/desktop-app/ui/src/hooks/domain/useNavigationController.ts
+++ b/desktop-app/ui/src/hooks/domain/useNavigationController.ts
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { AGENT_WORKSPACE_ROUTES, DESKTOP_ROUTES } from '../../constants/navigation'
+import type { GfsPreviewResource } from '../../lib/gfsPreview'
import {
activeWorkspaceTab,
createWorkspaceTabsState,
newChatTab,
openChatTab,
openFilesTab,
+ openPreviewTab,
openSettingsTab,
} from '../../lib/workspaceTabs'
import type { WorkspaceTabsState } from '../../lib/workspaceTabs.types'
@@ -148,6 +150,27 @@ export function useNavigationController() {
[nextWorkspaceTabId]
)
+ // Open/focus a preview tab for a previewable file (spec 18 §3.B.1). Dedupes by
+ // gfsUri in the store: opening the same file twice focuses its existing tab
+ // instead of stacking duplicates. A direct clone of `openFilesSection`.
+ const openPreviewSection = useCallback(
+ (preview: GfsPreviewResource) => {
+ setAppsPickerActive(false)
+ const id = nextWorkspaceTabId()
+ setWorkspaceTabs(current =>
+ openPreviewTab(current, {
+ id,
+ title: preview.name,
+ gfsUri: preview.gfsUri,
+ fileKind: preview.kind,
+ byteLength: preview.bytes,
+ ...('mimeType' in preview ? { mimeType: preview.mimeType } : {}),
+ })
+ )
+ },
+ [nextWorkspaceTabId]
+ )
+
// Base section navigation: every legacy `handleNavSelect(route)` call-site
// routes here and becomes an open/focus tab action (the single writer). For
// `chat`/`agents` it also clears `selectedAgent` exactly as before.
@@ -200,6 +223,7 @@ export function useNavigationController() {
activateChatTab,
lastActiveChatTabId,
openFilesSection,
+ openPreviewSection,
// Agent/chat selection state (stays here through this slice; §4).
selectedAgent,
selectedAgentRoute,
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index bfe29b13d..1e8405c4c 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -1351,6 +1351,7 @@ export function useAppController() {
activateWorkspaceChatTab: nav.activateChatTab,
lastActiveChatTabId: nav.lastActiveChatTabId,
openFilesSection: nav.openFilesSection,
+ openPreviewSection: nav.openPreviewSection,
handleOpenAgentWorkspace,
handleSelectChatAgent,
handleEnsureTeamContext: ensureTeamContext,
diff --git a/desktop-app/ui/src/lib/__tests__/gfsPreview.test.ts b/desktop-app/ui/src/lib/__tests__/gfsPreview.test.ts
new file mode 100644
index 000000000..fdd7c3240
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/gfsPreview.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest'
+import { isGfsPreviewFile, resolveGfsPreview } from '../gfsPreview'
+
+const resource = (name: string) => ({ name, gfsUri: `gfs://main/${name}`, bytes: 10 })
+
+describe('gfsPreview — resolveGfsPreview', () => {
+ it('detects an image and carries its mimeType (case-insensitive extension)', () => {
+ expect(resolveGfsPreview(resource('diagram.PNG'))).toEqual({
+ gfsUri: 'gfs://main/diagram.PNG',
+ kind: 'image',
+ mimeType: 'image/png',
+ name: 'diagram.PNG',
+ bytes: 10,
+ })
+ })
+
+ it('detects markdown with no mimeType field', () => {
+ const preview = resolveGfsPreview(resource('README.md'))
+ expect(preview).toEqual({
+ gfsUri: 'gfs://main/README.md',
+ kind: 'markdown',
+ name: 'README.md',
+ bytes: 10,
+ })
+ expect(Object.prototype.hasOwnProperty.call(preview, 'mimeType')).toBe(false)
+ })
+
+ it('detects a video and carries its mimeType', () => {
+ expect(resolveGfsPreview(resource('demo.mp4'))).toEqual({
+ gfsUri: 'gfs://main/demo.mp4',
+ kind: 'video',
+ mimeType: 'video/mp4',
+ name: 'demo.mp4',
+ bytes: 10,
+ })
+ })
+
+ it('treats .txt as a (markdown-kind) previewable text file', () => {
+ expect(resolveGfsPreview(resource('notes.txt'))?.kind).toBe('markdown')
+ })
+
+ it('returns null for a non-previewable file (caller downloads instead)', () => {
+ expect(resolveGfsPreview(resource('archive.zip'))).toBeNull()
+ expect(resolveGfsPreview(resource('no-extension'))).toBeNull()
+ })
+})
+
+describe('gfsPreview — isGfsPreviewFile', () => {
+ it('mirrors resolveGfsPreview for the extension-only gate', () => {
+ expect(isGfsPreviewFile('diagram.png')).toBe(true)
+ expect(isGfsPreviewFile('README.md')).toBe(true)
+ expect(isGfsPreviewFile('demo.mp4')).toBe(true)
+ expect(isGfsPreviewFile('archive.zip')).toBe(false)
+ expect(isGfsPreviewFile('no-extension')).toBe(false)
+ })
+})
diff --git a/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts b/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts
index 87e77c4d3..d75a39c21 100644
--- a/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts
@@ -12,6 +12,7 @@ import {
openAppTab,
openChatTab,
openFilesTab,
+ openPreviewTab,
openSettingsTab,
reconcileWorkspaceChatTab,
reorderWorkspaceTab,
@@ -315,6 +316,141 @@ describe('workspaceTabs — files multi-instance by path (mini-spec 06 §3)', ()
})
})
+describe('workspaceTabs — preview multi-instance by gfsUri (spec 18 §3.B.1)', () => {
+ const previewInput = (id: string, gfsUri: string, title?: string) => ({
+ id,
+ gfsUri,
+ fileKind: 'image' as const,
+ mimeType: 'image/png',
+ byteLength: 3,
+ ...(title !== undefined ? { title } : {}),
+ })
+
+ it('opens distinct tabs for distinct gfsUris and dedupes (focuses) the same gfsUri', () => {
+ let state = createEmptyWorkspaceTabsState()
+ state = openPreviewTab(state, previewInput('p-a', 'gfs://main/aaa', 'A.png'))
+ state = openPreviewTab(state, previewInput('p-b', 'gfs://main/bbb', 'B.png'))
+ expect(state.tabs.filter(t => t.kind === 'preview')).toHaveLength(2)
+ expect(state.activeTabId).toBe('p-b')
+
+ // Re-opening an existing gfsUri FOCUSES it — no new tab (retiro del modal:
+ // double-open of the same file focuses the existing preview tab).
+ const before = state.tabs.length
+ state = openPreviewTab(state, previewInput('p-a-again', 'gfs://main/aaa', 'A.png'))
+ expect(state.tabs.length).toBe(before)
+ expect(state.activeTabId).toBe('p-a')
+ expect(state.tabs.filter(t => t.kind === 'preview')).toHaveLength(2)
+ })
+
+ it('carries the payload and title on a newly created preview tab', () => {
+ let state = createEmptyWorkspaceTabsState()
+ state = openPreviewTab(state, {
+ id: 'p-1',
+ gfsUri: 'gfs://main/clip',
+ fileKind: 'video',
+ mimeType: 'video/mp4',
+ byteLength: 42,
+ title: 'clip.mp4',
+ })
+ const tab = state.tabs.find(t => t.id === 'p-1')
+ expect(tab?.kind).toBe('preview')
+ expect(tab?.title).toBe('clip.mp4')
+ expect(tab?.preview).toEqual({
+ gfsUri: 'gfs://main/clip',
+ fileKind: 'video',
+ mimeType: 'video/mp4',
+ byteLength: 42,
+ })
+ })
+
+ it('omits mimeType from the payload when absent (markdown has none)', () => {
+ let state = createEmptyWorkspaceTabsState()
+ state = openPreviewTab(state, {
+ id: 'p-md',
+ gfsUri: 'gfs://main/readme',
+ fileKind: 'markdown',
+ byteLength: 12,
+ title: 'README.md',
+ })
+ const preview = state.tabs.find(t => t.id === 'p-md')?.preview
+ expect(preview).toEqual({ gfsUri: 'gfs://main/readme', fileKind: 'markdown', byteLength: 12 })
+ expect(Object.prototype.hasOwnProperty.call(preview, 'mimeType')).toBe(false)
+ })
+
+ it('aligns the title when focusing an existing gfsUri; a same-title re-open is a no-op (same ref)', () => {
+ let state = createEmptyWorkspaceTabsState()
+ state = openPreviewTab(state, previewInput('p-a', 'gfs://main/aaa', 'Old.png'))
+ state = openPreviewTab(state, previewInput('p-a2', 'gfs://main/aaa', 'Renamed.png'))
+ expect(state.tabs.filter(t => t.kind === 'preview')).toHaveLength(1)
+ expect(state.tabs.find(t => t.kind === 'preview')?.title).toBe('Renamed.png')
+
+ // Re-open with the same (or no) title preserves the tabs reference so a
+ // setState bails out — mirrors the other open* dedupe branches.
+ const sameTabs = state.tabs
+ expect(openPreviewTab(state, previewInput('p-a3', 'gfs://main/aaa', 'Renamed.png')).tabs).toBe(
+ sameTabs
+ )
+ expect(openPreviewTab(state, previewInput('p-a4', 'gfs://main/aaa')).tabs).toBe(sameTabs)
+ })
+
+ // T2 property: dedupe by gfsUri is an equivalence on the preview sub-slice.
+ it('property: one preview tab per distinct gfsUri; no duplicate ids; insertion order preserved', () => {
+ const uriArb = fc.constantFrom('gfs://main/a', 'gfs://main/b', 'gfs://main/c', 'gfs://main/d')
+ fc.assert(
+ fc.property(fc.array(uriArb, { maxLength: 40 }), uris => {
+ let state = createEmptyWorkspaceTabsState()
+ uris.forEach((gfsUri, i) => {
+ state = openPreviewTab(state, previewInput(`p-${i}`, gfsUri))
+ })
+ const previews = state.tabs.filter(t => t.kind === 'preview')
+ // One tab per DISTINCT gfsUri opened.
+ const distinct = new Set(uris)
+ expect(previews.length).toBe(uris.length === 0 ? 0 : distinct.size)
+ // No two preview tabs share a gfsUri (open-time dedupe).
+ const seen = new Set<string>()
+ for (const t of previews) {
+ const uri = t.preview?.gfsUri ?? ''
+ expect(seen.has(uri)).toBe(false)
+ seen.add(uri)
+ }
+ // No duplicate tab ids overall.
+ const ids = state.tabs.map(t => t.id)
+ expect(new Set(ids).size).toBe(ids.length)
+ // Strip order = the first opener of each distinct gfsUri, in open order.
+ const expectedOrder: string[] = []
+ const seenUris = new Set<string>()
+ uris.forEach((gfsUri, i) => {
+ if (!seenUris.has(gfsUri)) {
+ seenUris.add(gfsUri)
+ expectedOrder.push(`p-${i}`)
+ }
+ })
+ expect(previews.map(t => t.id)).toEqual(expectedOrder)
+ })
+ )
+ })
+
+ // T2 property: idempotence — open(open(s,x),x) === open(s,x); the second open
+ // finds the existing tab, keeps it active, and preserves the tabs reference.
+ it('property: opening the same gfsUri twice is idempotent (same tabs ref)', () => {
+ const uriArb = fc.constantFrom('gfs://main/a', 'gfs://main/b', 'gfs://main/c')
+ fc.assert(
+ fc.property(fc.array(uriArb, { minLength: 1, maxLength: 20 }), fc.nat(30), (uris, pick) => {
+ let state = createEmptyWorkspaceTabsState()
+ uris.forEach((gfsUri, i) => {
+ state = openPreviewTab(state, previewInput(`p-${i}`, gfsUri))
+ })
+ const target = state.tabs[pick % state.tabs.length]!
+ const gfsUri = target.preview?.gfsUri ?? uris[0]!
+ const once = openPreviewTab(state, previewInput('again', gfsUri))
+ const twice = openPreviewTab(once, previewInput('again-2', gfsUri))
+ expect(twice.tabs).toBe(once.tabs)
+ expect(twice.activeTabId).toBe(once.activeTabId)
+ })
+ )
+ })
+})
+
describe('workspaceTabs — new chat (blank) with kind guard', () => {
it('reuses the active blank chat tab (aligns the agent)', () => {
let state = createWorkspaceTabsState('boot', null)
diff --git a/desktop-app/ui/src/lib/__tests__/workspaceTabsRoute.test.ts b/desktop-app/ui/src/lib/__tests__/workspaceTabsRoute.test.ts
index d24cc5d23..abc66bf19 100644
--- a/desktop-app/ui/src/lib/__tests__/workspaceTabsRoute.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/workspaceTabsRoute.test.ts
@@ -17,6 +17,7 @@ describe('workspaceTabsRoute', () => {
expect(mapKindToRoute(tab({ kind: 'chat' }))).toBe(DESKTOP_ROUTES.chat)
expect(mapKindToRoute(tab({ kind: 'app' }))).toBe(DESKTOP_ROUTES.apps)
expect(mapKindToRoute(tab({ kind: 'files' }))).toBe(DESKTOP_ROUTES.files)
+ expect(mapKindToRoute(tab({ kind: 'preview' }))).toBe(DESKTOP_ROUTES.preview)
})
it('maps each settings section to its route', () => {
@@ -55,6 +56,7 @@ describe('workspaceTabsRoute', () => {
expect(settingsSectionForRoute(DESKTOP_ROUTES.chat)).toBeNull()
expect(settingsSectionForRoute(DESKTOP_ROUTES.apps)).toBeNull()
expect(settingsSectionForRoute(DESKTOP_ROUTES.files)).toBeNull()
+ expect(settingsSectionForRoute(DESKTOP_ROUTES.preview)).toBeNull()
})
})
})
diff --git a/desktop-app/ui/src/lib/gfsPreview.ts b/desktop-app/ui/src/lib/gfsPreview.ts
new file mode 100644
index 000000000..0a860b81d
--- /dev/null
+++ b/desktop-app/ui/src/lib/gfsPreview.ts
@@ -0,0 +1,61 @@
+import type { GfsDriveResource } from '../pages/FilesPage.types'
+import { gfsImagePreviewMimeType } from './gfsImagePreview'
+import { isGfsMarkdownPreviewFile } from './gfsMarkdownPreview'
+import { gfsVideoPreviewMimeType } from './gfsVideoPreview'
+
+/**
+ * The minimal shape a preview surface needs to render a GFS file, tagged by the
+ * `kind` it was detected as. Lives here (not in `FilesPage.types.ts`) so BOTH
+ * the files browser (spec 18 S1) and the sidebar file tree (S2) build the same
+ * descriptor from the same detection rule — there is one place that decides
+ * "previewable, and as what" (spec 18 §3.B.2).
+ */
+export type GfsPreviewResource = Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'> &
+ ({ kind: 'image'; mimeType: string } | { kind: 'markdown' } | { kind: 'video'; mimeType: string })
+
+/**
+ * Decide whether a resource is previewable and, if so, as which kind — the
+ * single source of the preview-vs-download branch (spec 18 §3.B.2). Detection is
+ * by file extension via the existing per-kind helpers; the precedence
+ * (image → markdown → video) matches the modal-era `openFilePreview` it
+ * replaces. Returns `null` for anything with no inline preview (the caller
+ * falls back to download).
+ */
+export function resolveGfsPreview(
+ resource: Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'>
+): GfsPreviewResource | null {
+ const imageMimeType = gfsImagePreviewMimeType(resource.name)
+ if (imageMimeType) {
+ return {
+ gfsUri: resource.gfsUri,
+ kind: 'image',
+ mimeType: imageMimeType,
+ name: resource.name,
+ bytes: resource.bytes,
+ }
+ }
+ if (isGfsMarkdownPreviewFile(resource.name)) {
+ return { gfsUri: resource.gfsUri, kind: 'markdown', name: resource.name, bytes: resource.bytes }
+ }
+ const videoMimeType = gfsVideoPreviewMimeType(resource.name)
+ if (videoMimeType) {
+ return {
+ gfsUri: resource.gfsUri,
+ kind: 'video',
+ mimeType: videoMimeType,
+ name: resource.name,
+ bytes: resource.bytes,
+ }
+ }
+ return null
+}
+
+/** Extension-only previewability check (no bytes/gfsUri needed) — the gate for
+ * "show the Preview affordance" on a row/menu. Mirrors `resolveGfsPreview`. */
+export function isGfsPreviewFile(fileName: string): boolean {
+ return (
+ gfsImagePreviewMimeType(fileName) !== null ||
+ isGfsMarkdownPreviewFile(fileName) ||
+ gfsVideoPreviewMimeType(fileName) !== null
+ )
+}
diff --git a/desktop-app/ui/src/lib/workspaceTabs.ts b/desktop-app/ui/src/lib/workspaceTabs.ts
index 1a80bf848..eccf27867 100644
--- a/desktop-app/ui/src/lib/workspaceTabs.ts
+++ b/desktop-app/ui/src/lib/workspaceTabs.ts
@@ -4,6 +4,7 @@ import type {
OpenAppTabInput,
OpenChatTabInput,
OpenFilesTabInput,
+ OpenPreviewTabInput,
OpenSettingsTabInput,
WorkspaceTab,
WorkspaceTabsState,
@@ -279,6 +280,44 @@ export function setFilesTabPath(
}
}
+/**
+ * Preview: multi-instance, deduped by `gfsUri` (spec 18 §3.B.1 — a direct clone
+ * of `openFilesTab`'s open-or-focus). Opening a `gfsUri` that already has a
+ * preview tab FOCUSES it (aligning its title to the current file name);
+ * otherwise a new preview tab is created and activated. Dedupe is applied ONLY
+ * here (open-time), matching every other open* action.
+ */
+export function openPreviewTab(
+ state: WorkspaceTabsState,
+ input: OpenPreviewTabInput
+): WorkspaceTabsState {
+ const existing = state.tabs.find(
+ tab => tab.kind === 'preview' && tab.preview?.gfsUri === input.gfsUri
+ )
+ const title = input.title?.trim()
+ if (existing) {
+ return {
+ tabs:
+ title && existing.title !== title
+ ? state.tabs.map(tab => (tab.id === existing.id ? { ...tab, title } : tab))
+ : state.tabs,
+ activeTabId: existing.id,
+ }
+ }
+ const tab: WorkspaceTab = {
+ id: input.id,
+ kind: 'preview',
+ title: title || 'Preview',
+ preview: {
+ gfsUri: input.gfsUri,
+ fileKind: input.fileKind,
+ byteLength: input.byteLength,
+ ...(input.mimeType !== undefined ? { mimeType: input.mimeType } : {}),
+ },
+ }
+ return { tabs: [...state.tabs, tab], activeTabId: input.id }
+}
+
/** Settings: unique per `section` — focus the existing section tab (R6). */
export function openSettingsTab(
state: WorkspaceTabsState,
diff --git a/desktop-app/ui/src/lib/workspaceTabs.types.ts b/desktop-app/ui/src/lib/workspaceTabs.types.ts
index 96feb816f..6d9bb9479 100644
--- a/desktop-app/ui/src/lib/workspaceTabs.types.ts
+++ b/desktop-app/ui/src/lib/workspaceTabs.types.ts
@@ -1,4 +1,4 @@
-export type WorkspaceTabKind = 'chat' | 'app' | 'files' | 'settings'
+export type WorkspaceTabKind = 'chat' | 'app' | 'files' | 'settings' | 'preview'
export type SettingsSection = 'connectors' | 'agents' | 'plugins' | 'settings'
@@ -26,11 +26,25 @@ export type FilesTabPayload = {
path: string | null
}
+/**
+ * A preview tab's payload (spec 18 §3.B.1): everything a `FilePreviewPage` needs
+ * to mount the right `Gfs*PreviewBody` and fail-closed re-fetch the bytes. The
+ * `gfsUri` is the tab's dedupe key. `byteLength` is the file SIZE (for the
+ * size-guard), never the bytes themselves — the body downloads by `gfsUri`.
+ */
+export type PreviewTabPayload = {
+ gfsUri: string
+ fileKind: 'image' | 'markdown' | 'video'
+ mimeType?: string
+ byteLength: number
+}
+
/**
* A single tab in the universal strip. `kind` discriminates the payload:
* `chat` carries `chat`, `app` carries `app`, `settings` carries `settings`,
- * and `files` carries `files` (its live gfsUri; multi-instance by path, §3 —
- * supersedes R8's single instance).
+ * `files` carries `files` (its live gfsUri; multi-instance by path, §3 —
+ * supersedes R8's single instance), and `preview` carries `preview` (a file
+ * preview, multi-instance by gfsUri — spec 18 §3.B.1).
*/
export type WorkspaceTab = {
id: string
@@ -40,6 +54,7 @@ export type WorkspaceTab = {
app?: AppTabPayload
settings?: SettingsTabPayload
files?: FilesTabPayload
+ preview?: PreviewTabPayload
}
/**
@@ -82,6 +97,16 @@ export type OpenSettingsTabInput = {
title?: string
}
+export type OpenPreviewTabInput = {
+ id: string
+ title?: string
+ /** The gfsUri to preview (dedupe key). */
+ gfsUri: string
+ fileKind: 'image' | 'markdown' | 'video'
+ mimeType?: string
+ byteLength: number
+}
+
/**
* The chat currently displayed by the chat controller — the primary that
* `reconcileWorkspaceChatTab` aligns tab state to (`chatId === null` = a blank
diff --git a/desktop-app/ui/src/lib/workspaceTabsRoute.ts b/desktop-app/ui/src/lib/workspaceTabsRoute.ts
index 319cd4274..a34f1425f 100644
--- a/desktop-app/ui/src/lib/workspaceTabsRoute.ts
+++ b/desktop-app/ui/src/lib/workspaceTabsRoute.ts
@@ -37,6 +37,8 @@ export function mapKindToRoute(tab: WorkspaceTab | undefined): NavItem {
return DESKTOP_ROUTES.apps
case 'files':
return DESKTOP_ROUTES.files
+ case 'preview':
+ return DESKTOP_ROUTES.preview
case 'settings':
return SETTINGS_SECTION_TO_ROUTE[tab.settings?.section ?? 'settings']
}
diff --git a/desktop-app/ui/src/pages/FilePreviewPage.tsx b/desktop-app/ui/src/pages/FilePreviewPage.tsx
new file mode 100644
index 000000000..27772f7ff
--- /dev/null
+++ b/desktop-app/ui/src/pages/FilePreviewPage.tsx
@@ -0,0 +1,93 @@
+import { useCallback, useEffect, useState } from 'react'
+import { GfsImagePreviewBody } from '@components/GfsImagePreview'
+import { GfsMarkdownPreviewBody } from '@components/GfsMarkdownPreview'
+import { GfsVideoPreviewBody } from '@components/GfsVideoPreview'
+import { useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'
+import type { FilePreviewPageProps } from './FilePreviewPage.types'
+
+/**
+ * A previewed GFS file living in its own workspace tab (spec 18 §3.B.3). Thin by
+ * design: it mounts the `Gfs*PreviewBody` matching the tab's `fileKind` (each
+ * body owns its own fetch + size-guard) and wires the fail-closed behavior.
+ *
+ * Reload hookpoint (§3.B.3): `reloadToken` is the single lever that re-fetches
+ * the body (via a `key` bump → remount). The change watcher (spec 02) is
+ * deferred, so it stays INERT with respect to file changes — but it is already
+ * CONNECTED to the authority signal for the R-4 security requirement (§3.B.5):
+ * this tab does NOT close when access is revoked; instead the authority
+ * controller's revocation re-fetches the body, which then fails closed and
+ * renders the reason (no stale content survives a revoke). The body's download
+ * error is also routed back through the same controller so a revoke discovered
+ * at fetch time fails the session closed exactly as the modal era did.
+ */
+export function FilePreviewPage({
+ gfsUri,
+ fileName,
+ fileKind,
+ mimeType,
+ byteLength,
+}: FilePreviewPageProps) {
+ const ctrl = useGfsBrowserController()
+ const [reloadToken, setReloadToken] = useState(0)
+ const accessRevoked = ctrl.accessState === 'revoked'
+
+ // R-4: when the authority controller detects a revocation while this tab is
+ // mounted, bump the reload token so the body re-fetches and fails closed
+ // instead of leaving already-rendered bytes on screen.
+ useEffect(() => {
+ if (accessRevoked) setReloadToken(token => token + 1)
+ }, [accessRevoked])
+
+ const handleDownloadError = useCallback(
+ (error: unknown) => {
+ ctrl.handleAuthorityFailure(
+ error instanceof Error ? error.message : String(error),
+ 'operation'
+ )
+ },
+ [ctrl]
+ )
+
+ // Remounting the body on a reload bump discards any stale bytes and re-runs the
+ // fetch from scratch — the simplest correct "re-dispatch the fetch" (§3.B.3).
+ const bodyKey = `${gfsUri}:${reloadToken}`
+
+ return (
+ <section className="page">
+ <div className="da-gfs-preview-page">
+ {fileKind === 'image' ? (
+ <GfsImagePreviewBody
+ key={bodyKey}
+ byteLength={byteLength}
+ fileName={fileName}
+ gfsUri={gfsUri}
+ mimeType={mimeType ?? ''}
+ onDownloadError={handleDownloadError}
+ headingLevel={2}
+ />
+ ) : null}
+ {fileKind === 'markdown' ? (
+ <GfsMarkdownPreviewBody
+ key={bodyKey}
+ byteLength={byteLength}
+ fileName={fileName}
+ gfsUri={gfsUri}
+ onDownloadError={handleDownloadError}
+ headingLevel={2}
+ />
+ ) : null}
+ {fileKind === 'video' ? (
+ <GfsVideoPreviewBody
+ key={bodyKey}
+ byteLength={byteLength}
+ fileName={fileName}
+ gfsUri={gfsUri}
+ mimeType={mimeType ?? ''}
+ onDownloadError={handleDownloadError}
+ headingLevel={2}
+ />
+ ) : null}
+ </div>
+ </section>
+ )
+}
diff --git a/desktop-app/ui/src/pages/FilePreviewPage.types.ts b/desktop-app/ui/src/pages/FilePreviewPage.types.ts
new file mode 100644
index 000000000..57f0d1a7b
--- /dev/null
+++ b/desktop-app/ui/src/pages/FilePreviewPage.types.ts
@@ -0,0 +1,10 @@
+export interface FilePreviewPageProps {
+ /** The previewed file's gfsUri — the byte source and the tab's identity. */
+ gfsUri: string
+ /** The file name (the tab title), used for the preview heading and alt text. */
+ fileName: string
+ fileKind: 'image' | 'markdown' | 'video'
+ mimeType?: string
+ /** File size in bytes, for the per-kind size-guard (not the bytes). */
+ byteLength: number
+}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index dbdc1d679..f9baab1b5 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -18,10 +18,7 @@ import {
import { Badge, Button, EmptyState, IconButton, StatusBanner, TextInput } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
import { GfsFileIcon } from '@components/GfsFileIcon'
-import { GfsImagePreview } from '@components/GfsImagePreview'
-import { GfsMarkdownPreview } from '@components/GfsMarkdownPreview'
import { GfsResourceMenu } from '@components/GfsResourceMenu'
-import { GfsVideoPreview } from '@components/GfsVideoPreview'
import {
IconAttachFile,
IconCheck,
@@ -39,9 +36,7 @@ import { type GfsCrumb, useGfsBrowserController } from '@hooks/domain/useGfsBrow
import { isEventFromNestedInteractive } from '@lib/clickableRowProps'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
import { describeGfsGrantError } from '@lib/gfsGrantErrors'
-import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
-import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'
-import { gfsVideoPreviewMimeType } from '@lib/gfsVideoPreview'
+import { isGfsPreviewFile, resolveGfsPreview } from '@lib/gfsPreview'
import { formatSharedFileSize } from '@lib/sharedFiles'
import { GfsGrantList } from '@/gfs/GfsGrantList'
import type { GfsAccessRole } from '@/gfs/GfsGrantList'
@@ -54,12 +49,7 @@ import {
import { GfsFilePicker } from '@/gfs/filePicker'
import { GfsMoveDialog } from '@/gfs/moveDialog'
import type { TeamDirectoryResult } from '../../../src/types'
-import type {
- FilesPageProps,
- GfsDriveResource,
- GfsPreviewResource,
- MyAgentEntry,
-} from './FilesPage.types'
+import type { FilesPageProps, GfsDriveResource, MyAgentEntry } from './FilesPage.types'
function hasBit(affordances: { held?: string[] } | null, bit: string): boolean {
return Boolean(affordances?.held?.includes(bit))
@@ -77,14 +67,6 @@ function hasDraggedGfsResource(event: ReactDragEvent<HTMLElement>): boolean {
type FolderDropAccessResult = { allowed: boolean; error?: unknown }
-function isGfsPreviewFile(fileName: string): boolean {
- return (
- gfsImagePreviewMimeType(fileName) !== null ||
- isGfsMarkdownPreviewFile(fileName) ||
- gfsVideoPreviewMimeType(fileName) !== null
- )
-}
-
function delegationSubjectOptions(
directory: TeamDirectoryResult | undefined
): GfsDelegationSubjectOption[] {
@@ -213,6 +195,7 @@ export function FilesPage({
pendingGfsUri,
onPendingGfsUriHandled,
onLocationChange,
+ onOpenPreview,
}: FilesPageProps) {
const [createFolderName, setCreateFolderName] = useState('')
const [createFolderOpen, setCreateFolderOpen] = useState(false)
@@ -228,7 +211,6 @@ export function FilesPage({
const [manageOpen, setManageOpen] = useState(false)
const [shareDetailsOpen, setShareDetailsOpen] = useState(false)
const [updatingAccessRole, setUpdatingAccessRole] = useState(false)
- const [filePreview, setFilePreview] = useState<GfsPreviewResource | null>(null)
const [dragActive, setDragActive] = useState(false)
const [droppedUploadCount, setDroppedUploadCount] = useState(0)
const [draggingResourceId, setDraggingResourceId] = useState<string | null>(null)
@@ -369,12 +351,13 @@ export function FilesPage({
}, [closeCreateFolder, createFolderOpen, ctrl.mutating])
const accessRevoked = ctrl.accessState === 'revoked'
// R4 spec §1: on an authority failure every local surface that could show
- // or act on stale GFS data must close — preview bytes, Manage, Move, rename,
- // delete, open-link, and the inline create-folder form.
+ // or act on stale GFS data must close — Manage, Move, rename, delete,
+ // open-link, and the inline create-folder form. File previews now live in
+ // their own tab (spec 18 §3.B.5), which fails closed independently via its own
+ // authority controller, so there is nothing preview-related to reset here.
useEffect(() => {
if (!accessRevoked) return
manageReturnCrumbsRef.current = null
- setFilePreview(null)
setManageOpen(false)
setMoveTarget(null)
setRenameTarget(null)
@@ -427,50 +410,19 @@ export function FilesPage({
void refreshAffordances()
}, [current?.resourceId, manageOpen, refreshAffordances])
- // Preview byte-fetches are imperative downloads: an authority failure must
- // reach the central fail-closed boundary, not just the in-dialog error.
- const handlePreviewDownloadError = useCallback(
- (error: unknown) => {
- failClosedOnAuthorizationError(error)
- },
- [failClosedOnAuthorizationError]
- )
-
+ // Open (or focus) a preview TAB for a previewable file (spec 18 §3.B.4). The
+ // preview no longer renders in a modal here: resolve the kind via the shared
+ // helper and hand the descriptor to the tab store. Returns true when the file
+ // is previewable (so the caller skips its download fallback), matching the
+ // old modal-era contract. When no `onOpenPreview` is wired, it reports
+ // "not previewable" so the caller downloads instead of silently doing nothing.
const openFilePreview = (
resource: Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'>
): boolean => {
- const mimeType = gfsImagePreviewMimeType(resource.name)
- if (mimeType) {
- setFilePreview({
- gfsUri: resource.gfsUri,
- kind: 'image',
- mimeType,
- name: resource.name,
- bytes: resource.bytes,
- })
- return true
- }
- if (isGfsMarkdownPreviewFile(resource.name)) {
- setFilePreview({
- bytes: resource.bytes,
- gfsUri: resource.gfsUri,
- kind: 'markdown',
- name: resource.name,
- })
- return true
- }
- const videoMimeType = gfsVideoPreviewMimeType(resource.name)
- if (videoMimeType) {
- setFilePreview({
- bytes: resource.bytes,
- gfsUri: resource.gfsUri,
- kind: 'video',
- mimeType: videoMimeType,
- name: resource.name,
- })
- return true
- }
- return false
+ const preview = resolveGfsPreview(resource)
+ if (!preview || !onOpenPreview) return false
+ onOpenPreview(preview)
+ return true
}
useEffect(() => {
@@ -1781,38 +1733,6 @@ export function FilesPage({
</div>
) : null}
- {filePreview?.kind === 'image' ? (
- <GfsImagePreview
- byteLength={filePreview.bytes}
- fileName={filePreview.name}
- gfsUri={filePreview.gfsUri}
- mimeType={filePreview.mimeType}
- onClose={() => setFilePreview(null)}
- onDownloadError={handlePreviewDownloadError}
- />
- ) : null}
-
- {filePreview?.kind === 'markdown' ? (
- <GfsMarkdownPreview
- byteLength={filePreview.bytes}
- fileName={filePreview.name}
- gfsUri={filePreview.gfsUri}
- onClose={() => setFilePreview(null)}
- onDownloadError={handlePreviewDownloadError}
- />
- ) : null}
-
- {filePreview?.kind === 'video' ? (
- <GfsVideoPreview
- byteLength={filePreview.bytes}
- fileName={filePreview.name}
- gfsUri={filePreview.gfsUri}
- mimeType={filePreview.mimeType}
- onClose={() => setFilePreview(null)}
- onDownloadError={handlePreviewDownloadError}
- />
- ) : null}
-
{deleteTarget ? (
<ConfirmDialog
body={
diff --git a/desktop-app/ui/src/pages/FilesPage.types.ts b/desktop-app/ui/src/pages/FilesPage.types.ts
index 01e109adf..810997f80 100644
--- a/desktop-app/ui/src/pages/FilesPage.types.ts
+++ b/desktop-app/ui/src/pages/FilesPage.types.ts
@@ -1,4 +1,5 @@
import type { GfsBrowserChild } from '@hooks/domain/useGfsBrowserController'
+import type { GfsPreviewResource } from '@lib/gfsPreview'
import type { Tone } from '@/uiTypes'
export type GfsDriveResource = GfsBrowserChild & {
@@ -7,9 +8,6 @@ export type GfsDriveResource = GfsBrowserChild & {
coversDescendants?: boolean
}
-export type GfsPreviewResource = Pick<GfsDriveResource, 'bytes' | 'gfsUri' | 'name'> &
- ({ kind: 'image'; mimeType: string } | { kind: 'markdown' } | { kind: 'video'; mimeType: string })
-
export interface FilesPageProps {
/** App-level toast dispatcher for success feedback (desktop-app/ui rule). */
pushToast?: (message: string, tone: Tone) => void
@@ -28,6 +26,13 @@ export interface FilesPageProps {
* `gfsUri` carries no name, hence the second argument.
*/
onLocationChange?: (gfsUri: string | null, name: string | null) => void
+ /**
+ * Open (or focus) a preview tab for a previewable file (spec 18 §3.B.4). The
+ * files browser no longer renders a preview modal: `openFilePreview` resolves
+ * the file kind and hands the descriptor up to the tab store through this
+ * callback. Absent ⇒ no preview surface is available (the file downloads).
+ */
+ onOpenPreview?: (preview: GfsPreviewResource) => void
}
/**
diff --git a/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx
new file mode 100644
index 000000000..03e2c9a9d
--- /dev/null
+++ b/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx
@@ -0,0 +1,136 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { FilePreviewPage } from '../FilePreviewPage'
+
+const hookMock = vi.hoisted(() => ({
+ useGfsBrowserController: vi.fn(),
+}))
+
+vi.mock('@hooks/domain/useGfsBrowserController', () => hookMock)
+
+function controller(accessState: 'active' | 'revoked' = 'active') {
+ return {
+ accessState,
+ handleAuthorityFailure: vi.fn(() => false),
+ }
+}
+
+// The producer (`window.clerum.gfs.download`) returns `{ bytes: ArrayBuffer }`.
+function stubDownload(impl: () => Promise<{ bytes: ArrayBuffer }>) {
+ const download = vi.fn(impl)
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { download } },
+ })
+ return download
+}
+
+describe('FilePreviewPage', () => {
+ beforeEach(() => {
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ value: vi.fn(() => 'blob:gfs-preview'),
+ })
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ it('mounts the image body for an image preview tab', async () => {
+ hookMock.useGfsBrowserController.mockReturnValue(controller())
+ stubDownload(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
+
+ render(
+ <FilePreviewPage
+ gfsUri="gfs://main/image-1"
+ fileName="diagram.png"
+ fileKind="image"
+ mimeType="image/png"
+ byteLength={3}
+ />
+ )
+
+ expect(await screen.findByAltText('Preview of diagram.png')).toBeTruthy()
+ // The preview page title is a page-level h2 (not a dialog h3).
+ expect(screen.getByRole('heading', { name: 'diagram.png', level: 2 })).toBeTruthy()
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+
+ it('mounts the markdown body for a markdown preview tab', async () => {
+ hookMock.useGfsBrowserController.mockReturnValue(controller())
+ stubDownload(async () => ({ bytes: new TextEncoder().encode('# Hi').buffer }))
+
+ render(
+ <FilePreviewPage
+ gfsUri="gfs://main/md-1"
+ fileName="README.md"
+ fileKind="markdown"
+ byteLength={4}
+ />
+ )
+
+ expect(await screen.findByRole('heading', { name: 'Hi', level: 1 })).toBeTruthy()
+ })
+
+ it('mounts the video body for a video preview tab', async () => {
+ hookMock.useGfsBrowserController.mockReturnValue(controller())
+ stubDownload(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
+
+ render(
+ <FilePreviewPage
+ gfsUri="gfs://main/video-1"
+ fileName="demo.mp4"
+ fileKind="video"
+ mimeType="video/mp4"
+ byteLength={3}
+ />
+ )
+
+ expect(await screen.findByLabelText('Video preview of demo.mp4')).toBeTruthy()
+ })
+
+ // R-4 (spec 18 §3.B.5): the preview tab must NOT close when access is revoked;
+ // the revocation signal re-fetches the body so stale bytes are replaced by the
+ // fail-closed error. Here the second fetch (after revocation) returns 403.
+ it('re-fetches and fails closed when authority is revoked while the tab is mounted', async () => {
+ let revoked = false
+ const download = stubDownload(async () => {
+ if (revoked) throw new Error('403 Forbidden')
+ return { bytes: new Uint8Array([1, 2, 3]).buffer }
+ })
+ const controllerState = controller('active')
+ hookMock.useGfsBrowserController.mockReturnValue(controllerState)
+
+ // A fresh element per render pass so the mutated mock is observed.
+ const makeElement = () => (
+ <FilePreviewPage
+ gfsUri="gfs://main/secret"
+ fileName="secret.png"
+ fileKind="image"
+ mimeType="image/png"
+ byteLength={3}
+ />
+ )
+ const { rerender } = render(makeElement())
+
+ // First fetch succeeds and the image renders.
+ expect(await screen.findByAltText('Preview of secret.png')).toBeTruthy()
+ expect(download).toHaveBeenCalledTimes(1)
+
+ // Access is revoked out-of-band → the authority controller reports revoked.
+ revoked = true
+ controllerState.accessState = 'revoked'
+ rerender(makeElement())
+
+ // The tab stays mounted (heading still present) but the stale image is gone
+ // and the revoke reason is shown — no accessible content survives the revoke.
+ await waitFor(() => expect(screen.queryByAltText('Preview of secret.png')).toBeNull())
+ expect(await screen.findByText('403 Forbidden')).toBeTruthy()
+ expect(screen.getByRole('heading', { name: 'secret.png', level: 2 })).toBeTruthy()
+ expect(download).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index c9830e808..113e69ee1 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -4,8 +4,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { GFS_FILE_UPLOAD_PROTOCOL_MAX_BYTES } from '@constants/gfsFileUpload'
-import { GFS_IMAGE_PREVIEW_MAX_BYTES } from '@constants/gfsImagePreview'
-import { GFS_MARKDOWN_PREVIEW_MAX_BYTES } from '@constants/gfsMarkdownPreview'
import type { GfsCrumb } from '@hooks/domain/useGfsBrowserController'
import type { Tone } from '@/uiTypes'
import { FilesPage } from '../FilesPage'
@@ -80,11 +78,14 @@ function baseController() {
}
}
-function renderFilesPage(pushToast?: (message: string, tone: Tone) => void) {
+function renderFilesPage(
+ pushToast?: (message: string, tone: Tone) => void,
+ onOpenPreview?: (preview: unknown) => void
+) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
- <FilesPage pushToast={pushToast} />
+ <FilesPage pushToast={pushToast} onOpenPreview={onOpenPreview} />
</QueryClientProvider>
)
}
@@ -1984,59 +1985,6 @@ describe('FilesPage', () => {
expect(retryAccess).toHaveBeenCalledTimes(1)
})
- // R4 spec §1 — on revocation, every local surface that could show or act on
- // stale GFS data must close. Here: an open image preview (already-fetched
- // bytes) and an open Move dialog.
- it('closes an open preview when authority is revoked mid-session', async () => {
- const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
- const createObjectURL = vi.fn(() => 'blob:gfs-image-preview')
- Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL })
- Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
- const controllerState = {
- ...baseController(),
- accessibleResources: [
- {
- resourceId: 'image-1',
- rid: 'image-1',
- gfsUri: 'gfs://main/image-1',
- drive: 'main',
- parentResourceId: null,
- name: 'secret.PNG',
- kind: 'file',
- path: '/secret.PNG',
- version: 1,
- bytes: 3,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
- }
- hookMock.useGfsBrowserController.mockReturnValue(controllerState)
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- // A fresh element per render pass: rerendering the identical element
- // reference would bail out and never observe the mutated mock.
- const makeElement = () => (
- <QueryClientProvider client={queryClient}>
- <FilesPage />
- </QueryClientProvider>
- )
- const { rerender } = render(makeElement())
-
- fireEvent.click(screen.getByRole('button', { name: 'secret.PNG' }))
- expect(await screen.findByRole('dialog', { name: 'secret.PNG' })).toBeTruthy()
-
- controllerState.accessState = 'revoked'
- rerender(makeElement())
-
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'secret.PNG' })).toBeNull())
- expect(await screen.findByText('File access is not authorized')).toBeTruthy()
- })
-
it('closes the move dialog when authority is revoked mid-session', async () => {
const moveResource = vi.fn(async () => ({}))
const controllerState = {
@@ -2738,323 +2686,115 @@ describe('FilesPage', () => {
expect(pushToast).toHaveBeenCalledWith('Deleted shared-report.txt', 'success')
})
- it('previews an image file in a closable modal without downloading it to disk', async () => {
- const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
- const createObjectURL = vi.fn(() => 'blob:gfs-image-preview')
- const revokeObjectURL = vi.fn()
- const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
- Object.defineProperty(URL, 'createObjectURL', {
- configurable: true,
- value: createObjectURL,
- })
- Object.defineProperty(URL, 'revokeObjectURL', {
- configurable: true,
- value: revokeObjectURL,
- })
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
+ // Preview no longer opens a modal inside FilesPage (spec 18 §3.B.4): the page
+ // resolves the file kind and hands a descriptor up through onOpenPreview so the
+ // tab store opens/focuses a FilePreviewPage. These assert the observable
+ // handoff (T4), not the byte fetch — the fetch now lives in Gfs*PreviewBody.
+ const previewRow = (
+ name: string,
+ resourceId: string,
+ bytes: number
+ ): Record<string, unknown> => ({
+ resourceId,
+ rid: resourceId,
+ gfsUri: `gfs://main/${resourceId}`,
+ drive: 'main',
+ parentResourceId: null,
+ name,
+ kind: 'file',
+ path: `/${name}`,
+ version: 1,
+ bytes,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: false,
+ })
+
+ it('opens a preview tab for an image file instead of rendering a modal', () => {
+ const download = vi.fn()
+ Object.defineProperty(window, 'clerum', { configurable: true, value: { gfs: { download } } })
+ const onOpenPreview = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
- accessibleResources: [
- {
- resourceId: 'image-1',
- rid: 'image-1',
- gfsUri: 'gfs://main/image-1',
- drive: 'main',
- parentResourceId: null,
- name: 'diagram.PNG',
- kind: 'file',
- path: '/diagram.PNG',
- version: 1,
- bytes: 3,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ accessibleResources: [previewRow('diagram.PNG', 'image-1', 3)],
})
- renderFilesPage()
- expect(download).not.toHaveBeenCalled()
+ renderFilesPage(undefined, onOpenPreview)
fireEvent.click(screen.getByRole('button', { name: 'diagram.PNG' }))
- const dialog = await screen.findByRole('dialog', { name: 'diagram.PNG' })
- await waitFor(() => expect(within(dialog).getByAltText('Preview of diagram.PNG')).toBeTruthy())
- const copyButton = within(dialog).getByRole('button', { name: /Copy image to clipboard/i })
- expect(copyButton.querySelector('svg')?.getAttribute('viewBox')).toBe('0 0 24 24')
- expect(copyButton.querySelector('path')?.getAttribute('d')).toBe('M0 0h24v24H0z')
- expect(download).toHaveBeenCalledWith('gfs://main/image-1')
- expect(download).toHaveBeenCalledTimes(1)
- expect(anchorClick).not.toHaveBeenCalled()
-
- fireEvent.click(within(dialog).getByRole('button', { name: 'Close image preview' }))
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'diagram.PNG' })).toBeNull())
- expect(revokeObjectURL).toHaveBeenCalledWith('blob:gfs-image-preview')
- })
-
- it('copies markdown source to the clipboard via the preview header button', async () => {
- const writeText = vi.fn(async () => undefined)
- Object.defineProperty(navigator, 'clipboard', {
- configurable: true,
- value: { ...(navigator.clipboard ?? {}), writeText },
+ expect(onOpenPreview).toHaveBeenCalledWith({
+ gfsUri: 'gfs://main/image-1',
+ kind: 'image',
+ mimeType: 'image/png',
+ name: 'diagram.PNG',
+ bytes: 3,
})
+ // No modal, and FilesPage itself never fetches the bytes.
+ expect(screen.queryByRole('dialog', { name: 'diagram.PNG' })).toBeNull()
+ expect(download).not.toHaveBeenCalled()
+ })
- const markdown = '# Hello\n\nGreetings.'
- const download = vi.fn(async () => ({
- bytes: new TextEncoder().encode(markdown).buffer,
- }))
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
+ it('opens a preview tab for a markdown file (no mimeType in the descriptor)', () => {
+ const onOpenPreview = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
- accessibleResources: [
- {
- resourceId: 'markdown-2',
- rid: 'markdown-2',
- gfsUri: 'gfs://main/markdown-2',
- drive: 'main',
- parentResourceId: null,
- name: 'README.md',
- kind: 'file',
- path: '/README.md',
- version: 1,
- bytes: markdown.length,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ accessibleResources: [previewRow('README.md', 'markdown-1', 12)],
})
- renderFilesPage()
+ renderFilesPage(undefined, onOpenPreview)
fireEvent.click(screen.getByRole('button', { name: 'README.md' }))
- const dialog = await screen.findByRole('dialog', { name: 'README.md' })
- const copyButton = within(dialog).getByRole('button', {
- name: /Copy preview contents to clipboard/i,
- })
- expect(copyButton.querySelector('svg')?.getAttribute('viewBox')).toBe('0 0 24 24')
- expect(copyButton.querySelector('path')?.getAttribute('d')).toBe('M0 0h24v24H0z')
- fireEvent.click(copyButton)
-
- await waitFor(() => expect(writeText).toHaveBeenCalledWith(markdown))
- })
-
- it('renders a .txt file as plain text inside the preview dialog', async () => {
- const download = vi.fn(async () => ({
- bytes: new TextEncoder().encode('line one\nline two\twith tab').buffer,
- }))
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
- hookMock.useGfsBrowserController.mockReturnValue({
- ...baseController(),
- accessibleResources: [
- {
- resourceId: 'text-1',
- rid: 'text-1',
- gfsUri: 'gfs://main/text-1',
- drive: 'main',
- parentResourceId: null,
- name: 'notes.txt',
- kind: 'file',
- path: '/notes.txt',
- version: 1,
- bytes: 26,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ expect(onOpenPreview).toHaveBeenCalledWith({
+ gfsUri: 'gfs://main/markdown-1',
+ kind: 'markdown',
+ name: 'README.md',
+ bytes: 12,
})
-
- renderFilesPage()
- fireEvent.click(screen.getByRole('button', { name: 'notes.txt' }))
- const dialog = await screen.findByRole('dialog', { name: 'notes.txt' })
- const pre = await within(dialog).findByText(/line one/)
- expect(pre.tagName).toBe('PRE')
- expect(pre.textContent).toContain('line two\twith tab')
})
- it('previews a video file in a closable HTML5 video dialog', async () => {
- const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
- const createObjectURL = vi.fn(() => 'blob:gfs-video-preview')
- const revokeObjectURL = vi.fn()
- Object.defineProperty(URL, 'createObjectURL', {
- configurable: true,
- value: createObjectURL,
- })
- Object.defineProperty(URL, 'revokeObjectURL', {
- configurable: true,
- value: revokeObjectURL,
- })
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
+ it('opens a preview tab for a video file with its detected mimeType', () => {
+ const onOpenPreview = vi.fn()
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
- accessibleResources: [
- {
- resourceId: 'video-1',
- rid: 'video-1',
- gfsUri: 'gfs://main/video-1',
- drive: 'main',
- parentResourceId: null,
- name: 'demo.mp4',
- kind: 'file',
- path: '/demo.mp4',
- version: 1,
- bytes: 3,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ accessibleResources: [previewRow('demo.mp4', 'video-1', 3)],
})
- renderFilesPage()
+ renderFilesPage(undefined, onOpenPreview)
fireEvent.click(screen.getByRole('button', { name: 'demo.mp4' }))
- const dialog = await screen.findByRole('dialog', { name: 'demo.mp4' })
- const video = await within(dialog).findByLabelText('Video preview of demo.mp4')
- expect(video.tagName).toBe('VIDEO')
- expect(video.getAttribute('controls')).not.toBeNull()
- expect(video.getAttribute('src')).toBe('blob:gfs-video-preview')
- expect(createObjectURL).toHaveBeenCalledWith(expect.objectContaining({ type: 'video/mp4' }))
-
- fireEvent.click(within(dialog).getByRole('button', { name: 'Close video preview' }))
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'demo.mp4' })).toBeNull())
- expect(revokeObjectURL).toHaveBeenCalledWith('blob:gfs-video-preview')
- })
-
- it('previews Markdown files with safe vanilla rendering', async () => {
- const markdown =
- '# Project guide\n\nUse **safe rendering**.\n\n1. First\n2. Second\n\n[Unsafe](javascript:alert)\n\n<script>alert("no")</script>'
- const download = vi.fn(async () => ({ bytes: new TextEncoder().encode(markdown).buffer }))
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
- hookMock.useGfsBrowserController.mockReturnValue({
- ...baseController(),
- accessibleResources: [
- {
- resourceId: 'markdown-1',
- rid: 'markdown-1',
- gfsUri: 'gfs://main/markdown-1',
- drive: 'main',
- parentResourceId: null,
- name: 'README.md',
- kind: 'file',
- path: '/README.md',
- version: 1,
- bytes: markdown.length,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ expect(onOpenPreview).toHaveBeenCalledWith({
+ gfsUri: 'gfs://main/video-1',
+ kind: 'video',
+ mimeType: 'video/mp4',
+ name: 'demo.mp4',
+ bytes: 3,
})
-
- renderFilesPage()
- fireEvent.click(screen.getByRole('button', { name: 'README.md' }))
-
- const dialog = await screen.findByRole('dialog', { name: 'README.md' })
- expect(
- await within(dialog).findByRole('heading', { name: 'Project guide', level: 1 })
- ).toBeTruthy()
- expect(within(dialog).getByText('safe rendering').tagName).toBe('STRONG')
- expect(within(dialog).getAllByRole('listitem')).toHaveLength(2)
- expect(within(dialog).getByText('Unsafe').closest('a')).toBeNull()
- expect(dialog.querySelector('script')).toBeNull()
- expect(download).toHaveBeenCalledWith('gfs://main/markdown-1')
-
- fireEvent.click(within(dialog).getByRole('button', { name: 'Close preview' }))
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'README.md' })).toBeNull())
})
- it('rejects oversized previews from metadata before downloading them', async () => {
- const download = vi.fn()
- Object.defineProperty(window, 'clerum', {
- configurable: true,
- value: { gfs: { download } },
- })
+ it('downloads a previewable file when no preview surface is wired (fail-open to download)', async () => {
+ const download = vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer }))
+ const createObjectURL = vi.fn(() => 'blob:gfs-download')
+ const revokeObjectURL = vi.fn()
+ const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: createObjectURL })
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: revokeObjectURL })
+ Object.defineProperty(window, 'clerum', { configurable: true, value: { gfs: { download } } })
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
- accessibleResources: [
- {
- resourceId: 'large-image',
- rid: 'large-image',
- gfsUri: 'gfs://main/large-image',
- drive: 'main',
- parentResourceId: null,
- name: 'oversized.png',
- kind: 'file',
- path: '/oversized.png',
- version: 1,
- bytes: GFS_IMAGE_PREVIEW_MAX_BYTES + 1,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- {
- resourceId: 'large-markdown',
- rid: 'large-markdown',
- gfsUri: 'gfs://main/large-markdown',
- drive: 'main',
- parentResourceId: null,
- name: 'oversized.md',
- kind: 'file',
- path: '/oversized.md',
- version: 1,
- bytes: GFS_MARKDOWN_PREVIEW_MAX_BYTES + 1,
- sources: ['grant'],
- permissions: ['read'],
- coversDescendants: false,
- },
- ],
+ accessibleResources: [previewRow('diagram.PNG', 'image-1', 3)],
})
+ // No onOpenPreview: openFilePreview reports "not previewable" so the click
+ // falls through to the download path instead of silently doing nothing.
renderFilesPage()
- fireEvent.click(screen.getByRole('button', { name: 'oversized.png' }))
- let dialog = await screen.findByRole('dialog', { name: 'oversized.png' })
- expect(await within(dialog).findByText(/Image previews are limited to 10 MB/)).toBeTruthy()
- fireEvent.click(within(dialog).getByRole('button', { name: 'Close image preview' }))
-
- fireEvent.click(screen.getByRole('button', { name: 'oversized.md' }))
- dialog = await screen.findByRole('dialog', { name: 'oversized.md' })
- expect(await within(dialog).findByText(/Markdown previews are limited to 2 MB/)).toBeTruthy()
- expect(download).not.toHaveBeenCalled()
- })
-
- it('opens a GFS URI from the modal and closes after a successful resolve', async () => {
- const openUri = vi.fn(async () => true)
- hookMock.useGfsBrowserController.mockReturnValue({ ...baseController(), openUri })
- renderFilesPage()
-
- expect(screen.queryByRole('button', { name: 'Open GFS link' })).toBeNull()
- fireEvent.click(screen.getByRole('button', { name: 'Options for Shared with me' }))
- fireEvent.click(screen.getByRole('menuitem', { name: 'Open GFS link' }))
- const dialog = await screen.findByRole('dialog', { name: 'Open GFS link' })
- fireEvent.change(within(dialog).getByLabelText('gfs URI'), {
- target: { value: 'gfs://main/resource-1' },
- })
- fireEvent.click(within(dialog).getByRole('button', { name: 'Open' }))
+ fireEvent.click(screen.getByRole('button', { name: 'diagram.PNG' }))
- await waitFor(() => expect(openUri).toHaveBeenCalledWith('gfs://main/resource-1'))
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Open GFS link' })).toBeNull())
+ await waitFor(() => expect(download).toHaveBeenCalledWith('gfs://main/image-1'))
+ expect(anchorClick).toHaveBeenCalled()
})
- it('opens an SVG GFS link in preview without leaving the browser on a file-only route', async () => {
- const download = vi.fn(async () => ({ bytes: new Uint8Array([60, 115, 118, 103]).buffer }))
- const createObjectURL = vi.fn(() => 'blob:gfs-svg-preview')
- const revokeObjectURL = vi.fn()
+ it('opens a preview tab from a resolved GFS link and closes the link dialog', async () => {
+ const onOpenPreview = vi.fn()
const resolvedFile: GfsCrumb = {
resourceId: 'svg-1',
gfsUri: 'gfs://main/svg-1',
@@ -3068,17 +2808,9 @@ describe('FilesPage', () => {
selectResolvedFile?.()
return resolvedFile
})
- Object.defineProperty(URL, 'createObjectURL', {
- configurable: true,
- value: createObjectURL,
- })
- Object.defineProperty(URL, 'revokeObjectURL', {
- configurable: true,
- value: revokeObjectURL,
- })
Object.defineProperty(window, 'clerum', {
configurable: true,
- value: { gfs: { download } },
+ value: { gfs: { download: vi.fn() } },
})
function useResolvedFileController() {
const [crumbs, setCrumbs] = useState<GfsCrumb[]>([])
@@ -3093,7 +2825,7 @@ describe('FilesPage', () => {
}
hookMock.useGfsBrowserController.mockImplementation(useResolvedFileController)
- renderFilesPage()
+ renderFilesPage(undefined, onOpenPreview)
fireEvent.click(screen.getByRole('button', { name: 'Options for Shared with me' }))
fireEvent.click(screen.getByRole('menuitem', { name: 'Open GFS link' }))
const linkDialog = await screen.findByRole('dialog', { name: 'Open GFS link' })
@@ -3102,16 +2834,16 @@ describe('FilesPage', () => {
})
fireEvent.click(within(linkDialog).getByRole('button', { name: 'Open' }))
- const preview = await screen.findByRole('dialog', { name: 'architecture.svg' })
await waitFor(() =>
- expect(within(preview).getByAltText('Preview of architecture.svg')).toBeTruthy()
+ expect(onOpenPreview).toHaveBeenCalledWith({
+ gfsUri: 'gfs://main/svg-1',
+ kind: 'image',
+ mimeType: 'image/svg+xml',
+ name: 'architecture.svg',
+ bytes: 4,
+ })
)
- expect(download).toHaveBeenCalledWith('gfs://main/svg-1')
- expect(createObjectURL).toHaveBeenCalledWith(expect.objectContaining({ type: 'image/svg+xml' }))
- expect(screen.queryByRole('dialog', { name: 'Open GFS link' })).toBeNull()
-
- fireEvent.click(within(preview).getByRole('button', { name: 'Close image preview' }))
- expect(screen.queryByRole('heading', { name: 'architecture.svg' })).toBeNull()
+ await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Open GFS link' })).toBeNull())
expect(screen.getByRole('button', { name: 'Options for Shared with me' })).toBeTruthy()
})
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index 07b5fe754..7e6bff0da 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -15440,7 +15440,8 @@ pre {
.da-gfs-image-preview-dialog__header h3,
.da-gfs-markdown-preview-dialog__header h3,
-.da-gfs-video-preview-dialog__header h3 {
+.da-gfs-video-preview-dialog__header h3,
+.da-gfs-preview-title {
min-width: 0;
overflow: hidden;
margin: 0;
@@ -15452,6 +15453,21 @@ pre {
white-space: nowrap;
}
+/* File preview in a workspace tab (spec 18 §3.B.3). Reuses the shared
+ * Gfs*PreviewBody inner classes; this container gives the header + body the same
+ * two-row layout the dialog frame provided, without any modal chrome. */
+.da-gfs-preview-page {
+ flex: 1 1 0;
+ min-width: 0;
+ min-height: 0;
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr);
+ overflow: hidden;
+ border: 1px solid var(--table-frame-border);
+ border-radius: var(--table-radius);
+ background: var(--table-frame-bg);
+}
+
.da-gfs-image-preview-dialog__body,
.da-gfs-video-preview-dialog__body {
min-width: 0;