Skip to content

The agent that grows with you

fix(desktop): single-flight refreshProfiles with retry recovery in global remote mode

David Metcalfe57043c2bc07a
diff --git a/apps/desktop/src/store/profile.test.ts b/apps/desktop/src/store/profile.test.ts
index c2e7cf36c02..a4c6d75e3da 100644
--- a/apps/desktop/src/store/profile.test.ts
+++ b/apps/desktop/src/store/profile.test.ts
@@ -161,6 +161,16 @@ describe('prewarmProfileBackend (hover-intent pool spawn)', () => {
})
describe('refreshProfiles shared rail list (#49289)', () => {
+ beforeEach(() => {
+ vi.mocked(getProfiles).mockReset()
+ vi.useFakeTimers()
+ })
+
+ afterEach(() => {
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ })
+
it('removes a deleted profile from the shared $profiles cache after Manage Profiles refreshes', async () => {
$profiles.set([profile('default', true), profile('test1')])
vi.mocked(getProfiles).mockResolvedValueOnce({ profiles: [profile('default', true)] })
@@ -170,12 +180,54 @@ describe('refreshProfiles shared rail list (#49289)', () => {
expect($profiles.get().map(profile => profile.name)).toEqual(['default'])
})
- it('leaves the shared $profiles cache intact when the refresh fails', async () => {
+ it('recovers from transient failures and writes the returned profile list (#70679)', async () => {
+ // Global remote mode: the refresh fires while the remote HTTP proxy is still
+ // routing, so the first attempts fail and a later one succeeds. The retry
+ // backoff is 500ms then 1000ms (refreshProfiles retries twice on failure).
+ $profiles.set([])
+ vi.mocked(getProfiles)
+ .mockRejectedValueOnce(new Error('backend unavailable'))
+ .mockRejectedValueOnce(new Error('backend unavailable'))
+ .mockResolvedValueOnce({ profiles: [profile('default', true), profile('healthops')] })
+
+ const refresh = refreshProfiles()
+ await vi.advanceTimersByTimeAsync(500)
+ await vi.advanceTimersByTimeAsync(1000)
+ await expect(refresh).resolves.toHaveLength(2)
+
+ expect(vi.mocked(getProfiles)).toHaveBeenCalledTimes(3)
+ expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'healthops'])
+ })
+
+ it('shares one retry chain across concurrent callers (single-flight)', async () => {
+ // Gateway open fires both useBackgroundSync and the activeGatewayProfile
+ // effect at once; both callers must ride the same chain, not double it.
+ $profiles.set([])
+ vi.mocked(getProfiles)
+ .mockRejectedValueOnce(new Error('backend unavailable'))
+ .mockResolvedValueOnce({ profiles: [profile('default', true), profile('healthops')] })
+
+ const first = refreshProfiles()
+ const second = refreshProfiles()
+ await vi.advanceTimersByTimeAsync(500)
+ await expect(first).resolves.toHaveLength(2)
+ await expect(second).resolves.toHaveLength(2)
+
+ expect(vi.mocked(getProfiles)).toHaveBeenCalledTimes(2)
+ expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'healthops'])
+ })
+
+ it('leaves the shared $profiles cache intact when every retry fails', async () => {
$profiles.set([profile('default', true), profile('test1')])
- vi.mocked(getProfiles).mockRejectedValueOnce(new Error('backend unavailable'))
+ vi.mocked(getProfiles).mockRejectedValue(new Error('backend unavailable'))
- await expect(refreshProfiles()).rejects.toThrow('backend unavailable')
+ const refresh = refreshProfiles()
+ const rejection = expect(refresh).rejects.toThrow('backend unavailable')
+ await vi.advanceTimersByTimeAsync(500)
+ await vi.advanceTimersByTimeAsync(1000)
+ await rejection
+ expect(vi.mocked(getProfiles)).toHaveBeenCalledTimes(3)
expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'test1'])
})
})
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index ed695f046d5..39dba687c13 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -72,17 +72,64 @@ let profileListEpoch = 0
export function invalidateProfileListFetches(): void {
profileListEpoch += 1
+ // Detach the single-flight slot too: a caller arriving AFTER a backend
+ // switch must start a fresh fetch against the new backend, not ride the
+ // previous backend's in-flight retry chain.
+ refreshInFlight = null
}
-export async function refreshProfiles(): Promise<ProfileInfo[]> {
- const epoch = profileListEpoch
- const { profiles } = await getProfiles()
+// Single-flight guard: on gateway open both useBackgroundSync and the
+// activeGatewayProfile-change effect call refreshActiveProfile() at once, and
+// the Manage Profiles panel can join mid-flight. Dedupe so concurrent callers
+// share one retry chain instead of stampeding /api/profiles (#70679).
+let refreshInFlight: Promise<ProfileInfo[]> | null = null
- if (epoch === profileListEpoch) {
- $profiles.set(profiles)
+export function refreshProfiles(): Promise<ProfileInfo[]> {
+ if (refreshInFlight) {
+ return refreshInFlight
}
- return profiles
+ const flight = (async () => {
+ const epoch = profileListEpoch
+ const MAX_RETRIES = 2
+
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
+ try {
+ const { profiles } = await getProfiles()
+
+ if (epoch === profileListEpoch) {
+ $profiles.set(profiles)
+ }
+
+ return profiles
+ } catch (error) {
+ if (attempt === MAX_RETRIES || epoch !== profileListEpoch) {
+ // Surface the failure so it's visible in the console — the prior
+ // silent catch in refreshActiveProfile() hid global-remote timing
+ // races (#70679). A stranded epoch stops retrying against the past.
+ console.error(`[profiles] refreshProfiles failed after ${attempt + 1} attempt(s):`, error)
+
+ throw error
+ }
+
+ // Back off before retrying: 500ms, then 1000ms. Gives the remote proxy
+ // a window to finish routing after WebSocket-ready but pre-HTTP-proxy
+ // states (global remote mode, #70679).
+ await new Promise(resolve => setTimeout(resolve, 500 * (attempt + 1)))
+ }
+ }
+
+ // Unreachable — satisfies TypeScript.
+ return []
+ })().finally(() => {
+ if (refreshInFlight === flight) {
+ refreshInFlight = null
+ }
+ })
+
+ refreshInFlight = flight
+
+ return flight
}
// ── Rail order ─────────────────────────────────────────────────────────────