Skip to content

Commit 36a46ff

Browse files
Duncanwpfleger96
andcommitted
fix(desktop): install new queryFn before invalidating on target change
The target-change invalidation useEffect was declared before useQuery, causing invalidateQueries to reach query.fetch() while the observer still held the previous (null) queryFn closure. In TanStack 5.100.14, useBaseQuery installs new query options in a later effect; a settled null→target transition would refetch with the old closure, validating against null and settling success without detecting the missing target. Move useQuery before the useEffect so React runs TanStack's options- update effect first on each render cycle. The observer installs the current expectedEventId closure before our invalidation fires, ensuring the replacement fetch validates against the new target and retries when the event is absent. Replace the fetch-count-only settled-invalidation test with a behavioral regression: settle with null target, supply target on same root, return missing-target page (triggers ThreadExpectedEventMissingError under new closure, silent success under old), retry, assert target-bearing data. Mutation-checks: remove invalidateQueries → red; revert useQuery after useEffect → old null closure settles without retry → red. Co-authored-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]>
1 parent 0ee208a commit 36a46ff

2 files changed

Lines changed: 164 additions & 64 deletions

File tree

‎desktop/src/features/messages/useThreadReplies.test.mjs‎

Lines changed: 112 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -342,22 +342,37 @@ test("useThreadReplies resolves to data after exhausting missing-event retries",
342342
}
343343
});
344344

345-
// ── Test: mounted-thread target change triggers invalidation ──────────────────
345+
// ── Test: settled null→target change triggers retry and lands target data ──────
346346
//
347-
// Load-bearing for the useEffect invalidation seam in useThreadReplies.
347+
// Load-bearing for the useEffect invalidation seam AND for the TanStack effect-
348+
// ordering fix in useThreadReplies.
348349
//
349-
// When expectedEventId changes from null to a non-null value while the same
350-
// thread root is already mounted and the query key is constant, the production
351-
// useEffect calls queryClient.invalidateQueries, triggering a second fetch. If
352-
// that invalidateQueries call is removed from the useEffect, fetchCount stays
353-
// at 1 and this test FAILS.
350+
// Required shape (Carl's requirement, P2 finding on PR #7188):
351+
// 1. Mount with expectedEventId=null. Wait for the initial fetch to settle
352+
// with a non-target reply — query is success with data, no target active.
353+
// 2. Rerender with expectedEventId="target-evt-settled" (same root, same key).
354+
// The useEffect must invalidate; the refetch must use the new queryFn
355+
// closure (capturing "target-evt-settled"), not the stale null closure.
356+
// 3. First post-invalidation fetch returns a page WITHOUT the target —
357+
// loadThreadReplies throws ThreadExpectedEventMissingError. This is the
358+
// failure path the pre-fix code silently passed: old null closure
359+
// validated against null, settled success([]) without retrying.
360+
// 4. TanStack retries; second post-invalidation fetch returns the target.
361+
// Hook settles success with the target event in data.
362+
//
363+
// Mutation checks:
364+
// - Remove invalidateQueries from the useEffect → hook never re-fetches,
365+
// data stays at initial non-target reply → target-bearing assertion red.
366+
// - Restore effect but revert useQuery back to before the effect (pre-fix
367+
// ordering) → refetch uses old null closure, settles success([]) without
368+
// the target or a retry → target-bearing assertion red.
354369
//
355370
// Also load-bearing for the ChannelScreen wiring: the source assertion verifies
356371
// that ChannelScreen.tsx passes threadScrollTargetId as the third argument to
357372
// useThreadReplies. Removing that argument fails the source check, catching the
358373
// exact bypass that allowed notification routing to skip the missing-event check.
359374

