Skip to content

feat(instrumentation): pass a router transition start event with instrumentationClientRouterTransitionEvents - #4910

Draft
james-elicx wants to merge 10 commits into
fix/instrumentation-client-inject-hooksfrom
fix/instrumentation-client-transition-events
Draft

james-elicx wants to merge 10 commits into
fix/instrumentation-client-inject-hooksfrom
fix/instrumentation-client-transition-events

Conversation

@james-elicx

@james-elicx james-elicx commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Stacked on #4909.

Found by the Next.js v16.4.6 deploy suite (run 45649241516): the router transition start context group of test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts (5 tests) failed.

What Next.js does

With experimental.instrumentationClientRouterTransitionEvents, onRouterTransitionStart(url, type, event) receives a start event as its third argument instead of null. Ref: packages/next/src/client/components/router-transition.ts and client/router-transition-types.ts.

  • id: ${Date.now().toString(36)}-${counter.toString(36)}.
  • timestamp: performance.timeOrigin + performance.now().
  • fromRoutes: source route patterns of the tree being left, from getActiveRoutePaths.
    • The primary (children) route comes first, then each parallel slot, sorted.
    • Route groups are omitted.
    • A slot showing its default reports @slot/default.
    • An intercepted slot reports the intercepting page, e.g. /gallery/@modal/(.)photos/[id].
  • prefetchIntent: the Link's prop (prefetch={false} → "none", true → "full", otherwise "auto"). router.push/replace and back/forward send null.

The flag reaches the client as process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS, a raw boolean (build/define-env.ts). Building the event is inside the per-hook try, so a failure is logged as An instrumentation-client router transition hook failed.

