Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): refresh deduped preview payload and bound preview downloads (R1-H4)
Diego Zacarias3efa15662efc
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 585ca3c8a..df6e868d6 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -16,6 +16,7 @@ import {saveDesktopRuntimeConfig,selectDesktopRuntimeConfigOption,} from './config.js'+import { fetchBoundedBytes } from './gfs/boundedDownload.js'import { type DelegationAffordances, delegationAffordances } from './gfs/delegation.js'import {DesktopGfsUploadJob,@@ -853,13 +854,7 @@ export class AppService {return config.externalRestApiBaseUrl},requestJson,- fetchBytes: async (url, token) => {- const res = await fetch(url, { headers: { authorization: `Bearer ${token}` } })- if (!res.ok) {- throw new ApiError(`gfs download failed: ${res.status}`, res.status, '')- }- return res.arrayBuffer()- },+ fetchBytes: (url, token, opts) => fetchBoundedBytes(url, token, opts),})private readonly tokenStore = new TokenStore()private readonly rpcTokenManager = new RpcTokenManager(this.authClient)@@ -1930,9 +1925,18 @@ export class AppService {return this.gfsClient.resolveUri(uri, this.requireSessionToken())}- /** Resolve then download a gfs:// resource's bytes through the brokered proxy. */- async downloadGfsUri(uri: string) {- return this.gfsClient.download(uri, this.requireSessionToken())+ /**+ * Resolve then download a gfs:// resource's bytes through the brokered proxy.+ * `maxBytes` bounds the download for the preview path (rejected before an+ * oversized payload materializes); omitting it (save-to-disk, plugin SDK)+ * reads the full body.+ */+ async downloadGfsUri(uri: string, maxBytes?: number) {+ return this.gfsClient.download(+ uri,+ this.requireSessionToken(),+ maxBytes !== undefined ? { maxBytes } : undefined+ )}/** List a gfs directory's children (deny-by-default: only what the user is granted). */diff --git a/desktop-app/src/gfs/boundedDownload.ts b/desktop-app/src/gfs/boundedDownload.tsnew file mode 100644index 000000000..0f23a1748--- /dev/null+++ b/desktop-app/src/gfs/boundedDownload.ts@@ -0,0 +1,92 @@+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, '')+ }+ 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 --git a/desktop-app/src/gfs/uriHandler.ts b/desktop-app/src/gfs/uriHandler.tsindex 2f0e988c3..6eaca4ecd 100644--- a/desktop-app/src/gfs/uriHandler.ts+++ b/desktop-app/src/gfs/uriHandler.ts@@ -89,8 +89,12 @@ export interface GfsTransport {url: string,options?: { token?: string; body?: unknown; timeoutMs?: number; signal?: AbortSignal }): Promise<T>- /** Binary fetch for downloads (resolves to the raw bytes). */- fetchBytes(url: string, token: string): Promise<ArrayBuffer>+ /**+ * Binary fetch for downloads (resolves to the raw bytes). `opts.maxBytes`+ * bounds the download so an oversized payload is rejected before it fully+ * materializes; omitting it reads the whole body (the save-to-disk path).+ */+ fetchBytes(url: string, token: string, opts?: { maxBytes?: number }): Promise<ArrayBuffer>}/**@@ -425,19 +429,26 @@ export class GfsClient {return unwrap(payload)}- /** 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 }> {const resource = await this.resolveUri(uri, token)- const bytes = await this.transport.fetchBytes(- joinUrl(- this.transport.baseUrl,- `/api/v1/me/gfs/proxy/${resource.resourceId}?drive=${encodeURIComponent(resource.drive)}`- ),- 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 }}diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex dfe769665..e072288de 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -409,6 +409,20 @@ export function registerIpcHandlers(service: AppService): void {assertTrustedSender(event)return service.downloadGfsUri(sanitizeString(payload?.uri))})+ ipcMain.handle(+ 'gfs:downloadPreview',+ async (event, payload: { uri: string; maxBytes: number }) => {+ assertTrustedSender(event)+ // The preview path is bounded: a required ceiling caps the download so an+ // oversized payload is rejected before it materializes (the save-to-disk+ // 'gfs:download' path above stays intentionally uncapped).+ const maxBytes = sanitizeOptionalPositiveInteger(payload?.maxBytes, 'maxBytes')+ if (maxBytes === undefined) {+ throw new Error('maxBytes is required for a preview download')+ }+ return service.downloadGfsUri(sanitizeString(payload?.uri), maxBytes)+ }+ )ipcMain.handle('gfs:listAccessible',async (event, payload: { drive?: string; cursor?: string }) => {diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex 0651361ee..79a047e4f 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -135,6 +135,8 @@ const clerum = Object.freeze({gfs: {resolve: (uri: string) => ipcRenderer.invoke('gfs:resolve', { uri }),download: (uri: string) => ipcRenderer.invoke('gfs:download', { uri }),+ downloadPreview: (uri: string, maxBytes: number) =>+ ipcRenderer.invoke('gfs:downloadPreview', { uri, maxBytes }),listAccessible: (drive?: string, cursor?: string) =>ipcRenderer.invoke('gfs:listAccessible', { drive, cursor }),listChildren: (resourceId: string, drive?: string, cursor?: string) =>diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex 2bfb8194b..1b9ba4585 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -140,6 +140,26 @@ declare global {}bytes: ArrayBuffer}>+ downloadPreview: (+ uri: string,+ maxBytes: number+ ) => Promise<{+ resource: {+ drive: string+ resourceId: string+ parentResourceId: string | null+ rid?: string+ gfsUri: string+ name: string+ kind: string+ pathCache: string | null+ path?: string | null+ version: number+ bytes?: number+ updatedAt?: string+ }+ bytes: ArrayBuffer+ }>listAccessible: (drive?: string,cursor?: stringdiff --git a/desktop-app/test/gfsBoundedDownload.test.ts b/desktop-app/test/gfsBoundedDownload.test.tsnew file mode 100644index 000000000..b8b98008f--- /dev/null+++ b/desktop-app/test/gfsBoundedDownload.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it, vi } 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+ 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,+ }+ 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,+ }+ }) 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 })+ })+})diff --git a/desktop-app/test/gfsPreviewDownloadWiring.test.ts b/desktop-app/test/gfsPreviewDownloadWiring.test.tsnew file mode 100644index 000000000..34443835d--- /dev/null+++ b/desktop-app/test/gfsPreviewDownloadWiring.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it, vi } from 'vitest'+import { GfsClient, type GfsTransport, type ResolvedGfsResource } from '../src/gfs/uriHandler.js'+import { ApiError } from '../src/httpClient.js'++/**+ * R1-H4 Part B — the PREVIEW download path must be bounded. This is the+ * regression fixture: it drives `GfsClient.download` and proves the bound is+ * threaded through to the transport (the ceiling reaches `fetchBytes`), while+ * the save-to-disk path stays uncapped.+ *+ * It fails against the pre-fix head because there `download` had no `maxBytes`+ * option: the preview call materialized the full (oversized) payload and+ * resolved instead of rejecting. The bound mechanics themselves (up-front+ * Content-Length reject + mid-stream abort) are unit-tested in+ * `gfsBoundedDownload.test.ts` against the real producer.+ */++const RID = '0123456789abcdef0123456789abcdef'++const RESOURCE: ResolvedGfsResource = {+ drive: 'main',+ resourceId: RID,+ parentResourceId: null,+ rid: RID,+ gfsUri: `gfs://main/${RID}`,+ name: 'huge.png',+ kind: 'file',+ pathCache: '/huge.png',+ version: 1,+ bytes: 5,+}++// Stand-in for the real bounded transport: it honors `opts.maxBytes` exactly as+// production `fetchBoundedBytes` does — an over-ceiling payload is rejected+// rather than returned. (The real bound's stream/Content-Length mechanics are+// covered in gfsBoundedDownload.test.ts; here we assert `download` WIRES it.)+const OVERSIZED = new Uint8Array(50).fill(7).buffer++function boundedTransport(): GfsTransport {+ return {+ baseUrl: 'https://api.example/',+ requestJson: vi.fn(async () => ({ ok: true, data: RESOURCE })) as GfsTransport['requestJson'],+ fetchBytes: vi.fn(async (_url: string, _token: string, opts?: { maxBytes?: number }) => {+ if (opts?.maxBytes !== undefined && OVERSIZED.byteLength > opts.maxBytes) {+ throw new ApiError(`gfs preview download exceeds the ${opts.maxBytes}-byte limit`, 413, '')+ }+ return OVERSIZED+ }) as GfsTransport['fetchBytes'],+ }+}++describe('GfsClient.download — preview bound wiring (R1-H4 Part B)', () => {+ it('rejects an oversized preview download before returning the full payload', async () => {+ const t = boundedTransport()+ await expect(+ new GfsClient(t).download(`gfs://main/${RID}`, 'tok', { maxBytes: 10 })+ ).rejects.toThrow(/exceeds the 10-byte limit/)+ // The ceiling must reach the transport — this is what the pre-fix head omits.+ expect(t.fetchBytes).toHaveBeenCalledWith(+ `https://api.example/api/v1/me/gfs/proxy/${RID}?drive=main`,+ 'tok',+ { maxBytes: 10 }+ )+ })++ it('leaves the save-to-disk path uncapped (no bound forwarded, full payload returned)', async () => {+ const t = boundedTransport()+ const { bytes } = await new GfsClient(t).download(`gfs://main/${RID}`, 'tok')+ expect(bytes.byteLength).toBe(OVERSIZED.byteLength)+ // Unbounded call keeps the exact 2-arg signature (no third opts arg).+ expect(t.fetchBytes).toHaveBeenCalledWith(+ `https://api.example/api/v1/me/gfs/proxy/${RID}?drive=main`,+ 'tok'+ )+ })+})diff --git a/desktop-app/ui/src/components/GfsImagePreview/Body.tsx b/desktop-app/ui/src/components/GfsImagePreview/Body.tsxindex 36a334cb1..078369c25 100644--- a/desktop-app/ui/src/components/GfsImagePreview/Body.tsx+++ b/desktop-app/ui/src/components/GfsImagePreview/Body.tsx@@ -1,6 +1,7 @@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 { assertGfsImagePreviewSize } from '@lib/gfsImagePreview'import type { GfsImagePreviewBodyProps } from './types'@@ -42,8 +43,14 @@ export function GfsImagePreviewBody({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.download(gfsUri)+ const { bytes } = await window.clerum.gfs.downloadPreview(+ gfsUri,+ GFS_IMAGE_PREVIEW_MAX_BYTES+ )assertGfsImagePreviewSize(bytes.byteLength)if (!active) returnconst blob = new Blob([bytes], { type: mimeType })diff --git a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreview.test.tsx b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreview.test.tsxindex f5ac94d92..3774392f3 100644--- a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreview.test.tsx+++ b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreview.test.tsx@@ -14,7 +14,7 @@ describe('GfsImagePreview layout', () => {configurable: true,value: {gfs: {- download: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer })),+ downloadPreview: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]).buffer })),},},})diff --git a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsxindex 4460e80ad..3d226378e 100644--- a/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx+++ b/desktop-app/ui/src/components/GfsImagePreview/GfsImagePreviewBody.test.tsx@@ -4,15 +4,15 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/reimport { GFS_IMAGE_PREVIEW_MAX_BYTES } from '@constants/gfsImagePreview'import { GfsImagePreviewBody } from './Body'-// The producer (`window.clerum.gfs.download`) returns `{ bytes: ArrayBuffer }`+// The producer (`window.clerum.gfs.downloadPreview`) 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 }))+ const downloadPreview = vi.fn(async () => ({ bytes }))Object.defineProperty(window, 'clerum', {configurable: true,- value: { gfs: { download } },+ value: { gfs: { downloadPreview } },})- return download+ return downloadPreview}describe('GfsImagePreviewBody', () => {@@ -30,7 +30,7 @@ describe('GfsImagePreviewBody', () => {})it('downloads by gfsUri and renders the image without a modal', async () => {- const download = stubDownload(new Uint8Array([1, 2, 3]).buffer)+ const downloadPreview = stubDownload(new Uint8Array([1, 2, 3]).buffer)render(<GfsImagePreviewBody@@ -44,7 +44,9 @@ describe('GfsImagePreviewBody', () => {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')+ // The preview download carries its per-kind ceiling so the main process can+ // bound the fetch (R1-H4 Part B).+ expect(downloadPreview).toHaveBeenCalledWith('gfs://main/image-1', GFS_IMAGE_PREVIEW_MAX_BYTES)// No portal/backdrop/dialog chrome — this is the de-modalized body.expect(screen.queryByRole('dialog')).toBeNull()expect(screen.queryByRole('presentation')).toBeNull()@@ -65,7 +67,7 @@ describe('GfsImagePreviewBody', () => {})it('rejects an oversized image from metadata before downloading', async () => {- const download = stubDownload(new Uint8Array([1]).buffer)+ const downloadPreview = stubDownload(new Uint8Array([1]).buffer)render(<GfsImagePreviewBodybyteLength={GFS_IMAGE_PREVIEW_MAX_BYTES + 1}@@ -75,17 +77,17 @@ describe('GfsImagePreviewBody', () => {/>)expect(await screen.findByText(/Image previews are limited to 10 MB/)).toBeTruthy()- expect(download).not.toHaveBeenCalled()+ expect(downloadPreview).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 () => {+ const downloadPreview = vi.fn(async () => {throw new Error('403 Forbidden')})Object.defineProperty(window, 'clerum', {configurable: true,- value: { gfs: { download } },+ value: { gfs: { downloadPreview } },})render(diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsxindex 6abe2eab3..c57b75c2b 100644--- a/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/Body.tsx@@ -2,6 +2,7 @@ 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 { assertGfsMarkdownPreviewSize } from '@lib/gfsMarkdownPreview'import { parseVanillaMarkdown } from '@lib/vanillaMarkdown'import type { MarkdownBlock, MarkdownInlineNode } from '@lib/vanillaMarkdown.types'@@ -104,8 +105,14 @@ export function GfsMarkdownPreviewBody({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.download(gfsUri)+ 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)diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.test.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.test.tsxindex af8c1743b..ba807001a 100644--- a/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.test.tsx+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/GfsMarkdownPreviewBody.test.tsx@@ -4,14 +4,14 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/reimport { GFS_MARKDOWN_PREVIEW_MAX_BYTES } from '@constants/gfsMarkdownPreview'import { GfsMarkdownPreviewBody } from './Body'-// Mirror the producer shape: `window.clerum.gfs.download` → `{ bytes: ArrayBuffer }`.+// Mirror the producer shape: `window.clerum.gfs.downloadPreview` → `{ bytes: ArrayBuffer }`.function stubDownload(text: string) {- const download = vi.fn(async () => ({ bytes: new TextEncoder().encode(text).buffer }))+ const downloadPreview = vi.fn(async () => ({ bytes: new TextEncoder().encode(text).buffer }))Object.defineProperty(window, 'clerum', {configurable: true,- value: { gfs: { download } },+ value: { gfs: { downloadPreview } },})- return download+ return downloadPreview}describe('GfsMarkdownPreviewBody', () => {@@ -23,7 +23,7 @@ describe('GfsMarkdownPreviewBody', () => {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 downloadPreview = stubDownload(markdown)const { container } = render(<GfsMarkdownPreviewBody@@ -38,7 +38,10 @@ describe('GfsMarkdownPreviewBody', () => {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(downloadPreview).toHaveBeenCalledWith(+ 'gfs://main/markdown-1',+ GFS_MARKDOWN_PREVIEW_MAX_BYTES+ )expect(screen.queryByRole('dialog')).toBeNull()})@@ -76,7 +79,7 @@ describe('GfsMarkdownPreviewBody', () => {})it('rejects an oversized markdown file from metadata before downloading', async () => {- const download = stubDownload('x')+ const downloadPreview = stubDownload('x')render(<GfsMarkdownPreviewBodybyteLength={GFS_MARKDOWN_PREVIEW_MAX_BYTES + 1}@@ -85,17 +88,17 @@ describe('GfsMarkdownPreviewBody', () => {/>)expect(await screen.findByText(/Markdown previews are limited to 2 MB/)).toBeTruthy()- expect(download).not.toHaveBeenCalled()+ expect(downloadPreview).not.toHaveBeenCalled()})it('fails closed on a download error and notifies onDownloadError', async () => {const onDownloadError = vi.fn()- const download = vi.fn(async () => {+ const downloadPreview = vi.fn(async () => {throw new Error('401 not authenticated')})Object.defineProperty(window, 'clerum', {configurable: true,- value: { gfs: { download } },+ value: { gfs: { downloadPreview } },})render(<GfsMarkdownPreviewBodydiff --git a/desktop-app/ui/src/components/GfsVideoPreview/Body.tsx b/desktop-app/ui/src/components/GfsVideoPreview/Body.tsxindex 6ed221f75..041b72b9b 100644--- a/desktop-app/ui/src/components/GfsVideoPreview/Body.tsx+++ b/desktop-app/ui/src/components/GfsVideoPreview/Body.tsx@@ -1,5 +1,6 @@import { useEffect, useId, useRef, useState } from 'react'import { StatusBanner } from '@components/Common'+import { GFS_VIDEO_PREVIEW_MAX_BYTES } from '@constants/gfsVideoPreview'import { assertGfsVideoPreviewSize } from '@lib/gfsVideoPreview'import type { GfsVideoPreviewBodyProps } from './types'@@ -36,8 +37,14 @@ export function GfsVideoPreviewBody({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.download(gfsUri)+ const { bytes } = await window.clerum.gfs.downloadPreview(+ gfsUri,+ GFS_VIDEO_PREVIEW_MAX_BYTES+ )assertGfsVideoPreviewSize(bytes.byteLength)if (!active) returnobjectUrl = URL.createObjectURL(new Blob([bytes], { type: mimeType }))diff --git a/desktop-app/ui/src/components/GfsVideoPreview/GfsVideoPreviewBody.test.tsx b/desktop-app/ui/src/components/GfsVideoPreview/GfsVideoPreviewBody.test.tsxindex 3670ca63b..eb4c78635 100644--- a/desktop-app/ui/src/components/GfsVideoPreview/GfsVideoPreviewBody.test.tsx+++ b/desktop-app/ui/src/components/GfsVideoPreview/GfsVideoPreviewBody.test.tsx@@ -5,12 +5,12 @@ import { GFS_VIDEO_PREVIEW_MAX_BYTES } from '@constants/gfsVideoPreview'import { GfsVideoPreviewBody } from './Body'function stubDownload(bytes: ArrayBuffer) {- const download = vi.fn(async () => ({ bytes }))+ const downloadPreview = vi.fn(async () => ({ bytes }))Object.defineProperty(window, 'clerum', {configurable: true,- value: { gfs: { download } },+ value: { gfs: { downloadPreview } },})- return download+ return downloadPreview}describe('GfsVideoPreviewBody', () => {@@ -30,7 +30,7 @@ describe('GfsVideoPreviewBody', () => {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)+ const downloadPreview = stubDownload(new Uint8Array([1, 2, 3]).buffer)render(<GfsVideoPreviewBody@@ -46,12 +46,12 @@ describe('GfsVideoPreviewBody', () => {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(downloadPreview).toHaveBeenCalledWith('gfs://main/video-1', GFS_VIDEO_PREVIEW_MAX_BYTES)expect(screen.queryByRole('dialog')).toBeNull()})it('rejects an oversized video from metadata before downloading', async () => {- const download = stubDownload(new Uint8Array([1]).buffer)+ const downloadPreview = stubDownload(new Uint8Array([1]).buffer)render(<GfsVideoPreviewBodybyteLength={GFS_VIDEO_PREVIEW_MAX_BYTES + 1}@@ -61,17 +61,17 @@ describe('GfsVideoPreviewBody', () => {/>)expect(await screen.findByText(/Video previews are limited to 100 MB/)).toBeTruthy()- expect(download).not.toHaveBeenCalled()+ expect(downloadPreview).not.toHaveBeenCalled()})it('fails closed on a download error and notifies onDownloadError', async () => {const onDownloadError = vi.fn()- const download = vi.fn(async () => {+ const downloadPreview = vi.fn(async () => {throw new Error('403 Forbidden')})Object.defineProperty(window, 'clerum', {configurable: true,- value: { gfs: { download } },+ value: { gfs: { downloadPreview } },})render(<GfsVideoPreviewBodydiff --git a/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts b/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.tsindex 0f8e73dd2..5f24598a9 100644--- a/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts+++ b/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts@@ -23,7 +23,13 @@ import {setAppTabTitle,setFilesTabPath,} from '../workspaceTabs'-import type { ActiveChat, SettingsSection, WorkspaceTabsState } from '../workspaceTabs.types'+import type {+ ActiveChat,+ OpenPreviewTabInput,+ PreviewTabPayload,+ SettingsSection,+ WorkspaceTabsState,+} from '../workspaceTabs.types'const SECTIONS: SettingsSection[] = ['connectors', 'agents', 'plugins', 'settings']@@ -518,6 +524,169 @@ describe('workspaceTabs — preview multi-instance by gfsUri (spec 18 §3.B.1)',}))})++ // ---- R1-H4 Part A: refocusing a changed resource refreshes the WHOLE payload+ // (a preview tab, unlike the other dedupe branches, carries non-key fields).+ const expectedPreviewPayload = (input: OpenPreviewTabInput): PreviewTabPayload => ({+ gfsUri: input.gfsUri,+ fileKind: input.fileKind,+ byteLength: input.byteLength,+ ...(input.mimeType !== undefined ? { mimeType: input.mimeType } : {}),+ })++ it('refreshes the whole payload when refocusing a changed resource at the same gfsUri', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openPreviewTab(state, {+ id: 'p-1',+ gfsUri: 'gfs://main/same',+ fileKind: 'image',+ mimeType: 'image/png',+ byteLength: 3,+ title: 'small.png',+ })+ // The resource at the SAME uri changed: a large video with a new mime.+ state = openPreviewTab(state, {+ id: 'p-2',+ gfsUri: 'gfs://main/same',+ fileKind: 'video',+ mimeType: 'video/mp4',+ byteLength: 150_000_000,+ title: 'clip.mp4',+ })+ const previews = state.tabs.filter(t => t.kind === 'preview')+ expect(previews).toHaveLength(1)+ expect(previews[0]?.preview).toEqual({+ gfsUri: 'gfs://main/same',+ fileKind: 'video',+ mimeType: 'video/mp4',+ byteLength: 150_000_000,+ })+ expect(previews[0]?.title).toBe('clip.mp4')+ expect(state.activeTabId).toBe('p-1') // focuses the existing tab, keeps its id+ })++ it('refreshes byteLength on refocus even when no new title is supplied (stale-size guard)', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openPreviewTab(state, {+ id: 'p-1',+ gfsUri: 'gfs://main/x',+ fileKind: 'image',+ mimeType: 'image/png',+ byteLength: 3,+ title: 'a.png',+ })+ // A replaced body: same name/kind/mime, but the size ballooned. A title-only+ // patch would keep the stale small byteLength and defeat the size-guard.+ state = openPreviewTab(state, {+ id: 'p-2',+ gfsUri: 'gfs://main/x',+ fileKind: 'image',+ mimeType: 'image/png',+ byteLength: 99_000_000,+ })+ const tab = state.tabs.find(t => t.preview?.gfsUri === 'gfs://main/x')+ expect(tab?.preview?.byteLength).toBe(99_000_000)+ expect(tab?.title).toBe('a.png') // no new title supplied → previous title kept+ })++ it('drops mimeType on refocus when the new resource has none (no stale mime survives)', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openPreviewTab(state, {+ id: 'p-1',+ gfsUri: 'gfs://main/y',+ fileKind: 'image',+ mimeType: 'image/png',+ byteLength: 3,+ })+ state = openPreviewTab(state, {+ id: 'p-2',+ gfsUri: 'gfs://main/y',+ fileKind: 'markdown',+ byteLength: 12,+ })+ const preview = state.tabs.find(t => t.preview?.gfsUri === 'gfs://main/y')?.preview+ expect(preview).toEqual({ gfsUri: 'gfs://main/y', fileKind: 'markdown', byteLength: 12 })+ expect(Object.prototype.hasOwnProperty.call(preview, 'mimeType')).toBe(false)+ })++ // T2 property: a preview tab always reflects the LAST open for its gfsUri — no+ // field of an earlier open survives a refocus.+ it('property: a preview tab carries the payload of the LAST open for its gfsUri', () => {+ const inputArb: fc.Arbitrary<Omit<OpenPreviewTabInput, 'id'>> = fc.record({+ gfsUri: fc.constantFrom('gfs://main/a', 'gfs://main/b', 'gfs://main/c'),+ fileKind: fc.constantFrom('image' as const, 'markdown' as const, 'video' as const),+ byteLength: fc.nat(200_000_000),+ mimeType: fc.option(fc.constantFrom('image/png', 'video/mp4'), { nil: undefined }),+ })+ fc.assert(+ fc.property(fc.array(inputArb, { maxLength: 40 }), partials => {+ const inputs: OpenPreviewTabInput[] = partials.map((p, i) => ({ ...p, id: `p-${i}` }))+ let state = createEmptyWorkspaceTabsState()+ inputs.forEach(input => {+ state = openPreviewTab(state, input)+ })+ const lastByUri = new Map<string, PreviewTabPayload>()+ for (const input of inputs) lastByUri.set(input.gfsUri, expectedPreviewPayload(input))+ const previews = state.tabs.filter(t => t.kind === 'preview')+ // One tab per distinct gfsUri; no duplicate ids.+ expect(previews.length).toBe(new Set(inputs.map(i => i.gfsUri)).size)+ expect(new Set(state.tabs.map(t => t.id)).size).toBe(state.tabs.length)+ for (const t of previews) {+ expect(t.preview).toEqual(lastByUri.get(t.preview!.gfsUri))+ }+ })+ )+ })++ // T2 property: idempotence — reopening the EXACT same input twice preserves the+ // tabs reference (a `setState` bails out) and the active tab.+ it('property: reopening the exact same input is idempotent (same tabs ref)', () => {+ const inputArb: fc.Arbitrary<Omit<OpenPreviewTabInput, 'id'>> = fc.record({+ gfsUri: fc.constantFrom('gfs://main/a', 'gfs://main/b'),+ fileKind: fc.constantFrom('image' as const, 'markdown' as const, 'video' as const),+ byteLength: fc.nat(1_000),+ mimeType: fc.option(fc.constantFrom('image/png'), { nil: undefined }),+ title: fc.option(fc.constantFrom('one.png', 'two.md'), { nil: undefined }),+ })+ fc.assert(+ fc.property(+ fc.array(inputArb, { minLength: 1, maxLength: 20 }),+ fc.nat(),+ (partials, pick) => {+ const inputs: OpenPreviewTabInput[] = partials.map((p, i) => ({ ...p, id: `p-${i}` }))+ let state = createEmptyWorkspaceTabsState()+ inputs.forEach(input => {+ state = openPreviewTab(state, input)+ })+ const chosen = { ...inputs[pick % inputs.length]!, id: 'again' }+ const once = openPreviewTab(state, chosen)+ const twice = openPreviewTab(once, { ...chosen, id: 'again-2' })+ expect(twice.tabs).toBe(once.tabs)+ expect(twice.activeTabId).toBe(once.activeTabId)+ }+ )+ )+ })++ // T2 property: a brand-new gfsUri appends exactly one tab.+ it('property: opening a brand-new gfsUri appends exactly one tab', () => {+ const uriArb = fc.constantFrom('gfs://main/a', 'gfs://main/b', 'gfs://main/c')+ fc.assert(+ fc.property(fc.array(uriArb, { maxLength: 20 }), uriArb, (seed, fresh) => {+ let state = createEmptyWorkspaceTabsState()+ seed+ .filter(u => u !== fresh)+ .forEach((gfsUri, i) => {+ state = openPreviewTab(state, previewInput(`seed-${i}`, gfsUri))+ })+ const before = state.tabs.length+ const next = openPreviewTab(state, previewInput('fresh', fresh))+ expect(next.tabs.length).toBe(before + 1)+ expect(next.tabs.at(-1)?.preview?.gfsUri).toBe(fresh)+ expect(next.activeTabId).toBe('fresh')+ })+ )+ })})describe('workspaceTabs — new chat (blank) with kind guard', () => {diff --git a/desktop-app/ui/src/lib/workspaceTabs.ts b/desktop-app/ui/src/lib/workspaceTabs.tsindex fadefc131..e85248063 100644--- a/desktop-app/ui/src/lib/workspaceTabs.ts+++ b/desktop-app/ui/src/lib/workspaceTabs.ts@@ -7,6 +7,7 @@ import type {OpenFilesTabInput,OpenPreviewTabInput,OpenSettingsTabInput,+ PreviewTabPayload,WorkspaceTab,WorkspaceTabsState,} from './workspaceTabs.types'@@ -307,12 +308,35 @@ export function openPreviewTab(// sanitizer at this single store border; every render site inherits the cleaned// value. Empty-after-sanitize falls back to 'Preview' below.const title = input.title ? sanitizeAppTabTitle(input.title) : ''+ const nextPreview: PreviewTabPayload = {+ gfsUri: input.gfsUri,+ fileKind: input.fileKind,+ byteLength: input.byteLength,+ ...(input.mimeType !== undefined ? { mimeType: input.mimeType } : {}),+ }if (existing) {+ // Focus AND refresh the whole payload: unlike the other open* dedupe+ // branches, a preview tab's payload carries non-key fields (fileKind /+ // byteLength / mimeType) beyond its `gfsUri` key. If the resource at the URI+ // changed (a rename that keeps the URI, a replaced body), a title-only patch+ // would leave STALE metadata — and a stale small `byteLength` lets the body's+ // size-guard wave an oversized new payload through. Keep the same-reference+ // no-op when nothing actually changed so a `setState` still bails out.+ const nextTitle = title || existing.title+ const p = existing.preview+ const unchanged =+ existing.title === nextTitle &&+ p !== undefined &&+ p.gfsUri === nextPreview.gfsUri &&+ p.fileKind === nextPreview.fileKind &&+ p.byteLength === nextPreview.byteLength &&+ p.mimeType === nextPreview.mimeTypereturn {- tabs:- title && existing.title !== title- ? state.tabs.map(tab => (tab.id === existing.id ? { ...tab, title } : tab))- : state.tabs,+ tabs: unchanged+ ? state.tabs+ : state.tabs.map(tab =>+ tab.id === existing.id ? { ...tab, title: nextTitle, preview: nextPreview } : tab+ ),activeTabId: existing.id,}}@@ -320,12 +344,7 @@ export function openPreviewTab(id: input.id,kind: 'preview',title: title || 'Preview',- preview: {- gfsUri: input.gfsUri,- fileKind: input.fileKind,- byteLength: input.byteLength,- ...(input.mimeType !== undefined ? { mimeType: input.mimeType } : {}),- },+ preview: nextPreview,}return { tabs: [...state.tabs, tab], activeTabId: input.id }}diff --git a/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsxindex 03e2c9a9d..c01f04e77 100644--- a/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilePreviewPage.test.tsx@@ -16,14 +16,14 @@ function controller(accessState: 'active' | 'revoked' = 'active') {}}-// The producer (`window.clerum.gfs.download`) returns `{ bytes: ArrayBuffer }`.+// The producer (`window.clerum.gfs.downloadPreview`) returns `{ bytes: ArrayBuffer }`.function stubDownload(impl: () => Promise<{ bytes: ArrayBuffer }>) {- const download = vi.fn(impl)+ const downloadPreview = vi.fn(impl)Object.defineProperty(window, 'clerum', {configurable: true,- value: { gfs: { download } },+ value: { gfs: { downloadPreview } },})- return download+ return downloadPreview}describe('FilePreviewPage', () => {@@ -98,7 +98,7 @@ describe('FilePreviewPage', () => {// 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 () => {+ const downloadPreview = stubDownload(async () => {if (revoked) throw new Error('403 Forbidden')return { bytes: new Uint8Array([1, 2, 3]).buffer }})@@ -119,7 +119,7 @@ describe('FilePreviewPage', () => {// First fetch succeeds and the image renders.expect(await screen.findByAltText('Preview of secret.png')).toBeTruthy()- expect(download).toHaveBeenCalledTimes(1)+ expect(downloadPreview).toHaveBeenCalledTimes(1)// Access is revoked out-of-band → the authority controller reports revoked.revoked = true@@ -131,6 +131,6 @@ describe('FilePreviewPage', () => {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)+ expect(downloadPreview).toHaveBeenCalledTimes(2)})})