Skip to content

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

TypeScript

fix(desktop): prefetch only uncached folder children, capped at 10

Alfredo Lopez695fdd686da5
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index b8678fd45..0fee923c3 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -215,6 +215,15 @@ function GfsInlineRename({
/** Sub-second, so a throttled or delayed wake-up cannot leave a stale number on screen. */
const COUNTDOWN_TICK_MS = 250
+/**
+ * How many uncached subfolders one listing may speculatively warm.
+ *
+ * The server meters reads per minute per actor, so the cap is a count, not a
+ * concurrency limit — sending the same ten requests four at a time spends
+ * exactly the same budget as sending them at once.
+ */
+const PREFETCH_FOLDER_LIMIT = 10
+
function secondsUntil(deadline: number | null): number {
if (deadline === null) return 0
return Math.max(0, Math.ceil((deadline - Date.now()) / 1000))
@@ -359,21 +368,35 @@ export function FilesPage({
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.
+ // Warm the cache for directory rows in the current view so clicking into a
+ // folder is instant. TanStack Query's staleTime:Infinity (set in
+ // lib/queryClient.ts) keeps the cached data hot until the user navigates.
+ //
+ // Bounded on both axes, because this is an optimization spending a shared
+ // budget. Opening a folder with 38 subfolders sent 38 speculative listings
+ // in one burst — 38 of the 85 requests in wave 1 of the incident behind
+ // #681, for folders the user mostly never opened.
+ //
+ // The cached-key skip is not redundant with the cap, it is what makes the
+ // cap advance: the effect re-runs on every `items` change (loadMore pages
+ // included), so a bare `slice(0, 10)` would re-select the same first ten
+ // forever and never reach the rest.
useEffect(() => {
if (!sessionScope) return
- const folders = items.filter(item => item.kind === 'directory')
+ const folders = items
+ .filter(item => item.kind === 'directory')
+ .map(folder => ({
+ folder,
+ key: desktopQueryKeys.gfsChildren(sessionScope, folder.resourceId, 'main'),
+ }))
+ .filter(({ key }) => queryClient.getQueryState(key)?.data === undefined)
+ .slice(0, PREFETCH_FOLDER_LIMIT)
if (folders.length === 0) return
void Promise.all(
- folders.map(folder =>
+ folders.map(({ folder, key }) =>
queryClient
.fetchInfiniteQuery({
- queryKey: desktopQueryKeys.gfsChildren(sessionScope, folder.resourceId, 'main'),
+ queryKey: key,
queryFn: ({ pageParam }) =>
window.clerum.gfs.listChildren(folder.resourceId, 'main', pageParam),
initialPageParam: undefined as string | undefined,
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index f9e173767..062b56e40 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -6,6 +6,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testi
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'
@@ -3374,6 +3375,79 @@ describe('FilesPage', () => {
expect(listChildren).toHaveBeenCalledWith('folder-b', 'main', undefined)
})
+ it('prefetches only the first ten uncached subfolders, skipping those already in cache', async () => {
+ // The mock carries the real signature so `calls.map(call => call[0])`
+ // below is typed as the resource id, not as an empty tuple.
+ const listChildren = vi.fn(async (_resourceId: string) => ({
+ items: [],
+ nextCursor: null,
+ }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { list: () => ({ items: [] }), download: vi.fn(), listChildren } },
+ })
+ const scope = 'env-1:user-1:team-1'
+ const folders = Array.from({ length: 15 }, (_, index) => ({
+ resourceId: `folder-${String(index).padStart(2, '0')}`,
+ rid: `folder-${index}`,
+ gfsUri: `gfs://main/folder-${index}`,
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: `Folder ${index}`,
+ kind: 'directory',
+ path: `/Product/Folder ${index}`,
+ version: 1,
+ bytes: 0,
+ }))
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ },
+ items: folders,
+ })
+
+ const cached = ['folder-02', 'folder-05', 'folder-09']
+ // Scattered, not leading: a cap applied before the skip would still get
+ // the first ten right if the cached ids were all at the front.
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ cached.forEach(resourceId =>
+ queryClient.setQueryData(desktopQueryKeys.gfsChildren(scope, resourceId, 'main'), {
+ pages: [{ items: [], nextCursor: null }],
+ pageParams: [undefined],
+ })
+ )
+ render(
+ <QueryClientProvider client={queryClient}>
+ <FilesPage />
+ </QueryClientProvider>
+ )
+
+ // Positive, and the witness: the effect ran and sent exactly the cap.
+ // Under production defaults `fetchInfiniteQuery` would serve the cached
+ // pages without a request anyway; this harness runs at `staleTime: 0`, so
+ // the explicit cached-key check is the only thing keeping those three out.
+ await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(10))
+ const requested = listChildren.mock.calls.map(call => call[0])
+ cached.forEach(resourceId => expect(requested).not.toContain(resourceId))
+ expect(requested).toEqual([
+ 'folder-00',
+ 'folder-01',
+ 'folder-03',
+ 'folder-04',
+ 'folder-06',
+ 'folder-07',
+ 'folder-08',
+ 'folder-10',
+ 'folder-11',
+ 'folder-12',
+ ])
+ })
+
it('renders a rate-limited discovery failure as a card with a retry countdown', async () => {
vi.useFakeTimers()
const retryDiscovery = vi.fn()