Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): carry the HTTP status across IPC and stop misreporting refused GFS reads
Alfredo Lopezbe93dd6c0f4d
diff --git a/desktop-app/src/__tests__/appService.gfs.test.ts b/desktop-app/src/__tests__/appService.gfs.test.tsindex e13e36065..5675075a1 100644--- a/desktop-app/src/__tests__/appService.gfs.test.ts+++ b/desktop-app/src/__tests__/appService.gfs.test.ts@@ -1043,6 +1043,10 @@ describe('AppService GFS proxy read transport', () => {const message = error instanceof Error ? error.message : String(error)expect(message).toContain('gfs download failed: 429')expect(message).toContain('retryAfterSeconds=7')+ // The status travels as its own vetted field, and `retryAfterSeconds`+ // stays last: the renderer anchors that one to the end of the message.+ expect(message).toContain('httpStatus=429')+ expect(message.endsWith('retryAfterSeconds=7')).toBe(true)// 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)@@ -1052,6 +1056,53 @@ describe('AppService GFS proxy read transport', () => {}})+ it('reports the status the server answered with, not the one its body quotes', async () => {+ // `requestJson` puts the RAW body in the message when the JSON carries no+ // top-level `error`/`message`, so this 500's text reaches the renderer with+ // an upstream 429 in it. Flattened, both are three delimited digits, and+ // the renderer read the body's — a failing server presented as a rate+ // limit, with a retry window and a paused revalidation nobody asked for.+ // The body writes `httpStatus=` itself as well: the marker is trustworthy+ // only because this boundary strips every copy it did not write.+ const service = new AppService() as unknown as {+ sessionToken: string | null+ listGfsChildren: (resourceId: string) => Promise<unknown>+ }+ service.sessionToken = 'session-token'++ const originalFetch = globalThis.fetch+ const fetchMock = vi.fn(+ async () =>+ new Response('upstream 429 from the pool httpStatus=429', {+ status: 500,+ statusText: 'Internal Server Error',+ headers: { 'content-type': 'text/plain' },+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ try {+ const error = await service.listGfsChildren(RESOURCE_ID).then(+ () => {+ throw new Error('expected the failing children listing to reject')+ },+ (rejected: unknown) => rejected+ )+ const message = error instanceof Error ? error.message : String(error)+ expect(message).toContain('httpStatus=500')+ expect(message).not.toContain('httpStatus=429')+ // Witness: the server's own words survive — only the counterfeit field+ // was removed, so the verdict is never swallowed, and the body's 429 is+ // still there for the classifier to have been fooled by.+ expect(message).toContain('upstream 429 from the pool')+ // Liveness witness: the message came from a request that was actually+ // made, not from a client-side guard that rejected before the call.+ expect(fetchMock).toHaveBeenCalled()+ } finally {+ 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 assertiondiff --git a/desktop-app/src/gfs/uriHandler.ts b/desktop-app/src/gfs/uriHandler.tsindex a8a21cb21..23d8fca68 100644--- a/desktop-app/src/gfs/uriHandler.ts+++ b/desktop-app/src/gfs/uriHandler.ts@@ -790,28 +790,47 @@ function parseGfsGrantErrorFields(bodyText: string): GfsGrantErrorFields {* `{ retryAfterSeconds }`, but an upstream proxy or CDN answers 429 with its* own body and only the standard header, and that body parses to nothing.*+ * The STATUS travels as `httpStatus=…` for the same reason the window does.+ * Once flattened into the message text, `429` is three digits like any other:+ * `httpClient` composes `${status} ${statusText}: ${body}`, so a 500 whose body+ * says `upstream 429 from the pool` is byte-indistinguishable from a real rate+ * limit to anything reading the string. `ApiError.status` is the transport's+ * own verdict and the only authority on which one it was; carrying it across+ * lets the renderer classify on the status instead of guessing from prose.+ ** When there is nothing structured to surface AND the original message carries* no counterfeit field, the ORIGINAL error propagates unchanged (fail loud;* never swallow the server's verdict).*/function surfaceGfsGrantError(error: unknown): unknown {if (!error || typeof error !== 'object') return error- const transportError = error as { bodyText?: unknown; retryAfter?: unknown }+ const transportError = error as { bodyText?: unknown; retryAfter?: unknown; status?: unknown }const bodyText = typeof transportError.bodyText === 'string' ? transportError.bodyText : ''const fields = bodyText ? parseGfsGrantErrorFields(bodyText) : {}const retryAfterSeconds =fields.retryAfterSeconds ?? parseRetryAfterHeader(transportError.retryAfter)+ const httpStatus = vettedHttpStatus(transportError.status)const parts: string[] = []if (fields.invalidIndexes) parts.push(`invalidIndexes=[${fields.invalidIndexes.join(',')}]`)+ // Before `retryAfterSeconds`, never after: the renderer anchors that field to+ // the END of the message so an earlier occurrence in the server's own text+ // cannot win, and a token appended behind it would take the anchor away.+ if (httpStatus !== undefined) parts.push(`httpStatus=${httpStatus}`)if (retryAfterSeconds !== undefined) parts.push(`retryAfterSeconds=${retryAfterSeconds}`)// `error` is a non-null object by the guard above, so it needs no nullish// coalescing here: a `?? ''` branch could never be taken.const rawMessage = error instanceof Error ? error.message : String(error)- const baseMessage = stripUnvettedRetryAfter(rawMessage)+ const baseMessage = stripUnvettedRetryAfter(stripUnvettedHttpStatus(rawMessage))// Nothing vetted to append and nothing counterfeit to remove: the server's// own error is already exactly what the renderer should see.if (parts.length === 0 && baseMessage === rawMessage) return errorconst suffix = parts.length > 0 ? ` ${parts.join(' ')}` : ''+ // Every `ApiError` now yields a `httpStatus=` part, so a wrapper is the norm+ // rather than the exception it used to be. The transport fields are not+ // copied onto it: `cause` keeps the original error object intact, and no+ // main-process caller of these nine methods reads `.status`/`.bodyText` off+ // the rejection (the `ApiError` branches in `appService` belong to rpc-proxy+ // and stored-session paths; the upload retry path never imports this module).return new GfsUriError(`${baseMessage}${suffix}`, { cause: error })}@@ -846,6 +865,38 @@ function stripUnvettedRetryAfter(message: string): string {return message.replace(UNVETTED_RETRY_AFTER_TOKEN, '')}+/** Counterpart of `UNVETTED_RETRY_AFTER_TOKEN` for the status marker. */+const UNVETTED_HTTP_STATUS_TOKEN = /(?:^|\s)httpStatus=\S*/g++/**+ * Strip any `httpStatus=` the server's own text already printed.+ *+ * The marker is only worth reading because this module is the one that writes+ * it. A response body is free to contain the same token — `httpClient` copies+ * the raw body into the message when the JSON carries no `error`/`message` key+ * — and the renderer would then classify a failure on a number the server's+ * own payload chose. Removing it costs nothing: the status also stays in the+ * message's leading `<status> <statusText>:`, and `cause` keeps the original.+ */+function stripUnvettedHttpStatus(message: string): string {+ return message.replace(UNVETTED_HTTP_STATUS_TOKEN, '')+}++/**+ * `ApiError.status` when it is a real HTTP status code, otherwise nothing.+ *+ * Every GFS transport failure is an `ApiError` (`httpClient.requestJson` and+ * the `fetchBytes` literal on `AppService` both throw one), so this is the+ * common path rather than a rare one. The range check is not ceremony: the+ * property is typed `number` but reached through an `unknown` cast, and+ * emitting `httpStatus=0` for a value that never was a status would hand the+ * renderer a verdict the transport never made.+ */+function vettedHttpStatus(status: unknown): number | undefined {+ if (typeof status !== 'number' || !Number.isInteger(status)) return undefined+ return status >= 100 && status <= 599 ? status : undefined+}+/*** Read a `Retry-After` header value as a delay in seconds.*diff --git a/desktop-app/test/gfsUriHandler.test.ts b/desktop-app/test/gfsUriHandler.test.tsindex e8a6a18ca..bb656b9f5 100644--- a/desktop-app/test/gfsUriHandler.test.ts+++ b/desktop-app/test/gfsUriHandler.test.ts@@ -316,7 +316,7 @@ describe('GfsClient.grant', () => {).rejects.toThrow(/subjects_invalid invalidIndexes=\[0,2\]/)})- it('leaves the original error untouched when the body carries no structured fields', async () => {+ it('keeps the server verdict and the original error when the body carries no structured fields', async () => {const original = new ApiError('403 Forbidden: escalation_rejected',403,@@ -325,12 +325,24 @@ describe('GfsClient.grant', () => {const requestJson = vi.fn(async () => {throw original}) as GfsTransport['requestJson']- await expect(- new GfsClient(transport({ requestJson })).grant(+ // The transport's status now always travels as a vetted marker, so the+ // wrapper is the norm rather than the exception. What must not change is+ // that nothing is swallowed: the server's own words reach the renderer+ // verbatim, and the untouched `ApiError` stays reachable as `cause`.+ const rejection = await new GfsClient(transport({ requestJson }))+ .grant({ resourceId: RID, subjects: [{ type: 'user', id: 'u2' }], permissions: ['read'] },'tok')- ).rejects.toBe(original)+ .then(+ () => {+ throw new Error('grant resolved; expected the transport rejection to propagate')+ },+ (error: unknown) => error as Error+ )+ expect(requestJson).toHaveBeenCalledTimes(1)+ expect(rejection.message).toBe('403 Forbidden: escalation_rejected httpStatus=403')+ expect((rejection as { cause?: unknown }).cause).toBe(original)})})@@ -684,21 +696,25 @@ describe('GfsClient read paths surface retryAfterSeconds across IPC', () => {await expect(client.affordances(RID, 'tok')).rejects.toThrow(/retryAfterSeconds=7/)})- it('leaves a non-rate-limited read rejection untouched', async () => {+ it('gives a non-rate-limited read rejection its status and nothing else', async () => {const t = transport({requestJson: vi.fn(async () => {throw new ApiError('403 Forbidden: denied', 403, '{"error":"forbidden"}')}) as GfsTransport['requestJson'],})- // Fail loud: an error with nothing structured to surface propagates verbatim,- // it is never rewritten or swallowed.+ // Fail loud: the server's words are never rewritten or swallowed. The only+ // addition is the vetted status marker, and specifically NOT a retry+ // window — a 403 that arrived with one would tell the renderer to pause the+ // read plane over a permission failure that pausing cannot fix.//// 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+ // express the exactness its name promises, and survived deleting the// feature it guards.- await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(/^403 Forbidden: denied$/)+ await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(+ /^403 Forbidden: denied httpStatus=403$/+ )expect(t.requestJson).toHaveBeenCalledTimes(1)})@@ -740,18 +756,21 @@ describe('GfsClient read paths surface retryAfterSeconds across IPC', () => {})// Anchored: the vetted value is the LAST thing in the message, and the- // counterfeit one is gone rather than merely outranked.+ // counterfeit one is gone rather than merely outranked. The status marker+ // sits in front of it, never behind — appending anything after the window+ // would take away the trailing anchor the renderer authenticates it by.await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(- /^429 Too Many Requests: slow down retryAfterSeconds=7$/+ /^429 Too Many Requests: slow down httpStatus=429 retryAfterSeconds=7$/)expect(t.requestJson).toHaveBeenCalledTimes(1)})it('strips a counterfeit retry window even when it has nothing vetted to append', async () => {- // The stripping path must not depend on there being a replacement. With no- // parseable body and no `Retry-After`, this error would otherwise propagate- // verbatim — carrying a window the authoritative parser never accepted,- // which the renderer's trailing anchor would then read as ours.+ // The stripping path must not depend on there being a replacement window.+ // With no parseable body and no `Retry-After`, the counterfeit one is+ // removed and nothing takes its place — the renderer is told it was rate+ // limited and not when to retry, rather than being handed a number the+ // authoritative parser never accepted.const t = transport({requestJson: vi.fn(async () => {throw new ApiError(@@ -763,7 +782,7 @@ describe('GfsClient read paths surface retryAfterSeconds across IPC', () => {})await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(- /^429 Too Many Requests: slow down$/+ /^429 Too Many Requests: slow down httpStatus=429$/)// Witness: the rejection still reaches the caller and the read really ran,// so the absent token is the strip doing its job, not the call being skipped.@@ -786,7 +805,7 @@ describe('GfsClient read paths surface retryAfterSeconds across IPC', () => {})await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(- /^429 Too Many Requests: Too Many Requests$/+ /^429 Too Many Requests: Too Many Requests httpStatus=429$/)expect(t.requestJson).toHaveBeenCalledTimes(1)})diff --git a/desktop-app/ui/src/components/GfsImagePreview/index.tsx b/desktop-app/ui/src/components/GfsImagePreview/index.tsxindex c7e92e858..32074c14a 100644--- a/desktop-app/ui/src/components/GfsImagePreview/index.tsx+++ b/desktop-app/ui/src/components/GfsImagePreview/index.tsx@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom'import { Button, StatusBanner } from '@components/Common'import { IconClose, IconCopy } from '@components/SidebarNav/icons'import { useWorkspaceModalStyle } from '@hooks/useWorkspaceModalStyle'+import { describeGfsReadError } from '@lib/gfsGrantErrors'import { assertGfsImagePreviewSize } from '@lib/gfsImagePreview'import type { GfsImagePreviewProps } from './types'@@ -55,7 +56,18 @@ export function GfsImagePreview({} catch (error) {if (!active) returnonDownloadErrorRef.current?.(error)- setPreviewError(error instanceof Error ? error.message : 'Could not load the image preview')+ // Through the shared read-plane presenter, not raw. `download` crosses+ // Electron IPC, so a rejection arrives as+ // "Error invoking remote method 'gfs:download': Error: 429 …" — our own+ // process boundary plus a bare status line, put in front of the user in+ // a banner. The presenter strips the wrapper and gives a rate limit the+ // same words the Files page uses; the size guards above keep theirs,+ // because it passes every other verdict through untouched.+ setPreviewError(+ error instanceof Error+ ? describeGfsReadError(error).message+ : 'Could not load the image preview'+ )}}diff --git a/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx b/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsxindex 9c4ad8c75..2be7a3427 100644--- a/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx+++ b/desktop-app/ui/src/components/GfsMarkdownPreview/index.tsx@@ -4,6 +4,7 @@ import { createPortal } from 'react-dom'import { Button, StatusBanner } from '@components/Common'import { IconClose, IconCopy } from '@components/SidebarNav/icons'import { useWorkspaceModalStyle } from '@hooks/useWorkspaceModalStyle'+import { describeGfsReadError } from '@lib/gfsGrantErrors'import { assertGfsMarkdownPreviewSize } from '@lib/gfsMarkdownPreview'import { parseVanillaMarkdown } from '@lib/vanillaMarkdown'import type { MarkdownBlock, MarkdownInlineNode } from '@lib/vanillaMarkdown.types'@@ -114,8 +115,14 @@ export function GfsMarkdownPreview({} catch (error) {if (!active) returnonDownloadErrorRef.current?.(error)+ // Same contract as the image and video previews: the IPC wrapper and+ // the bare status line are ours, not the user's, and a 429 gets the+ // shared read-plane words. Every other verdict passes through+ // untouched, including the size guard above.setPreviewError(- error instanceof Error ? error.message : 'Could not load the Markdown preview'+ error instanceof Error+ ? describeGfsReadError(error).message+ : 'Could not load the Markdown preview')}}diff --git a/desktop-app/ui/src/components/GfsVideoPreview/index.tsx b/desktop-app/ui/src/components/GfsVideoPreview/index.tsxindex 51cd9fe86..d87f07c01 100644--- a/desktop-app/ui/src/components/GfsVideoPreview/index.tsx+++ b/desktop-app/ui/src/components/GfsVideoPreview/index.tsx@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom'import { Button, StatusBanner } from '@components/Common'import { IconClose } from '@components/SidebarNav/icons'import { useWorkspaceModalStyle } from '@hooks/useWorkspaceModalStyle'+import { describeGfsReadError } from '@lib/gfsGrantErrors'import { assertGfsVideoPreviewSize } from '@lib/gfsVideoPreview'import type { GfsVideoPreviewProps } from './types'@@ -49,7 +50,14 @@ export function GfsVideoPreview({} catch (error) {if (!active) returnonDownloadErrorRef.current?.(error)- setPreviewError(error instanceof Error ? error.message : 'Could not load the video preview')+ // Same contract as the image preview: the IPC wrapper and the bare+ // status line are ours, not the user's, and a 429 gets the shared+ // read-plane words. Every other verdict passes through untouched.+ setPreviewError(+ error instanceof Error+ ? describeGfsReadError(error).message+ : 'Could not load the video preview'+ )}}diff --git a/desktop-app/ui/src/components/__tests__/gfsPreviewReadErrors.test.tsx b/desktop-app/ui/src/components/__tests__/gfsPreviewReadErrors.test.tsxnew file mode 100644index 000000000..0a9ebd3da--- /dev/null+++ b/desktop-app/ui/src/components/__tests__/gfsPreviewReadErrors.test.tsx@@ -0,0 +1,133 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { GfsImagePreview } from '../GfsImagePreview'+import { GfsMarkdownPreview } from '../GfsMarkdownPreview'+import { GfsVideoPreview } from '../GfsVideoPreview'++/**+ * The three previews all read bytes through `window.clerum.gfs.download`, which+ * crosses Electron IPC, and all three put whatever comes back into a+ * `StatusBanner`. Raw, that banner reads+ * "Error invoking remote method 'gfs:download': Error: 429 Too Many Requests"+ * — our own main/renderer split plus a bare status line, in front of a user who+ * opened a file. The Files page stopped saying that; these had not.+ *+ * One file for the three because the contract is one function. A preview that+ * stops routing through it fails here regardless of which one it is.+ */++const RATE_LIMITED_DOWNLOAD =+ "Error invoking remote method 'gfs:download': Error: 429 Too Many Requests: " ++ 'Too Many Requests httpStatus=429 retryAfterSeconds=7'++const PREVIEWS = [+ [+ 'image',+ () => (+ <GfsImagePreview+ byteLength={3}+ fileName="diagram.png"+ gfsUri="gfs://main/image-1"+ mimeType="image/png"+ onClose={vi.fn()}+ />+ ),+ ],+ [+ 'video',+ () => (+ <GfsVideoPreview+ byteLength={3}+ fileName="clip.mp4"+ gfsUri="gfs://main/video-1"+ mimeType="video/mp4"+ onClose={vi.fn()}+ />+ ),+ ],+ [+ 'markdown',+ () => (+ <GfsMarkdownPreview+ byteLength={3}+ fileName="notes.md"+ gfsUri="gfs://main/markdown-1"+ onClose={vi.fn()}+ />+ ),+ ],+] as const++describe('GFS preview read failures', () => {+ let download: ReturnType<typeof vi.fn>++ beforeEach(() => {+ download = vi.fn(async () => {+ throw new Error(RATE_LIMITED_DOWNLOAD)+ })+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { gfs: { download } },+ })+ Object.defineProperty(URL, 'createObjectURL', {+ configurable: true,+ value: vi.fn(() => 'blob:gfs-preview'),+ })+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}++ disconnect() {}+ }+ )+ })++ afterEach(() => {+ cleanup()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ })++ it.each(PREVIEWS)(+ 'presents a rate-limited %s download in the shared read-plane words',+ async (_label, renderPreview) => {+ render(renderPreview())++ // Liveness witness: the read really ran and really rejected, so the+ // absence of the IPC wrapper below is a presented verdict and not a+ // preview that never attempted the download.+ await waitFor(() => expect(download).toHaveBeenCalledTimes(1))+ await waitFor(() =>+ expect(screen.getByText('Too many file requests — try again in 7s.')).toBeTruthy()+ )+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()+ }+ )++ it.each(PREVIEWS)(+ 'keeps a non-rate-limited %s verdict, minus the IPC wrapper',+ async (_label, renderPreview) => {+ download.mockImplementation(async () => {+ throw new Error(+ "Error invoking remote method 'gfs:download': Error: 403 Forbidden: " ++ 'read access was revoked httpStatus=403'+ )+ })++ render(renderPreview())++ await waitFor(() => expect(download).toHaveBeenCalledTimes(1))+ // The server's own verdict survives — fail loud, never swallowed — while+ // the wrapper naming our process boundary does not. Without this case the+ // assertions above would also pass on a presenter that answered+ // "Too many file requests" to everything.+ await waitFor(() =>+ expect(screen.getByText(/403 Forbidden: read access was revoked/)).toBeTruthy()+ )+ expect(screen.queryByText(/Error invoking remote method/)).toBeNull()+ }+ )+})diff --git a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsxindex 0496156bc..be07839cb 100644--- a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx+++ b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx@@ -62,6 +62,10 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFiles// `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.+ // Scoped to the root for the same reason the failure card is: the discovery+ // verdict describes the root listing and stays set while the user browses+ // into a folder, where an empty result really does mean an empty folder.+ const rootListingUnsupported = !ctrl.current && ctrl.discoveryFailure?.kind === 'unsupported'const blockingFailure = useMemo<{failure: GfsDiscoveryFailureretry: () => void@@ -252,12 +256,27 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFiles) : null}</div>) : (+ // `unsupported` is excluded from the failure card above because no+ // Retry can conjure an endpoint the server does not have — but that+ // left this state to say "No shared files yet", which reports the+ // absence of an answer as an answer. The picker is where it costs+ // most: a user told they have nothing to attach stops looking,+ // while the files may be there and only the listing is missing.+ // Same copy as the Files page, because it is the same fact.<EmptyState- title={ctrl.current ? 'This folder is empty' : 'No shared files yet'}+ title={+ rootListingUnsupported+ ? 'Files cannot be listed here'+ : ctrl.current+ ? 'This folder is empty'+ : 'No shared files yet'+ }body={- ctrl.current- ? 'Choose another folder to continue browsing.'- : 'Files shared with you through the Global File System 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.'+ : ctrl.current+ ? 'Choose another folder to continue browsing.'+ : 'Files shared with you through the Global File System will appear here.'}/>)}diff --git a/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsxindex 4b52540b3..d14416164 100644--- a/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsx@@ -225,6 +225,40 @@ describe('ComposerGlobalFilesModal', () => {// was pressed.expect(screen.queryByRole('button', { name: /retry file listing/i })).toBeNull()expect(screen.queryByText('Too many file requests')).toBeNull()+ // Excluding the failure card left the empty state to speak, and it claimed+ // the library was empty — an answer the server explicitly could not give.+ // A user told they have nothing to attach stops looking.+ expect(screen.getByText('Files cannot be listed here')).toBeTruthy()+ expect(screen.queryByText('No shared files yet')).toBeNull()+ })++ it('still reports an empty FOLDER as empty while discovery is unsupported', () => {+ // The unsupported verdict describes the ROOT listing and stays set while+ // the user browses. Inside a folder the server did answer — with nothing —+ // so "cannot be listed" would be the false statement here.+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ current: {+ resourceId: 'folder-a',+ gfsUri: 'gfs://main/folder-a',+ name: 'Marketing',+ kind: 'directory',+ },+ crumbs: [{ resourceId: 'folder-a', name: 'Marketing' }],+ discoveryFailure: {+ kind: 'unsupported',+ message: '404 Not Found: Not Found',+ retryAvailableAt: null,+ },+ })++ renderModal()++ // Witness: the modal really is inside that folder, so the copy below is the+ // folder branch and not a root render that never saw `current`.+ expect(screen.getByText('Marketing')).toBeTruthy()+ expect(screen.getByText('This folder is empty')).toBeTruthy()+ expect(screen.queryByText('Files cannot be listed here')).toBeNull()})it('reports an empty library only when discovery actually answered', () => {diff --git a/desktop-app/ui/src/gfs/__tests__/moveDialog.test.tsx b/desktop-app/ui/src/gfs/__tests__/moveDialog.test.tsxindex 34cc89986..93a085abc 100644--- a/desktop-app/ui/src/gfs/__tests__/moveDialog.test.tsx+++ b/desktop-app/ui/src/gfs/__tests__/moveDialog.test.tsx@@ -196,6 +196,33 @@ describe('GfsMoveDialog pagination', () => {expect(await within(dialog).findByText('No folders here.')).toBeTruthy()expect(within(dialog).queryByRole('button', { name: 'Load more' })).toBeNull()})++ it('presents a refused destination listing instead of reporting no folders', async () => {+ // Two separate claims the dialog used to make about a 429: the banner read+ // "Error invoking remote method 'gfs:listAccessible'" — our own process+ // boundary — and the tree said there were no folders, which the refused+ // request never established.+ const listAccessible = vi.fn(async () => {+ throw new Error(+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " ++ 'Too Many Requests httpStatus=429 retryAfterSeconds=7'+ )+ })++ renderDialog({ listAccessible })++ const dialog = await screen.findByRole('dialog', { name: 'Move file notes.txt' })+ // Liveness witness: the listing really ran and really rejected, so the+ // absence of "No folders here." is a presented refusal and not a dialog+ // that never asked.+ expect(listAccessible).toHaveBeenCalled()+ expect(+ await within(dialog).findByText('Too many file requests — try again in 7s.')+ ).toBeTruthy()+ expect(within(dialog).queryByText(/Error invoking remote method/)).toBeNull()+ expect(within(dialog).queryByText('No folders here.')).toBeNull()+ expect(within(dialog).getByText('Destinations could not be listed.')).toBeTruthy()+ })})describe('GfsMoveDialog no-op destination guard', () => {diff --git a/desktop-app/ui/src/gfs/moveDialog.tsx b/desktop-app/ui/src/gfs/moveDialog.tsxindex b774e73e7..c09e425e6 100644--- a/desktop-app/ui/src/gfs/moveDialog.tsx+++ b/desktop-app/ui/src/gfs/moveDialog.tsx@@ -5,13 +5,22 @@ import { IconCheck, IconChevronRight, IconClose, IconContexts } from '@componentimport { GFS_DRIVE_MAIN } from '@constants/gfsBrowser'import { desktopQueryKeys } from '@hooks/domain/queryKeys'import type { GfsBrowserChild } from '@hooks/domain/useGfsBrowserController'+import { describeGfsReadError } from '@lib/gfsGrantErrors'import type { GfsMoveDialogProps } from './moveDialog.types'type SelectedDestination = Pick<GfsBrowserChild, 'resourceId' | 'name'>+/**+ * Both banners in this dialog show server verdicts that crossed Electron IPC,+ * so the raw message opens with `Error invoking remote method 'gfs:…'` — our+ * own process boundary — and renders a 429 as a bare status line. The shared+ * read-plane presenter strips the wrapper and gives a rate limit the same+ * words every other GFS surface uses; everything else passes through, so the+ * server's verdict is never swallowed.+ */function errorMessage(error: unknown): string | null {if (!error) return null- return error instanceof Error ? error.message : String(error)+ return describeGfsReadError(error).message}function folderItems(items: GfsBrowserChild[], excludedIds: ReadonlySet<string>) {@@ -356,7 +365,14 @@ export function GfsMoveDialog({Loading folders…</p>) : rootFolders.length === 0 && !accessibleQuery.hasNextPage ? (- <p className="muted">No folders here.</p>+ // A refused listing is not an absence of folders. The banner+ // above already states the failure, so this only has to stop+ // contradicting it — asserting "no folders" next to an error the+ // user is reading is how a 429 ends up looking like an empty+ // library.+ <p className="muted">+ {listError ? 'Destinations could not be listed.' : 'No folders here.'}+ </p>) : (<div className="da-gfs-move-dialog__tree-root">{rootFolders.map(folder => (diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsxindex 989612c7f..88834f9e6 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx@@ -98,6 +98,7 @@ function Probe() {<div data-testid="authority-pending">{ctrl.authorityPending ? 'pending' : 'ready'}</div><div data-testid="accessible-count">{ctrl.accessibleResources.length}</div><div data-testid="items-count">{ctrl.items.length}</div>+ <div data-testid="children-error">{ctrl.error ?? 'none'}</div><div data-testid="accessible-error">{ctrl.accessibleError ?? 'none'}</div><div data-testid="accessible-notice">{ctrl.accessibleNotice ?? 'none'}</div><div data-testid="discovery-failure-kind">{ctrl.discoveryFailure?.kind ?? 'none'}</div>@@ -1373,6 +1374,156 @@ describe('useGfsBrowserController', () => {expect(listAccessible).toHaveBeenCalledTimes(3)})+ it('reveals a folder listing that landed while discovery was still refused', async () => {+ // The authority window exists to keep PREFETCHED or 30-minute-cached state+ // from rendering before the session is re-proved. A children page fetched+ // after this mount's epoch is neither — it is a fresh authorized read —+ // and withholding it made the page state "This folder is empty", the one+ // thing the successful listing disproves. Reachable without a deep link:+ // discovery is refused with a 429, the root menu is still mounted, and+ // Open GFS link on a folder resolves and lists it.+ const child = {+ resourceId: 'child-1',+ rid: 'rid-child-1',+ gfsUri: 'gfs://main/child-1',+ drive: 'main',+ parentResourceId: 'root',+ name: 'report.md',+ kind: 'file' as const,+ path: '/report.md',+ version: 1,+ bytes: 10,+ }+ const listChildren = vi.fn(async () => ({ items: [child], nextCursor: null }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible: vi.fn(async () => {+ throw new Error(+ "Error invoking remote method 'gfs:listAccessible': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=7'+ )+ }),+ resolve: vi.fn(async () => ({+ resourceId: 'root',+ gfsUri: 'gfs://main/root',+ name: 'Root',+ kind: 'directory',+ })),+ listChildren,+ 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()+ })+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))+ // Liveness witness: the children read really happened and really answered+ // with a row. Without it the row assertion below would pass just as well on+ // a listing that never ran.+ await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(1))++ // The gate is still shut — this is not a test of discovery recovering.+ expect(screen.getByTestId('authority-pending').textContent).toBe('pending')+ // And the three states the page reads to decide what to render. Rows, no+ // error, no load in flight: the empty-folder copy must have no input left+ // that would justify it.+ expect(screen.getByTestId('items-count').textContent).toBe('1')+ expect(screen.getByTestId('children-error').textContent).toBe('none')+ expect(screen.getByTestId('loading').textContent).toBe('idle')+ // Discovery's own surface stays withheld: the fresh evidence is the folder+ // listing, and it says nothing about what the session may see at the root.+ expect(screen.getByTestId('accessible-count').textContent).toBe('0')+ })++ it("suppresses the window-focus folder refetch until the folder's own window expires", async () => {+ // `listAccessible` and `listChildren` are refused by ONE server budget, so+ // a folder 429 has to arm the same pause a discovery 429 does. Arming only+ // from discovery left this open: the card says Evenfire will wait out the+ // server's window while every window focus spent another request against+ // it, each refusal re-dating the countdown the user is watching.+ const listChildren = vi.fn(async () => {+ throw new Error(+ "Error invoking remote method 'gfs:listChildren': Error: 429 Too Many Requests: " ++ 'Too Many Requests retryAfterSeconds=7'+ )+ })+ const listAccessible = vi.fn(async () => ({ items: [], nextCursor: null }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ gfs: {+ listAccessible,+ resolve: vi.fn(async () => ({+ resourceId: 'root',+ gfsUri: 'gfs://main/root',+ name: 'Root',+ kind: 'directory',+ })),+ listChildren,+ affordances: vi.fn(async () => ({+ held: ['read'],+ canDelegate: false,+ grantableBits: [],+ canCreateShare: false,+ })),+ },+ },+ })++ render(<Probe />, { wrapper: Harness })+ await act(async () => {+ screen.getByRole('button', { name: 'open' }).click()+ })+ await waitFor(() => expect(screen.getByTestId('current').textContent).toBe('root'))+ await waitFor(() => expect(listChildren).toHaveBeenCalledTimes(1))+ // Liveness witness: the folder listing really carries the budget verdict.+ // Discovery succeeded here, which is the whole point — the pause may not+ // depend on discovery being the one that failed.+ await waitFor(() => expect(screen.getByTestId('children-error').textContent).toContain('429'))+ expect(screen.getByTestId('discovery-failure-kind').textContent).toBe('none')++ vi.useFakeTimers({ toFake: ['Date'] })+ const pausedAt = Date.now()++ await act(async () => {+ focusManager.setFocused(false)+ focusManager.setFocused(true)+ })+ await act(async () => {+ await new Promise(resolve => globalThis.setTimeout(resolve, 0))+ })+ expect(listChildren).toHaveBeenCalledTimes(1)+ // The shared budget means discovery waits too, even though its own last+ // answer was a success.+ expect(listAccessible).toHaveBeenCalledTimes(1)++ // Past the window both resume, which is what keeps the two assertions+ // above a suppression rather than a controller that stopped refetching.+ vi.setSystemTime(pausedAt + 8_000)+ await act(async () => {+ focusManager.setFocused(false)+ focusManager.setFocused(true)+ })+ await act(async () => {+ await new Promise(resolve => globalThis.setTimeout(resolve, 0))+ })+ expect(listChildren).toHaveBeenCalledTimes(2)+ })+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 waitdiff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.tsindex 193a281ee..654a0034a 100644--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts@@ -8,7 +8,12 @@ import {useQueryClient,} from '@tanstack/react-query'import { GFS_BREADCRUMB_MAX_DEPTH } from '@constants/gfsBrowser'-import { describeGfsReadError, isRateLimited, parseRetryAfterSeconds } from '@lib/gfsGrantErrors'+import {+ describeGfsReadError,+ isRateLimited,+ parseHttpStatus,+ parseRetryAfterSeconds,+} from '@lib/gfsGrantErrors'import type { GfsGrantListItem, GfsShareListItem } from '@/gfs/delegation.types'import { desktopQueryKeys } from './queryKeys'@@ -210,8 +215,19 @@ export interface GfsDiscoveryFailure {* Every shape the wire produces delimits the status the same way* (`404 Not Found: <body>`, and through IPC `…: Error: 404 Not Found: …`), so* requiring the delimiter loses no real detection.+ *+ * The vetted status outranks both patterns when the main process supplied one.+ * `unsupported` is the verdict with no way back, and prose is a poor thing to+ * reach it on: a 500 whose body quotes `404 Not Found` from an upstream hop is+ * a server that is failing, not one that lacks the endpoint. `ApiError.status`+ * says which, and it arrives here as `httpStatus=…`.*/function classifyDiscoveryFailure(message: string): GfsDiscoveryFailureKind {+ const status = parseHttpStatus(message)+ if (status !== null) {+ if (status === 404) return 'unsupported'+ return isRateLimited(message) ? 'rate-limited' : 'failed'+ }if (/(?:^|[\s:])404 Not Found(?=[\s:]|$)/.test(message)) return 'unsupported'// 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@@ -616,11 +632,25 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {// Cached GFS state is a rendering optimization only (R4 spec §1): while the// authority revalidation window is open, nothing cached may be exposed —- // rows, affordances, grants, and shares all stay withheld until discovery+ // affordances, grants, and shares all stay withheld until discovery// re-proves the session (or an authority failure clears everything).+ //+ // Children are the one surface that clears the gate on its own evidence. The+ // window exists to keep PREFETCHED or 30-minute-cached state from rendering+ // before the session is re-proved, and a page fetched after this mount's+ // epoch is neither: it is a fresh server read the current principal was+ // authorized for. Withholding it renders "This folder is empty", which is+ // the one thing that successful listing disproves — the same false statement+ // this controller stopped making about a refused discovery. Row affordances+ // stay behind `authorityPending` regardless, so the rows arrive without+ // per-row actions until discovery lands.+ const childrenFetchedThisEpoch = childrenQuery.dataUpdatedAt >= authorityEpochRef.currentconst items = useMemo<GfsBrowserChild[]>(- () => (authorityPending ? [] : (childrenQuery.data?.pages ?? []).flatMap(page => page.items)),- [authorityPending, childrenQuery.data]+ () =>+ authorityPending && !childrenFetchedThisEpoch+ ? []+ : (childrenQuery.data?.pages ?? []).flatMap(page => page.items),+ [authorityPending, childrenFetchedThisEpoch, childrenQuery.data])/*** Children listings deliberately contain no permission bits. Resolve the@@ -731,6 +761,8 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {// 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 childrenErrorMessage = childrenQuery.error ? toMessage(childrenQuery.error) : null+ const childrenErrorUpdatedAt = childrenQuery.error ? childrenQuery.errorUpdatedAt : 0const discoveryFailure = useMemo<GfsDiscoveryFailure | null>(() => {if (!accessibleErrorMessage) return nullconst kind = classifyDiscoveryFailure(accessibleErrorMessage)@@ -744,27 +776,49 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {: null,}}, [accessibleErrorMessage, accessibleErrorUpdatedAt])+ // The folder plane's own rate-limit deadline. `listAccessible` and+ // `listChildren` are refused by ONE server budget, so a 429 on either means+ // the next focus-driven refetch of either spends a request the server just+ // turned down. Derived here rather than inside the effect below because the+ // timestamp is what separates two consecutive refusals carrying the same+ // message — without it the second one never recomputes.+ const childrenRateLimitedUntil = useMemo<number | null>(() => {+ if (!childrenErrorMessage || !isRateLimited(childrenErrorMessage)) return null+ const retryAfterSeconds = parseRetryAfterSeconds(childrenErrorMessage)+ return retryAfterSeconds !== null+ ? childrenErrorUpdatedAt + retryAfterSeconds * 1000+ : Date.now() + UNKNOWN_RATE_LIMIT_PAUSE_MS+ }, [childrenErrorMessage, childrenErrorUpdatedAt])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.retryAvailableAt ?? Date.now() + UNKNOWN_RATE_LIMIT_PAUSE_MS- }, [discoveryFailure])+ const discoveryUntil =+ discoveryFailure?.kind === 'rate-limited'+ ? (discoveryFailure.retryAvailableAt ?? Date.now() + UNKNOWN_RATE_LIMIT_PAUSE_MS)+ : 0+ // The later of the two deadlines, never whichever one settled last. A+ // discovery refetch that succeeds does not buy back the budget a refused+ // folder listing is still waiting on, and arming from discovery alone left+ // a folder 429 free to be re-spent on the very next window focus.+ pausedUntilRef.current = Math.max(discoveryUntil, childrenRateLimitedUntil ?? 0)+ }, [childrenRateLimitedUntil, 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// countdown in the UI is what keeps them from spending the request early.+ // It drops back to the folder plane's deadline rather than to zero — the+ // user asked for discovery, not for the next window focus to re-spend a+ // folder listing the same budget is still refusing.const retryDiscovery = useCallback(async () => {- pausedUntilRef.current = 0+ pausedUntilRef.current = childrenRateLimitedUntil ?? 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.+ }, [accessibleQuery, childrenRateLimitedUntil])+ // The same contract for the children query. Nothing to clear here: `refetch`+ // is not gated by the focus predicate, and the pause is shared with+ // discovery — clearing it on a folder retry would hand the next window focus+ // a discovery request the server is still refusing. A folder listing is NOT+ // fetched only on request, though: `refetchOnMount: 'always'` and the window+ // focus bridge both reach it, which is why the pause above now covers it.const retryChildren = useCallback(async () => {await childrenQuery.refetch()}, [childrenQuery])@@ -1018,11 +1072,11 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {(canListAccessibleResources &&accessibleQuery.isFetching &&accessibleResources.length === 0)),- error: childrenQuery.error ? toMessage(childrenQuery.error) : null,+ error: childrenErrorMessage,// 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,+ errorUpdatedAt: childrenErrorUpdatedAt,accessibleError: accessibleNotice ? null : accessibleErrorMessage,accessibleNotice,discoveryFailure,diff --git a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.tsindex 258e2e5f1..df80b57e5 100644--- a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts+++ b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts@@ -3,6 +3,7 @@ import {describeGfsGrantError,describeGfsReadError,isRateLimited,+ parseHttpStatus,parseRetryAfterSeconds,} from '../gfsGrantErrors'@@ -137,6 +138,49 @@ describe('describeGfsGrantError', () => {expect(describeGfsReadError(new Error(raw)).code).toBe('rate_limited')})+ it('believes the vetted status over a 429 the response body merely mentions', () => {+ // The case no regex over the message can decide. `httpClient` composes+ // `${status} ${statusText}: ${body}`, so by the time the text exists both+ // numbers are three delimited digits and the real status is gone. The user+ // was told to wait out a rate-limit window that nobody had opened, on a+ // server that was simply failing.+ const raw =+ "Error invoking remote method 'gfs:listChildren': Error: " ++ '500 Internal Server Error: upstream 429 from the pool httpStatus=500'++ expect(describeGfsReadError(new Error(raw)).code).toBeNull()+ // Witness: the classifier ran on this exact message and still answers+ // `rate_limited` when the vetted status is the one that says so. Without+ // it, an `isRateLimited` that returned `false` unconditionally would leave+ // the assertion above green.+ expect(+ describeGfsReadError(+ new Error(raw.replace('httpStatus=500', 'httpStatus=429')) // same text, real 429+ ).code+ ).toBe('rate_limited')+ })++ it('ignores an httpStatus the server body wrote itself', () => {+ // The marker is only worth reading because the main process writes it and+ // strips every copy the body carried. This is what the renderer must do+ // with one that reached it anyway: the token is trusted at the suffix+ // position and nowhere else, so a body quoting it changes no verdict.+ expect(parseHttpStatus('500 Internal Server Error: httpStatus=429 said the proxy')).toBeNull()+ // Witness: the same token IS read at the position the main process writes+ // it, so the null above is a rejected position rather than a dead parser.+ expect(parseHttpStatus('500 Internal Server Error: upstream said so httpStatus=429')).toBe(429)+ expect(parseHttpStatus('429 Too Many Requests httpStatus=429 retryAfterSeconds=7')).toBe(429)+ })++ it('does not read the server saying NOT rate limited as saying it is', () => {+ // `rate_limited` was matched as a bare substring, and `not_rate_limited` is+ // the server's own negation of the very code being looked for.+ expect(isRateLimited('503 Service Unavailable: reason=not_rate_limited')).toBe(false)+ // Witness: the code is still recognised as a code, so the false above is a+ // rejected embedding and not a matcher that stopped firing.+ expect(isRateLimited('503 Service Unavailable: reason=rate_limited')).toBe(true)+ })+it('passes unknown errors through verbatim — fail loud, never swallow', () => {expect(describeGfsGrantError(new Error('total surprise'))).toEqual({code: null,diff --git a/desktop-app/ui/src/lib/gfsGrantErrors.ts b/desktop-app/ui/src/lib/gfsGrantErrors.tsindex 56078fcfd..f113b10bc 100644--- a/desktop-app/ui/src/lib/gfsGrantErrors.ts+++ b/desktop-app/ui/src/lib/gfsGrantErrors.ts@@ -112,22 +112,57 @@ export function parseRetryAfterSeconds(message: string): number | null {}/**- * A 429 is recognised as a STATUS TOKEN, not as three digits anywhere.+ * The HTTP status the main process vetted, or `null` when nothing vetted one.*- * `\b` treats `-` and `/` as boundaries, so it matched `429` inside a path or- * a name — and `httpClient` copies the RAW response body into the message- * whenever the JSON carries no top-level `error`/`message` key, so such text- * genuinely reaches here. A non-429 failure whose body mentioned, say, an edge- * pool called `edge-429-pool` was presented as "Too many file requests" and- * armed a focus pause on a listing that was never rate limited.+ * `surfaceGfsGrantError` appends `httpStatus=<code>` from `ApiError.status` —+ * the transport's own verdict — and strips any copy the server's text carried,+ * exactly as it does for the retry window. The position is what makes the+ * token trustworthy here: it sits at the very end of the message, or directly+ * before the `retryAfterSeconds=` suffix, and the lookahead admits nothing+ * else. A counterfeit inside the response body lands ahead of that position+ * and `String.match` without `/g` would otherwise return it first.*- * Every shape the wire actually produces delimits the status with whitespace- * or a colon — `429 Too Many Requests`, `gfs download failed: 429:` — so- * requiring that delimiter on both sides loses no real detection. Erring the- * other way is the costly one: a missed 429 is the original incident.+ * A message with no marker is one that never crossed that boundary — an error+ * raised in the renderer, or a transport failure with no response at all. The+ * status is then unknown, not 200, and the caller says so rather than assuming.+ */+export function parseHttpStatus(message: string): number | null {+ const match = message.match(/(?:^|\s)httpStatus=(\d{3})(?=(?: retryAfterSeconds=\d+)?$)/)+ if (!match?.[1]) return null+ const status = Number.parseInt(match[1], 10)+ return status >= 100 && status <= 599 ? status : null+}++/**+ * The rate-limit verdict: the vetted status when there is one, the message text+ * only when there is not.+ *+ * A status flattened into prose cannot be recovered from prose. `httpClient`+ * composes `${status} ${statusText}: ${body}`, so a 500 whose body reads+ * `upstream 429 from the pool` produces a message in which both numbers are+ * three digits delimited by whitespace — no regex can tell which one the+ * server answered with, because the distinction was destroyed before the+ * string existed. Reading `httpStatus=` first restores it: a 500 is a 500 even+ * when its body talks about a 429 somewhere upstream, and the user stops being+ * told to wait out a window nobody opened.+ *+ * The textual path below still runs for messages with no marker, and stays+ * anchored for the same reason it was: `\b` treats `-` and `/` as boundaries,+ * so `edge-429-pool` in a body matched, while every real shape delimits the+ * status with whitespace or a colon (`429 Too Many Requests`,+ * `gfs download failed: 429:`). `rate_limited` is anchored to a token boundary+ * too — as a bare substring it also matched `not_rate_limited`, which is the+ * server saying the opposite. A missed 429 is the original incident, so the+ * text is still read when nothing better exists; it is no longer read when+ * something better does.*/export function isRateLimited(message: string): boolean {- return /(?:^|[\s:])429(?=[\s:]|$)/.test(message) || message.includes('rate_limited')+ const status = parseHttpStatus(message)+ if (status !== null) return status === 429+ return (+ /(?:^|[\s:])429(?=[\s:]|$)/.test(message) ||+ /(?:^|[^A-Za-z0-9_])rate_limited(?![A-Za-z0-9_])/.test(message)+ )}function describeRateLimited(raw: string, subject: string): GfsGrantErrorPresentation {