6 Commits

Author SHA1 Message Date
Nathan Nguyen 5f6bccbd03 feat: track previousNextUrl for intercepted App Router entries (#755)
* docs: refresh stale app browser entry comments

* feat: track previousNextUrl for intercepted App Router entries

* refactor: bind getBrowserRouterState() once in refresh case

Avoid calling getBrowserRouterState() twice in the refresh branch of
getRequestState by binding previousNextUrl to a local. Behavior-preserving
nit raised in PR review.

* refactor: drop dead history-state interception-context read path

After previousNextUrl became the source of truth for interception context
in history state, nothing in production writes the legacy
__vinext_interceptionContext key anymore. The fall-through read in
getCurrentInterceptionContext was vestigial and getCurrentInterceptionContext
now derives strictly from the current pathname.

- Removes the unused VINEXT_INTERCEPTION_CONTEXT_HISTORY_STATE_KEY export
- Removes readHistoryStateInterceptionContext
- Updates the prefetch-cache unit test to assert the new pathname-derived
  contract instead of the legacy history-state override

* test(e2e): cover back/forward restoration of intercepted modal view

Adds the back-then-forward case for App Router intercepting routes:
after intercepted navigation from /feed to /photos/42, going back to
/feed and then forward should restore the modal (rather than rendering
the full /photos/42 page). Directly exercises the previousNextUrl read
in the traverse branch of getRequestState.

* docs: reword stale 'belongs to PR 5' comments

Two inline comments in app-browser-entry.ts referenced "PR 5" as a future
PR, but this is PR 5. Reworded to describe the deferred scope as-is:
interception context on server-action POSTs and HMR re-renders is
intentionally not propagated.

* fix: distinguish explicit null from undefined in previousNextUrl fallback

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: James <james@eli.cx>
2026-04-12 13:01:50 +00:00
Nathan Nguyen b8c44fdd52 feat: encode interception context in App Router payload IDs and caches (#753)
* test: add E2E verification for layout persistence flat payload pipeline

Prove the flat keyed map architecture works end-to-end:
- Layout state persists across sibling navigation (counter survives)
- Template remounts on segment boundary change, persists within segment
- Error boundary clears on navigate-away-and-back
- Back/forward preserves layout state through history
- Parallel slots persist on soft nav, show default.tsx on hard nav

Zero production code changes — test fixtures and Playwright specs only.

* test: harden layout persistence hydration assertions

* test: address layout-persistence spec gaps

* test: tighten not.toBeAttached() assertions for absent elements

* chore: trigger CI

* feat: encode interception context in App Router payload IDs and caches

* test: update App Router entry snapshots for interception encoding

* fix: reuse committed interception context for soft navigations

* chore: fix formatting in app-browser-entry after rebase

* fix: update mounted-slot test helper calls for 4-arg createResolvedElements signature

PR 3 added mounted-slot tests using createResolvedElements(routeId, root, extraEntries).
PR 4 inserted interceptionContext as the 3rd param, shifting extraEntries to 4th.
The object was being swallowed as interceptionContext, causing getMountedSlotIds to return [].
Also add missing renderId to the interception context pending-commit test.

* chore: document intentional interception context omission in HMR handler

Add a comment to the HMR rsc:update handler noting that interception
context is intentionally omitted, matching the existing documentation
pattern in the server action handler.

https://claude.ai/code/session_01EnvJuSwsZS9n862q7Veamo

* fix: prefetch cache test now exercises interception-context partitioning

The test was passing pre-computed cache keys as the rscUrl parameter to
storePrefetchResponse(), which internally calls createAppPayloadCacheKey
again. With the default interceptionContext=null the key passed through
unchanged, so the test only verified Map key uniqueness rather than the
actual partitioning logic. Pass raw RSC URLs with separate interception
context parameters instead.

Also add a comment clarifying that PendingNavigationCommit's top-level
interceptionContext/rootLayoutTreePath/routeId are convenience aliases
for the corresponding action fields.

https://claude.ai/code/session_01EnvJuSwsZS9n862q7Veamo

* fix: strip NUL bytes from interception context request header

Defensively remove \0 from the incoming X-Vinext-Interception-Context
header to prevent a malicious client from crafting cache keys that
contain the internal NUL separator.

https://claude.ai/code/session_01EnvJuSwsZS9n862q7Veamo

* fix: resolve rebase conflicts in slot preservation tests

After rebase onto upstream main, two fixes needed:
- Pass extraEntries as 4th arg to createResolvedElements (3rd is now
  interceptionContext)
- Add missing interceptionContext field to test action objects

https://claude.ai/code/session_01EnvJuSwsZS9n862q7Veamo

* test: update entry template snapshots for NUL-byte header sanitization

https://claude.ai/code/session_01EnvJuSwsZS9n862q7Veamo

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-11 17:28:31 +01:00
Nathan Nguyen ca0d542947 Fix parallel slot persistence and cache variants (#811)
* Fix parallel slot persistence and cache variants

* Address App Router review follow-ups

* Fix generated mounted-slot regex escaping

* Address review feedback on slot normalization and cache comments

Align generated entry's __normalizeMountedSlotsHeader regex with the
typed module in app-elements.ts (both now use /\s+/). Clarify the
HTML vs RSC cache asymmetry comment in stale regen path.

* Remove redundant .map(trim) and clarify regen slot context

split(/\s+/) never produces tokens with leading/trailing whitespace,
so .map(trim) was a no-op in both normalizeMountedSlotsHeader and its
generated counterpart. Also add a comment clarifying that background
regen intentionally inherits the triggering request's slot context.

* Clarify regen dedup and prefetch slot-mismatch tradeoffs

Add comments explaining that pathname-only regen dedup is intentional
(avoids concurrent regen storms across slot variants) and that
consumePrefetchResponse unconditionally removes the entry before the
slot-mismatch check (simplest correct behavior, prefetch is wasted on
mismatch).

* Document storePrefetchResponse slot-awareness gap

Add JSDoc note that storePrefetchResponse is slot-unaware: the
snapshot's mountedSlotsHeader comes from the response headers rather
than the caller, so consumePrefetchResponse may reject the entry on
slot context mismatch.
2026-04-10 15:29:33 +01:00
Divanshu Chauhan (divkix) ef4192db49 fix: cross-route client navigation hangs in Firefox (#652) (#690)
* fix: cross-route client navigation hangs in Firefox (#652)

Replace flushSync-based RSC tree rendering with a two-phase navigation
commit that uses startTransition for same-route navigations and
synchronous updates for cross-route navigations. This fixes the Firefox
hang where startTransition never commits when the entire component tree
is replaced, and also resolves the Suspense double-flash from #639.

Key changes:
- navigation.ts: ClientNavigationState on Symbol.for global for module
  instance safety, render snapshot context for hook consistency during
  transitions, RSC response snapshot/restore for visited cache, unified
  navigateClientSide() entry point, history suppression helpers
- app-browser-entry.ts: BrowserRoot component with useState-managed tree,
  NavigationCommitSignal that defers URL commit to useLayoutEffect,
  visited response cache with LRU eviction, navigation ID counter for
  stale navigation bailout, manual scroll restoration
- link.tsx: remove duplicated helpers, delegate to navigateClientSide
- form.tsx: delegate App Router GET navigation to navigateClientSide

Closes #652

* fix: detect React Flight Thenables in updateBrowserTree and apply params eagerly

createFromFetch() returns a Thenable (not instanceof Promise), so the
async branch was never taken. The raw unresolved Thenable was set as
React children, causing suspension without a Suspense boundary and
empty content after cross-route navigations.

- Duck-type the .then() check to handle both Promises and Thenables
- Replace stageClientParams with applyClientParams so useSyncExternalStore
  subscribers see correct params immediately
- Remove dead stageClientParams function and replaceClientParamsWithoutNotify import

Fixes useParams E2E failures in CI (hooks.spec.ts:161, hooks.spec.ts:180).

* fix: await createFromFetch before passing RSC payload to tree

The Flight Thenable from createFromFetch was passed unresolved to
renderNavigationPayload/updateBrowserTree. The .then() callback fired
unreliably across consecutive navigations, causing empty content.

Await createFromFetch in both navigation paths (cached and fresh) so
renderNavigationPayload always receives a resolved ReactNode. Add stale
navigation checks after the new await points.

The HMR handler and server action handler already awaited correctly.

* fix: preserve app router params across cached navigation

Preserve the X-Vinext-Params header when snapshotting prefetched and visited RSC responses so cached navigations keep dynamic params intact. Stage client params until the URL commit lands so useParams, history state, and redirect handling stay aligned during App Router transitions.

* fix: address review feedback on navigation caching and history management

- Remove double history push for RSC navigations: let the commit effect
  in navigateRsc own push/replace exclusively. Also fixes a hidden bug
  where the early push broke isSameRoute detection (always true),
  negating the Firefox cross-route hang fix.
- Enforce prefetch cache size limits in prefetchRscResponse() by
  extracting shared eviction logic from storePrefetchResponse().
- Add TTL check in consumePrefetchResponse() so expired snapshots are
  discarded instead of served as stale UI.
- Prevent navigationSnapshotActiveCount leak when async payloads reject
  in updateBrowserTree by adding error handlers that balance the
  activate/commit pairing.
- Move BrowserRoot setBrowserTreeState assignment from render to
  useLayoutEffect to avoid side effects under React Strict Mode.
- Make visited response cache true LRU (delete+set on hit) and add a
  30-minute upper bound for traversal cache hits to prevent arbitrarily
  stale back/forward content.

* fix(navigation): address PR review feedback for Firefox navigation fix

Fixes the following review issues from ask-bonk:

Major fixes:
- Fix prefetch cache eviction order to add entry first, then evict (prevents
  temporary overflow past MAX_PREFETCH_CACHE_SIZE)
- Add error handling in renderNavigationPayload to ensure
  navigationSnapshotActiveCount is decremented on synchronous errors,
  preventing counter leaks

Minor fixes:
- Add cross-reference comments between Pages Router and App Router scroll
  restoration handlers (navigation.ts and app-browser-entry.ts)
- Add JSDoc to getPathnameSnapshot/getSearchParamsSnapshot explaining cached
  behavior vs live window.location reads
- Add comment documenting server action navigation flow (doesn't use
  activateNavigationSnapshot because it stays on same URL)
- Add comment explaining Map iteration safety in resolveCommittedNavigations
- Use stripBasePath in isSameRoute comparison for robust basePath handling
- Explicitly pass undefined for historyUpdateMode in redirect chains with
  explanatory comment (prevents double URL push)

All 1094 tests pass.

* fix: prevent stale navigation bailout from leaking staged params

Addresses review feedback on PR #690:
- Move stageClientParams() to after final navId check in both cached and fresh paths
- Build navigationSnapshot from local params instead of latestClientParams
- Move storeVisitedResponseSnapshot after final stale check
- Add doc comment about history method patching behavior

This fixes a race where cancelled navigations could leak their staged params
into subsequent unrelated navigations when commitClientNavigationState()
was called later without clearing the pending state.

Test: Add E2E test for cancelled slow navigation param leak scenario

* fix: remove duplicate onRouterTransitionStart call and fix formatting

The refactor to delegate Link navigation to navigateClientSide() left a
duplicate notifyAppRouterTransitionStart() call in link.tsx, causing the
callback to fire twice per push navigation.

* fix(navigation): address code review feedback on Firefox cross-route navigation hang fix

Fixes four edge cases identified in code review:

1. NavigationCommitSignal cleanup now resolves pending promises on unmount
   to prevent hanging callers if React unmounts the component (e.g., error
   boundary triggers full-page nav)

2. Added dev-mode warning for navigationSnapshotActiveCount going to 0 before
   decrement to catch activate/commit pairing bugs early

3. Changed prefetch eviction from if to while loop to match visited cache
   pattern and prevent temporary cache overflow during rapid prefetch calls

4. Moved storeVisitedResponseSnapshot below final navId check to avoid storing
   stale cache entries from superseded navigations

Also added cross-reference comments between the two popstate handlers in
app-browser-entry.ts and navigation.ts for future maintainers.

* fix(navigation): resolve infinite recursion in getServerSearchParamsSnapshot

The function getServerSearchParamsSnapshot had infinite recursion when
called on the server - it would call itself infinitely when
getClientNavigationState() returned null.

Fixed by implementing proper server context handling:
- Use _getServerContext() to access server navigation context
- Cache ReadonlyURLSearchParams wrapper using symbol-based caching
- Return cached empty instance when no context available
- Follows established patterns from getServerParamsSnapshot and
  getSearchParamsSnapshot

Fixes CI failures in PR #690 where 18 tests were failing with
"Maximum call stack size exceeded" errors during SSR.

* style(navigation): fix lint errors from stricter oxlint rules

Convert interface declarations to type aliases per consistent-type-definitions rule:
- CachedRscResponse, PrefetchCacheEntry, ClientNavigationRenderSnapshot
- VisitedResponseCacheEntry in app-browser-entry.ts

Add oxlint-disable block comments for react-hooks/rules-of-hooks violations:
- useChildSegments, useClientNavigationRenderSnapshot, usePathname
- useSearchParams, useParams

The original conditional hook pattern (if isServer return early) is intentional
and required for SSR/client duality. Server components must not call client-only
React hooks. Block-level disable comments suppress the false positives while
maintaining the correct runtime behavior.

* fix(navigation): address review feedback on Firefox cross-route navigation fix

- Fix isHashOnlyChange to strip basePath for consistent comparison with isSameRoute
- Add snapshotPending guard to prevent double-decrement in catch block
- Document storePrefetchResponse API contract (callers manage prefetchedUrls)
- Remove duplicate prefetched.add from _appRouter.prefetch (ownership now in prefetchRscResponse)
- Add invariant comment to drainPrePaintEffects explaining activate/commit pairing
- Improve test error handling in cancelled navigation test with debug logging

* fix: address PR review — prefetch dedup, comments, and test robustness

- Add dedup guard to router.prefetch() matching link.tsx pattern
  (check/add prefetchedUrls before calling prefetchRscResponse)
- Fix incorrect comments claiming prefetchRscResponse manages prefetchedUrls
- Add doc comment to storePrefetchResponse noting caller owns URL tracking
- Document module-level state assumption in app-browser-entry.ts
- Add inline comments in drainPrePaintEffects for winning/superseded pairing
- Add element visibility assertion in E2E cancelled-navigation test

* chore: review changes implemented

* Address ask-bonk review feedback: remove dead code and add defensive comments

- Remove vestigial response field from PrefetchCacheEntry (never read by consumePrefetchResponse)
- Add defensive comment for _snapshotPending guard brittleness
- Document isSameRoute race condition during rapid navigations
- Update test helper to use snapshot instead of response

All changes are non-behavioral documentation/clarity improvements.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix: prevent double-decrement of navigationSnapshotActiveCount on renderNavigationPayload throw

When updateBrowserTree throws synchronously inside renderNavigationPayload,
the inner catch already calls commitClientNavigationState() and re-throws.
Previously the outer navigateRsc catch saw _snapshotPending === true and
decremented again, leaving the counter off by 1 for concurrent navigations.

Fix by wrapping each renderNavigationPayload call in try-finally that always
clears _snapshotPending, so the outer catch guard correctly skips the
already-committed case.

* docs: document latestClientParams staging invariant in stageClientParams

Per bonk review: stageClientParams diverges latestClientParams from
ClientNavigationState.clientParams between staging and commit. Server
action snapshots read latestClientParams, so add a comment clarifying
this narrow race is acceptable since the commit effect fires synchronously
in the same React commit phase.

* fix: address two blocking concerns from bonk review

1. Guard outer catch against hard-navigating to stale URL when superseded:
   - Hoist navId above the try block so it is accessible in the catch
   - Add 'if (navId !== activeNavigationId) return' before window.location.href
   - Move navId check before createFromFetch in cached route path to avoid
     wasted parse work and the same stale-URL risk on throw

2. Guard handleAsyncError in updateBrowserTree against counter corruption:
   - Add snapshotActivated parameter (default false) to updateBrowserTree
   - Only call commitClientNavigationState() when snapshotActivated is true
   - renderNavigationPayload passes true; server actions and HMR pass false
     (they never call activateNavigationSnapshot so must not decrement)
   - Update comments on server action and HMR call sites to document why

Also add a note on restoreRscResponse that reconstructed Response.url is
always empty string — the Response constructor does not accept a url option.

* fix: tighten cached-route stale-nav guards and fix stale comment

- Add navId check between cachedNavigationSnapshot creation and
  createFromFetch in the cached route path, so superseded navigations
  bail out before the async parse rather than only after
- Fix stale line reference in stageClientParams comment (533 -> 544/558)
- Document slow-route fixture delay / click timeout coupling in E2E test
  so future changes to the fixture delay don't silently break the test

* fix: stage params after _snapshotPending=true in both nav paths, fix stale comment

Move stageClientParams() to after _snapshotPending = true in both the
cached-route path and the non-cached path. This makes the intent clearer:
params are staged as part of an in-flight snapshot, not as a standalone
side-effect before the snapshot flag is set.

If renderNavigationPayload throws synchronously, its inner catch calls
commitClientNavigationState() which flushes pendingClientParams — committing
params for a route that never rendered. The hard-nav fallback in the outer
catch resets everything, so this was self-correcting, but reordering makes
the relationship explicit and guards the intent.

Also replace the stale "lines 544/558" reference in the stageClientParams
comment with the function name (registerServerActionCallback) so it doesn't
rot as the file evolves.

* fix: expand module-singleton comment, remove redundant stale-nav check, document BASE URL

- Expand the module-level state comment to call out Map fragmentation as
  the most severe consequence of multiple instances: pendingNavigationCommits
  and pendingNavigationPrePaintEffects would split across instances, causing
  drainPrePaintEffects to miss effects queued by the other instance and
  permanently leaking navigationSnapshotActiveCount.

- Remove the redundant navId !== activeNavigationId check between
  createClientNavigationRenderSnapshot (synchronous) and createFromFetch
  (async). The pre-check before createClientNavigationRenderSnapshot is
  sufficient; the meaningful post-check is after the await of createFromFetch.
  Added a comment noting the function is synchronous so no recheck is needed.

- Add a comment to BASE in navigation-regressions.spec.ts explaining it
  follows the established repo convention (same pattern in navigation.spec.ts,
  server-client-only.spec.ts, after.spec.ts, etc.).

* docs: annotate stageClientParams throw path in both nav paths

If stageClientParams throws (e.g. a param object with a throwing getter),
_snapshotPending is true but renderNavigationPayload was never called.
The outer catch then calls commitClientNavigationState() which decrements
a counter never incremented by activateNavigationSnapshot() — safe due to
the > 0 guard — but pendingClientParams and hasPendingNavigationUpdate
could persist until the hard-nav fallback resets JS state.

Add a brief NB comment on both stageClientParams call sites noting that
the outer catch hard-navigates, which resets all JS state, making this
benign in practice.

* fix: store visited response snapshot only after successful render

Move storeVisitedResponseSnapshot to after the renderNavigationPayload
try-finally block so we only cache RSC responses from navigations that
actually rendered successfully. Previously, the cache write happened
before renderNavigationPayload — if it threw, a future back/forward
navigation could replay a snapshot from a navigation that never rendered.

The hard-nav fallback in the outer catch made this self-correcting in
practice, but caching only on success is the correct invariant.

Also expand the cached-path navId comment to acknowledge the style
asymmetry vs the non-cached path, explaining why no extra check is
needed between createClientNavigationRenderSnapshot (synchronous) and
createFromFetch.

---------

Co-authored-by: Nathan Nguyen <146415969+NathanDrake2406@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: James <james@eli.cx>
2026-04-01 22:12:52 +01:00
Stephen Zhou c17d6941be chore: migrate to vite plus (#535)
* chore: migrate to vite plus

* Disable typeAware and typeCheck

* Update CI

* Fix CI

* Fix test

* Clean

* Run test with vp

* Try revert

* react: false In test

* Fix test

* Revert "Try revert"

This reverts commit 009da10473.

* Update

* Update

* Try revert ci changes

* revert

* Run vp migrate

* Disable typeAware and typeCheck for now

* Better resolve for test

* Use vp dev instead of vite

* Update expect

* Fix NormalizeManifestModuleId

* Try increase timeout

* Update to use vp

* Try new check

* Bring back npx vp

* Migrate CI

* Make next-intl resolvable

* Update

* Update

* Update
2026-03-15 10:50:13 +00:00
Divanshu Chauhan (divkix) 1c3401e245 perf: TTL-based eviction sweep for prefetch cache (#434)
* perf: add TTL-based eviction sweep for prefetch cache

Before this change, expired prefetch cache entries were only cleaned on
individual access or displaced by FIFO when at the 50-entry cap. On
link-heavy pages, expired entries wasted slots and caused premature
eviction of still-valid entries.

Now storePrefetchResponse() sweeps all expired entries before falling
back to FIFO eviction, so fresh entries survive longer under pressure.

* fix: sync prefetched URL set on cache eviction

Evicted entries were not removed from getPrefetchedUrls(), causing
Link's prefetched.has() check to return true for stale URLs and skip
re-prefetch. Clean up the prefetched set in both sweep and FIFO paths.

Also derive test counts from MAX_PREFETCH_CACHE_SIZE constant and
assert prefetched URL set consistency after eviction.

* fix: address review comments on prefetch cache TTL sweep

- Hoist Date.now() to top of storePrefetchResponse so sweep and new entry timestamp use the same instant
- Export MAX_PREFETCH_CACHE_SIZE in next-shims.d.ts to match runtime export
- Use fixed arbitrary time values in tests instead of real wall clock
- Clarify why prefetchedUrls count excludes the new entry in the below-capacity test

---------

Co-authored-by: James <james@eli.cx>
2026-03-11 12:39:49 +00:00