Skip to content

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

TypeScript

Merge remote-tracking branch 'origin/dev' into fix/gfs-files-read-budget

Alfredo Lopez22b62d0595e4
diff --cc desktop-app/src/gfs/boundedDownload.ts
index 000000000,0f23a1748..ba3a09144
mode 000000,100644..100644
--- a/desktop-app/src/gfs/boundedDownload.ts
+++ b/desktop-app/src/gfs/boundedDownload.ts
@@@ -1,0 -1,92 +1,105 @@@
+ import { ApiError } from '../httpClient.js'
+
+ /** The dependency seam so the bound can be tested with a fabricated response. */
+ export interface BoundedDownloadDeps {
+ fetch: typeof fetch
+ }
+
+ /**
+ * Fetch a resource's raw bytes with an OPTIONAL hard ceiling.
+ *
+ * Without `maxBytes` the whole body is read — the save-to-disk path, which
+ * legitimately materializes large files.
+ *
+ * With `maxBytes` the response is rejected two ways so the ceiling holds even
+ * when the server lies about (or omits) the length:
+ * 1. up front, when a truthful `Content-Length` already exceeds the ceiling;
+ * 2. mid-stream, the moment cumulative bytes cross the ceiling — so an absent
+ * or dishonest `Content-Length` cannot materialize an oversized payload in
+ * memory. The in-flight request is aborted on rejection.
+ *
+ * A caller must NOT rely on a post-download size assert alone: that runs only
+ * after the full buffer is already resident, which is exactly the exhaustion
+ * this bound prevents.
+ */
+ export async function fetchBoundedBytes(
+ url: string,
+ token: string,
+ opts?: { maxBytes?: number },
+ deps: BoundedDownloadDeps = { fetch }
+ ): Promise<ArrayBuffer> {
+ const maxBytes = opts?.maxBytes
+ const controller = new AbortController()
+ const res = await deps.fetch(url, {
+ headers: { authorization: `Bearer ${token}` },
+ signal: controller.signal,
+ })
+ if (!res.ok) {
- throw new ApiError(`gfs download failed: ${res.status}`, res.status, '')
++ // Keep the body AND Retry-After. `surfaceGfsGrantError` reads the retry
++ // window from `{ retryAfterSeconds }` in the body and falls back to the
++ // header when the 429 came from an upstream proxy whose body it cannot
++ // parse. Discarding either leaves the renderer able to tell that it was
++ // rate-limited but not for how long, which is the state the read plane
++ // cannot recover from on its own. The ceiling does not apply here: an
++ // error body is the server's own diagnostic, not the payload this bound
++ // exists to keep out of memory.
++ throw new ApiError(
++ `gfs download failed: ${res.status}`,
++ res.status,
++ await res.text(),
++ res.headers.get('retry-after')
++ )
+ }
+ if (maxBytes === undefined) {
+ return res.arrayBuffer()
+ }
+
+ const overLimit = () =>
+ new ApiError(`gfs preview download exceeds the ${maxBytes}-byte limit`, 413, '')
+
+ const declared = Number(res.headers.get('content-length'))
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ controller.abort()
+ throw overLimit()
+ }
+
+ const body = res.body
+ if (!body) {
+ // No readable stream to bound (some platforms/tests). Fall back to a
+ // buffered read guarded post-hoc — the length header was already checked.
+ const buffer = await res.arrayBuffer()
+ if (buffer.byteLength > maxBytes) throw overLimit()
+ return buffer
+ }
+
+ const reader = body.getReader()
+ const chunks: Uint8Array[] = []
+ let total = 0
+ try {
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ if (!value) continue
+ total += value.byteLength
+ if (total > maxBytes) {
+ controller.abort()
+ throw overLimit()
+ }
+ chunks.push(value)
+ }
+ } finally {
+ try {
+ reader.releaseLock()
+ } catch {
+ // The reader may already be released after an abort; ignore.
+ }
+ }
+
+ const out = new Uint8Array(total)
+ let offset = 0
+ for (const chunk of chunks) {
+ out.set(chunk, offset)
+ offset += chunk.byteLength
+ }
+ return out.buffer
+ }
diff --cc desktop-app/src/gfs/uriHandler.ts
index 23d8fca68,6eaca4ecd..3d299de2e
--- a/desktop-app/src/gfs/uriHandler.ts
+++ b/desktop-app/src/gfs/uriHandler.ts
@@@ -417,38 -421,35 +421,45 @@@ export class GfsClient
/** Resolve a gfs:// URI to its current resource (validates the URI locally first). */
async resolveUri(uri: string, token: string): Promise<ResolvedGfsResource> {
parseGfsUri(uri) // fail fast on a malformed URI before a round-trip
- const payload = await this.transport.requestJson<GfsEnvelope<ResolvedGfsResource>>(
- 'GET',
- joinUrl(this.transport.baseUrl, `/api/v1/me/gfs/resolve?uri=${encodeURIComponent(uri)}`),
- { token }
- )
- return unwrap(payload)
+ try {
+ const payload = await this.transport.requestJson<GfsEnvelope<ResolvedGfsResource>>(
+ 'GET',
+ joinUrl(this.transport.baseUrl, `/api/v1/me/gfs/resolve?uri=${encodeURIComponent(uri)}`),
+ { token }
+ )
+ return unwrap(payload)
+ } catch (error) {
+ throw surfaceGfsGrantError(error)
+ }
}
- /** Resolve then download the resource bytes through the brokered proxy. */
+ /**
+ * Resolve then download the resource bytes through the brokered proxy.
+ * `opts.maxBytes` bounds the download (preview path); omitting it reads the
+ * full body (save-to-disk). The unbounded call keeps the exact 2-arg
+ * `fetchBytes` signature so existing callers are byte-for-byte unchanged.
+ */
async download(
uri: string,
- token: string
+ token: string,
+ opts?: { maxBytes?: number }
): Promise<{ resource: ResolvedGfsResource; bytes: ArrayBuffer }> {
+ // resolveUri runs first and already surfaces its own verdict, so a 429 on the
+ // resolve leg reaches the renderer with the resolve message, not this one.
const resource = await this.resolveUri(uri, token)
+ const proxyUrl = joinUrl(
+ this.transport.baseUrl,
+ `/api/v1/me/gfs/proxy/${resource.resourceId}?drive=${encodeURIComponent(resource.drive)}`
+ )
- const bytes =
- opts?.maxBytes !== undefined
- ? await this.transport.fetchBytes(proxyUrl, token, { maxBytes: opts.maxBytes })
- : await this.transport.fetchBytes(proxyUrl, token)
- return { resource, bytes }
+ try {
- const bytes = await this.transport.fetchBytes(
- joinUrl(
- this.transport.baseUrl,
- `/api/v1/me/gfs/proxy/${resource.resourceId}?drive=${encodeURIComponent(resource.drive)}`
- ),
- token
- )
++ const bytes =
++ opts?.maxBytes !== undefined
++ ? await this.transport.fetchBytes(proxyUrl, token, { maxBytes: opts.maxBytes })
++ : await this.transport.fetchBytes(proxyUrl, token)
+ return { resource, bytes }
+ } catch (error) {
+ throw surfaceGfsGrantError(error)
+ }
}
/**
diff --cc desktop-app/test/gfsBoundedDownload.test.ts
index 000000000,f8888aedc..ec3f47957
mode 000000,100644..100644
--- a/desktop-app/test/gfsBoundedDownload.test.ts
+++ b/desktop-app/test/gfsBoundedDownload.test.ts
@@@ -1,0 -1,124 +1,165 @@@
+ import { describe, expect, it } from 'vitest'
+ import { fetchBoundedBytes } from '../src/gfs/boundedDownload.js'
+ import { ApiError } from '../src/httpClient.js'
+
+ /**
+ * R1-H4 Part B — bound mechanics. A fabricated oversized stream is the STIMULUS
+ * for the abort path (allowed by T1: it is not a cross-layer contract fixture).
+ * The observable being asserted is that an over-ceiling payload is rejected
+ * WITHOUT fully materializing — the stream is not drained to completion.
+ */
+
+ interface FakeResponseSpec {
+ ok?: boolean
+ status?: number
+ contentLength?: string | null
++ bodyText?: string
++ retryAfter?: string | null
+ chunks: Uint8Array[]
+ }
+
+ function fakeFetch(spec: FakeResponseSpec): {
+ fetch: typeof fetch
+ pulledChunks: () => number
+ aborted: () => boolean
+ } {
+ let index = 0
+ let pulled = 0
+ let seenAbort = false
+ const chunks = spec.chunks
+ const body = {
+ getReader() {
+ return {
+ read: async () => {
+ if (index >= chunks.length) return { done: true, value: undefined }
+ const value = chunks[index++]!
+ pulled += 1
+ return { done: false, value }
+ },
+ releaseLock() {},
+ }
+ },
+ } as unknown as ReadableStream<Uint8Array>
+ const headers = {
- get: (name: string) =>
- name.toLowerCase() === 'content-length' ? (spec.contentLength ?? null) : null,
++ get: (name: string) => {
++ const key = name.toLowerCase()
++ if (key === 'content-length') return spec.contentLength ?? null
++ if (key === 'retry-after') return spec.retryAfter ?? null
++ return null
++ },
+ }
++ // A real `Response` always has `text()`. The error path reads it so the
++ // server's own diagnostic survives to the renderer, so the fake must have it
++ // too — a fixture that omits it turns a preserved body into a TypeError.
++ const text = async () => spec.bodyText ?? ''
+ const arrayBuffer = async () => {
+ const total = chunks.reduce((n, c) => n + c.byteLength, 0)
+ const out = new Uint8Array(total)
+ let off = 0
+ for (const c of chunks) {
+ out.set(c, off)
+ off += c.byteLength
+ }
+ return out.buffer
+ }
+ const fetchImpl = (async (_url: string, init?: { signal?: AbortSignal }) => {
+ init?.signal?.addEventListener('abort', () => {
+ seenAbort = true
+ })
+ return {
+ ok: spec.ok ?? true,
+ status: spec.status ?? 200,
+ headers,
+ body: spec.ok === false ? null : body,
+ arrayBuffer,
++ text,
+ }
+ }) as unknown as typeof fetch
+ return { fetch: fetchImpl, pulledChunks: () => pulled, aborted: () => seenAbort }
+ }
+
+ const chunk = (n: number) => new Uint8Array(n).fill(1)
+
+ describe('fetchBoundedBytes', () => {
+ it('reads the whole body when no ceiling is given (save-to-disk path)', async () => {
+ const f = fakeFetch({ chunks: [chunk(8), chunk(8), chunk(8)] })
+ const bytes = await fetchBoundedBytes('u', 't', undefined, { fetch: f.fetch })
+ expect(bytes.byteLength).toBe(24)
+ })
+
+ it('returns the payload when it is within the ceiling', async () => {
+ const f = fakeFetch({ contentLength: '16', chunks: [chunk(8), chunk(8)] })
+ const bytes = await fetchBoundedBytes('u', 't', { maxBytes: 16 }, { fetch: f.fetch })
+ expect(bytes.byteLength).toBe(16)
+ expect(f.pulledChunks()).toBe(2)
+ })
+
+ it('rejects up front on a truthful over-ceiling Content-Length WITHOUT reading the body', async () => {
+ const f = fakeFetch({ contentLength: '999999', chunks: [chunk(8), chunk(8), chunk(8)] })
+ await expect(
+ fetchBoundedBytes('u', 't', { maxBytes: 10 }, { fetch: f.fetch })
+ ).rejects.toBeInstanceOf(ApiError)
+ // Observable: the body was never streamed (no chunk pulled) and the request
+ // was aborted — the full buffer is never allocated.
+ expect(f.pulledChunks()).toBe(0)
+ expect(f.aborted()).toBe(true)
+ })
+
+ it('aborts mid-stream when a lying/absent Content-Length hides an over-ceiling body', async () => {
+ // Content-Length claims tiny (or is absent); the real body is 80 bytes.
+ const chunks = Array.from({ length: 10 }, () => chunk(8))
+ const f = fakeFetch({ contentLength: '4', chunks })
+ await expect(fetchBoundedBytes('u', 't', { maxBytes: 10 }, { fetch: f.fetch })).rejects.toThrow(
+ /exceeds the 10-byte limit/
+ )
+ // Observable: it stopped early — it did NOT drain all 10 chunks — and aborted.
+ expect(f.pulledChunks()).toBeLessThan(chunks.length)
+ expect(f.aborted()).toBe(true)
+ })
+
+ it('also aborts when Content-Length is absent entirely', async () => {
+ const chunks = Array.from({ length: 10 }, () => chunk(8))
+ const f = fakeFetch({ contentLength: null, chunks })
+ await expect(fetchBoundedBytes('u', 't', { maxBytes: 10 }, { fetch: f.fetch })).rejects.toThrow(
+ /exceeds the 10-byte limit/
+ )
+ expect(f.pulledChunks()).toBeLessThan(chunks.length)
+ })
+
+ it('throws an ApiError with the upstream status on a non-ok response', async () => {
+ const f = fakeFetch({ ok: false, status: 403, chunks: [] })
+ await expect(
+ fetchBoundedBytes('u', 't', { maxBytes: 10 }, { fetch: f.fetch })
+ ).rejects.toMatchObject({ status: 403 })
+ })
++
++ it('carries the body and Retry-After off a rate-limited response', async () => {
++ // The status alone tells the renderer it was throttled but not for how
++ // long, and a read plane that cannot name the window has nothing to wait
++ // for. `surfaceGfsGrantError` reads `retryAfterSeconds` out of the body and
++ // falls back to the header when an upstream proxy returned a body it cannot
++ // parse, so the ceiling must not consume either on the way through. The
++ // ceiling itself is deliberately not applied to an error body: that is the
++ // server's own diagnostic, not the payload this bound exists to keep out of
++ // memory.
++ const f = fakeFetch({
++ ok: false,
++ status: 429,
++ bodyText: JSON.stringify({ error: 'rate_limited', retryAfterSeconds: 7 }),
++ retryAfter: '7',
++ chunks: [],
++ })
++
++ const rejection = await fetchBoundedBytes('u', 't', { maxBytes: 10 }, { fetch: f.fetch }).then(
++ () => {
++ throw new Error('fetchBoundedBytes resolved; expected the upstream 429 to propagate')
++ },
++ (error: unknown) => error
++ )
++
++ expect(rejection).toBeInstanceOf(ApiError)
++ expect((rejection as ApiError).status).toBe(429)
++ expect((rejection as ApiError).bodyText).toContain('"retryAfterSeconds":7')
++ expect((rejection as ApiError).retryAfter).toBe('7')
++ })
+ })
diff --cc desktop-app/ui/src/components/GfsImagePreview/Body.tsx
index 000000000,078369c25..d8ebab419
mode 000000,100644..100644
--- a/desktop-app/ui/src/components/GfsImagePreview/Body.tsx
+++ b/desktop-app/ui/src/components/GfsImagePreview/Body.tsx
@@@ -1,0 -1,192 +1,205 @@@
+ import { useEffect, useId, useRef, useState } from 'react'
+ import { Button, StatusBanner } from '@components/Common'
+ import { IconCopy } from '@components/SidebarNav/icons'
+ import { GFS_IMAGE_PREVIEW_MAX_BYTES } from '@constants/gfsImagePreview'
++import { describeGfsReadError } from '@lib/gfsGrantErrors'
+ 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 {
+ // The listed size is a skip HINT (fail fast without a round-trip); the
+ // download itself is independently bounded so a wrong listed size cannot
+ // materialize an oversized payload.
+ assertGfsImagePreviewSize(byteLength)
+ const { bytes } = await window.clerum.gfs.downloadPreview(
+ gfsUri,
+ GFS_IMAGE_PREVIEW_MAX_BYTES
+ )
+ 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')
++ // Through the shared read-plane presenter, not raw. `downloadPreview`
++ // crosses Electron IPC, so a rejection arrives as
++ // "Error invoking remote method 'gfs:downloadPreview': Error: 429 …" —
++ // our own process boundary plus a bare status line, put in front of the
++ // user in a banner. The presenter strips the wrapper and gives a rate
++ // limit the same words the Files page uses; the size guards above and
++ // the download ceiling keep theirs, because it passes every other
++ // verdict through untouched.
++ setPreviewError(
++ error instanceof Error
++ ? describeGfsReadError(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 --cc desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx
index 000000000,c57b75c2b..f4380f676
mode 000000,100644..100644
--- a/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx
+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx
@@@ -1,0 -1,221 +1,229 @@@
+ 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 { GFS_MARKDOWN_PREVIEW_MAX_BYTES } from '@constants/gfsMarkdownPreview'
++import { describeGfsReadError } from '@lib/gfsGrantErrors'
+ 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 {
+ // The listed size is a skip HINT (fail fast without a round-trip); the
+ // download itself is independently bounded so a wrong listed size cannot
+ // materialize an oversized payload.
+ assertGfsMarkdownPreviewSize(byteLength)
+ const { bytes } = await window.clerum.gfs.downloadPreview(
+ gfsUri,
+ GFS_MARKDOWN_PREVIEW_MAX_BYTES
+ )
+ assertGfsMarkdownPreviewSize(bytes.byteLength)
+ const markdown = new TextDecoder().decode(bytes)
+ if (active) setSource(markdown)
+ } catch (error) {
+ if (!active) return
+ onDownloadErrorRef.current?.(error)
++ // Through the shared read-plane presenter, not raw — see the note in
++ // `GfsImagePreview/Body.tsx`. A 429 crossing Electron IPC otherwise
++ // reaches the banner as "Error invoking remote method
++ // 'gfs:downloadPreview': Error: 429 …"; every other verdict, including
++ // the size guard and the download ceiling, passes through untouched.
+ setPreviewError(
- error instanceof Error ? error.message : 'Could not load the Markdown preview'
++ error instanceof Error
++ ? describeGfsReadError(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 --cc desktop-app/ui/src/components/GfsVideoPreview/Body.tsx
index 000000000,041b72b9b..ff325a911
mode 000000,100644..100644
--- a/desktop-app/ui/src/components/GfsVideoPreview/Body.tsx
+++ b/desktop-app/ui/src/components/GfsVideoPreview/Body.tsx
@@@ -1,0 -1,94 +1,104 @@@
+ import { useEffect, useId, useRef, useState } from 'react'
+ import { StatusBanner } from '@components/Common'
+ import { GFS_VIDEO_PREVIEW_MAX_BYTES } from '@constants/gfsVideoPreview'
++import { describeGfsReadError } from '@lib/gfsGrantErrors'
+ 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 {
+ // The listed size is a skip HINT (fail fast without a round-trip); the
+ // download itself is independently bounded so a wrong listed size cannot
+ // materialize an oversized payload.
+ assertGfsVideoPreviewSize(byteLength)
+ const { bytes } = await window.clerum.gfs.downloadPreview(
+ gfsUri,
+ GFS_VIDEO_PREVIEW_MAX_BYTES
+ )
+ 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')
++ // Through the shared read-plane presenter, not raw — see the note in
++ // `GfsImagePreview/Body.tsx`. A 429 crossing Electron IPC otherwise
++ // reaches the banner as "Error invoking remote method
++ // 'gfs:downloadPreview': Error: 429 …"; every other verdict, including
++ // the size guard and the download ceiling, passes through untouched.
++ setPreviewError(
++ error instanceof Error
++ ? describeGfsReadError(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 --cc desktop-app/ui/src/components/__tests__/gfsPreviewReadErrors.test.tsx
index 0a9ebd3da,000000000..436cc36b1
mode 100644,000000..100644
--- a/desktop-app/ui/src/components/__tests__/gfsPreviewReadErrors.test.tsx
+++ b/desktop-app/ui/src/components/__tests__/gfsPreviewReadErrors.test.tsx
@@@ -1,133 -1,0 +1,129 @@@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
- import { GfsImagePreview } from '../GfsImagePreview'
- import { GfsMarkdownPreview } from '../GfsMarkdownPreview'
- import { GfsVideoPreview } from '../GfsVideoPreview'
++import { GfsImagePreviewBody } from '../GfsImagePreview'
++import { GfsMarkdownPreviewBody } from '../GfsMarkdownPreview'
++import { GfsVideoPreviewBody } from '../GfsVideoPreview'
+
+/**
- * The three previews all read bytes through `window.clerum.gfs.download`, which
- * crosses Electron IPC, and all three put whatever comes back into a
- * `StatusBanner`. Raw, that banner reads
- * "Error invoking remote method 'gfs:download': Error: 429 Too Many Requests"
- * — our own main/renderer split plus a bare status line, in front of a user who
- * opened a file. The Files page stopped saying that; these had not.
++ * The three preview bodies all read bytes through
++ * `window.clerum.gfs.downloadPreview`, which crosses Electron IPC, and all three
++ * put whatever comes back into a `StatusBanner`. Raw, that banner reads
++ * "Error invoking remote method 'gfs:downloadPreview': Error: 429 Too Many
++ * Requests" — our own main/renderer split plus a bare status line, in front of a
++ * user who opened a file. The Files page stopped saying that; these had not.
++ *
++ * The bodies are the unit under test rather than the modal chrome: after the
++ * de-modalization only the image preview still has a modal wrapper, and every
++ * surface that reads bytes (the surviving modal, `FilePreviewPage`, the
++ * workspace preview tab) mounts one of these three.
+ *
+ * One file for the three because the contract is one function. A preview that
+ * stops routing through it fails here regardless of which one it is.
+ */
+
+const RATE_LIMITED_DOWNLOAD =
- "Error invoking remote method 'gfs:download': Error: 429 Too Many Requests: " +
++ "Error invoking remote method 'gfs:downloadPreview': Error: 429 Too Many Requests: " +
+ 'Too Many Requests httpStatus=429 retryAfterSeconds=7'
+
+const PREVIEWS = [
+ [
+ 'image',
+ () => (
- <GfsImagePreview
++ <GfsImagePreviewBody
+ byteLength={3}
+ fileName="diagram.png"
+ gfsUri="gfs://main/image-1"
+ mimeType="image/png"
- onClose={vi.fn()}
+ />
+ ),
+ ],
+ [
+ 'video',
+ () => (
- <GfsVideoPreview
++ <GfsVideoPreviewBody
+ byteLength={3}
+ fileName="clip.mp4"
+ gfsUri="gfs://main/video-1"
+ mimeType="video/mp4"
- onClose={vi.fn()}
+ />
+ ),
+ ],
+ [
+ 'markdown',
- () => (
- <GfsMarkdownPreview
- byteLength={3}
- fileName="notes.md"
- gfsUri="gfs://main/markdown-1"
- onClose={vi.fn()}
- />
- ),
++ () => <GfsMarkdownPreviewBody byteLength={3} fileName="notes.md" gfsUri="gfs://main/md-1" />,
+ ],
+] as const
+
+describe('GFS preview read failures', () => {
- let download: ReturnType<typeof vi.fn>
++ let downloadPreview: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
- download = vi.fn(async () => {
++ downloadPreview = vi.fn(async () => {
+ throw new Error(RATE_LIMITED_DOWNLOAD)
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
- value: { gfs: { download } },
++ value: { gfs: { downloadPreview } },
+ })
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ value: vi.fn(() => 'blob:gfs-preview'),
+ })
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+
+ disconnect() {}
+ }
+ )
+ })
+
+ afterEach(() => {
+ cleanup()
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it.each(PREVIEWS)(
+ 'presents a rate-limited %s download in the shared read-plane words',
+ async (_label, renderPreview) => {
+ render(renderPreview())
+
+ // Liveness witness: the read really ran and really rejected, so the
+ // absence of the IPC wrapper below is a presented verdict and not a
+ // preview that never attempted the download.
- await waitFor(() => expect(download).toHaveBeenCalledTimes(1))
++ await waitFor(() => expect(downloadPreview).toHaveBeenCalledTimes(1))
+ await waitFor(() =>
+ expect(screen.getByText('Too many file requests — try again in 7s.')).toBeTruthy()
+ )
+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()
+ }
+ )
+
+ it.each(PREVIEWS)(
+ 'keeps a non-rate-limited %s verdict, minus the IPC wrapper',
+ async (_label, renderPreview) => {
- download.mockImplementation(async () => {
++ downloadPreview.mockImplementation(async () => {
+ throw new Error(
- "Error invoking remote method 'gfs:download': Error: 403 Forbidden: " +
++ "Error invoking remote method 'gfs:downloadPreview': Error: 403 Forbidden: " +
+ 'read access was revoked httpStatus=403'
+ )
+ })
+
+ render(renderPreview())
+
- await waitFor(() => expect(download).toHaveBeenCalledTimes(1))
++ await waitFor(() => expect(downloadPreview).toHaveBeenCalledTimes(1))
+ // The server's own verdict survives — fail loud, never swallowed — while
+ // the wrapper naming our process boundary does not. Without this case the
+ // assertions above would also pass on a presenter that answered
+ // "Too many file requests" to everything.
+ await waitFor(() =>
+ expect(screen.getByText(/403 Forbidden: read access was revoked/)).toBeTruthy()
+ )
+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()
+ }
+ )
+})
diff --cc desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 654a0034a,185d230ae..8cbd3dfa9
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@@ -334,27 -253,8 +359,27 @@@ export function useGfsBrowserController
setAccessState('active')
void queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
}
- }, [queryClient, sessionScope])
+ }, [queryClient, sessionScope, setAccessState])
+ // Epoch (ms) before which a focus-driven revalidation would only burn
+ // another slice of the rate-limit budget the server just refused. A ref,
+ // not state: the refetch predicates read it when focus fires, and mutating
+ // it must not re-render. 0 means "not paused".
+ const pausedUntilRef = useRef(0)
+ // TanStack 5 accepts `(query) => boolean | 'always'` here. It must return
+ // 'always' | false, never a boolean: `true` means "refetch if stale", and
+ // under desktopQueryDefaults' staleTime of Infinity a query that HOLDS DATA
+ // never is — so `true` would drop the focus revalidation this option exists
+ // for, which is picking up grants made from another surface. (It is not that
+ // staleness is impossible under Infinity: `isStaleByTime` short-circuits to
+ // true when `data === undefined` or the query was invalidated, both
+ // reachable here. `'always'` is unconditional, which is what we want when
+ // not paused.)
+ const refetchOnFocusUnlessPaused = useCallback(
+ (): 'always' | false => (Date.now() >= pausedUntilRef.current ? 'always' : false),
+ []
+ )
+
const accessibleQuery = useInfiniteQuery({
queryKey: desktopQueryKeys.gfsAccessible(sessionScope ?? 'anonymous', DRIVE),
queryFn: async ({ pageParam }): Promise<GfsAccessibleWirePage> => {
diff --cc desktop-app/ui/src/pages/FilesPage.tsx
index 7b82b9ef4,5ce81da4e..25c1b5914
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@@ -18,11 -18,7 +18,8 @@@ 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 { GfsReadFailureCard } from '@components/GfsReadFailureCard'
import { GfsResourceMenu } from '@components/GfsResourceMenu'
- import { GfsVideoPreview } from '@components/GfsVideoPreview'
import {
IconAttachFile,
IconCheck,
@@@ -36,22 -32,12 +33,21 @@@
IconUpload,
} from '@components/SidebarNav/icons'
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
-import { type GfsCrumb, useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'
+import {
+ type GfsCrumb,
+ type GfsDiscoveryFailure,
+ useGfsBrowserController,
+} from '@hooks/domain/useGfsBrowserController'
import { isEventFromNestedInteractive } from '@lib/clickableRowProps'
+ import { saveGfsFileToDisk } from '@lib/gfsDownload'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
-import { describeGfsGrantError } from '@lib/gfsGrantErrors'
+import {
+ describeGfsGrantError,
+ describeGfsReadError,
+ isRateLimited,
+ parseRetryAfterSeconds,
+} 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'
diff --cc desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 083268fbb,361e762ac..fc73ddbff
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@@ -4,9 -4,6 +4,7 @@@ import { afterEach, beforeEach, describ
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 { desktopQueryKeys } from '@hooks/domain/queryKeys'
import type { GfsCrumb } from '@hooks/domain/useGfsBrowserController'
import type { Tone } from '@/uiTypes'
import { FilesPage } from '../FilesPage'