Skip to content

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

TypeScript

fix(desktop): honour only the trailing retry window the main process vetted

Alfredo Lopez593772ebe97c
diff --git a/desktop-app/src/gfs/uriHandler.ts b/desktop-app/src/gfs/uriHandler.ts
index 3098c65f2..c85a32faa 100644
--- a/desktop-app/src/gfs/uriHandler.ts
+++ b/desktop-app/src/gfs/uriHandler.ts
@@ -790,8 +790,9 @@ 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.
*
- * When there is nothing structured to surface, the ORIGINAL error propagates
- * unchanged (fail loud; never swallow the server's verdict).
+ * 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
@@ -803,9 +804,44 @@ function surfaceGfsGrantError(error: unknown): unknown {
const parts: string[] = []
if (fields.invalidIndexes) parts.push(`invalidIndexes=[${fields.invalidIndexes.join(',')}]`)
if (retryAfterSeconds !== undefined) parts.push(`retryAfterSeconds=${retryAfterSeconds}`)
- if (parts.length === 0) return error
- const baseMessage = error instanceof Error ? error.message : String(error ?? '')
- return new GfsUriError(`${baseMessage} ${parts.join(' ')}`, { cause: error })
+ const rawMessage = error instanceof Error ? error.message : String(error ?? '')
+ const baseMessage = stripUnvettedRetryAfter(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 error
+ const suffix = parts.length > 0 ? ` ${parts.join(' ')}` : ''
+ return new GfsUriError(`${baseMessage}${suffix}`, { cause: error })
+}
+
+/**
+ * Any `retryAfterSeconds=` token the incoming message already carried, with the
+ * whitespace that delimits it.
+ *
+ * `\S*` consumes the whole token rather than just its digits, so a malformed
+ * one (`retryAfterSeconds=5s`) cannot leave a fragment behind that the renderer
+ * would then read as our own suffix.
+ */
+const UNVETTED_RETRY_AFTER_TOKEN = /(?:^|\s)retryAfterSeconds=\S*/g
+
+/**
+ * Strip any retry window the server's own message already printed, so the only
+ * one that can reach the renderer is the one this module vetted above.
+ *
+ * `httpClient` copies the RAW response body into `Error.message` whenever the
+ * JSON carries no top-level `error`/`message` key, so a body that itself prints
+ * the field — `{"detail":"slow down retryAfterSeconds=3600"}` — arrives here as
+ * ordinary message text, in the exact shape the renderer parses. The renderer
+ * reads the TRAILING token as our suffix; leaving an unvetted one in place
+ * would hand it a window that neither `parseGfsGrantErrorFields` (top level
+ * only) nor `parseRetryAfterHeader` ever accepted, and that window gates the
+ * Retry button and focus revalidation on real wall-clock time.
+ *
+ * Removing the token loses nothing a user can act on: the status, the code and
+ * the rest of the server's verdict all survive, and the `cause` keeps the
+ * untouched original for logs.
+ */
+function stripUnvettedRetryAfter(message: string): string {
+ return message.replace(UNVETTED_RETRY_AFTER_TOKEN, '')
}
/**
diff --git a/desktop-app/test/gfsUriHandler.test.ts b/desktop-app/test/gfsUriHandler.test.ts
index 0f18371cb..e8a6a18ca 100644
--- a/desktop-app/test/gfsUriHandler.test.ts
+++ b/desktop-app/test/gfsUriHandler.test.ts
@@ -721,6 +721,55 @@ describe('GfsClient read paths surface retryAfterSeconds across IPC', () => {
expect(t.requestJson).toHaveBeenCalledTimes(1)
})
+ it('strips a counterfeit retry window the server printed in its own message', async () => {
+ // httpClient copies the RAW response body into `Error.message` whenever the
+ // JSON carries no top-level `error`/`message` key, so a body that prints
+ // `retryAfterSeconds=` itself arrives here in the exact shape the renderer
+ // parses. Appending our vetted value after it would put TWO tokens in one
+ // message, and the renderer resolves that by position — so the server's
+ // number, not ours, would gate the Retry button and focus revalidation.
+ const t = transport({
+ requestJson: vi.fn(async () => {
+ throw new ApiError(
+ '429 Too Many Requests: slow down retryAfterSeconds=3600',
+ 429,
+ JSON.stringify({ error: 'Too Many Requests', retryAfterSeconds: 7 }),
+ '7'
+ )
+ }) as GfsTransport['requestJson'],
+ })
+
+ // Anchored: the vetted value is the LAST thing in the message, and the
+ // counterfeit one is gone rather than merely outranked.
+ await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(
+ /^429 Too Many Requests: slow down 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.
+ const t = transport({
+ requestJson: vi.fn(async () => {
+ throw new ApiError(
+ '429 Too Many Requests: slow down retryAfterSeconds=3600',
+ 429,
+ '<html><body>429 Too Many Requests</body></html>'
+ )
+ }) as GfsTransport['requestJson'],
+ })
+
+ await expect(new GfsClient(t).listAccessible('sess')).rejects.toThrow(
+ /^429 Too Many Requests: slow down$/
+ )
+ // 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.
+ expect(t.requestJson).toHaveBeenCalledTimes(1)
+ })
+
it('ignores an HTTP-date Retry-After rather than translating it against a local clock', async () => {
// RFC 9110 permits a date here. Converting it would depend on this
// machine's clock agreeing with the server's, and a skewed clock produces
diff --git a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
index ad21c517f..282e9e94c 100644
--- a/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/gfsGrantErrors.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import {
describeGfsGrantError,
describeGfsReadError,
+ isRateLimited,
parseRetryAfterSeconds,
} from '../gfsGrantErrors'
@@ -234,4 +235,43 @@ describe('describeGfsReadError', () => {
// Witness: the clamp is a ceiling, not a constant.
expect(parseRetryAfterSeconds('429 retryAfterSeconds=45')).toBe(45)
})
+
+ it('reads the vetted trailing suffix, not an earlier lookalike in the body', () => {
+ // `String.match` without `/g` returns the FIRST match, so an unanchored
+ // pattern resolves by position in the concatenation: the server's text
+ // comes before the suffix the main process appends, and therefore won.
+ // httpClient copies the RAW body into the message whenever the JSON has no
+ // top-level `error`/`message` key, so a body that prints the field itself
+ // arrives in the exact shape this parser reads.
+ //
+ // `retryAfterSeconds=0` is the damaging spelling: it is a VALID window, so
+ // nothing downstream rejects it. It renders "try again in 0s" and clears
+ // the gate immediately, restoring the refetch-on-focus loop that the 120/min
+ // budget was already refusing — the original incident, one layer down.
+ expect(
+ parseRetryAfterSeconds(
+ '429 Too Many Requests: please retryAfterSeconds=0 retryAfterSeconds=5'
+ )
+ ).toBe(5)
+ // The same ordering with a large earlier value gates for the full clamp
+ // instead, so the defect is not specific to zero.
+ expect(parseRetryAfterSeconds('429: please retryAfterSeconds=300 retryAfterSeconds=5')).toBe(5)
+ // Witness: the parser still resolves a message whose ONLY token is the
+ // vetted suffix, so the assertions above are about which token wins and
+ // not about a parser that stopped matching.
+ expect(
+ parseRetryAfterSeconds('429 Too Many Requests: please slow down retryAfterSeconds=5')
+ ).toBe(5)
+ })
+
+ it('declines a lookalike token that the main process never republished', () => {
+ // With the trailing anchor, a body whose own text ENDS in the field would
+ // otherwise be read as our suffix. `surfaceGfsGrantError` strips any such
+ // token before composing, so this shape cannot reach the renderer — and if
+ // it ever does, no window is better than a counterfeit one.
+ expect(parseRetryAfterSeconds('429 Too Many Requests: slow down')).toBeNull()
+ // Witness: the message is otherwise recognised as a rate limit, so the
+ // null above is the retry window being absent, not the error being unread.
+ expect(isRateLimited('429 Too Many Requests: slow down')).toBe(true)
+ })
})
diff --git a/desktop-app/ui/src/lib/gfsGrantErrors.ts b/desktop-app/ui/src/lib/gfsGrantErrors.ts
index b35f971e0..56078fcfd 100644
--- a/desktop-app/ui/src/lib/gfsGrantErrors.ts
+++ b/desktop-app/ui/src/lib/gfsGrantErrors.ts
@@ -73,23 +73,38 @@ const MAX_RETRY_AFTER_SECONDS = 300
*
* Only the main process may declare one. It parses the response body itself
* (uriHandler `parseGfsGrantErrorFields`), accepts the field only at the TOP
- * level, and republishes what it accepted as its own ` retryAfterSeconds=N`
- * suffix. This pattern matches that suffix and nothing else.
+ * level, strips any counterfeit token the server's own message carried, and
+ * republishes what it accepted as its own trailing ` retryAfterSeconds=N`
+ * suffix — always last, after `invalidIndexes=[…]`.
*
- * Matching `:` as well would re-admit exactly what the main process rejected.
- * `httpClient` puts the RAW response body into the error message whenever the
- * JSON carries no top-level `error`/`message` key, so a body such as
- * `{"policy":{"retryAfterSeconds":3600},"limit":100}` crosses IPC verbatim;
- * a separator-agnostic pattern reads the nested field and gates the UI for
- * five minutes on a value the authoritative parser refused to trust.
+ * Both anchors are load-bearing, and each closes a different hole:
*
- * The leading `(?:^|\s)` anchors to the suffix boundary, so a longer token
- * cannot smuggle the field in. Nothing scans for "the next number ANYWHERE",
- * which would both invent a window out of an unrelated field and run
- * quadratically over an upstream proxy's HTML 429 page.
+ * - The leading `(?:^|\s)` keeps a longer token from smuggling the field in.
+ * - The trailing `$` keeps an EARLIER occurrence from winning. `String.match`
+ * without `/g` returns the FIRST match, so an unanchored pattern reads
+ * whichever token appears earliest in the concatenation — which is the
+ * server's text, not our suffix. `httpClient` puts the RAW response body
+ * into the error message whenever the JSON carries no top-level
+ * `error`/`message` key, so a body such as
+ * `{"detail":"slow down retryAfterSeconds=0"}` crosses IPC verbatim and
+ * lands ahead of the vetted value.
+ *
+ * Matching `:` as well would re-admit what the main process rejected outright:
+ * `{"policy":{"retryAfterSeconds":3600},"limit":100}` is a NESTED field the
+ * authoritative parser refused to trust. Nothing scans for "the next number
+ * ANYWHERE", which would both invent a window out of an unrelated field and
+ * run quadratically over an upstream proxy's HTML 429 page.
+ *
+ * The digit run is unbounded because both anchors leave exactly ONE candidate
+ * position, which matches in linear time. Bounding its LENGTH instead would
+ * silently truncate an over-long value to its leading digits — reading part of
+ * a number as though it were the whole — or, once anchored, drop it entirely
+ * and skip the clamp below. `Math.min` is the bound that matters, and a run
+ * long enough to exceed `Number.MAX_VALUE` fails the integer check and yields
+ * no window at all.
*/
export function parseRetryAfterSeconds(message: string): number | null {
- const match = message.match(/(?:^|\s)retryAfterSeconds=(\d{1,7})/)
+ const match = message.match(/(?:^|\s)retryAfterSeconds=(\d+)$/)
if (!match?.[1]) return null
const seconds = Number.parseInt(match[1], 10)
if (!Number.isInteger(seconds) || seconds < 0) return null