Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): answer a refused GFS read with a verdict on both surfaces
Alfredo Lopezaa059cc3bf3d
diff --git a/desktop-app/ui/src/components/GfsReadFailureCard/index.tsx b/desktop-app/ui/src/components/GfsReadFailureCard/index.tsxnew file mode 100644index 000000000..9b5abfc2d--- /dev/null+++ b/desktop-app/ui/src/components/GfsReadFailureCard/index.tsx@@ -0,0 +1,91 @@+import { useEffect, useId, useState } from 'react'+import { Button, EmptyState } from '@components/Common'+import { describeGfsReadError } from '@lib/gfsGrantErrors'+import type { GfsReadFailureCardProps } from './types'++/** 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 GFS read the server refused.+ *+ * Before this existed no surface had a way to say "the request was answered,+ * and the answer was no": a rejected read left the loader spinning and 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.+ *+ * Shared rather than page-local because both read planes need it and they must+ * not drift: the Files page shows it for root discovery and for a folder+ * listing, the composer's picker for the same two. A second copy would be a+ * second countdown to keep correct.+ */+export function GfsReadFailureCard({ failure, onRetry }: GfsReadFailureCardProps) {+ 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(secondsUntil(retryAvailableAt))+ if (retryAvailableAt === null || retryAvailableAt <= Date.now()) return+ const timer = setInterval(() => {+ const remaining = secondsUntil(retryAvailableAt)+ setRemainingSeconds(remaining)+ if (remaining <= 0) clearInterval(timer)+ }, COUNTDOWN_TICK_MS)+ return () => clearInterval(timer)+ }, [retryAvailableAt])++ return (+ <>+ {/* 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 ? (+ // 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+ aria-describedby={remainingSeconds > 0 ? countdownId : undefined}+ disabled={remainingSeconds > 0}+ onClick={onRetry}+ size="sm"+ variant="outline"+ >+ Retry file listing+ </Button>+ </div>+ </>+ )+}diff --git a/desktop-app/ui/src/components/GfsReadFailureCard/types.ts b/desktop-app/ui/src/components/GfsReadFailureCard/types.tsnew file mode 100644index 000000000..99dcde4c2--- /dev/null+++ b/desktop-app/ui/src/components/GfsReadFailureCard/types.ts@@ -0,0 +1,6 @@+import type { GfsDiscoveryFailure } from '@hooks/domain/useGfsBrowserController'++export interface GfsReadFailureCardProps {+ failure: GfsDiscoveryFailure+ onRetry: () => void+}diff --git a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsxindex 05b8eaca6..c4ba7379b 100644--- a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx+++ b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx@@ -1,9 +1,13 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { Button, EmptyState, IconButton, StatusBanner } from '@components/Common'import { GfsFileIcon } from '@components/GfsFileIcon'+import { GfsReadFailureCard } from '@components/GfsReadFailureCard'import { IconChevronRight, IconClose, IconContexts } from '@components/SidebarNav/icons'-import { useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'-import { describeGfsReadError } from '@lib/gfsGrantErrors'+import {+ type GfsDiscoveryFailure,+ useGfsBrowserController,+} from '@hooks/domain/useGfsBrowserController'+import { describeGfsReadError, isRateLimited, parseRetryAfterSeconds } from '@lib/gfsGrantErrors'import { formatSharedFileSize } from '@lib/sharedFiles'import type { ComposerGlobalFileReference } from '@/uiTypes'import type { ComposerGlobalFileSelection, ComposerGlobalFilesModalProps } from './types'@@ -49,6 +53,49 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFilesconst hasMore = ctrl.current ? ctrl.hasMore : ctrl.hasMoreAccessibleconst loadingMore = ctrl.current ? ctrl.isFetchingMore : ctrl.isFetchingMoreAccessibleconst loadMore = ctrl.current ? ctrl.loadMore : ctrl.loadMoreAccessible+ // A refused read is not an empty picker. Without this the modal answered a+ // 429 with "No shared files yet" — a claim about the user's library that the+ // rejected request never established — and offered nothing to retry, so the+ // only exit was to close the modal and reopen it, spending another request+ // against the budget that had just refused one.+ //+ // `unsupported` stays out: that server cannot list at all, and a Retry button+ // would promise an endpoint that will not appear. The existing info banner+ // already explains it, and the empty state below is what the user gets.+ const blockingFailure = useMemo<{+ failure: GfsDiscoveryFailure+ retry: () => void+ } | null>(() => {+ if (entries.length > 0) return null+ if (!ctrl.current) {+ return ctrl.discoveryFailure && ctrl.discoveryFailure.kind !== 'unsupported'+ ? { failure: ctrl.discoveryFailure, retry: ctrl.retryDiscovery }+ : null+ }+ if (!ctrl.error) return null+ const kind = isRateLimited(ctrl.error) ? 'rate-limited' : 'failed'+ const retryAfterSeconds = parseRetryAfterSeconds(ctrl.error)+ return {+ failure: {+ kind,+ message: ctrl.error,+ retryAfterSeconds,+ retryAvailableAt:+ kind === 'rate-limited' && retryAfterSeconds !== null+ ? ctrl.errorUpdatedAt + retryAfterSeconds * 1000+ : null,+ },+ retry: ctrl.retryChildren,+ }+ }, [+ ctrl.current,+ ctrl.discoveryFailure,+ ctrl.error,+ ctrl.errorUpdatedAt,+ ctrl.retryChildren,+ ctrl.retryDiscovery,+ entries.length,+ ])return (<div@@ -113,9 +160,19 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFiles<div className="composer-global-files-browser">{ctrl.accessibleNotice ? <StatusBanner tone="info" text={ctrl.accessibleNotice} /> : null}- {error ? <StatusBanner tone="error" text={error} /> : null}+ {/* The banner is the non-blocking half of the same failure the card+ takes over, so it stands down when the card is up rather than+ stating the error twice. */}+ {error && !blockingFailure ? <StatusBanner tone="error" text={error} /> : null}- {loading ? (+ {blockingFailure ? (+ <GfsReadFailureCard+ failure={blockingFailure.failure}+ onRetry={() => {+ void blockingFailure.retry()+ }}+ />+ ) : loading ? (<div className="composer-global-files-loading" role="status"><span className="composer-send-spinner" aria-hidden="true" />Loading files…diff --git a/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsxnew file mode 100644index 000000000..cf5ff32e4--- /dev/null+++ b/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsx@@ -0,0 +1,241 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { ComposerGlobalFilesModal } from '../ComposerGlobalFilesModal'++const hookMock = vi.hoisted(() => ({+ useGfsBrowserController: vi.fn(),+}))++vi.mock('@hooks/domain/useGfsBrowserController', () => hookMock)+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++/**+ * Only the fields this modal reads. The component destructures them directly,+ * so a field added to the controller and consumed here without landing in this+ * fixture surfaces as `undefined` rather than as a type error.+ */+function baseController() {+ return {+ current: null,+ crumbs: [],+ items: [],+ accessibleResources: [],+ loading: false,+ loadingAccessible: false,+ error: null,+ errorUpdatedAt: 0,+ accessibleError: null,+ accessibleNotice: null,+ discoveryFailure: null,+ retryDiscovery: vi.fn(),+ retryChildren: vi.fn(),+ hasMore: false,+ hasMoreAccessible: false,+ isFetchingMore: false,+ isFetchingMoreAccessible: false,+ loadMore: vi.fn(),+ loadMoreAccessible: vi.fn(),+ openChild: vi.fn(),+ openResource: vi.fn(),+ goToCrumb: vi.fn(),+ reset: vi.fn(),+ }+}++function renderModal() {+ const onAdd = vi.fn()+ const onClose = vi.fn()+ render(<ComposerGlobalFilesModal onAdd={onAdd} onClose={onClose} />)+ return { onAdd, onClose }+}++const RATE_LIMITED_DISCOVERY =+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=7'++const RATE_LIMITED_CHILDREN =+ "Error invoking remote method 'gfs:listChildren': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=7'++describe('ComposerGlobalFilesModal', () => {+ afterEach(() => {+ cleanup()+ vi.useRealTimers()+ vi.clearAllMocks()+ })++ it('lists the resources discovery returned', () => {+ // Liveness witness for the whole file: the happy path really renders rows,+ // so every "not shown" assertion below describes a branch that was taken+ // and not a modal that failed to mount at all.+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ accessibleResources: [+ {+ resourceId: 'file-1',+ rid: 'file-1',+ gfsUri: 'gfs://main/file-1',+ drive: 'main',+ parentResourceId: null,+ name: 'notes.txt',+ kind: 'file',+ path: '/notes.txt',+ version: 1,+ bytes: 12,+ },+ ],+ })++ renderModal()++ expect(screen.getByText('notes.txt')).toBeTruthy()+ expect(screen.queryByText('No shared files yet')).toBeNull()+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()+ })++ it('answers a rate-limited discovery with a retry, not "No shared files yet"', async () => {+ vi.useFakeTimers()+ const retryDiscovery = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ accessibleError: RATE_LIMITED_DISCOVERY,+ discoveryFailure: {+ kind: 'rate-limited',+ message: RATE_LIMITED_DISCOVERY,+ retryAfterSeconds: 7,+ retryAvailableAt: Date.now() + 7_000,+ },+ retryDiscovery,+ })++ renderModal()++ // The picker used to state the user's library was empty on the strength of+ // a request the server refused, and offered no way back: the only exit was+ // to close and reopen the modal, spending another request against the+ // budget that had just refused one.+ expect(screen.queryByText('No shared files yet')).toBeNull()+ expect(screen.getByText('Too many file requests')).toBeTruthy()+ expect(screen.getByTestId('gfs-discovery-retry-seconds').textContent).toBe('7')+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()++ const disabled = screen.getByRole('button', {+ name: /retry file listing/i,+ }) as HTMLButtonElement+ expect(disabled.disabled).toBe(true)++ await act(async () => {+ await vi.advanceTimersByTimeAsync(7_000)+ })+ const enabled = screen.getByRole('button', { name: /retry file listing/i }) as HTMLButtonElement+ expect(enabled.disabled).toBe(false)+ await act(async () => {+ fireEvent.click(enabled)+ })+ // Witness: wired to the controller, not to a local no-op.+ expect(retryDiscovery).toHaveBeenCalledTimes(1)+ })++ it('answers a rate-limited folder listing by retrying the children query', async () => {+ const retryChildren = vi.fn()+ const retryDiscovery = vi.fn()+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'parent-1',+ gfsUri: 'gfs://main/parent-1',+ name: 'Workspace',+ kind: 'directory',+ version: 1,+ bytes: 0,+ },+ items: [],+ error: RATE_LIMITED_CHILDREN,+ errorUpdatedAt: Date.now() - 7_000,+ retryChildren,+ retryDiscovery,+ })++ renderModal()++ expect(screen.queryByText('This folder is empty')).toBeNull()+ expect(screen.getByText('Too many file requests')).toBeTruthy()++ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: /retry file listing/i }))+ })+ // The query that failed is the one retried. Discovery was never asked+ // anything on this plane and must not be spent here.+ expect(retryChildren).toHaveBeenCalledTimes(1)+ expect(retryDiscovery).not.toHaveBeenCalled()+ })++ it('keeps a loaded listing when only the next page was refused', () => {+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ accessibleResources: [+ {+ resourceId: 'file-1',+ rid: 'file-1',+ gfsUri: 'gfs://main/file-1',+ drive: 'main',+ parentResourceId: null,+ name: 'notes.txt',+ kind: 'file',+ path: '/notes.txt',+ version: 1,+ bytes: 12,+ },+ ],+ hasMoreAccessible: true,+ accessibleError: RATE_LIMITED_DISCOVERY,+ discoveryFailure: {+ kind: 'rate-limited',+ message: RATE_LIMITED_DISCOVERY,+ retryAfterSeconds: 7,+ retryAvailableAt: Date.now() + 7_000,+ },+ })++ renderModal()++ // Witness: the row the user already had is still there.+ expect(screen.getByText('notes.txt')).toBeTruthy()+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()+ // Still surfaced, as the banner, and presented rather than raw.+ expect(screen.getByText(/Too many file requests — try again in 7s\./)).toBeTruthy()+ })++ it('leaves an unsupported discovery on its notice, with no retry to offer', () => {+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ accessibleNotice:+ 'Automatic GFS discovery is not available from this server yet. You can still open any GFS link you have.',+ discoveryFailure: {+ kind: 'unsupported',+ message: '404 Not Found: Not Found',+ retryAfterSeconds: null,+ retryAvailableAt: null,+ },+ })++ renderModal()++ // Witness: this is the unsupported branch, not an unmounted modal.+ expect(screen.getByText(/Automatic GFS discovery is not available/)).toBeTruthy()+ // A Retry would promise an endpoint that does not appear because a button+ // was pressed.+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()+ expect(screen.queryByText('Too many file requests')).toBeNull()+ })++ it('reports an empty library only when discovery actually answered', () => {+ hookMock.useGfsBrowserController.mockReturnValue(baseController())++ renderModal()++ expect(screen.getByText('No shared files yet')).toBeTruthy()+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()+ })+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsxindex 3d2307355..793518f22 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx@@ -1428,14 +1428,18 @@ describe('useGfsBrowserController', () => {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.+ // Settled, and reported as settled. The R4 authority gate is still open —+ // a 429 never advances the discovery query's `dataUpdatedAt`, so the+ // session is not re-proved and every cached GFS surface stays withheld —+ // but that is a statement about what may be SHOWN, not about whether a+ // request is outstanding. While the two shared this field, a folder that+ // had already answered went on reporting a load nothing would ever end,+ // and the consumers that read it alone sat on "Loading files…" forever.+ //+ // `authority-pending` is asserted first and deliberately: it is the witness+ // that the gate itself was not falsified to buy the line below.expect(screen.getByTestId('authority-pending').textContent).toBe('pending')- expect(screen.getByTestId('loading').textContent).toBe('loading')+ expect(screen.getByTestId('loading').textContent).toBe('idle')})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.tsindex a3edbb83e..878c72c54 100644--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts@@ -745,6 +745,12 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {pausedUntilRef.current = 0await accessibleQuery.refetch()}, [accessibleQuery])+ // The same contract for the children query. No pause to clear: the focus+ // pause guards discovery, which refetches on its own; a folder listing is+ // only ever fetched because the user asked for it.+ const retryChildren = useCallback(async () => {+ await childrenQuery.refetch()+ }, [childrenQuery])const accessibleNotice =sessionScope && !canListAccessibleResources? 'Automatic GFS discovery is not available in this desktop runtime. You can still open any GFS link you have.'@@ -974,7 +980,15 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {rowAffordancesError: rowAffordancesQuery.error? toPresentedMessage(rowAffordancesQuery.error): null,- loading: (authorityPending || childrenQuery.isFetching) && items.length === 0,+ // Only the `authorityPending` term stands down on a settled discovery+ // error, never the children term: a folder that is genuinely fetching must+ // keep the spinner, or the view flashes "this folder is empty" mid-load.+ // Without the gate a 429 on discovery — which leaves `authorityPending`+ // true by design, because a rate limit does not re-prove the session —+ // pinned every consumer of this field on "Loading files…" with nothing+ // in flight to end it.+ loading:+ ((authorityPending && !discoveryFailure) || 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). The term@@ -988,10 +1002,15 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {accessibleQuery.isFetching &&accessibleResources.length === 0)),error: childrenQuery.error ? toMessage(childrenQuery.error) : null,+ // The clock the children failure is dated by. A countdown needs the moment+ // the server refused, and only the query knows it; deriving it from render+ // time would restart the wait on every re-render.+ errorUpdatedAt: childrenQuery.error ? childrenQuery.errorUpdatedAt : 0,accessibleError: accessibleNotice ? null : accessibleErrorMessage,accessibleNotice,discoveryFailure,retryDiscovery,+ retryChildren,openError,resolving,hasMore: Boolean(childrenQuery.hasNextPage),diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsxindex 1bdba5c2c..4b4d4a694 100644--- a/desktop-app/ui/src/pages/FilesPage.tsx+++ b/desktop-app/ui/src/pages/FilesPage.tsx@@ -20,6 +20,7 @@ import { ConfirmDialog } from '@components/ConfirmDialog'import { GfsFileIcon } from '@components/GfsFileIcon'import { GfsImagePreview } from '@components/GfsImagePreview'import { GfsMarkdownPreview } from '@components/GfsMarkdownPreview'+import { GfsReadFailureCard } from '@components/GfsReadFailureCard'import { GfsResourceMenu } from '@components/GfsResourceMenu'import { GfsVideoPreview } from '@components/GfsVideoPreview'import {@@ -42,7 +43,12 @@ import {} from '@hooks/domain/useGfsBrowserController'import { isEventFromNestedInteractive } from '@lib/clickableRowProps'import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'-import { describeGfsGrantError, describeGfsReadError } from '@lib/gfsGrantErrors'+import {+ describeGfsGrantError,+ describeGfsReadError,+ isRateLimited,+ parseRetryAfterSeconds,+} from '@lib/gfsGrantErrors'import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'import { gfsVideoPreviewMimeType } from '@lib/gfsVideoPreview'@@ -212,9 +218,6 @@ 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.*@@ -224,91 +227,6 @@ const COUNTDOWN_TICK_MS = 250*/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))-}--/**- * 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 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,- onRetry,-}: {- failure: GfsDiscoveryFailure- onRetry: () => void-}) {- 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(secondsUntil(retryAvailableAt))- if (retryAvailableAt === null || retryAvailableAt <= Date.now()) return- const timer = setInterval(() => {- const remaining = secondsUntil(retryAvailableAt)- setRemainingSeconds(remaining)- if (remaining <= 0) clearInterval(timer)- }, COUNTDOWN_TICK_MS)- return () => clearInterval(timer)- }, [retryAvailableAt])-- return (- <>- {/* 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 ? (- // 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- aria-describedby={remainingSeconds > 0 ? countdownId : undefined}- disabled={remainingSeconds > 0}- onClick={onRetry}- size="sm"- variant="outline"- >- Retry file listing- </Button>- </div>- </>- )-}-export function FilesPage({pushToast,pendingGfsUri,@@ -1178,8 +1096,18 @@ export function FilesPage({// authorityPending keeps the loading state up: cached rows must not render// (and must not be mistaken for an empty folder) until discovery re-proves// the session (R4 spec §1).+ //+ // A settled discovery error is not a pending load, though — the same+ // principle the controller already applies to `loadingAccessible`. The flag+ // itself stays true, because a 429 or a 404 does not re-prove the session and+ // the controller must go on withholding every cached surface; what changes is+ // only that the page stops calling that a load in progress. Without this a+ // 404 from an older server leaves "Loading files…" spinning forever+ // underneath the notice that says discovery is unavailable, and a link opened+ // while discovery is down never reveals the file it resolved.const visibleLoading =- ctrl.authorityPending || (currentIsFolder ? loading : !current ? loadingAccessible : false)+ (ctrl.authorityPending && !ctrl.discoveryFailure) ||+ (currentIsFolder ? loading : !current ? loadingAccessible : false)const visibleError = currentIsFolder ? error : !current ? accessibleError : null// Scoped to the root view on purpose: `accessibleError` only reaches// `visibleError` when there is no `current`, so the card replaces exactly the@@ -1199,11 +1127,45 @@ export function FilesPage({ctrl.discoveryFailure.kind !== 'unsupported'? ctrl.discoveryFailure: null+ // The same verdict for the other read plane. A folder listing refused by the+ // budget used to fall through to "This folder is empty", which states as fact+ // the one thing the failed request could not establish — and offered nothing+ // to retry. The classification reuses the exported helpers rather than a+ // second classifier; `unsupported` has no meaning here because listing+ // children is not the endpoint an older server lacks.+ const folderFailure = useMemo<GfsDiscoveryFailure | null>(() => {+ if (!currentIsFolder || !error || visibleResources.length > 0) return null+ const kind = isRateLimited(error) ? 'rate-limited' : 'failed'+ const retryAfterSeconds = parseRetryAfterSeconds(error)+ return {+ kind,+ message: error,+ retryAfterSeconds,+ retryAvailableAt:+ kind === 'rate-limited' && retryAfterSeconds !== null+ ? ctrl.errorUpdatedAt + retryAfterSeconds * 1000+ : null,+ }+ }, [ctrl.errorUpdatedAt, currentIsFolder, error, visibleResources.length])+ // One card, two planes, each retrying the query that actually failed. Root+ // discovery wins when both are set: `folderFailure` needs `currentIsFolder`,+ // and `blockingDiscoveryFailure` needs no `current`, so the two are mutually+ // exclusive by construction — the order below is a formality, not a policy.+ const blockingFailure = blockingDiscoveryFailure+ ? { failure: blockingDiscoveryFailure, retry: ctrl.retryDiscovery }+ : folderFailure+ ? { failure: folderFailure, retry: ctrl.retryChildren }+ : null+ // Scoped to the root for the same reason the card is: `discoveryFailure`+ // describes the root listing and stays set while the user browses a folder.+ // Without `!current`, a genuinely empty directory would be reported as a+ // server that cannot list.+ const rootListingUnsupported = !current && ctrl.discoveryFailure?.kind === 'unsupported'// `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 driveBusy = (visibleLoading && !blockingFailure) || droppedUploadCount > 0const hasMoreVisible = currentIsFolder ? ctrl.hasMore : !current && ctrl.hasMoreAccessibleconst loadingMoreVisible = currentIsFolder ? ctrl.isFetchingMore : ctrl.isFetchingMoreAccessible@@ -1381,7 +1343,7 @@ export function FilesPage({) : null}{accessibleNotice ? <StatusBanner tone="info" text={accessibleNotice} /> : null}- {visibleError && !accessRevoked && !blockingDiscoveryFailure ? (+ {visibleError && !accessRevoked && !blockingFailure ? (// Presented, not raw. The banner is the non-blocking half of the// same read-plane failure the card shows, so it must not be the one// surface left leaking `Error invoking remote method '…'` at the@@ -1402,11 +1364,11 @@ export function FilesPage({</Button></div></>- ) : blockingDiscoveryFailure ? (- <GfsDiscoveryFailureCard- failure={blockingDiscoveryFailure}+ ) : blockingFailure ? (+ <GfsReadFailureCard+ failure={blockingFailure.failure}onRetry={() => {- void ctrl.retryDiscovery()+ void blockingFailure.retry()}}/>) : visibleLoading ? (@@ -1478,12 +1440,28 @@ export function FilesPage({</div></div>) : visibleResources.length === 0 ? (+ // `unsupported` earns its own copy because the other two assert+ // something this branch cannot know. An older server that has no+ // listing endpoint never told us the library was empty — it told us+ // it cannot answer — and "No shared files yet" reports the absence+ // of an answer as an answer. No Retry either: the endpoint will not+ // appear because the user pressed a button. The banner above already+ // points at opening a link, so this states the one thing it does+ // not: the list is missing, the files may not be.<EmptyState- title={currentIsFolder ? 'This folder is empty' : 'No shared files yet'}+ title={+ rootListingUnsupported+ ? 'Files cannot be listed here'+ : currentIsFolder+ ? 'This folder is empty'+ : 'No shared files yet'+ }body={- currentIsFolder- ? 'Files and folders added here will appear in this list.'- : 'Resources shared directly with you or your teams will appear here.'+ rootListingUnsupported+ ? 'This server cannot list shared resources, so Evenfire has no way to tell what you have access to. That does not mean you have none.'+ : currentIsFolder+ ? 'Files and folders added here will appear in this list.'+ : 'Resources shared directly with you or your teams will appear here.'}/>) : (diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsxindex cf2185d92..a66006065 100644--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx@@ -80,6 +80,9 @@ function baseController() {refreshAffordances: vi.fn(),discoveryFailure: null,retryDiscovery: vi.fn(),+ authorityPending: false,+ errorUpdatedAt: 0,+ retryChildren: vi.fn(),}}@@ -3713,4 +3716,249 @@ describe('FilesPage', () => {expect(screen.getByText('Too many file requests')).toBeTruthy()expect(drive.getAttribute('aria-busy')).toBe('false')})++ // The five fixtures above all set `authorityPending: true`, no rows and+ // `hasMoreAccessible: false` together, so nothing distinguishes the three+ // clauses of the card's guard: swapping the empty-listing test for either+ // sibling left the whole suite green. These two break that correlation, one+ // clause at a time, and each holds one clause on its own.+ it('keeps a loaded row while the authority gate is still pending', () => {+ // Rows present, gate pending, and no further page to fetch. Only+ // `visibleResources.length === 0` can decide here, so a guard rewritten to+ // read `authorityPending` (or `!hasMoreAccessible`) wipes out a listing the+ // user can see — the failure the empty-listing clause exists to prevent.+ const rawMessage =+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=7'+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ authorityPending: true,+ hasMoreAccessible: false,+ accessibleResources: [+ {+ resourceId: 'folder-1',+ rid: 'folder-1',+ gfsUri: 'gfs://main/folder-1',+ drive: 'main',+ parentResourceId: null,+ name: 'Product',+ kind: 'directory',+ path: '/Product',+ version: 1,+ bytes: 0,+ sources: ['grant'],+ permissions: ['read'],+ coversDescendants: true,+ },+ ],+ accessibleError: rawMessage,+ discoveryFailure: {+ kind: 'rate-limited',+ message: rawMessage,+ retryAfterSeconds: 7,+ retryAvailableAt: Date.now() + 7_000,+ },+ })++ renderFilesPage()++ // Witness: the row is on screen, so the two absences below describe a+ // listing that survived rather than a page that drew nothing at all.+ expect(screen.getByRole('button', { name: 'Product' })).toBeTruthy()+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()+ })++ it('shows the card for an empty listing once the authority gate has closed', () => {+ // The mirror image: gate closed, no further page, and nothing to show. A+ // guard that read `authorityPending` instead would skip the card and leave+ // the user on "No shared files yet" for a listing that was refused.+ const rawMessage =+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=120'+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ authorityPending: false,+ hasMoreAccessible: false,+ accessibleError: rawMessage,+ discoveryFailure: {+ kind: 'rate-limited',+ message: rawMessage,+ retryAfterSeconds: 120,+ retryAvailableAt: Date.now() + 120_000,+ },+ })++ renderFilesPage()++ expect(screen.getByTestId('gfs-discovery-retry-seconds').textContent).toBe('120')+ expect(screen.queryByText('No shared files yet')).toBeNull()+ })++ it('answers a 404 discovery failure with its own empty state, never a loader', () => {+ // The original incident's symptom through a different door. An older+ // control-api has no `listAccessible`, so the 404 leaves `authorityPending`+ // true forever — correctly, since nothing re-proved the session — and the+ // page used to spin "Loading files…" underneath the very notice explaining+ // that discovery is unavailable. Two contradictory claims at once.+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ authorityPending: true,+ accessibleNotice:+ 'Automatic GFS discovery is not available from this server yet. You can still open any GFS link you have.',+ discoveryFailure: {+ kind: 'unsupported',+ message: '404 Not Found: Not Found',+ retryAfterSeconds: null,+ retryAvailableAt: null,+ },+ })++ renderFilesPage()++ // Witness: the settled state really rendered.+ expect(screen.getByText('Files cannot be listed here')).toBeTruthy()+ expect(screen.getByText(/That does not mean you have none/)).toBeTruthy()+ expect(screen.queryByText('Loading files…')).toBeNull()+ // No Retry: the endpoint does not appear because a button was pressed.+ expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()+ // The copy that would assert an empty library must not be the one shown.+ expect(screen.queryByText('No shared files yet')).toBeNull()+ })++ it('reveals a file opened by link while discovery is still rate limited', () => {+ // Opening a `gfs://` link does not go through discovery, so a 429 there has+ // no bearing on whether the resolved file can be shown. It was shown only+ // as a spinner, because the page called the pending authority gate a load+ // in progress and the loader renders ahead of the file.+ const rawMessage =+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=7'+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ authorityPending: true,+ current: {+ resourceId: 'file-1',+ gfsUri: 'gfs://main/file-1',+ name: 'quarterly.pdf',+ kind: 'file',+ version: 1,+ bytes: 2048,+ },+ crumbs: [+ {+ resourceId: 'file-1',+ gfsUri: 'gfs://main/file-1',+ name: 'quarterly.pdf',+ kind: 'file',+ },+ ],+ accessibleError: rawMessage,+ discoveryFailure: {+ kind: 'rate-limited',+ message: rawMessage,+ retryAfterSeconds: 7,+ retryAvailableAt: Date.now() + 7_000,+ },+ })++ renderFilesPage()++ // The heading, not the breadcrumb: the breadcrumb renders above the+ // loader and would be present even while the spinner hid the file, so+ // only the heading proves the file view itself was reached.+ expect(screen.getByRole('heading', { name: 'quarterly.pdf' })).toBeTruthy()+ expect(screen.queryByText('Loading files…')).toBeNull()+ // The discovery failure belongs to the root listing, not to this file, so+ // it must not take the surface over either.+ expect(screen.queryByText('Too many file requests')).toBeNull()+ })++ it('answers a rate-limited folder listing with the card, not an empty folder', async () => {+ vi.useFakeTimers()+ const retryChildren = vi.fn()+ const rawMessage =+ "Error invoking remote method 'gfs:listChildren': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=7'+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'parent-1',+ gfsUri: 'gfs://main/parent-1',+ name: 'Workspace',+ kind: 'directory',+ version: 1,+ bytes: 0,+ },+ items: [],+ error: rawMessage,+ errorUpdatedAt: Date.now(),+ retryChildren,+ })++ renderFilesPage()++ // "This folder is empty" states as fact the one thing the refused request+ // could not establish, and offered nothing to retry.+ expect(screen.queryByText('This folder is empty')).toBeNull()+ expect(screen.getByText('Too many file requests')).toBeTruthy()+ expect(screen.getByTestId('gfs-discovery-retry-seconds').textContent).toBe('7')+ // The raw channel name stays out of the user's way on this plane too.+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()++ await act(async () => {+ await vi.advanceTimersByTimeAsync(7_000)+ })+ const retry = screen.getByRole('button', { name: /retry file listing/i }) as HTMLButtonElement+ expect(retry.disabled).toBe(false)+ await act(async () => {+ fireEvent.click(retry)+ })+ // Witness: the button retries the query that actually failed — the children+ // listing — and not discovery, which was never asked anything here.+ expect(retryChildren).toHaveBeenCalledTimes(1)+ })++ it('keeps a loaded folder listing when only its next page was refused', () => {+ // The folder-plane sibling of the `Load more` case: rows already fetched+ // must not be razed to report that the page behind them failed.+ const rawMessage =+ "Error invoking remote method 'gfs:listChildren': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=7'+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'parent-1',+ gfsUri: 'gfs://main/parent-1',+ name: 'Workspace',+ kind: 'directory',+ version: 1,+ bytes: 0,+ },+ items: [+ {+ resourceId: 'file-child',+ rid: 'file-child',+ gfsUri: 'gfs://main/file-child',+ drive: 'main',+ parentResourceId: 'parent-1',+ name: 'notes.txt',+ kind: 'file',+ path: '/notes.txt',+ version: 1,+ bytes: 12,+ },+ ],+ error: rawMessage,+ errorUpdatedAt: Date.now(),+ })++ renderFilesPage()++ // Witness: the row survived the failure.+ expect(screen.getByText('notes.txt')).toBeTruthy()+ expect(screen.queryByTestId('gfs-discovery-retry-seconds')).toBeNull()+ // Still surfaced, as the banner — and presented, not as the IPC wrapper.+ expect(screen.getByText(/Too many file requests — try again in 7s\./)).toBeTruthy()+ })})