diff --git a/src/renderer/src/hooks/metadata-request-cache.test.ts b/src/renderer/src/hooks/metadata-request-cache.test.ts index 89644e5a8..7770aca96 100644 --- a/src/renderer/src/hooks/metadata-request-cache.test.ts +++ b/src/renderer/src/hooks/metadata-request-cache.test.ts @@ -49,19 +49,88 @@ describe('metadata-request-cache', () => { expect(getFreshMetadata(store, 'repo-b:labels')?.data).toEqual(['b']) }) - it('does not cache failed requests', async () => { + it('paces failed requests with a short negative TTL instead of refetching immediately', async () => { const store = createMetadataRequestStore() const fetcher = vi .fn<() => Promise>() .mockRejectedValueOnce(new Error('network')) .mockResolvedValueOnce(['triage']) - await expect(loadMetadata(store, 'repo:labels', fetcher)).rejects.toThrow('network') - await expect(loadMetadata(store, 'repo:labels', fetcher)).resolves.toEqual(['triage']) + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 1_000)).rejects.toThrow( + 'network' + ) + // Within the failure TTL the cached rejection is reused without a fetch. + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 2_000)).rejects.toThrow( + 'network' + ) + expect(fetcher).toHaveBeenCalledTimes(1) + // Past the failure TTL the key becomes fetchable again. + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 11_000)).resolves.toEqual([ + 'triage' + ]) expect(fetcher).toHaveBeenCalledTimes(2) }) + it('a success clears the remembered failure for its key', async () => { + const store = createMetadataRequestStore() + const fetcher = vi + .fn<() => Promise>() + .mockRejectedValueOnce(new Error('network')) + .mockResolvedValueOnce(['triage']) + + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 1_000)).rejects.toThrow( + 'network' + ) + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 12_000)).resolves.toEqual([ + 'triage' + ]) + expect(store.failures.has('repo:labels')).toBe(false) + }) + + it('keeps failure entries isolated per key and bounded', async () => { + const store = createMetadataRequestStore() + await expect( + loadMetadata( + store, + 'repo-a:labels', + () => Promise.reject(new Error('down')), + () => 1_000 + ) + ).rejects.toThrow('down') + + const fetcherB = vi.fn(() => Promise.resolve(['ok'])) + await expect(loadMetadata(store, 'repo-b:labels', fetcherB, () => 1_000)).resolves.toEqual([ + 'ok' + ]) + expect(fetcherB).toHaveBeenCalledTimes(1) + }) + + it('does not record failures from a cleared generation', async () => { + const store = createMetadataRequestStore() + let rejectRequest: (error: Error) => void = () => {} + const pending = loadMetadata( + store, + 'repo:labels', + () => + new Promise((_resolve, reject) => { + rejectRequest = reject + }), + () => 1_000 + ) + + clearMetadataRequestStore(store) + rejectRequest(new Error('stale failure')) + await expect(pending).rejects.toThrow('stale failure') + expect(store.failures.size).toBe(0) + + const fetcher = vi.fn(() => Promise.resolve(['fresh'])) + await expect(loadMetadata(store, 'repo:labels', fetcher, () => 1_500)).resolves.toEqual([ + 'fresh' + ]) + expect(fetcher).toHaveBeenCalledTimes(1) + }) + it('does not let stale in-flight responses repopulate after clear', async () => { const store = createMetadataRequestStore() let resolveRequest: (value: string[]) => void = () => {} diff --git a/src/renderer/src/hooks/metadata-request-cache.ts b/src/renderer/src/hooks/metadata-request-cache.ts index 20df229f0..033f5e984 100644 --- a/src/renderer/src/hooks/metadata-request-cache.ts +++ b/src/renderer/src/hooks/metadata-request-cache.ts @@ -1,11 +1,19 @@ const METADATA_TTL = 300_000 // 5 min const MAX_METADATA_CACHE_ENTRIES = 500 +// Why: an unreachable provider/runtime fails every consumer render; without a +// negative cache each settlement re-issues the fetch, which storms a dead +// remote. Failures are remembered briefly so retries are paced, not disabled — +// short enough that a recovered provider is picked up within seconds. +const METADATA_FAILURE_TTL = 10_000 +const MAX_METADATA_FAILURE_ENTRIES = 200 type CachedMetadata = { data: T; fetchedAt: number } +type CachedMetadataFailure = { error: unknown; failedAt: number } export type MetadataRequestStore = { cache: Map> inflight: Map> + failures: Map generation: number } @@ -13,6 +21,7 @@ export function createMetadataRequestStore(): MetadataRequestStore { return { cache: new Map(), inflight: new Map(), + failures: new Map(), generation: 0 } } @@ -21,6 +30,7 @@ export function clearMetadataRequestStore(store: MetadataRequestStore): vo store.generation += 1 store.cache.clear() store.inflight.clear() + store.failures.clear() } function pruneMetadataCache( @@ -55,6 +65,37 @@ export function getFreshMetadata( return entry } +function pruneMetadataFailures( + store: MetadataRequestStore, + now: number, + maxEntries = MAX_METADATA_FAILURE_ENTRIES +): void { + for (const [key, entry] of store.failures) { + if (now - entry.failedAt >= METADATA_FAILURE_TTL) { + store.failures.delete(key) + } + } + if (store.failures.size <= maxEntries) { + return + } + const sorted = [...store.failures.entries()].sort((a, b) => b[1].failedAt - a[1].failedAt) + for (const [key] of sorted.slice(maxEntries)) { + store.failures.delete(key) + } +} + +export function getRecentMetadataFailure( + store: MetadataRequestStore, + key: string, + now = Date.now() +): CachedMetadataFailure | null { + const entry = store.failures.get(key) + if (!entry || now - entry.failedAt >= METADATA_FAILURE_TTL) { + return null + } + return entry +} + export function loadMetadata( store: MetadataRequestStore, key: string, @@ -71,6 +112,11 @@ export function loadMetadata( return inflight } + const recentFailure = getRecentMetadataFailure(store, key, now()) + if (recentFailure) { + return Promise.reject(recentFailure.error) + } + // Why: clearMetadataRequestStore invalidates auth/repo boundaries; late // responses from the previous generation must not repopulate the cache. const generation = store.generation @@ -79,6 +125,7 @@ export function loadMetadata( if (store.generation === generation) { const fetchedAt = now() store.cache.set(key, { data, fetchedAt }) + store.failures.delete(key) // Why: these module-level stores are reused across dialogs and // repo/runtime keys; TTL controls freshness but also needs pruning so // long sessions do not retain stale metadata indefinitely. @@ -86,6 +133,14 @@ export function loadMetadata( } return data }) + .catch((error: unknown) => { + if (store.generation === generation) { + const failedAt = now() + store.failures.set(key, { error, failedAt }) + pruneMetadataFailures(store, failedAt) + } + throw error + }) .finally(() => { if (store.inflight.get(key) === promise) { store.inflight.delete(key) diff --git a/src/renderer/src/hooks/runtime-client-events-sync.test.ts b/src/renderer/src/hooks/runtime-client-events-sync.test.ts index 3546b5b7b..c3ebb64cd 100644 --- a/src/renderer/src/hooks/runtime-client-events-sync.test.ts +++ b/src/renderer/src/hooks/runtime-client-events-sync.test.ts @@ -135,7 +135,8 @@ describe('createRuntimeClientEventsSync', () => { getDesiredEnvironmentIds: () => desired, subscribe, onEvent: vi.fn(), - retryDelayMs: 10 + retryDelayMs: 10, + random: () => 1 }) sync.sync() @@ -156,4 +157,212 @@ describe('createRuntimeClientEventsSync', () => { vi.useRealTimers() } }) + + it('backs off exponentially with a cap while an environment keeps failing', async () => { + vi.useFakeTimers() + try { + const subscribe = vi.fn( + (): Promise => + Promise.reject(new Error('unreachable')) + ) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => ['A'], + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10, + retryMaxDelayMs: 40, + random: () => 1 + }) + + sync.sync() + await Promise.resolve() + expect(subscribe).toHaveBeenCalledTimes(1) + + // Attempt 2 after 10ms (base). + await vi.advanceTimersByTimeAsync(10) + expect(subscribe).toHaveBeenCalledTimes(2) + // Attempt 3 after 20ms more (doubled) — not before. + await vi.advanceTimersByTimeAsync(19) + expect(subscribe).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(subscribe).toHaveBeenCalledTimes(3) + // Attempt 4 after 40ms more (doubled again, hits cap). + await vi.advanceTimersByTimeAsync(40) + expect(subscribe).toHaveBeenCalledTimes(4) + // Attempt 5 stays at the 40ms cap. + await vi.advanceTimersByTimeAsync(39) + expect(subscribe).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(1) + expect(subscribe).toHaveBeenCalledTimes(5) + } finally { + vi.useRealTimers() + } + }) + + it('applies jitter below the full backoff delay', async () => { + vi.useFakeTimers() + try { + const subscribe = vi.fn( + (): Promise => + Promise.reject(new Error('unreachable')) + ) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => ['A'], + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10, + random: () => 0 + }) + + sync.sync() + await Promise.resolve() + expect(subscribe).toHaveBeenCalledTimes(1) + + // random() => 0 halves the delay: retry at 5ms instead of 10ms. + await vi.advanceTimersByTimeAsync(5) + expect(subscribe).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + } + }) + + it('starts a fresh backoff epoch after a successful subscribe', async () => { + vi.useFakeTimers() + try { + let desired = ['A'] + let failing = true + const unsubscribe = vi.fn() + const subscribe = vi.fn((): Promise => { + if (failing) { + return Promise.reject(new Error('unreachable')) + } + return Promise.resolve({ unsubscribe }) + }) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => desired, + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10, + random: () => 1 + }) + + // Two failures escalate the delay to 20ms. + sync.sync() + await Promise.resolve() + await vi.advanceTimersByTimeAsync(10) + expect(subscribe).toHaveBeenCalledTimes(2) + + // Third attempt succeeds — failure count resets. + failing = false + await vi.advanceTimersByTimeAsync(20) + await Promise.resolve() + expect(subscribe).toHaveBeenCalledTimes(3) + + // Env leaves and re-enters the desired set, then fails again: the first + // retry is back at the 10ms base, not the escalated delay. + desired = [] + sync.sync() + desired = ['A'] + failing = true + sync.sync() + await Promise.resolve() + expect(subscribe).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(9) + expect(subscribe).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(1) + expect(subscribe).toHaveBeenCalledTimes(5) + } finally { + vi.useRealTimers() + } + }) + + it('an external sync retries a waiting environment immediately (recovery path)', async () => { + vi.useFakeTimers() + try { + const subscribe = vi.fn( + (): Promise => + Promise.reject(new Error('unreachable')) + ) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => ['A'], + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10_000, + random: () => 1 + }) + + sync.sync() + // Let the rejection propagate through the then/catch chain so the retry + // timer is armed before the external sync fires. + await vi.advanceTimersByTimeAsync(0) + expect(subscribe).toHaveBeenCalledTimes(1) + + // A reachable-set transition calls sync() directly; the pending backoff + // timer must not delay this immediate re-attempt. + sync.sync() + await vi.advanceTimersByTimeAsync(0) + expect(subscribe).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + } + }) + + it('does not carry a stale failure count when a rejection lands after the env left the set', async () => { + vi.useFakeTimers() + try { + // 'B' stays pending forever so the desired set is never empty and the + // generation never bumps — this is what lets A's late rejection still be + // observed by its .catch (the exact leave-while-in-flight race). + let desired = ['A', 'B'] + const aRejecters: ((error: Error) => void)[] = [] + let aAttempts = 0 + const subscribe = vi.fn( + (environmentId: string): Promise => { + if (environmentId === 'B') { + return new Promise(() => {}) + } + aAttempts += 1 + return new Promise((_resolve, reject) => { + aRejecters.push(reject) + }) + } + ) + const sync = createRuntimeClientEventsSync({ + getDesiredEnvironmentIds: () => desired, + subscribe, + onEvent: vi.fn(), + retryDelayMs: 10, + random: () => 1 + }) + + sync.sync() + expect(aAttempts).toBe(1) + + // A leaves the desired set while its subscribe is still in flight. + desired = ['B'] + sync.sync() + + // A's in-flight subscribe rejects now, after it is no longer desired. + aRejecters[0](new Error('unreachable')) + await vi.advanceTimersByTimeAsync(0) + + // A re-enters and its fresh subscribe (attempt 2) also fails. + desired = ['A', 'B'] + sync.sync() + await vi.advanceTimersByTimeAsync(0) + expect(aAttempts).toBe(2) + aRejecters[1](new Error('unreachable')) + await vi.advanceTimersByTimeAsync(0) + + // The first retry after re-entry must use the base delay (10ms). A stale + // count from the discarded rejection would have doubled it to 20ms. + await vi.advanceTimersByTimeAsync(9) + expect(aAttempts).toBe(2) + await vi.advanceTimersByTimeAsync(1) + await Promise.resolve() + expect(aAttempts).toBe(3) + } finally { + vi.useRealTimers() + } + }) }) diff --git a/src/renderer/src/hooks/runtime-client-events-sync.ts b/src/renderer/src/hooks/runtime-client-events-sync.ts index 128341dac..b23b6f01e 100644 --- a/src/renderer/src/hooks/runtime-client-events-sync.ts +++ b/src/renderer/src/hooks/runtime-client-events-sync.ts @@ -14,7 +14,11 @@ export type RuntimeClientEventsSyncDeps = { onError: (error: unknown) => void ) => Promise onEvent: (environmentId: string, event: RuntimeClientEvent) => void + /** Base retry delay; doubles per consecutive failure up to retryMaxDelayMs. */ retryDelayMs?: number + retryMaxDelayMs?: number + /** Injectable randomness for deterministic backoff-jitter tests. */ + random?: () => number } export type RuntimeClientEventsSync = { @@ -46,7 +50,10 @@ export function createRuntimeClientEventsSync( const subscriptions = new Map void>() const pending = new Set() const retryTimers = new Map>() + const consecutiveFailures = new Map() const retryDelayMs = deps.retryDelayMs ?? 1_000 + const retryMaxDelayMs = deps.retryMaxDelayMs ?? 30_000 + const random = deps.random ?? Math.random let generation = 0 const clearRetryTimer = (environmentId: string): void => { @@ -58,6 +65,17 @@ export function createRuntimeClientEventsSync( retryTimers.delete(environmentId) } + const nextRetryDelayMs = (environmentId: string): number => { + // Why: a flat retry hammers an unreachable runtime with one socket dial per + // tick forever. Exponential-with-cap keeps transient blips fast to recover + // while a dead host settles at one attempt per cap window; jitter keeps + // multiple envs from dialing in lockstep. External sync() (desired/reachable + // transitions) still retries immediately, so recovery is not delayed. + const failures = consecutiveFailures.get(environmentId) ?? 0 + const capped = Math.min(retryDelayMs * 2 ** Math.max(0, failures - 1), retryMaxDelayMs) + return capped * (0.5 + random() * 0.5) + } + const scheduleRetry = (environmentId: string, subscribeGeneration: number): void => { if (retryTimers.has(environmentId)) { return @@ -73,7 +91,7 @@ export function createRuntimeClientEventsSync( return } sync() - }, retryDelayMs) + }, nextRetryDelayMs(environmentId)) retryTimers.set(environmentId, retryTimer) } @@ -88,6 +106,7 @@ export function createRuntimeClientEventsSync( clearTimeout(retryTimer) } retryTimers.clear() + consecutiveFailures.clear() } const sync = (): void => { @@ -98,6 +117,11 @@ export function createRuntimeClientEventsSync( } clearRetryTimer(environmentId) } + for (const environmentId of consecutiveFailures.keys()) { + if (!desiredIds.has(environmentId)) { + consecutiveFailures.delete(environmentId) + } + } for (const [environmentId, unsubscribe] of subscriptions) { if (desiredIds.has(environmentId)) { @@ -139,14 +163,25 @@ export function createRuntimeClientEventsSync( subscription.unsubscribe() return } + consecutiveFailures.delete(environmentId) subscriptions.set(environmentId, subscription.unsubscribe) }) .catch((error) => { pending.delete(environmentId) if (subscribeGeneration === generation) { console.warn('[runtime-client-events] failed to subscribe:', error) + // Why: only track a failure when we will actually retry this env. + // A failure that lands after the env left the desired set must not + // leave a stale count that makes its first retry after re-entry skip + // the base delay. if (deps.getDesiredEnvironmentIds().includes(environmentId)) { + consecutiveFailures.set( + environmentId, + (consecutiveFailures.get(environmentId) ?? 0) + 1 + ) scheduleRetry(environmentId, subscribeGeneration) + } else { + consecutiveFailures.delete(environmentId) } } }) diff --git a/src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx b/src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx index 4bec2a92d..4be71732d 100644 --- a/src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx +++ b/src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx @@ -122,4 +122,56 @@ describe('useGitHubSlugMetadata', () => { }) expect(renders).toBeLessThanOrEqual(4) }) + + it('does not re-issue a failed label fetch when a fresh settings object re-renders', async () => { + // Regression: with an unreachable provider, the failure setState re-rendered + // the consumer, the fresh settings identity re-armed the effect, and the hook + // re-issued the fetch each settlement — a render-paced request storm. + let renders = 0 + let error: string | null = null + apiMocks.listLabelsBySlug.mockRejectedValue(new Error('Could not connect')) + + function FailingLabelsProbe(): null { + renders += 1 + const metadata = useRepoLabelsBySlug('stablyai', 'orca', { + activeRuntimeEnvironmentId: null + }) + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + // Extra settlement rounds give a storm the chance to manifest. + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(apiMocks.listLabelsBySlug).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) + + it('does not re-issue a failed assignee fetch when a fresh settings object re-renders', async () => { + let renders = 0 + let error: string | null = null + apiMocks.listAssignableUsersBySlug.mockRejectedValue(new Error('Could not connect')) + + function FailingAssigneesProbe(): null { + renders += 1 + const metadata = useRepoAssigneesBySlug('stablyai', 'orca', ['jinwoo'], { + activeRuntimeEnvironmentId: null + }) + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(apiMocks.listAssignableUsersBySlug).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) }) diff --git a/src/renderer/src/hooks/useGitHubSlugMetadata.ts b/src/renderer/src/hooks/useGitHubSlugMetadata.ts index 26022191f..4b3c07696 100644 --- a/src/renderer/src/hooks/useGitHubSlugMetadata.ts +++ b/src/renderer/src/hooks/useGitHubSlugMetadata.ts @@ -44,12 +44,17 @@ export function useRepoLabelsBySlug( error: null }) const activeKeyRef = useRef(null) + // Why: parent selectors can pass a fresh settings object each render; keying + // the effect on the primitive env id keeps a failure's setState from re-running + // the effect and re-issuing the fetch in a render-paced loop (same class as + // the seedKey stabilization below). + const activeRuntimeEnvironmentId = settings?.activeRuntimeEnvironmentId ?? null useEffect(() => { if (!owner || !repo) { return } - const target = getActiveRuntimeTarget(settings) + const target = getActiveRuntimeTarget({ activeRuntimeEnvironmentId }) const key = target.kind === 'environment' ? `runtime:${target.environmentId}:${owner}/${repo}` @@ -57,8 +62,6 @@ export function useRepoLabelsBySlug( const cached = getFreshMetadata(slugLabelStore, key) if (cached) { - // Why: parent selectors can pass a fresh settings object each render; - // only the first cached hit for this key should write React state. if (activeKeyRef.current !== key) { setState({ data: cached.data, loading: false, error: null }) } @@ -110,7 +113,7 @@ export function useRepoLabelsBySlug( error: err instanceof Error ? err.message : 'Failed to load labels' })) }) - }, [owner, repo, settings]) + }, [owner, repo, activeRuntimeEnvironmentId]) return state } @@ -131,12 +134,15 @@ export function useRepoAssigneesBySlug( // the joined-string identity so the effect doesn't re-fire on every render // — this is the assignee popover refetch-storm fix. const seedKey = (seedLogins ?? []).slice().sort().join(',') + // Why: see useRepoLabelsBySlug — primitive env id keeps failure setState from + // re-arming the effect through a fresh settings object identity. + const activeRuntimeEnvironmentId = settings?.activeRuntimeEnvironmentId ?? null useEffect(() => { if (!owner || !repo) { return } - const target = getActiveRuntimeTarget(settings) + const target = getActiveRuntimeTarget({ activeRuntimeEnvironmentId }) const key = target.kind === 'environment' ? `runtime:${target.environmentId}:${owner}/${repo}#${seedKey}` @@ -202,7 +208,7 @@ export function useRepoAssigneesBySlug( error: err instanceof Error ? err.message : 'Failed to load assignees' })) }) - }, [owner, repo, seedKey, settings]) + }, [owner, repo, seedKey, activeRuntimeEnvironmentId]) return state } diff --git a/src/renderer/src/hooks/useIssueMetadata.test.tsx b/src/renderer/src/hooks/useIssueMetadata.test.tsx new file mode 100644 index 000000000..e7e6dda6d --- /dev/null +++ b/src/renderer/src/hooks/useIssueMetadata.test.tsx @@ -0,0 +1,153 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + clearLinearMetadataCache, + useTeamLabels, + useTeamMembers, + useTeamStates +} from './useIssueMetadata' + +const linearMocks = vi.hoisted(() => ({ + linearTeamStates: vi.fn(), + linearTeamLabels: vi.fn(), + linearTeamMembers: vi.fn() +})) + +vi.mock('@/runtime/runtime-linear-client', () => ({ + linearTeamStates: linearMocks.linearTeamStates, + linearTeamLabels: linearMocks.linearTeamLabels, + linearTeamMembers: linearMocks.linearTeamMembers +})) + +vi.mock('@/runtime/runtime-rpc-client', () => ({ + callRuntimeRpc: vi.fn(), + getActiveRuntimeTarget: (settings?: { activeRuntimeEnvironmentId?: string | null } | null) => + settings?.activeRuntimeEnvironmentId + ? { kind: 'environment', environmentId: settings.activeRuntimeEnvironmentId } + : { kind: 'local' } +})) + +const roots: Root[] = [] + +async function flushEffects(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +function renderProbe(element: React.ReactNode): void { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + roots.push(root) + act(() => { + root.render(element) + }) +} + +describe('useIssueMetadata Linear hooks', () => { + beforeEach(() => { + clearLinearMetadataCache() + linearMocks.linearTeamStates.mockReset() + linearMocks.linearTeamLabels.mockReset() + linearMocks.linearTeamMembers.mockReset() + }) + + afterEach(() => { + roots.splice(0).forEach((root) => { + act(() => root.unmount()) + }) + document.body.replaceChildren() + }) + + it('does not loop when cached team-state metadata is read with a fresh settings object', async () => { + let renders = 0 + let states: unknown[] = [] + linearMocks.linearTeamStates.mockResolvedValue([{ id: 's1', name: 'Todo' }]) + + function StatesProbe(): null { + renders += 1 + // Fresh settings object each render — the storm trigger. + const metadata = useTeamStates('team-1', { activeRuntimeEnvironmentId: null }, 'ws-1') + states = metadata.data + return null + } + + renderProbe() + await flushEffects() + + expect(states).toEqual([{ id: 's1', name: 'Todo' }]) + expect(linearMocks.linearTeamStates).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) + + it('does not re-issue a failed team-state fetch when a fresh settings object re-renders', async () => { + let renders = 0 + let error: string | null = null + linearMocks.linearTeamStates.mockRejectedValue(new Error('Could not connect')) + + function StatesProbe(): null { + renders += 1 + const metadata = useTeamStates('team-1', { activeRuntimeEnvironmentId: null }, 'ws-1') + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(linearMocks.linearTeamStates).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) + + it('does not re-issue a failed team-label fetch when a fresh settings object re-renders', async () => { + let renders = 0 + let error: string | null = null + linearMocks.linearTeamLabels.mockRejectedValue(new Error('Could not connect')) + + function LabelsProbe(): null { + renders += 1 + const metadata = useTeamLabels('team-1', { activeRuntimeEnvironmentId: null }, 'ws-1') + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(linearMocks.linearTeamLabels).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) + + it('does not re-issue a failed team-member fetch when a fresh settings object re-renders', async () => { + let renders = 0 + let error: string | null = null + linearMocks.linearTeamMembers.mockRejectedValue(new Error('Could not connect')) + + function MembersProbe(): null { + renders += 1 + const metadata = useTeamMembers('team-1', { activeRuntimeEnvironmentId: null }, 'ws-1') + error = metadata.error + return null + } + + renderProbe() + await flushEffects() + await flushEffects() + await flushEffects() + + expect(error).toBe('Could not connect') + expect(linearMocks.linearTeamMembers).toHaveBeenCalledTimes(1) + expect(renders).toBeLessThanOrEqual(4) + }) +}) diff --git a/src/renderer/src/hooks/useIssueMetadata.ts b/src/renderer/src/hooks/useIssueMetadata.ts index ea1e306ca..4bd89dbb6 100644 --- a/src/renderer/src/hooks/useIssueMetadata.ts +++ b/src/renderer/src/hooks/useIssueMetadata.ts @@ -231,13 +231,18 @@ export function useTeamStates( error: null }) const activeKeyRef = useRef(null) + // Why: parents can pass a fresh settings object each render; keying the effect + // on the derived cache key keeps a failure's setState from re-arming the fetch + // in a render-paced loop. The ref carries the latest settings for the call. + const settingsRef = useRef(settings) + settingsRef.current = settings + const cacheKey = teamId ? linearMetadataCacheKey(teamId, settings, workspaceId) : null useEffect(() => { - if (!teamId) { + if (!teamId || !cacheKey) { return } - const cacheKey = linearMetadataCacheKey(teamId, settings, workspaceId) const cached = getFreshMetadata(linearStateStore, cacheKey) if (cached) { if (activeKeyRef.current !== cacheKey) { @@ -256,7 +261,7 @@ export function useTeamStates( error: null })) loadMetadata(linearStateStore, cacheKey, () => - linearTeamStates(settings, teamId, workspaceId).then( + linearTeamStates(settingsRef.current, teamId, workspaceId).then( (states) => states as LinearWorkflowState[] ) ) @@ -277,7 +282,7 @@ export function useTeamStates( error: err instanceof Error ? err.message : 'Failed to load states' })) }) - }, [settings, teamId, workspaceId]) + }, [cacheKey, teamId, workspaceId]) return state } @@ -293,13 +298,17 @@ export function useTeamLabels( error: null }) const activeKeyRef = useRef(null) + // Why: see useTeamStates — cache-key deps + latest-settings ref stop the + // failure-setState render loop. + const settingsRef = useRef(settings) + settingsRef.current = settings + const cacheKey = teamId ? linearMetadataCacheKey(teamId, settings, workspaceId) : null useEffect(() => { - if (!teamId) { + if (!teamId || !cacheKey) { return } - const cacheKey = linearMetadataCacheKey(teamId, settings, workspaceId) const cached = getFreshMetadata(linearLabelStore, cacheKey) if (cached) { if (activeKeyRef.current !== cacheKey) { @@ -318,7 +327,9 @@ export function useTeamLabels( error: null })) loadMetadata(linearLabelStore, cacheKey, () => - linearTeamLabels(settings, teamId, workspaceId).then((labels) => labels as LinearLabel[]) + linearTeamLabels(settingsRef.current, teamId, workspaceId).then( + (labels) => labels as LinearLabel[] + ) ) .then((data) => { if (activeKeyRef.current !== requestKey) { @@ -337,7 +348,7 @@ export function useTeamLabels( error: err instanceof Error ? err.message : 'Failed to load labels' })) }) - }, [settings, teamId, workspaceId]) + }, [cacheKey, teamId, workspaceId]) return state } @@ -353,13 +364,17 @@ export function useTeamMembers( error: null }) const activeKeyRef = useRef(null) + // Why: see useTeamStates — cache-key deps + latest-settings ref stop the + // failure-setState render loop. + const settingsRef = useRef(settings) + settingsRef.current = settings + const cacheKey = teamId ? linearMetadataCacheKey(teamId, settings, workspaceId) : null useEffect(() => { - if (!teamId) { + if (!teamId || !cacheKey) { return } - const cacheKey = linearMetadataCacheKey(teamId, settings, workspaceId) const cached = getFreshMetadata(linearMemberStore, cacheKey) if (cached) { if (activeKeyRef.current !== cacheKey) { @@ -378,7 +393,9 @@ export function useTeamMembers( error: null })) loadMetadata(linearMemberStore, cacheKey, () => - linearTeamMembers(settings, teamId, workspaceId).then((members) => members as LinearMember[]) + linearTeamMembers(settingsRef.current, teamId, workspaceId).then( + (members) => members as LinearMember[] + ) ) .then((data) => { if (activeKeyRef.current !== requestKey) { @@ -397,7 +414,7 @@ export function useTeamMembers( error: err instanceof Error ? err.message : 'Failed to load members' })) }) - }, [settings, teamId, workspaceId]) + }, [cacheKey, teamId, workspaceId]) return state }