Skip to content

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

TypeScript

fix(desktop): re-arm the GFS rate-limit pause on every repeated 429

Alfredo Lopez28614f452b1b
diff --git a/desktop-app/src/__tests__/appService.gfs.test.ts b/desktop-app/src/__tests__/appService.gfs.test.ts
index 8e87383c7..e13e36065 100644
--- a/desktop-app/src/__tests__/appService.gfs.test.ts
+++ b/desktop-app/src/__tests__/appService.gfs.test.ts
@@ -1051,4 +1051,63 @@ describe('AppService GFS proxy read transport', () => {
globalThis.fetch = originalFetch
}
})
+
+ it('carries the retry window out of a proxy 429 whose body is not ours', async () => {
+ // The sibling test above sends BOTH the body field and the header, so the
+ // header argument passed to ApiError could be deleted with every assertion
+ // still green. This is the case that only the header can answer: an
+ // upstream proxy refusing with its own HTML page.
+ const service = new AppService() as unknown as {
+ sessionToken: string | null
+ downloadGfsUri: (uri: string) => Promise<{ bytes: ArrayBuffer }>
+ }
+ service.sessionToken = 'session-token'
+
+ const resolved = {
+ drive: 'main',
+ resourceId: RESOURCE_ID,
+ parentResourceId: null,
+ gfsUri: `gfs://main/${RESOURCE_ID}`,
+ name: 'report.md',
+ kind: 'file',
+ version: 3,
+ }
+ const originalFetch = globalThis.fetch
+ const fetchMock = vi.fn(async (input: unknown) => {
+ const url = String(input)
+ if (url.includes('/gfs/resolve')) {
+ return new Response(JSON.stringify({ ok: true, data: resolved }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ }
+ if (url.includes(`/gfs/proxy/${RESOURCE_ID}`)) {
+ return new Response('<html><body>429 Too Many Requests</body></html>', {
+ status: 429,
+ statusText: 'Too Many Requests',
+ headers: { 'content-type': 'text/html', 'retry-after': '11' },
+ })
+ }
+ throw new Error(`unexpected request to ${url}`)
+ })
+ globalThis.fetch = fetchMock as unknown as typeof fetch
+
+ try {
+ const error = await service.downloadGfsUri(`gfs://main/${RESOURCE_ID}`).then(
+ () => {
+ throw new Error('expected the rate-limited proxy download to reject')
+ },
+ (rejected: unknown) => rejected
+ )
+ const message = error instanceof Error ? error.message : String(error)
+ expect(message).toContain('gfs download failed: 429')
+ expect(message).toContain('retryAfterSeconds=11')
+ // Liveness witness: both legs ran, so the 429 came from the proxy read
+ // and not from a resolve that never happened.
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(String(fetchMock.mock.calls[1]?.[0])).toContain(`/gfs/proxy/${RESOURCE_ID}`)
+ } finally {
+ globalThis.fetch = originalFetch
+ }
+ })
})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 252883810..52f6eda5c 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -856,9 +856,10 @@ export class AppService {
fetchBytes: async (url, token) => {
const res = await fetch(url, { headers: { authorization: `Bearer ${token}` } })
if (!res.ok) {
- // Keep the body and Retry-After: a 429 on the proxy read carries
- // retryAfterSeconds, and surfaceGfsGrantError can only lift it out of
- // bodyText. Discarding them left the renderer with no retry hint.
+ // 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 left the renderer with no hint.
throw new ApiError(
`gfs download failed: ${res.status}`,
res.status,
diff --git a/desktop-app/src/gfs/uriHandler.ts b/desktop-app/src/gfs/uriHandler.ts
index a0e8f834b..3098c65f2 100644
--- a/desktop-app/src/gfs/uriHandler.ts
+++ b/desktop-app/src/gfs/uriHandler.ts
@@ -15,8 +15,8 @@ const RID_RE = /^[0-9a-f]{32}$/
const TRAILING_RID_RE = /-([0-9a-f]{32})$/
export class GfsUriError extends Error {
- constructor(message: string) {
- super(message)
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options)
this.name = 'GfsUriError'
}
}
@@ -779,29 +779,46 @@ function parseGfsGrantErrorFields(bodyText: string): GfsGrantErrorFields {
* error CODE (`subjects_invalid`, `foreign_agent_forbidden`, `429`, …) — intact.
*
* The READ methods (`resolveUri`, `download`, `listChildren`, `listAccessible`,
- * `affordances`) route through this too. They share the per-actor `resource`
- * rate-limit budget in control-api, so a 429 here is the common case, not an
- * edge one: without the hint the renderer can tell the user it was rate limited
- * but not when to retry.
+ * `affordances`) route through this too, so a 429 here is the common case, not
+ * an edge one: without the hint the renderer can tell the user it was rate
+ * limited but not when to retry. Four of them are metered per actor in the
+ * `resource` class; `download`'s proxy leg has its own `proxy-read` budget and
+ * its resolve leg falls under `resource`.
+ *
+ * The retry window is read from the JSON body first and from the `Retry-After`
+ * response header second. Both are needed: our own services answer with
+ * `{ retryAfterSeconds }`, but an upstream proxy or CDN answers 429 with its
+ * own body and only the standard header, and that body parses to nothing.
*
* When there is nothing structured to surface, the ORIGINAL error propagates
* unchanged (fail loud; never swallow the server's verdict).
*/
function surfaceGfsGrantError(error: unknown): unknown {
- const bodyText =
- error &&
- typeof error === 'object' &&
- typeof (error as { bodyText?: unknown }).bodyText === 'string'
- ? (error as { bodyText: string }).bodyText
- : ''
- if (!bodyText) return error
- const fields = parseGfsGrantErrorFields(bodyText)
+ if (!error || typeof error !== 'object') return error
+ const transportError = error as { bodyText?: unknown; retryAfter?: unknown }
+ const bodyText = typeof transportError.bodyText === 'string' ? transportError.bodyText : ''
+ const fields = bodyText ? parseGfsGrantErrorFields(bodyText) : {}
+ const retryAfterSeconds =
+ fields.retryAfterSeconds ?? parseRetryAfterHeader(transportError.retryAfter)
const parts: string[] = []
if (fields.invalidIndexes) parts.push(`invalidIndexes=[${fields.invalidIndexes.join(',')}]`)
- if (fields.retryAfterSeconds !== undefined) {
- parts.push(`retryAfterSeconds=${fields.retryAfterSeconds}`)
- }
+ if (retryAfterSeconds !== undefined) parts.push(`retryAfterSeconds=${retryAfterSeconds}`)
if (parts.length === 0) return error
const baseMessage = error instanceof Error ? error.message : String(error ?? '')
- return new GfsUriError(`${baseMessage} ${parts.join(' ')}`)
+ return new GfsUriError(`${baseMessage} ${parts.join(' ')}`, { cause: error })
+}
+
+/**
+ * Read a `Retry-After` header value as a delay in seconds.
+ *
+ * RFC 9110 also permits an HTTP-date, which we deliberately do not translate:
+ * a date depends on clock agreement between the server and this machine, and a
+ * skewed clock would produce a retry window that is wrong in either direction.
+ * An unparsed header yields no hint at all, which the renderer already handles
+ * — it says "try again shortly" and pauses automatic revalidation for the
+ * shortest window the limiters behind this endpoint can be enforcing.
+ */
+function parseRetryAfterHeader(retryAfter: unknown): number | undefined {
+ if (typeof retryAfter !== 'string' || !/^\d{1,7}$/.test(retryAfter.trim())) return undefined
+ return Number.parseInt(retryAfter.trim(), 10)
}
diff --git a/desktop-app/test/gfsUriHandler.test.ts b/desktop-app/test/gfsUriHandler.test.ts
index 52087f215..0f18371cb 100644
--- a/desktop-app/test/gfsUriHandler.test.ts
+++ b/desktop-app/test/gfsUriHandler.test.ts
@@ -692,7 +692,53 @@ describe('GfsClient read paths surface retryAfterSeconds across IPC', () => {
})
// Fail loud: an error with nothing structured to surface propagates verbatim,
// it is never rewritten or swallowed.
- await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow('403 Forbidden: denied')
+ //
+ // The anchors are what make this a negative control. `toThrow('…')` is a
+ // SUBSTRING match, so a message rewritten to "403 Forbidden: denied
+ // retryAfterSeconds=0" satisfies it identically — the assertion could not
+ // express the "untouched" its name promises, and survived deleting the
+ // feature it guards.
+ await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(/^403 Forbidden: denied$/)
+ expect(t.requestJson).toHaveBeenCalledTimes(1)
+ })
+
+ it('takes the retry window from Retry-After when the 429 body is not ours', async () => {
+ // An upstream proxy or CDN refuses with its own body, which parses to
+ // nothing — the case where the renderer previously got a rate limit with
+ // no window at all and put focus revalidation straight back on the budget.
+ const t = transport({
+ requestJson: vi.fn(async () => {
+ throw new ApiError(
+ '429 Too Many Requests: Too Many Requests',
+ 429,
+ '<html><body>429 Too Many Requests</body></html>',
+ '11'
+ )
+ }) as GfsTransport['requestJson'],
+ })
+
+ await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(/retryAfterSeconds=11/)
+ expect(t.requestJson).toHaveBeenCalledTimes(1)
+ })
+
+ it('ignores an HTTP-date Retry-After rather than translating it against a local clock', async () => {
+ // RFC 9110 permits a date here. Converting it would depend on this
+ // machine's clock agreeing with the server's, and a skewed clock produces
+ // a window that is wrong in either direction. No hint is the honest answer.
+ const t = transport({
+ requestJson: vi.fn(async () => {
+ throw new ApiError(
+ '429 Too Many Requests: Too Many Requests',
+ 429,
+ 'rate limited',
+ 'Wed, 21 Oct 2026 07:28:00 GMT'
+ )
+ }) as GfsTransport['requestJson'],
+ })
+
+ await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(
+ /^429 Too Many Requests: Too Many Requests$/
+ )
expect(t.requestJson).toHaveBeenCalledTimes(1)
})
})
diff --git a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx
index b2fa28099..05b8eaca6 100644
--- a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx
+++ b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx
@@ -3,6 +3,7 @@ import { Button, EmptyState, IconButton, StatusBanner } from '@components/Common
import { GfsFileIcon } from '@components/GfsFileIcon'
import { IconChevronRight, IconClose, IconContexts } from '@components/SidebarNav/icons'
import { useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'
+import { describeGfsReadError } from '@lib/gfsGrantErrors'
import { formatSharedFileSize } from '@lib/sharedFiles'
import type { ComposerGlobalFileReference } from '@/uiTypes'
import type { ComposerGlobalFileSelection, ComposerGlobalFilesModalProps } from './types'
@@ -39,7 +40,12 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFiles
const selectedFiles = useMemo(() => Object.values(selected), [selected])
const entries = ctrl.current ? ctrl.items : ctrl.accessibleResources
const loading = ctrl.current ? ctrl.loading : ctrl.loadingAccessible
- const error = ctrl.current ? ctrl.error : ctrl.accessibleError
+ // Present the verdict, never the transport. Until discovery failures were
+ // classified by signal, every rejection of the `gfs:listAccessible` channel
+ // became a friendly notice here; now only a 404 does, so a 429 would have
+ // put the raw "Error invoking remote method …" string in front of the user.
+ const rawError = ctrl.current ? ctrl.error : ctrl.accessibleError
+ const error = rawError ? describeGfsReadError(rawError).message : null
const hasMore = ctrl.current ? ctrl.hasMore : ctrl.hasMoreAccessible
const loadingMore = ctrl.current ? ctrl.isFetchingMore : ctrl.isFetchingMoreAccessible
const loadMore = ctrl.current ? ctrl.loadMore : ctrl.loadMoreAccessible
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
index ef5b1a7e2..6d6d0f507 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -93,6 +93,10 @@ function Probe() {
<div data-testid="discovery-failure-retry">
{ctrl.discoveryFailure?.retryAfterSeconds ?? 'none'}
</div>
+ <div data-testid="discovery-failure-retry-at">
+ {ctrl.discoveryFailure?.retryAvailableAt ?? 'none'}
+ </div>
+ <div data-testid="loading">{ctrl.loading ? 'loading' : 'idle'}</div>
<div data-testid="loading-accessible">{ctrl.loadingAccessible ? 'loading' : 'idle'}</div>
<div data-testid="row-affordances">{ctrl.rowAffordances?.held.join(',') ?? 'none'}</div>
<div data-testid="held-permissions">{ctrl.affordances?.held.join(',') ?? 'none'}</div>
@@ -949,6 +953,12 @@ describe('useGfsBrowserController', () => {
)
expect(screen.getByTestId('accessible-error').textContent).toBe('none')
expect(screen.getByTestId('accessible-count').textContent).toBe('0')
+ // Pin the classification, not only the copy it happens to produce. The page
+ // suppresses its retry card on `kind === 'unsupported'` and is tested
+ // against a hand-written controller, so without this assertion a 404 could
+ // start classifying as 'failed' and both suites would stay green while the
+ // user got a retry card with a raw 404 in it.
+ expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('unsupported')
})
it('classifies a rate-limited discovery failure instead of calling the server unsupported', async () => {
@@ -1058,6 +1068,165 @@ describe('useGfsBrowserController', () => {
await new Promise(resolve => globalThis.setTimeout(resolve, 0))
})
expect(listAccessible).toHaveBeenCalledTimes(2)
+
+ // That second attempt was refused with a BYTE-IDENTICAL message, which is
+ // the normal case: the server keeps saying the same thing while its window
+ // is open. Nothing derived from the message alone changes, so a verdict
+ // memoized on the message keeps its object identity and every effect keyed
+ // on it stays silent — leaving the pause at the FIRST failure's expired
+ // deadline and letting every later focus spend another request. Re-arming
+ // has to key off the error's timestamp.
+ expect(screen.getByTestId('discovery-failure-retry-at').textContent).toBe(
+ String(pausedAt + 8_000 + 7_000)
+ )
+
+ vi.setSystemTime(pausedAt + 9_000)
+ await act(async () => {
+ focusManager.setFocused(false)
+ focusManager.setFocused(true)
+ })
+ await act(async () => {
+ await new Promise(resolve => globalThis.setTimeout(resolve, 0))
+ })
+ expect(listAccessible).toHaveBeenCalledTimes(2)
+ expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
+
+ // And the re-armed window opens in turn, so the assertion above is a
+ // suppression rather than a controller that stopped refetching for good.
+ vi.setSystemTime(pausedAt + 16_000)
+ await act(async () => {
+ focusManager.setFocused(false)
+ focusManager.setFocused(true)
+ })
+ await act(async () => {
+ await new Promise(resolve => globalThis.setTimeout(resolve, 0))
+ })
+ expect(listAccessible).toHaveBeenCalledTimes(3)
+ })
+
+ it('pauses focus revalidation for a rate limit that names no window', async () => {
+ // An upstream proxy or CDN answers 429 with its own body, which carries no
+ // retryAfterSeconds for us to parse. Treating an unknown window as "no wait
+ // needed" put focus revalidation straight back on an exhausted budget.
+ const listAccessible = vi.fn(async () => {
+ throw new Error(
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ '<html><body>429 Too Many Requests</body></html>'
+ )
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible,
+ resolve: vi.fn(),
+ listChildren: vi.fn(async () => ({ items: [], nextCursor: null })),
+ affordances: vi.fn(async () => ({
+ held: [],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ })),
+ },
+ },
+ })
+
+ render(<Probe />, { wrapper: Harness })
+ await waitFor(() =>
+ expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
+ )
+ // The window really is unknown — this is the case under test, not a 429
+ // that happened to carry a hint.
+ expect(screen.getByTestId('discovery-failure-retry-at').textContent).toBe('none')
+ expect(listAccessible).toHaveBeenCalledTimes(1)
+
+ vi.useFakeTimers({ toFake: ['Date'] })
+ const pausedAt = Date.now()
+
+ await act(async () => {
+ focusManager.setFocused(false)
+ focusManager.setFocused(true)
+ })
+ expect(listAccessible).toHaveBeenCalledTimes(1)
+ expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
+
+ // Past the default window, revalidation resumes.
+ vi.setSystemTime(pausedAt + 61_000)
+ await act(async () => {
+ focusManager.setFocused(false)
+ focusManager.setFocused(true)
+ })
+ await act(async () => {
+ await new Promise(resolve => globalThis.setTimeout(resolve, 0))
+ })
+ expect(listAccessible).toHaveBeenCalledTimes(2)
+ })
+
+ it('keeps reporting the children load while discovery is rate limited', async () => {
+ // `loading` is the children query's state. Gating it on a discovery error
+ // hid the spinner while a folder was genuinely loading, so the consumer
+ // that derives its loading state from this field alone flashed an empty
+ // folder at the user.
+ let releaseChildren: (page: { items: never[]; nextCursor: null }) => void = () => {}
+ const listChildren = vi.fn(
+ () =>
+ new Promise<{ items: never[]; nextCursor: null }>(resolve => {
+ releaseChildren = resolve
+ })
+ )
+ const listAccessible = vi.fn(async () => {
+ throw new Error(
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=7'
+ )
+ })
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible,
+ listChildren,
+ resolve: vi.fn(async () => ({
+ resourceId: 'root',
+ gfsUri: 'gfs://main/root',
+ name: 'Root',
+ kind: 'directory',
+ })),
+ affordances: vi.fn(async () => ({
+ held: ['read'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ })),
+ },
+ },
+ })
+
+ render(<Probe />, { wrapper: Harness })
+ await waitFor(() =>
+ expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('rate-limited')
+ )
+
+ await act(async () => {
+ screen.getByRole('button', { name: 'open' }).click()
+ })
+ // Witness: the children request is genuinely in flight, so "loading" below
+ // describes a pending load and not a tree that never started one.
+ await waitFor(() => expect(listChildren).toHaveBeenCalled())
+ expect(screen.getByTestId('loading').textContent).toBe('loading')
+
+ await act(async () => {
+ releaseChildren({ items: [], nextCursor: null })
+ await new Promise(resolve => globalThis.setTimeout(resolve, 0))
+ })
+ // Still loading once the children settle, but now for the other reason:
+ // the R4 authority gate is open because a 429 never advances the discovery
+ // query's `dataUpdatedAt`, and this controller withholds every cached GFS
+ // surface until the session is re-proved. That is deliberate and unchanged
+ // here — the point of this test is that the two concerns stay separate, so
+ // a settled discovery error can no longer silence an in-flight folder.
+ expect(screen.getByTestId('authority-pending').textContent).toBe('pending')
+ expect(screen.getByTestId('loading').textContent).toBe('loading')
})
it('reconciles the open folder after a move and feeds the returned version into follow-up actions', async () => {
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index a7324e24f..9aa76a943 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -8,7 +8,7 @@ import {
useQueryClient,
} from '@tanstack/react-query'
import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'
-import { parseRetryAfterSeconds } from '@lib/gfsGrantErrors'
+import { isRateLimited, parseRetryAfterSeconds } from '@lib/gfsGrantErrors'
import type { GfsGrantListItem, GfsShareListItem } from '@/gfs/delegation.types'
import { desktopQueryKeys } from './queryKeys'
@@ -145,6 +145,23 @@ export interface GfsDiscoveryFailure {
kind: GfsDiscoveryFailureKind
message: string
retryAfterSeconds: number | null
+ /**
+ * Absolute epoch (ms) at which the server's own window closes, or null when
+ * this failure named no window.
+ *
+ * An absolute deadline, not a duration, and derived from the query's
+ * `errorUpdatedAt` rather than from the message. Two consecutive 429s carry a
+ * byte-identical message — the server keeps refusing with the same words —
+ * so anything memoized on the message alone returns the SAME object, and
+ * every effect keyed on it stays silent for the second failure. The pause
+ * would then never re-arm after a retry, which is the hammering this
+ * controller exists to prevent. `errorUpdatedAt` advances on every settled
+ * error, identical message or not.
+ *
+ * A deadline also survives a remount and cannot drift: a consumer counting
+ * down derives the remainder from the clock instead of decrementing state.
+ */
+ retryAvailableAt: number | null
}
/**
@@ -160,10 +177,29 @@ export interface GfsDiscoveryFailure {
*/
function classifyDiscoveryFailure(message: string): GfsDiscoveryFailureKind {
if (/\b404 Not Found\b/.test(message)) return 'unsupported'
- if (/\b429\b/.test(message)) return 'rate-limited'
+ // Share the predicate with the presentation layer rather than restating it.
+ // A third copy of "what counts as rate limited" is a copy that will rot, and
+ // the two must agree: the card renders copy chosen by `describeGfsReadError`
+ // for a failure this function classified.
+ if (isRateLimited(message)) return 'rate-limited'
return 'failed'
}
+/**
+ * Focus-refetch pause applied when the server rate limited us without naming a
+ * window.
+ *
+ * The manual Retry button stays enabled — spending the user's own click is
+ * their decision, and the card tells them to "try again shortly". What this
+ * suppresses is the automatic revalidation on every window focus, which would
+ * otherwise keep drawing on a budget the server is still refusing. The case is
+ * reachable: an upstream proxy or CDN answers 429 with its own body, which
+ * carries no `retryAfterSeconds` for us to parse.
+ *
+ * One minute is the window of the per-minute limiters behind this endpoint.
+ */
+const UNKNOWN_RATE_LIMIT_PAUSE_MS = 60_000
+
const SESSION_AUTHORITY_ERROR_CODES = [
'desktop_user_retired',
'operator_link_inactive',
@@ -254,9 +290,14 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
// 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: under desktopQueryDefaults' staleTime
- // of Infinity, `true` means "refetch if stale", which never happens — a
- // boolean predicate would silently disable focus refetch altogether.
+ // '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),
[]
@@ -637,22 +678,34 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
[authorityPending, sharesQuery.data]
)
const accessibleErrorMessage = accessibleQuery.error ? toMessage(accessibleQuery.error) : null
- const discoveryFailure = useMemo<GfsDiscoveryFailure | null>(
- () =>
- accessibleErrorMessage
- ? {
- kind: classifyDiscoveryFailure(accessibleErrorMessage),
- message: accessibleErrorMessage,
- retryAfterSeconds: parseRetryAfterSeconds(accessibleErrorMessage),
- }
- : null,
- [accessibleErrorMessage]
- )
+ // The timestamp is a dependency in its own right, not decoration. It is the
+ // only thing that distinguishes two consecutive failures carrying the same
+ // message, and without it the memo below never recomputes for the second one.
+ const accessibleErrorUpdatedAt = accessibleQuery.error ? accessibleQuery.errorUpdatedAt : 0
+ const discoveryFailure = useMemo<GfsDiscoveryFailure | null>(() => {
+ if (!accessibleErrorMessage) return null
+ const kind = classifyDiscoveryFailure(accessibleErrorMessage)
+ const retryAfterSeconds = parseRetryAfterSeconds(accessibleErrorMessage)
+ return {
+ kind,
+ message: accessibleErrorMessage,
+ retryAfterSeconds,
+ retryAvailableAt:
+ kind === 'rate-limited' && retryAfterSeconds !== null
+ ? accessibleErrorUpdatedAt + retryAfterSeconds * 1000
+ : null,
+ }
+ }, [accessibleErrorMessage, accessibleErrorUpdatedAt])
useEffect(() => {
+ if (discoveryFailure?.kind !== 'rate-limited') {
+ pausedUntilRef.current = 0
+ return
+ }
+ // A rate limit with no parseable window is still a rate limit. Leaving the
+ // pause open here would let every window focus spend another request
+ // against a server that just refused one.
pausedUntilRef.current =
- discoveryFailure?.kind === 'rate-limited' && discoveryFailure.retryAfterSeconds !== null
- ? Date.now() + discoveryFailure.retryAfterSeconds * 1000
- : 0
+ discoveryFailure.retryAvailableAt ?? Date.now() + UNKNOWN_RATE_LIMIT_PAUSE_MS
}, [discoveryFailure])
// The page must not reach into the query object to retry. Clearing the pause
// here is deliberate: an explicit retry is the user's decision, and the
@@ -885,14 +938,13 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
? null
: ((rowAffordancesQuery.data as GfsBrowserAffordances | undefined) ?? null),
rowAffordancesError: rowAffordancesQuery.error ? toMessage(rowAffordancesQuery.error) : null,
+ loading: (authorityPending || childrenQuery.isFetching) && items.length === 0,
// A settled discovery error is not a pending load. Without this the
// spinner outlived the failure for every consumer that derives its
- // loading state from here alone (ComposerGlobalFilesModal); FilesPage
- // reads authorityPending directly and is fixed separately.
- loading:
- (authorityPending || childrenQuery.isFetching) &&
- items.length === 0 &&
- !accessibleQuery.isError,
+ // loading state from here alone (ComposerGlobalFilesModal). The term
+ // belongs on this field only: `loading` above reports the INDEPENDENT
+ // children query, and gating it on a discovery error hid the spinner while
+ // a folder was genuinely loading, flashing "this folder is empty".
loadingAccessible:
!accessibleQuery.isError &&
((authorityPending && canListAccessibleResources) ||
diff --git a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
index 2b2adc298..7225cad6c 100644
--- a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
-import { describeGfsGrantError, describeGfsReadError } from '../gfsGrantErrors'
+import {
+ describeGfsGrantError,
+ describeGfsReadError,
+ parseRetryAfterSeconds,
+} from '../gfsGrantErrors'
/**
* Pure presentation map for GFS grant-plane server verdicts. Codes arrive
@@ -156,4 +160,41 @@ describe('describeGfsReadError', () => {
severity: 'error',
})
})
+
+ it('keeps the server verdict but drops the IPC wrapper around it', () => {
+ // The wrapper names our own main/renderer channel. It is noise to a user
+ // and the verdict after it is the part they can act on, so exactly one of
+ // the two is removed.
+ const presented = describeGfsReadError(
+ new Error(
+ "Error invoking remote method 'gfs:listChildren': GfsUriError: 503 Service Unavailable: upstream_unreachable"
+ )
+ )
+
+ expect(presented.message).toBe('503 Service Unavailable: upstream_unreachable')
+ })
+
+ it('reads a retry window only from its own field', () => {
+ // A pattern that skips non-digits binds to the next number ANYWHERE in the
+ // message, so a null window next to an unrelated number yielded that
+ // number — inventing a 100-second gate out of a rate-limit ceiling.
+ expect(
+ parseRetryAfterSeconds('429 Too Many Requests: {"retryAfterSeconds":null,"limit":100}')
+ ).toBeNull()
+ // Witness: the same parser does find the field when it is genuinely there,
+ // in both shapes the wire uses.
+ expect(parseRetryAfterSeconds('429 Too Many Requests retryAfterSeconds=7')).toBe(7)
+ expect(
+ parseRetryAfterSeconds('429: {"error":"Too Many Requests","retryAfterSeconds": 3}')
+ ).toBe(3)
+ })
+
+ it('bounds a retry window the server could never legitimately be asking for', () => {
+ // The value disables the Retry button and suppresses focus revalidation.
+ // Unbounded, one hostile or corrupt response wedges both for the lifetime
+ // of the controller — a durable outage out of a transient 429.
+ expect(parseRetryAfterSeconds('429 retryAfterSeconds=999999999')).toBe(300)
+ // Witness: the clamp is a ceiling, not a constant.
+ expect(parseRetryAfterSeconds('429 retryAfterSeconds=45')).toBe(45)
+ })
})
diff --git a/desktop-app/ui/src/lib/gfsGrantErrors.ts b/desktop-app/ui/src/lib/gfsGrantErrors.ts
index 94277788f..55f0b3b1d 100644
--- a/desktop-app/ui/src/lib/gfsGrantErrors.ts
+++ b/desktop-app/ui/src/lib/gfsGrantErrors.ts
@@ -1,15 +1,17 @@
/**
- * Pure presentation map for GFS grant/revoke/list server verdicts.
+ * Pure presentation map for GFS server verdicts, on both the grant plane
+ * (grant/revoke/list) and the read plane (resolve/download/list/affordances).
*
- * The renderer receives control-api error codes embedded in Electron IPC error
- * messages (e.g. "Error invoking remote method 'gfs:grant': Error: 403
- * Forbidden: foreign_agent_forbidden"), so codes are matched as substrings of
- * the raw message. Unknown errors keep their raw message — fail loud, never
- * swallow a server verdict.
+ * The renderer receives error codes embedded in Electron IPC error messages
+ * (e.g. "Error invoking remote method 'gfs:grant': Error: 403 Forbidden:
+ * foreign_agent_forbidden"), so codes are matched as substrings of the raw
+ * message. Unknown errors keep their server verdict — fail loud, never swallow
+ * it — but lose the IPC wrapper, which names our own process boundary and
+ * means nothing to a user.
*/
export interface GfsGrantErrorPresentation {
- /** Matched control-api error code, or null when the message is passed through. */
+ /** Matched server error code, or null when the message is passed through. */
code: string | null
message: string
/**
@@ -28,6 +30,19 @@ const GFS_GRANT_ERROR_MESSAGES: Record<string, string> = {
manage_acl_required: 'Only people with manage access can view who has access here.',
}
+/**
+ * Electron prefixes every IPC rejection with
+ * `Error invoking remote method '<channel>': <ErrorClass>: `. The channel name
+ * is an implementation detail of our own main/renderer split; the server
+ * verdict that follows it is the part a user can act on. This strips exactly
+ * the wrapper and leaves the verdict intact.
+ */
+const IPC_WRAPPER_PREFIX = /^Error invoking remote method '[^']*':\s*(?:[A-Za-z]*Error:\s*)?/
+
+export function stripIpcWrapper(message: string): string {
+ return message.replace(IPC_WRAPPER_PREFIX, '')
+}
+
function rawMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error ?? '')
}
@@ -41,58 +56,78 @@ function parseInvalidIndexes(message: string): number[] {
.filter(index => Number.isInteger(index) && index >= 0)
}
+/**
+ * Upper bound on a server-supplied retry window, in seconds.
+ *
+ * The value drives a real wall-clock gate: it disables the Retry button and
+ * suppresses focus revalidation. An unbounded value from the wire would wedge
+ * both for the controller's lifetime, recoverable only by remount — a durable
+ * self-denial of service out of a transient 429. Every limiter behind this
+ * endpoint meters per minute, so five minutes is already far past any window
+ * the server can legitimately be asking us to wait.
+ */
+const MAX_RETRY_AFTER_SECONDS = 300
+
+/**
+ * Lift a retry window out of an error message.
+ *
+ * The separator is matched explicitly (`=` from our own IPC suffix, `:` from a
+ * JSON body, with optional quote and spaces) rather than skipped with a
+ * permissive `[^\d]*`. A skipping pattern binds to the next number ANYWHERE in
+ * the message, so `{"retryAfterSeconds":null,"limit":100}` would yield 100 —
+ * a 100-second gate invented out of an unrelated field. It is also quadratic
+ * on long non-JSON bodies (an upstream proxy's HTML 429 page reaches this
+ * function verbatim), which freezes the renderer's main thread.
+ */
export function parseRetryAfterSeconds(message: string): number | null {
- const match = message.match(/retryAfterSeconds[^\d]*(\d+)/)
+ const match = message.match(/retryAfterSeconds["']?\s*[:=]\s*(\d{1,7})/)
if (!match?.[1]) return null
const seconds = Number.parseInt(match[1], 10)
- return Number.isInteger(seconds) && seconds >= 0 ? seconds : null
+ if (!Number.isInteger(seconds) || seconds < 0) return null
+ return Math.min(seconds, MAX_RETRY_AFTER_SECONDS)
}
export function isRateLimited(message: string): boolean {
return /\b429\b/.test(message) || message.includes('rate_limited')
}
+function describeRateLimited(raw: string, subject: string): GfsGrantErrorPresentation {
+ const retryAfterSeconds = parseRetryAfterSeconds(raw)
+ return {
+ code: 'rate_limited',
+ message:
+ retryAfterSeconds !== null
+ ? `Too many ${subject} — try again in ${retryAfterSeconds}s.`
+ : `Too many ${subject} — try again shortly.`,
+ severity: 'error',
+ }
+}
+
/**
* Read-plane counterpart of `describeGfsGrantError`.
*
* A read and a permission change fail under the same server budget but call for
* different words: "too many permission changes" tells a user who was only
* opening a file to stop doing something they never did. Only the rate limit is
- * translated here — every other read failure keeps its raw message, because the
- * grant-plane codes below describe an operation a read never performs.
+ * translated here — every other read failure keeps its server verdict, because
+ * the grant-plane codes below describe an operation a read never performs.
*/
export function describeGfsReadError(error: unknown): GfsGrantErrorPresentation {
const raw = rawMessage(error)
- if (isRateLimited(raw)) {
- const retryAfterSeconds = parseRetryAfterSeconds(raw)
- return {
- code: 'rate_limited',
- message:
- retryAfterSeconds !== null
- ? `Too many file requests — try again in ${retryAfterSeconds}s.`
- : 'Too many file requests — try again shortly.',
- severity: 'error',
- }
- }
+ if (isRateLimited(raw)) return describeRateLimited(raw, 'file requests')
- return { code: null, message: raw || 'The file request failed.', severity: 'error' }
+ return {
+ code: null,
+ message: stripIpcWrapper(raw) || 'The file request failed.',
+ severity: 'error',
+ }
}
export function describeGfsGrantError(error: unknown): GfsGrantErrorPresentation {
const raw = rawMessage(error)
- if (isRateLimited(raw)) {
- const retryAfterSeconds = parseRetryAfterSeconds(raw)
- return {
- code: 'rate_limited',
- message:
- retryAfterSeconds !== null
- ? `Too many permission changes — try again in ${retryAfterSeconds}s.`
- : 'Too many permission changes — try again shortly.',
- severity: 'error',
- }
- }
+ if (isRateLimited(raw)) return describeRateLimited(raw, 'permission changes')
for (const [code, message] of Object.entries(GFS_GRANT_ERROR_MESSAGES)) {
if (!raw.includes(code)) continue
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 5aa0f94be..d46cd5857 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -212,14 +212,23 @@ function GfsInlineRename({
)
}
+/** Sub-second, so a throttled or delayed wake-up cannot leave a stale number on screen. */
+const COUNTDOWN_TICK_MS = 250
+
+function secondsUntil(deadline: number | null): number {
+ if (deadline === null) return 0
+ return Math.max(0, Math.ceil((deadline - Date.now()) / 1000))
+}
+
/**
* Terminal state for a discovery attempt that the server refused.
*
* Before this existed the page had no way to say "the request was answered,
* and the answer was no": a rejected discovery left the loader spinning and
- * the raw IPC string in a red banner. The countdown is the point — it is the
- * server's own Retry-After, so the user waits the exact window instead of
- * hammering a budget that is already exhausted.
+ * the raw IPC string in a red banner. The countdown is the point — it runs to
+ * the server's own `retryAfterSeconds` (the value it also puts in
+ * `Retry-After`), so the user waits the exact window instead of hammering a
+ * budget that is already exhausted.
*/
function GfsDiscoveryFailureCard({
failure,
@@ -228,40 +237,62 @@ function GfsDiscoveryFailureCard({
failure: GfsDiscoveryFailure
onRetry: () => void
}) {
- const [remainingSeconds, setRemainingSeconds] = useState(failure.retryAfterSeconds ?? 0)
-
+ const countdownId = useId()
+ const { retryAvailableAt } = failure
+ const [remainingSeconds, setRemainingSeconds] = useState(() => secondsUntil(retryAvailableAt))
+
+ // One effect, keyed on the absolute deadline, and every tick recomputes the
+ // remainder from the clock. Decrementing a counter instead would drift —
+ // each 1000 ms interval actually fires later than that, and Electron
+ // throttles timers in a hidden window — so the countdown could still be
+ // running after the server's window had closed. Keying on the deadline (a
+ // number) rather than on `failure` (an object) is what re-arms the countdown
+ // for a second, identically-worded 429.
useEffect(() => {
- setRemainingSeconds(failure.retryAfterSeconds ?? 0)
- }, [failure])
-
- useEffect(() => {
- if (remainingSeconds <= 0) return
+ setRemainingSeconds(secondsUntil(retryAvailableAt))
+ if (retryAvailableAt === null || retryAvailableAt <= Date.now()) return
const timer = setInterval(() => {
- setRemainingSeconds(previous => (previous <= 1 ? 0 : previous - 1))
- }, 1_000)
+ const remaining = secondsUntil(retryAvailableAt)
+ setRemainingSeconds(remaining)
+ if (remaining <= 0) clearInterval(timer)
+ }, COUNTDOWN_TICK_MS)
return () => clearInterval(timer)
- }, [remainingSeconds])
+ }, [retryAvailableAt])
return (
<>
- <EmptyState
- title={
- failure.kind === 'rate-limited' ? 'Too many file requests' : 'Could not load your files'
- }
- body={
- failure.kind === 'rate-limited'
- ? 'File listing is temporarily rate limited. Evenfire will let you retry once the server’s own window closes.'
- : failure.message
- }
- />
+ {/* role="status" announces the switch from the loader to this card once.
+ Without it a screen-reader user is left on "Loading files…" with no
+ signal that the load has settled into a failure. */}
+ <div role="status">
+ <EmptyState
+ title={
+ failure.kind === 'rate-limited' ? 'Too many file requests' : 'Could not load your files'
+ }
+ body={
+ failure.kind === 'rate-limited'
+ ? 'File listing is temporarily rate limited. Evenfire will let you retry once the server’s own window closes.'
+ : describeGfsReadError(failure.message).message
+ }
+ />
+ </div>
<div className="da-gfs-footer-actions">
{remainingSeconds > 0 ? (
- <span className="muted">
+ // Deliberately NOT a live region: it changes every second, and a
+ // polite region would announce each tick. The button references it
+ // instead, so asking for the button reads the wait along with it.
+ <span className="muted" id={countdownId}>
Retry available in{' '}
<span data-testid="gfs-discovery-retry-seconds">{remainingSeconds}</span>s
</span>
) : null}
- <Button disabled={remainingSeconds > 0} onClick={onRetry} size="sm" variant="outline">
+ <Button
+ aria-describedby={remainingSeconds > 0 ? countdownId : undefined}
+ disabled={remainingSeconds > 0}
+ onClick={onRetry}
+ size="sm"
+ variant="outline"
+ >
Retry file listing
</Button>
</div>
@@ -1118,6 +1149,11 @@ export function FilesPage({
!current && ctrl.discoveryFailure && ctrl.discoveryFailure.kind !== 'unsupported'
? ctrl.discoveryFailure
: null
+ // `visibleLoading` starts with `authorityPending`, which a 429 leaves true on
+ // purpose — a rate limit does not re-prove the session. The failure card
+ // renders ahead of the loader, so without excluding it here a screen reader
+ // would call the region busy while it shows a settled error and a Retry button.
+ const driveBusy = (visibleLoading && !blockingDiscoveryFailure) || droppedUploadCount > 0
const hasMoreVisible = currentIsFolder ? ctrl.hasMore : !current && ctrl.hasMoreAccessible
const loadingMoreVisible = currentIsFolder ? ctrl.isFetchingMore : ctrl.isFetchingMoreAccessible
@@ -1169,7 +1205,7 @@ export function FilesPage({
<section
className="page-card da-gfs-drive"
aria-label="Global File System browser"
- aria-busy={visibleLoading || droppedUploadCount > 0}
+ aria-busy={driveBusy}
onDragEnter={handleGfsDragEnter}
onDragLeave={handleGfsDragLeave}
onDragOver={handleGfsDragOver}
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index f72c463aa..dd92a8faf 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -3384,7 +3384,12 @@ describe('FilesPage', () => {
...baseController(),
authorityPending: true,
accessibleError: rawMessage,
- discoveryFailure: { kind: 'rate-limited', message: rawMessage, retryAfterSeconds: 7 },
+ discoveryFailure: {
+ kind: 'rate-limited',
+ message: rawMessage,
+ retryAfterSeconds: 7,
+ retryAvailableAt: Date.now() + 7_000,
+ },
retryDiscovery,
})
@@ -3432,4 +3437,66 @@ describe('FilesPage', () => {
expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()
expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()
})
+
+ it('shows a server-side discovery failure without the IPC plumbing around it', () => {
+ // `kind: 'failed'` covers 5xx, network and timeout — everything that is
+ // neither a 404 nor a rate limit. It reaches the same card, so the card's
+ // body has to be presented rather than passed through: the raw value is an
+ // Electron wrapper around the verdict, and the seam test in this PR asserts
+ // that wrapper must never reach a user.
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: true,
+ accessibleError:
+ "Error invoking remote method 'gfs:listAccessible': Error: 503 Service Unavailable: upstream_unreachable",
+ discoveryFailure: {
+ kind: 'failed',
+ message:
+ "Error invoking remote method 'gfs:listAccessible': Error: 503 Service Unavailable: upstream_unreachable",
+ retryAfterSeconds: null,
+ retryAvailableAt: null,
+ },
+ })
+
+ renderFilesPage()
+
+ // Liveness witness: the card really rendered, so the absence assertions
+ // below describe a presented failure and not an unmounted branch.
+ expect(screen.getByText('Could not load your files')).toBeTruthy()
+ expect(screen.getByText(/503 Service Unavailable: upstream_unreachable/)).toBeTruthy()
+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()
+ // No window was named, so nothing pretends to know one.
+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()
+ const retry = screen.getByRole('button', { name: /retry file listing/i }) as HTMLButtonElement
+ expect(retry.disabled).toBe(false)
+ })
+
+ it('stops reporting the drive as busy once discovery has settled into a failure', () => {
+ // authorityPending stays true after a 429 on purpose — a rate limit does
+ // not re-prove the session — so aria-busy had to stop deriving from it
+ // alone, or a screen reader announces a loading region that is showing a
+ // settled error with a Retry button.
+ const rawMessage =
+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " +
+ 'Too Many Requests retryAfterSeconds=7'
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ authorityPending: true,
+ accessibleError: rawMessage,
+ discoveryFailure: {
+ kind: 'rate-limited',
+ message: rawMessage,
+ retryAfterSeconds: 7,
+ retryAvailableAt: Date.now() + 7_000,
+ },
+ })
+
+ renderFilesPage()
+
+ const drive = screen.getByLabelText('Global File System browser')
+ // Witness: this is the failure state, not a page that never rendered the
+ // drive region at all.
+ expect(screen.getByText('Too many file requests')).toBeTruthy()
+ expect(drive.getAttribute('aria-busy')).toBe('false')
+ })
})