Fix

  • Config: experimental.instrumentationClientRouterTransitionEvents is resolved (default false) and defined for the client as the same raw boolean. Without the flag, the event path drops out of the bundle.
  • State module: notifyAppRouterTransitionStart (client/instrumentation-client-state.ts) builds the event inside the try. fromRoutes comes from a resolver that the App Router browser entry registers only when the flag is on.
  • fromRoutes resolver: the new server/app-browser-transition-routes.ts builds fromRoutes from the committed tree, as Next.js walks its committed router state.
    • Primary route: taken from the committed payload's sourcePage (the source segments vinext already sends, as Next.js does for __internal_src_page). A URL that matched no route reports /_not-found. A sibling intercept reports its own page. When the deepest children slot shows its default (a synthetic parallel sub-route), it reports <owner>/default. A whole intercepting route reports the owner's default plus the intercepted slot.
    • Slots: each slot binding resolves through its own interceptionId, so an intercepted slot that a merge kept still reports the intercepting page. Active slot sub-pages use the manifest slot binding's raw routeSegments.
    • Manifest timing: the route manifest still loads alongside hydration, not before it (App Router: the browser entry inlines the full RouteManifest segment graph on every page, including maps the client never reads #3957), and the primary route doesn't need it.
  • Manifest field: the browser manifest gains one optional field per interception, sourcePagePath: the intercepting page's directory with route groups removed, built from the existing sourcePageSegments.
  • Link: <Link> passes its prefetch prop as prefetchIntent through navigateClientSide. Other callers pass null.

This is App Router only, as in Next.js. The server and worker entries are unaffected.

Regression tests

  • tests/e2e/app-router/instrumentation-client-transition-events.spec.ts ports the 5 Next.js tests and adds a back/forward case. It runs in app-router (dev) and app-router-isr-prod. It uses new pages under tests/fixtures/app-basic/app/instrumentation-client/transition-events, a copy of the Next.js fixture. app-basic now enables the flag, following the gestureTransition precedent, so the fix(instrumentation): read instrumentationClientInject hooks per transition and isolate their errors #4909 inject spec checks that the injected hook receives the event.
  • tests/app-browser-transition-routes.test.ts unit-tests the resolver against the scanned fixture: patterns, catch-alls, groups, slots, the default slot, interception (including a merged intercepted slot), route misses, sibling and whole intercepts (including an active sibling slot that a merge kept), and a synthetic sub-route's children default.
  • tests/instrumentation.test.ts covers the event shape and the logged resolver failure. tests/next-config.test.ts covers the flag.

With the pre-fix source (git restore --source=<#4909 head> -- packages/vinext/src, then rebuild), the 6 e2e tests fail in dev. With the fix they pass in dev and prod.

Targeted vp test run passes for these files:

  • tests/app-browser-transition-routes.test.ts
  • tests/instrumentation.test.ts
  • tests/app-route-graph.test.ts
  • tests/entry-templates.test.ts
  • tests/browser-route-manifest.test.ts
  • tests/next-config.test.ts

vp check is clean.

Deploy suite (local, ds-run.sh)

Declined

  • In a hybrid app, an App Router <Link> to a Pages- or document-owned URL navigates the document without calling onRouterTransitionStart, where Next.js calls it first. The same is true on main for the legacy hook, so it's a separate, pre-existing gap.
  • Before the route manifest chunk arrives, a first transition reports an active slot as its slot directory, not the slot sub-page or intercepting page. Holding hydration for the manifest would undo App Router: the browser entry inlines the full RouteManifest segment graph on every page, including maps the client never reads #3957 and broke route-manifest-chunk.spec.ts.
  • A synthetic parallel sub-route whose children fall through to a sibling catch-all reports the sub-route's path, not the catch-all's. That route is an existing documented limitation in routing/app-route-graph.ts (the catch-all already gets empty params), and the router state doesn't record which catch-all rendered.

Performance

Without the flag, nothing runs on the navigation path, because the event and resolver code is behind the compile-time define. The per-interception sourcePagePath adds a few bytes to the lazily loaded route-manifest chunk. CI's paired perf comparison covers build time and dev cold start.

@james-elicx
james-elicx added this pull request to stack #4911 November 26, 2026 06:26
@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 44cb38c334e63f3473c6f600ffebbccd70a3bde9 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@vinext/cloudflare

npm i https://pkg.pr.new/@vinext/cloudflare@4910

create-vinext-app

npm i https://pkg.pr.new/create-vinext-app@4910

@vinext/types

npm i https://pkg.pr.new/@vinext/types@4910

vinext

npm i https://pkg.pr.new/vinext@4910

@cloudflare/workers-response-store

npm i https://pkg.pr.new/@cloudflare/workers-response-store@4910

commit: 507e952

if (process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS) {
setRouterTransitionFromRoutesResolver(() =>
hasBrowserRouterState()
? resolveRouterTransitionFromRoutes(getBrowserRouterState(), getBrowserRouteManifest())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The resolver can run before the manifest exists. main() only starts loadNavigationRuntimeRouteManifest() fire-and-forget, while notifyAppRouterTransitionStart() runs before navigation awaits that load. On a first interaction under a slow manifest-chunk fetch, this passes null here and resolveRouteSourcePath falls back to concrete URLs (for example /blog/hello instead of /blog/[slug]) and loses slot/interception source paths. When this feature is enabled, make the manifest available before transition hooks can fire.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e4783fc: with instrumentationClientRouterTransitionEvents on, main() now awaits the manifest load it already starts before it hydrates (the fetch still overlaps reading the initial RSC stream). Nothing can start a client transition before hydration (Link, router hooks and popstate handling are wired by bootstrapHydration), so the resolver always sees the manifest. The primary route no longer reads the manifest at all (see the next thread). Without the flag, the await is dropped at build time and startup is unchanged.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update, 043cf1b: I reverted the pre-hydration manifest await. With the flag on in app-basic it put the manifest back on the hydration path, which #3957 deliberately removed, and route-manifest-chunk.spec.ts ("an intercepted navigation started before the route manifest loads waits for it") failed in app-router-isr-prod. I won't change hydration timing for an experimental instrumentation field.

The rest of this round's fix makes the remaining gap small. The primary route now comes from the committed payload's sourcePage and never reads the manifest. Only a transition that starts before the manifest chunk arrives (a first interaction under a slow chunk fetch) reports an active slot as its slot directory, not the slot sub-page or intercepting page. That's documented on the resolver and under Known limitations in the PR body.

? resolveInterceptionSourcePagePath(interception, null, routeManifest)
: null;

const primaryRoutePath = routePathFromId(interception?.sourceRouteId ?? state.routeId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This derives the primary route from URL identity rather than the committed rendered tree. That is wrong for states this router already represents separately: a route miss has sourcePage === null and must report /_not-found, while sibling/whole interceptions deliberately commit with interception: null but retain an interception-marker sourcePage; they currently report the requested target pattern instead. Include the committed elements/source-page metadata in this resolver and derive the primary source path from it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e4783fc: the primary route now comes from the committed payload's sourcePage metadata (the source segments Next.js carries in its router state), not from the URL. A route miss (sourcePage === null) reports /_not-found. A sibling intercept reports its own page (/gallery/(.)photos/[id]) whether or not interception is set. A whole intercepting route (wholeInterceptionSource) reports the slot owner's default as the primary route, plus the intercepted slot, which matches Next's tree (children __DEFAULT__, slot = intercepting page). Unit tests cover all three, and each one fails on the previous resolver.

const slot = AppElementsWire.parseElementKey(binding.slotId);
if (
slot?.kind !== "slot" ||
slot.name === "children" ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skipping every children binding loses the actual primary leaf for synthetic parallel routes. For example, /nested/subroute can have a synthetic children binding in default state, so Next’s tree traversal reports /nested/default; this code instead derives /nested/subroute from state.routeId. Active children can similarly fall through to a catch-all source. Use the children binding to resolve or override the primary route rather than discarding it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e4783fc: the deepest children binding above the committed source page now decides the primary route. In default/unmatched state it reports <owner>/default (/dashboard/default for a synthetic /dashboard/settings), as Next's __DEFAULT__ segment does. When it's active, the source page is reported.

Declining the catch-all sub-case. A synthetic sub-route whose children fall through to a sibling catch-all is an existing documented limitation of that route (see the "Known limitation" note in routing/app-route-graph.ts: the catch-all already gets empty params). Neither the payload nor the router state records which catch-all rendered, so reporting it would need new route-graph wiring for that limitation, which is outside this PR.

) {
continue;
}
if (interception !== null && interception.slotId === binding.slotId) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An intercepted slot is not necessarily represented by the current global state.interception. mergeSlotBindings can preserve a previously rendered binding, including its interceptionId, while the next ordinary payload sets the global interception to null. The intercepted page remains visible, but this condition then falls through to the ordinary/default slot path. Resolve an interception whenever binding.interceptionId identifies one, rather than requiring the transient global proof.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e4783fc: each slot binding now resolves through its own interceptionId first, whatever the latest state.interception says. The target-URL fallback still applies only when the latest interception names that slot. Covered by the new "merge keeps the intercepted slot" assertion (binding with interceptionId, interception: null), which fails on the previous resolver.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 4 findings.

Posted 4 inline warnings in review #6069539049.

github run

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Performance benchmarks

Compared 507e952 against base 56f6494 using alternating same-runner rounds. Next.js was unchanged and skipped.

1 improved · 0 regressed · 6 within ±1.5%

Scenario Framework Baseline Current Change
Client bundle size (gzip) vinext 157.3 KB 156.9 KB ⚫ -0.3%
Client entry size (gzip) vinext 145.5 KB 145.1 KB ⚫ -0.3%
Dev server cold start vinext 1.76 s 1.74 s ⚫ -0.9%
Dev server cold start (large Pages Router app) vinext 12.84 s 12.74 s ⚫ -0.8%
Production build time vinext 2.05 s 2.01 s 🟢 -1.9%
RSC entry closure size (gzip) vinext 150.6 KB 150.6 KB ⚫ +0.0%
Server bundle size (gzip) vinext 262.9 KB 262.9 KB ⚫ +0.0%

View detailed results and traces

🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head

@github-actions

Copy link
Copy Markdown
Contributor
Example Preview Production Original
app-router-cloudflare preview production
pages-router-cloudflare preview production
app-router-playground preview production original
realworld-api-rest preview production
nextra-docs-template preview production
benchmarks preview production
hackernews preview production original
response-store-demo preview production
workers-cache preview production
kv preview production
static-assets-cache preview production
static-assets-pages preview production
static-assets-pages-i18n preview production
static-export preview production
web preview production

@james-elicx
james-elicx force-pushed the fix/instrumentation-client-transition-events branch from 44cb38c to 0ae44cb Compare November 26, 2026 06:37
@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head e4783fc5d1772ab1b98c507ce6225b6f0541a411 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

fromRoutes: resolveRouterTransitionFromRoutes(),
prefetchIntent,
};
hooks.onRouterTransitionStart(href, navigationType, event);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With instrumentationClientInject, this calls the generated aggregate hook once with one mutable event object, and instrumentation-client-inject.ts then forwards that same object to every injected/user hook. Next.js v16.4.6 constructs the event object inside each callHooks invocation, so each module receives a fresh object and fromRoutes array. An early injected hook can currently mutate either and corrupt what later hooks observe. Rebuild or clone the event per generated fan-out invocation, including fromRoutes, and cover mutation isolation.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5e5007d: the generated fan-out now passes each hook its own copy of the event, with its own fromRoutes array ({ ...event, fromRoutes: [...event.fromRoutes] }), so a mutation in one inject never reaches a later hook. That matches Next.js building the event inside each callHooks invocation. A null event (flag off) passes through unchanged. New test: "gives each hook its own start event". An inject mutates id and fromRoutes, and the user hook still sees the original values; the test fails on the previous generator.

"transition",
// Next.js reports the Link's prefetch prop as the transition's
// prefetch intent (client/app-dir/link.tsx).
prefetchProp === false ? "none" : prefetchProp === true ? "full" : "auto",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Link intent reaches navigateClientSide only after the hybrid ownership branch above. An App Router Link to a Pages/document-owned local URL exits through location.assign/replace at lines 1688-1698, so it emits no transition event at all. Next.js app-dir Link sends every local URL through navigator.navigate, whose queue calls startRouterTransition before the reducer decides on a hard navigation. Notify before this direct document navigation (with this Link intent), and cover an App-to-Pages Link in a hybrid app.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining for this PR. The early document navigation for a Pages/document-owned URL in a hybrid app skips onRouterTransitionStart on main too, including the legacy two-argument hook without the flag. It's a pre-existing gap in when the hook fires, not in the start event this PR adds. I'll report it as a follow-up.

const wholeInterceptedSlot =
metadata.wholeInterceptionSource === null
? null
: (state.slotBindings.find((binding) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Selecting the first active non-children binding does not identify the intercepted slot. A whole-intercept payload may retain another mounted active slot; bindings are normalized by slotId, so an active @aside can precede the intercepted @modal. This then reports the intercepting source under @aside and treats @modal as an ordinary route. Resolve the slot from interception/source metadata (or preserve its identity explicitly) and add a case with a retained active sibling slot.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5e5007d: every active, non-children slot whose owner prefixes the source page is now a candidate. The resolver picks the one whose computed @slot/... path matches one of the manifest's interceptions for that slot, and falls back to the first candidate only when nothing matches (or before the manifest loads). New assertion: a kept active @aside sorts before @modal, and the result is still ["/gallery/default", "/gallery/@aside", "/gallery/@modal/(.)photos/[id]"]. It fails on the previous resolver.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Since last review: 4 resolved, 0 still open, 3 new.

Posted 3 inline warnings in review #6069737446.

github run

@james-elicx
james-elicx force-pushed the fix/instrumentation-client-transition-events branch from e4783fc to 3938247 Compare November 26, 2026 06:58
@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 043cf1b7273f1893b306a1f75cbab2b20a9ce170 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 5e5007d47efb1557b2debbc15d30f13b76455a41 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

}
const activeRoutePath = routePathFromId(binding.activeRouteId);
const activeRoute =
activeRoutePath === null ? null : matchManifestRoute(activeRoutePath, routeManifest);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

activeRouteId for ordinary slots is already the manifest route ID: createAppPageSlotBindings builds it from encodeRouteId(options.routePath, null), where callers pass the route pattern. Reinterpreting that pattern as an href can select a different sibling route. For example, an active catch-all ID such as route:/shop/:slug+ is a one-segment URL to the trie, so a sibling /shop/:id wins and this then reads the wrong slot binding (reporting the wrong/default fromRoutes path). Look up segmentGraph.routes.get(binding.activeRouteId) first, and reserve URL matching for IDs that are not manifest IDs, such as concrete interception targets.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e2d69d3: an active slot's route is now looked up directly by segmentGraph.routes.get(binding.activeRouteId). Ordinary slots carry route:<pattern>, since createAppPageSlotBindings gets route.pattern as routePath. Only an id that isn't a manifest key falls back to URL matching. New test: "reads an active slot's route by its manifest id, not as a URL" adds a sibling /shop/:id next to /shop/[[...slug]] with a @panel slot. It reports /shop/@panel/[[...slug]] and fails on the previous resolver (which reported the sibling's default).

The two findings listed as still open at 043cf1b were addressed in 5e5007d: per-hook event copies and manifest-based whole-intercept slot selection. The hybrid App→Pages Link case was declined there as a pre-existing gap.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Since last review: 1 resolved, 2 still open, 1 new.

Posted 1 new inline warning. The two existing warnings remain at exact head 043cf1b.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head e2d69d3d15eb9cf7d975c99f8938d47a558a85ff without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@james-elicx
james-elicx force-pushed the fix/instrumentation-client-transition-events branch from e2d69d3 to 689009e Compare November 26, 2026 07:15
@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 3 findings.

  • Warning packages/vinext/src/server/app-browser-transition-routes.ts:128: Whole interceptions nested through multiple parallel slots reconstruct only one @slot, producing incorrect fromRoutes. Use the manifest’s complete sourcePagePath.
  • Warning packages/vinext/src/client/instrumentation-client-inject.ts:99: Fan-out hooks reuse the first event timestamp. Next.js samples the timestamp independently for each hook invocation.
  • Warning packages/vinext/src/server/app-browser-entry.ts:27: The static resolver import is still fetched and evaluated in flag-disabled Vite dev sessions. Load it only inside the feature-gated path.

github run

@james-elicx
james-elicx force-pushed the fix/instrumentation-client-transition-events branch from 8a991c4 to c9c908b Compare November 26, 2026 07:24
@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head c9c908bbb82f8cbded1e085e5bd789b8c1e622ca without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@james-elicx

Copy link
Copy Markdown
Member Author

Thanks. Fixed in f8a2f92:

  • Nested whole interception (app-browser-transition-routes.ts): when the source page matches the slot's manifest interception, the whole-intercepted slot now reports that interception's sourcePagePath. The source page drops every @slot segment, so the comparison drops them too. That path names every slot between the intercepting route and its page, for example /@modal/(.)test-nested/@sidebar from the checked-in interception-dyn-seg fixture. The one-slot reconstruction is now only the fallback for when the manifest hasn't loaded yet. A new test covers it and fails on the previous head.
  • Per-hook timestamp (instrumentation-client-inject.ts): each hook's event copy now takes its own performance.timeOrigin + performance.now(), the same as Next's timestamp() in callHooks. The test stubs performance.now and checks that each hook gets its own value.

Declined:

  • Static resolver import in flag-off dev: production builds without the flag already drop the module, because the gated branch is dead code. In dev, the cost is one small module whose imports the browser entry already loads. A dynamic import would make the registration async. A transition that starts before it resolves would then report empty fromRoutes, and builds with the flag on would pay an extra chunk request. That trade isn't worth it for a dev-only fetch.

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head f8a2f92780ddd8e3afd5a9241af89075f24fd72d without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Since last review: 0 resolved, 3 still open, 0 new.

  • Warning app-browser-transition-routes.ts:125: Nested whole interceptions lose inner @slot segments.
  • Warning instrumentation-client-inject.ts:114: Fan-out hooks reuse one timestamp instead of sampling per hook.
  • Warning app-browser-entry.ts:27: The resolver loads in flag-disabled Vite dev sessions.

Head c9c908b only changes test typing, so none of these findings were affected.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

Rebased onto #4909's 56f64947c1, where the fan-out now calls each hook with Reflect.apply. The event copy is unchanged. Head is now 538b466345; the earlier /bigbonk trigger was cancelled before it ran.

@james-elicx
james-elicx force-pushed the fix/instrumentation-client-transition-events branch from f8a2f92 to 538b466 Compare November 26, 2026 07:35
@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 538b466345b6f3442dc5ba7a3626b9e13d4dc510 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

" Reflect.apply(hook, hooks, [",
" url,",
" type,",
" event == null",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This leaves the rich-event marker in flag-disabled bundles whenever instrumentationClientInject generates this aggregate hook. The exported function can receive an arbitrary event, so the bundler cannot prove this branch unreachable from the caller’s define and fromRoutes remains in the client chunk. Next.js explicitly tests that no client chunk contains fromRoutes when the flag is off (test/production/app-dir/instrumentation-client-dce/instrumentation-client-dce.test.ts). Gate this generated cloning branch with __NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS (or generate flag-specific source) so the payload is actually dead-code-eliminated.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 117fad3. The generated event copy now checks process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS, which vinext defines as a raw boolean. With the flag off, the conditional folds to event and the copy (fromRoutes) drops out. New test, ported from Next's instrumentation-client-dce: it minifies the generated module with the define applied and checks that fromRoutes is present with the flag on and absent with it off. It fails on the previous head. The dev e2e (instrumentation-client-transition-events.spec.ts, flag on) still passes.

}

slots.sort((left, right) => left.localeCompare(right));
return [primary, ...slots];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This always invents and prepends a primary route, but supported layout-only routes can have only named parallel branches and no children leaf. For example, the existing /parallel-nested/home fixture has no page.tsx; Next.js getActiveRoutePaths walks its @parallelB leaf only, while this returns an extra /parallel-nested/home before /parallel-nested/home/@parallelB/default. Use the committed route/manifest pageId plus the absence of a children binding to make the primary entry optional, and cover a layout-only slot route.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 117fad3 for the route Next actually renders, /parallel-nested/home/nested. Next 16.4 turns explicitParallelRouteChildren on by default, so a layout composed only of named slots gets no children branch. vinext records that as an unmatched synthetic children binding, which now omits the primary entry: the result is ["/parallel-nested/home/@parallelB/nested"]. The new test uses the checked-in parallel-nested fixture's manifest and fails on the previous head.

I'm not covering bare /parallel-nested/home. In Next it isn't a route, because a slot's default.tsx creates no app path, so there is no Next value for fromRoutes to match. vinext serving that URL at all is a separate, pre-existing routing difference, outside this PR.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 2 findings.

Posted 2 inline warnings in review #6070198948.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 117fad3a0925e9a328e277d11e03bd6df131b98c without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

// route reports only its slots (Next.js explicitParallelRouteChildren).
primary =
children === null || children.binding.state === "active"
? joinSourcePath(sourceSegments)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a slot-only navigation preserves an existing active children branch, this uses the latest payload’s sourcePage rather than the active children binding. For example, the existing /parallel-layouts/settings → /parallel-layouts/modal flow preserves the settings children branch (tests/e2e/app-router/advanced.spec.ts:137-147), while the merged metadata comes from the modal payload, so the next transition reports /parallel-layouts/modal instead of the still-rendered /parallel-layouts/settings. Resolve the active primary path from children.binding.activeRouteId and the manifest, as the named-slot path does.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 99f24ba. When the deepest children binding is active and names a different route from the latest payload's routeId (the merge kept the previous binding), the primary entry now comes from that binding's route id, converted to Next's source form with patternToNextFormat. Otherwise it still uses the committed source page. I checked this in the dev app: after /parallel-layouts/settings → /parallel-layouts/modal, the next transition now reports ["/parallel-layouts/settings", "/parallel-layouts/@bar/modal", "/parallel-layouts/@foo/default"] instead of /parallel-layouts/modal. New unit test: "reports the children route a slot-only navigation kept". It fails on the previous head.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Since last review: 2 resolved, 0 still open, 1 new.

Posted 1 inline warning.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 99f24bacc6619f2ddc98be01b34edd54da3e9141 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

: null;
primary =
childrenRoutePath !== null
? patternToNextFormat(childrenRoutePath)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still returns a concrete URL for a preserved dynamic children branch. The RSC entry calls buildPageElements(..., cleanPathname, ...), and createAppPageSlotBindings stores that render identity in activeRouteId, so a preserved /members/[id] branch carries route:/members/7; patternToNextFormat('/members/7') remains /members/7 instead of Next's /members/[id]. Resolve this ID through routeManifest (the same direct-ID-then-URL-match path used by resolveSlotSourcePath) and derive the source pattern from the matched route. The new test masks this by supplying the pattern-shaped route:/blog/:slug rather than a concrete dynamic ID.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 507e952. The kept children binding's activeRouteId now goes through the same manifest lookup as named slots (resolveManifestRoute): by id first, then by matching the concrete URL. The primary entry is derived from the matched route's patternParts, so a kept route:/members/7 reports /members/[id]. If the manifest hasn't loaded, it falls back to the committed source page. The test now uses a concrete id (route:/blog/hello → /blog/[slug]) and fails on the previous head. I also corrected the comment in resolveSlotSourcePath that said active route ids are pattern-shaped.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Since last review: 0 resolved, 1 still open, 0 new.

Posted 1 inline warning on preserved dynamic child routes.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 507e9521dc9586c2a8997a616ebbac730d686898 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

prefetchIntent: RouterTransitionPrefetchIntent | null = null,
): void {
const hooks = getClientInstrumentationHooks();
if (typeof hooks?.onRouterTransitionStart !== "function") return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With instrumentationClientInject, this guard sees the generated aggregate function even when none of the injected/user modules currently exports a hook. Next.js v16.4.6 checks the raw modules with .some(...) before incrementing nextTransitionId or resolving fromRoutes. Consequently, transitions before a late CommonJS hook is installed consume IDs (and can run/fail the resolver) that Next skips, so the first event that hook observes can be ...-2 instead of ...-1. Give the aggregate a live has-hook probe or defer rich-event creation into its fan-out.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Since last review: 1 resolved, 0 still open, 1 new.

Posted 1 inline warning.

github run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant