@@ -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 ────────────────────────────────────────
0 commit comments