360-
test("useThreadReplies invalidates when expectedEventId changes on settled query", async () => {
375+
test("useThreadReplies null-to-target change retries on missing-target page and lands target data", async () => {
361376
let queryClient;
362377
let unmount;
363378
let cleanup;
@@ -373,48 +388,117 @@ test("useThreadReplies invalidates when expectedEventId changes on settled query
373388
const { useThreadReplies } = await import("./useThreadReplies.ts");
374389
const { readFile } = await import("node:fs/promises");
375390

391+
const targetEvent = fakeEvent("target-evt-settled");
392+
const otherReply = fakeEvent("other-reply-settled");
393+
394+
// Phase tracking:
395+
// fetch 1 — initial null-target fetch: returns otherReply (no target active)
396+
// fetch 2 — first post-invalidation fetch: returns otherReply only (target
397+
// absent), triggering ThreadExpectedEventMissingError under the
398+
// new closure (captures "target-evt-settled"). Under the old
399+
// null closure this would silently settle without throwing.
400+
// fetch 3+ — retry fetch: returns targetEvent (relay caught up)
376401
let fetchCount = 0;
377402
globalThis.__tauriGetThreadReplies = async () => {
378403
fetchCount += 1;
379-
return singlePage([fakeEvent(`reply-ch-${fetchCount}`)]);
404+
if (fetchCount === 1) {
405+
// Initial null-target settle — no target validation needed.
406+
return singlePage([otherReply]);
407+
}
408+
if (fetchCount === 2) {
409+
// First post-invalidation fetch — target absent. Under the fixed code
410+
// the closure captures "target-evt-settled" and loadThreadReplies
411+
// throws ThreadExpectedEventMissingError → TanStack retries.
412+
// Under the pre-fix code (null closure) → settles success without retry.
413+
return singlePage([otherReply]);
414+
}
415+
// Retry fetch — relay has caught up, target available.
416+
return singlePage([targetEvent, otherReply]);
380417
};
381418

382419
queryClient = new QueryClient({
383-
defaultOptions: { queries: { retry: false, retryDelay: 0 } },
420+
defaultOptions: { queries: { retry: false } },
384421
});
385-
const channel = { id: "chan-hook", channelType: "group" };
422+
const channel = { id: "chan-settled", channelType: "group" };
386423
const wrapper = ({ children }) =>
387424
createElement(QueryClientProvider, { client: queryClient }, children);
388425

389426
const hook = renderHook(
390427
({ expectedEventId }) =>
391-
useThreadReplies(channel, "root-hook", expectedEventId),
428+
useThreadReplies(channel, "root-settled", expectedEventId),
392429
{ wrapper, initialProps: { expectedEventId: null } },
393430
);
394431
unmount = hook.unmount;
395-
const { rerender } = hook;
432+
const { rerender, result } = hook;
396433

397-
// Wait for the initial fetch to settle.
398-
await act(async () => {
399-
await new Promise((resolve) => setTimeout(resolve, 50));
400-
});
434+
// Wait for the initial null-target fetch to settle.
435+
for (let i = 0; i < 20; i++) {
436+
await act(async () => {
437+
await new Promise((resolve) => setImmediate(resolve));
438+
});
439+
if (!result.current.isPending) break;
440+
}
401441

402-
const afterFirstFetch = fetchCount;
403-
assert.ok(afterFirstFetch >= 1, "initial fetch must have occurred");
442+
assert.ok(fetchCount >= 1, "initial fetch must have occurred");
443+
assert.equal(
444+
result.current.isError,
445+
false,
446+
"hook must be in success state after initial null-target settle",
447+
);
404448

405-
// Change expectedEventId to a non-null value — the useEffect must invalidate
406-
// and trigger a second fetch.
449+
// Supply the target — hook must invalidate, refetch with current closure,
450+
// detect missing target, retry, and land target-bearing data.
451+
// The hook uses retryDelay: (attempt) => Math.min(1_000 * 2 ** attempt, 30_000).
452+
// Attempt 0 retries after 1_000ms (real time). Wait up to 3s for the retry.
407453
await act(async () => {
408-
rerender({ expectedEventId: "evt-target" });
409-
});
410-
await act(async () => {
411-
await new Promise((resolve) => setTimeout(resolve, 50));
454+
rerender({ expectedEventId: "target-evt-settled" });
412455
});
413456

457+
// Poll for target-bearing success, waiting up to 3 seconds total.
458+
// The retry delay is 1s (attempt 0), so the hook should settle in ~1.1s.
459+
let settled = false;
460+
for (let i = 0; i < 40; i++) {
461+
await act(async () => {
462+
await new Promise((resolve) => setTimeout(resolve, 100));
463+
});
464+
if (
465+
!result.current.isPending &&
466+
!result.current.isError &&
467+
result.current.data?.some((e) => e.id === targetEvent.id)
468+
) {
469+
settled = true;
470+
break;
471+
}
472+
}
473+
474+
assert.ok(
475+
settled,
476+
`hook must settle with target data after retry within 4s ` +
477+
`(isError=${result.current.isError}, ` +
478+
`data ids: ${result.current.data?.map((e) => e.id).join(",")}, ` +
479+
`fetchCount=${fetchCount})`,
480+
);
481+
482+
// Additional assertions on the settled state.
483+
assert.ok(
484+
!result.current.isError,
485+
`hook must not be in error state (error=${result.current.error})`,
486+
);
487+
assert.ok(
488+
Array.isArray(result.current.data),
489+
`hook must expose reply data (data=${JSON.stringify(result.current.data)})`,
490+
);
491+
assert.ok(
492+
result.current.data?.some((e) => e.id === targetEvent.id),
493+
`data must include the target event after retry ` +
494+
`(got ids: ${result.current.data?.map((e) => e.id).join(",")})`,
495+
);
496+
497+
// At minimum two more fetches must have occurred: the invalidation fetch
498+
// (fetch 2, missing target → throw) and the retry (fetch 3+, target present).
414499
assert.ok(
415-
fetchCount > afterFirstFetch,
416-
`expectedEventId change must trigger an invalidation fetch ` +
417-
`(fetchCount=${fetchCount}, afterFirstFetch=${afterFirstFetch})`,
500+
fetchCount >= 3,
501+
`missing-target retry must have fired (fetchCount=${fetchCount})`,
418502
);
419503

420504
// ── ChannelScreen wiring assertion ────────────────────────────────────────

‎desktop/src/features/messages/useThreadReplies.ts‎

Lines changed: 52 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -115,42 +115,16 @@ export function useThreadReplies(
115115
null,
116116
);
117117

118-
// Notification routing can change expectedEventId while the same thread root
119-
// is already mounted and the query is settled. Because the query key
120-
// (channelId + rootId) stays the same, the query fn closure does not re-run
121-
// automatically. Invalidate explicitly so the new target gets a fresh fetch
122-
// and validation pass.
123-
//
124-
// If the query is still in-flight with no data yet (cold start race: target
125-
// arrives before the first page returns), cancel the in-flight fetch first.
126-
// Without the cancel the obsolete empty-page response can settle before the
127-
// new target's validation closure is active, producing a false authoritative
128-
// [] result.
129-
const prevExpectedEventIdRef = React.useRef(expectedEventId);
130-
React.useEffect(() => {
131-
const prev = prevExpectedEventIdRef.current;
132-
prevExpectedEventIdRef.current = expectedEventId;
133-
if (
134-
expectedEventId !== null &&
135-
expectedEventId !== undefined &&
136-
expectedEventId !== prev &&
137-
!exhaustedTargetsRef.current.has(expectedEventId)
138-
) {
139-
const state = queryClient.getQueryState(queryKey);
140-
if (state?.fetchStatus === "fetching" && state.status === "pending") {
141-
// Cold fetch in-flight: cancel and re-fetch atomically so the stale
142-
// empty-page response cannot settle as authoritative data before the
143-
// new target's validation closure is active.
144-
void queryClient.cancelQueries({ queryKey }).then(() => {
145-
void queryClient.invalidateQueries({ queryKey });
146-
});
147-
} else {
148-
void queryClient.invalidateQueries({ queryKey });
149-
}
150-
}
151-
}, [expectedEventId, queryClient, queryKey]);
152-
153-
return useQuery({
118+
// useQuery is declared before the target-change invalidation effect so that
119+
// TanStack's internal options-update effect (useBaseQuery.ts, registered
120+
// inside useQuery) runs first on each render cycle. React runs effects in
121+
// declaration order; placing our invalidation effect after useQuery ensures
122+
// the observer has installed the new queryFn closure — capturing the current
123+
// expectedEventId — before invalidateQueries triggers query.fetch(). Without
124+
// this ordering, a settled null→target transition refetches with the previous
125+
// (null) queryFn, loadThreadReplies validates against null, and the missing
126+
// reply stays absent with no Retry error surface.
127+
const queryResult = useQuery({
154128
queryKey,
155129
enabled:
156130
activeChannel !== null &&
@@ -192,6 +166,48 @@ export function useThreadReplies(
192166
retry: 3,
193167
retryDelay: (attempt) => Math.min(1_000 * 2 ** attempt, 30_000),
194168
});
169+
170+
// Notification routing can change expectedEventId while the same thread root
171+
// is already mounted and the query is settled. Because the query key
172+
// (channelId + rootId) stays the same, the query fn closure does not re-run
173+
// automatically. Invalidate explicitly so the new target gets a fresh fetch
174+
// and validation pass.
175+
//
176+
// This effect is declared AFTER useQuery so that TanStack's options-update
177+
// effect (which installs the new queryFn closure) always runs first within
178+
// the same render cycle. The invalidation therefore reaches query.fetch()
179+
// with the current expectedEventId already captured — not the previous one.
180+
//
181+
// If the query is still in-flight with no data yet (cold start race: target
182+
// arrives before the first page returns), cancel the in-flight fetch first.
183+
// Without the cancel the obsolete empty-page response can settle before the
184+
// new target's validation closure is active, producing a false authoritative
185+
// [] result.
186+
const prevExpectedEventIdRef = React.useRef(expectedEventId);
187+
React.useEffect(() => {
188+
const prev = prevExpectedEventIdRef.current;
189+
prevExpectedEventIdRef.current = expectedEventId;
190+
if (
191+
expectedEventId !== null &&
192+
expectedEventId !== undefined &&
193+
expectedEventId !== prev &&
194+
!exhaustedTargetsRef.current.has(expectedEventId)
195+
) {
196+
const state = queryClient.getQueryState(queryKey);
197+
if (state?.fetchStatus === "fetching" && state.status === "pending") {
198+
// Cold fetch in-flight: cancel and re-fetch atomically so the stale
199+
// empty-page response cannot settle as authoritative data before the
200+
// new target's validation closure is active.
201+
void queryClient.cancelQueries({ queryKey }).then(() => {
202+
void queryClient.invalidateQueries({ queryKey });
203+
});
204+
} else {
205+
void queryClient.invalidateQueries({ queryKey });
206+
}
207+
}
208+
}, [expectedEventId, queryClient, queryKey]);
209+
210+
return queryResult;
195211
}
196212

197213
/**

0 commit comments

Comments
 (0)