Skip to content

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

TypeScript

feat(gfs): prefetch folder children + fix SVG thumbnail MIME

Miguelon Peluchonfb3f93f2f3f4
diff --git a/control-ui/components/GfsBrowser.tsx b/control-ui/components/GfsBrowser.tsx
index 44bb8248f..b70e97ebd 100644
--- a/control-ui/components/GfsBrowser.tsx
+++ b/control-ui/components/GfsBrowser.tsx
@@ -209,7 +209,52 @@ export function GfsBrowser(): React.JSX.Element {
})
}
+ // Cache of prefetched directory children, keyed by the folder's
+ // resourceId. Refs over state because we don't want to re-render
+ // every time a prefetch resolves — the data is consumed lazily in
+ // openDirectory(). Survives across navigation; cleared on unmount.
+ const childCacheRef = useRef<Map<string, TreePage>>(new Map())
+ // True after openDirectory() served cached data; the next useEffect
+ // pass skips the redundant load() so the user keeps seeing the
+ // cached rows instead of a flash of empty items + spinner.
+ const skipNextLoadRef = useRef(false)
+
+ // Warm the cache for every folder row visible in the current view.
+ // Re-runs whenever the listing changes (folder navigation, refresh,
+ // …) and silently no-ops if a folder was already cached. Failed
+ // prefetches are non-fatal; the real navigation surfaces the error.
+ useEffect(() => {
+ const folders = items.filter(child => child.kind === 'directory')
+ if (folders.length === 0) return
+ let cancelled = false
+ folders.forEach(folder => {
+ if (childCacheRef.current.has(folder.resourceId)) return
+ const response = apiGet(
+ `/api/v1/gfs/resources/${encodeURIComponent(folder.resourceId)}/children`,
+ { drive: DRIVE }
+ )
+ if (!response || typeof (response as Promise<TreePage>).then !== 'function') {
+ return
+ }
+ void (response as Promise<TreePage>)
+ .then(page => {
+ if (cancelled) return
+ childCacheRef.current.set(folder.resourceId, page)
+ })
+ .catch(() => {
+ /* ignore — openDirectory will surface the real error */
+ })
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [items])
+
useEffect(() => {
+ if (skipNextLoadRef.current) {
+ skipNextLoadRef.current = false
+ return
+ }
void load(current)
// Reload whenever the current folder changes (navigation).
}, [current, load])
@@ -225,8 +270,21 @@ export function GfsBrowser(): React.JSX.Element {
function openDirectory(child: GfsChild): void {
if (child.kind !== 'directory') return
- setLoading(true)
setCrumbs(prev => [...prev, { id: child.resourceId, rid: child.rid, name: child.name }])
+ const cached = childCacheRef.current.get(child.resourceId)
+ if (cached) {
+ // Render the cached listing immediately. The useEffect-driven
+ // load() will refresh in the background and overwrite if the
+ // server state diverged, so the user still gets fresh data —
+ // they just don't see the loading spinner.
+ setItems(sortChildrenWithDirectoriesFirst(cached.items))
+ setNextCursor(cached.nextCursor)
+ setError('')
+ setLoading(false)
+ skipNextLoadRef.current = true
+ return
+ }
+ setLoading(true)
}
function openFilePreview(child: GfsChild): boolean {
diff --git a/control-ui/components/GfsFileThumbnail/index.tsx b/control-ui/components/GfsFileThumbnail/index.tsx
index bc582e3f2..9b9c338af 100644
--- a/control-ui/components/GfsFileThumbnail/index.tsx
+++ b/control-ui/components/GfsFileThumbnail/index.tsx
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'
import { IconImage } from '@components/Sidebar/icons'
import { GFS_FILE_THUMBNAIL_MAX_BYTES } from '@constants/gfsFileThumbnail'
import { gfsFetchFileBlob } from '@lib/api'
+import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
import type { GfsFileThumbnailProps } from './types'
/**
@@ -32,13 +33,21 @@ export function GfsFileThumbnail({
async function load(): Promise<void> {
try {
- const blob = await gfsFetchFileBlob(rid)
+ const fetched = await gfsFetchFileBlob(rid)
if (cancelled) return
- if (blob.size > GFS_FILE_THUMBNAIL_MAX_BYTES) {
+ if (fetched.size > GFS_FILE_THUMBNAIL_MAX_BYTES) {
setFailed(true)
return
}
- objectUrl = URL.createObjectURL(blob)
+ // SVG (and other image) previews render through <img>, which
+ // only paints the data when the object URL's blob carries the
+ // right MIME type. The proxy may return application/octet-stream
+ // for SVG bodies, so wrap with the type the image preview
+ // modal already computes.
+ const mimeType = gfsImagePreviewMimeType(fileName) ?? fetched.type
+ objectUrl = URL.createObjectURL(
+ mimeType && mimeType !== fetched.type ? new Blob([fetched], { type: mimeType }) : fetched
+ )
setSrc(objectUrl)
} catch {
if (!cancelled) setFailed(true)
@@ -50,7 +59,7 @@ export function GfsFileThumbnail({
cancelled = true
if (objectUrl) URL.revokeObjectURL(objectUrl)
}
- }, [rid, shouldSkip])
+ }, [fileName, rid, shouldSkip])
if (failed || !src) {
return <IconImage />
diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsx
index 0638291a8..165ca1a68 100644
--- a/control-ui/components/__tests__/GfsBrowser.test.tsx
+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx
@@ -223,6 +223,30 @@ describe('GfsBrowser', () => {
expect(path?.getAttribute('stroke-width')).toBe('32')
})
+ it('prefetches every folder child into the in-memory cache', async () => {
+ mockApiGet
+ .mockResolvedValueOnce({
+ items: [
+ child('alpha', 'directory', 1),
+ child('beta', 'directory', 2),
+ child('notes.md', 'file', 3),
+ ],
+ nextCursor: null,
+ })
+ // The prefetch effect fans out one request per directory row.
+ .mockResolvedValue({ items: [], nextCursor: null })
+
+ renderBrowser()
+
+ await waitFor(() => expect(mockApiGet).toHaveBeenCalledTimes(3))
+ expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
+ drive: 'main',
+ })
+ expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-2/children', {
+ drive: 'main',
+ })
+ })
+
it('uses the paperclip header, labels the root as main, and ignores current-crumb clicks', async () => {
mockApiGet.mockResolvedValueOnce({ items: [], nextCursor: null })
renderBrowser()
@@ -719,12 +743,14 @@ describe('GfsBrowser', () => {
items: [child('org', 'directory', 1), child('report.md', 'file', 2)],
nextCursor: null,
})
+ // The 'org' folder prefetch resolves with an empty children page
+ // so the cache holds something realistic.
.mockResolvedValueOnce({ items: [], nextCursor: null })
+ // Navigate back: re-fetch the root listing.
.mockResolvedValueOnce({
items: [child('org', 'directory', 1), child('report.md', 'file', 2)],
nextCursor: null,
})
- .mockResolvedValueOnce({ items: [], nextCursor: null })
mockApiSend.mockResolvedValueOnce({ ok: true })
renderBrowser()
@@ -795,13 +821,20 @@ describe('GfsBrowser', () => {
it('navigates into a directory and lists its children', async () => {
mockApiGet
.mockResolvedValueOnce({ items: [child('org', 'directory', 1)], nextCursor: null })
+ // Prefetch returns org's children so the cache is populated.
.mockResolvedValueOnce({ items: [child('eng', 'directory', 3)], nextCursor: null })
+ // After the click navigates into eng, the prefetcher also reaches
+ // for eng's children. Empty page is fine — eng has no folders.
+ .mockResolvedValueOnce({ items: [], nextCursor: null })
+ // Navigate back: re-fetch the root listing.
.mockResolvedValueOnce({ items: [child('org', 'directory', 1)], nextCursor: null })
renderBrowser()
const orgButton = (await screen.findAllByRole('button', { name: 'org' }))[0]
fireEvent.click(orgButton)
await screen.findAllByText(/eng/)
- expect(mockApiGet).toHaveBeenLastCalledWith('/api/v1/gfs/resources/id-1/children', {
+ // The click handler is served from the prefetch cache; the recorded
+ // apiGet covers the org children fetch that primed the cache.
+ expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {
drive: 'main',
})
// Navigate back to the drive root via the breadcrumb root crumb (Back/Forward were removed).
diff --git a/control-ui/components/__tests__/GfsFileThumbnail.test.tsx b/control-ui/components/__tests__/GfsFileThumbnail.test.tsx
index 22207fbd9..d4832e2c9 100644
--- a/control-ui/components/__tests__/GfsFileThumbnail.test.tsx
+++ b/control-ui/components/__tests__/GfsFileThumbnail.test.tsx
@@ -63,6 +63,21 @@ describe('GfsFileThumbnail', () => {
expect(mockCreateObjectUrl).toHaveBeenCalledTimes(1)
})
+ it('rewraps the blob with image/svg+xml when the proxy returns SVG bytes', async () => {
+ const svgBytes = new Blob(['<svg></svg>'], { type: 'application/octet-stream' })
+ mockGfsFetchFileBlob.mockResolvedValueOnce(svgBytes)
+ renderThumb({
+ byteLength: 64 * 1024,
+ fileName: 'logo.svg',
+ rid: 'r-svg',
+ })
+
+ await screen.findByAltText('Thumbnail of logo.svg')
+ expect(mockCreateObjectUrl).toHaveBeenCalledTimes(1)
+ const blobArg = mockCreateObjectUrl.mock.calls[0]?.[0] as Blob
+ expect(blobArg.type).toBe('image/svg+xml')
+ })
+
it('falls back to the image glyph when the proxy fetch rejects', async () => {
mockGfsFetchFileBlob.mockRejectedValueOnce(new Error('boom'))
renderThumb({
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 285ef880b..314c50b2c 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.444",
+ "version": "0.1.445",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.444",
+ "version": "0.1.445",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-ui/package.json b/control-ui/package.json
index e63ae6c3c..b26a1c932 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.444",
+ "version": "0.1.445",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/desktop-app/ui/src/components/GfsFileThumbnail/index.tsx b/desktop-app/ui/src/components/GfsFileThumbnail/index.tsx
index cc46a6c68..831279035 100644
--- a/desktop-app/ui/src/components/GfsFileThumbnail/index.tsx
+++ b/desktop-app/ui/src/components/GfsFileThumbnail/index.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react'
import { IconImage } from '@components/SidebarNav/icons'
import { GFS_FILE_THUMBNAIL_MAX_BYTES } from '@constants/gfsFileThumbnail'
+import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
import type { GfsFileThumbnailProps } from './types'
/**
@@ -31,7 +32,13 @@ export function GfsFileThumbnail({ byteLength, fileName, rid }: GfsFileThumbnail
setFailed(true)
return
}
- objectUrl = URL.createObjectURL(new Blob([bytes]))
+ // SVG thumbnails need image/svg+xml on the object URL, but the
+ // download IPC can hand us application/octet-stream. Wrap the
+ // bytes with the type the preview modal already computes so the
+ // <img> can actually paint the SVG.
+ const mimeType = gfsImagePreviewMimeType(fileName)
+ const blob = mimeType !== null ? new Blob([bytes], { type: mimeType }) : new Blob([bytes])
+ objectUrl = URL.createObjectURL(blob)
setSrc(objectUrl)
} catch {
if (!cancelled) setFailed(true)
@@ -43,7 +50,7 @@ export function GfsFileThumbnail({ byteLength, fileName, rid }: GfsFileThumbnail
cancelled = true
if (objectUrl) URL.revokeObjectURL(objectUrl)
}
- }, [rid, shouldSkip])
+ }, [fileName, rid, shouldSkip])
if (failed || !src) {
return <IconImage />
diff --git a/desktop-app/ui/src/components/__tests__/GfsFileThumbnail.test.tsx b/desktop-app/ui/src/components/__tests__/GfsFileThumbnail.test.tsx
index 137ed2b75..207fb01ad 100644
--- a/desktop-app/ui/src/components/__tests__/GfsFileThumbnail.test.tsx
+++ b/desktop-app/ui/src/components/__tests__/GfsFileThumbnail.test.tsx
@@ -62,6 +62,21 @@ describe('GfsFileThumbnail', () => {
expect(mockCreateObjectUrl).toHaveBeenCalledTimes(1)
})
+ it('rewraps the blob with image/svg+xml when the download returns SVG bytes', async () => {
+ const svgBytes = new TextEncoder().encode('<svg></svg>').buffer
+ mockDownload.mockResolvedValueOnce({ bytes: svgBytes })
+ renderThumb({
+ byteLength: 64 * 1024,
+ fileName: 'logo.svg',
+ rid: 'r-svg',
+ })
+
+ await screen.findByAltText('Thumbnail of logo.svg')
+ expect(mockCreateObjectUrl).toHaveBeenCalledTimes(1)
+ const blobArg = mockCreateObjectUrl.mock.calls[0]?.[0] as Blob
+ expect(blobArg.type).toBe('image/svg+xml')
+ })
+
it('falls back to the image glyph when the download rejects', async () => {
let rejectDownload: (() => void) | undefined
const slowDownload = new Promise<{ bytes: ArrayBuffer }>((_, reject) => {
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 27d440904..50ab5a116 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -1,5 +1,5 @@
import { type DragEvent as ReactDragEvent, useEffect, useMemo, useRef, useState } from 'react'
-import { useQuery } from '@tanstack/react-query'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Button, EmptyState, IconButton, StatusBanner, TextInput } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
import { GfsFileIcon } from '@components/GfsFileIcon'
@@ -150,6 +150,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
const [droppedUploadCount, setDroppedUploadCount] = useState(0)
const uploadInputRef = useRef<HTMLInputElement | null>(null)
const replaceInputRef = useRef<HTMLInputElement | null>(null)
+ const queryClient = useQueryClient()
const ctrl = useGfsBrowserController({ grantsListEnabled: manageOpen })
const {
current,
@@ -170,6 +171,39 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
refreshAffordances,
} = ctrl
+ // Warm the cache for every directory row visible in the current view
+ // so clicking into a folder is instant. Re-runs whenever the listing
+ // changes (folder navigation, refresh, …) and silently no-ops if a
+ // folder was already prefetched. TanStack Query's staleTime:Infinity
+ // (set in lib/queryClient.ts) keeps the cached data hot until the user
+ // actually navigates there.
+ useEffect(() => {
+ if (!sessionScope) return
+ const folders = items.filter(item => item.kind === 'directory')
+ if (folders.length === 0) return
+ let cancelled = false
+ void Promise.all(
+ folders.map(folder =>
+ queryClient
+ .fetchInfiniteQuery({
+ queryKey: desktopQueryKeys.gfsChildren(sessionScope, folder.resourceId, 'main'),
+ queryFn: ({ pageParam }) =>
+ window.clerum.gfs.listChildren(folder.resourceId, 'main', pageParam),
+ initialPageParam: undefined as string | undefined,
+ })
+ .catch(() => {
+ // Pre-fetch failures (offline, permission) are non-fatal; the
+ // real navigation will surface the error normally.
+ })
+ )
+ ).then(() => {
+ if (cancelled) return
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [items, queryClient, sessionScope])
+
const teamDirectoryQuery = useQuery({
queryKey: desktopQueryKeys.teamsDirectory,
queryFn: () => window.clerum.team.directory(),
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index cc0a2c619..8fec94357 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -2079,4 +2079,75 @@ describe('FilesPage', () => {
expect((screen.getByLabelText('Folder name') as HTMLInputElement).value).toBe('')
})
+
+ it('prefetches each folder child into the TanStack cache so the next click is instant', async () => {
+ const listChildren = vi.fn(async () => ({
+ items: [],
+ nextCursor: null,
+ }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ list: () => ({ items: [] }),
+ download: vi.fn(),
+ listChildren,
+ },
+ },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ },
+ items: [
+ {
+ resourceId: 'folder-a',
+ rid: 'folder-a',
+ gfsUri: 'gfs://main/folder-a',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'Alpha',
+ kind: 'directory',
+ path: '/Product/Alpha',
+ version: 1,
+ bytes: 0,
+ },
+ {
+ resourceId: 'folder-b',
+ rid: 'folder-b',
+ gfsUri: 'gfs://main/folder-b',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'Beta',
+ kind: 'directory',
+ path: '/Product/Beta',
+ version: 1,
+ bytes: 0,
+ },
+ {
+ resourceId: 'file-1',
+ rid: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'notes.md',
+ kind: 'file',
+ path: '/Product/notes.md',
+ version: 1,
+ bytes: 12,
+ },
+ ],
+ })
+
+ renderFilesPage()
+
+ await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(2))
+ expect(listChildren).toHaveBeenCalledWith('folder-a', 'main', undefined)
+ expect(listChildren).toHaveBeenCalledWith('folder-b', 'main', undefined)
+ })
})