Unverified Commit 8a4920c1 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: clarify first-party Skills workflows (#96495)

## Summary

- clarify how runtime foundations, interactive workflows, and unattended
loops fit into the AI agents and Instant Navigation guides
- harden the Cache Components and Partial Prefetching Skills around
capability checks, trustworthy `instant()` tests, route scope, and
real-app verification failures
- add migration-guide comments to temporary Partial Prefetching route
config and update `remove-partial-prefetch` to remove only generated
comments while preserving runtime-prefetch TODOs and user comments

This keeps the experimental Partial Prefetching optimizer in #96471
separate.

## Testing

- `pnpm --filter @next/codemod build`
- `pnpm --filter @next/codemod test --
transforms/__tests__/remove-partial-prefetch.test.js --runInBand`
parent 4344b83a
...@@ -150,15 +150,23 @@ Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic ...@@ -150,15 +150,23 @@ Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
In `next dev` the stack frame resolves to your source, in both the dev overlay and the terminal. A production build minifies server code, so when the build error alone isn't enough, [`next build --debug-prerender`](/docs/app/guides/building#debugging-build-errors) turns on server source maps and continues past the first failure. In `next dev` the stack frame resolves to your source, in both the dev overlay and the terminal. A production build minifies server code, so when the build error alone isn't enough, [`next build --debug-prerender`](/docs/app/guides/building#debugging-build-errors) turns on server source maps and continues past the first failure.
The `Learn more` link resolves to a per-error page under [`/docs/messages`](https://nextjs.org/docs/messages/blocking-prerender-dynamic) written for agents to read. Each page follows the same shape, with the canonical patterns for every fix, the trade-offs against the other fixes, and the gotchas an agent is likely to miss on a first attempt. The [Instant navigation guide](/docs/app/guides/instant-navigation#ai-workflow) shows the full observe-fix-iterate loop an agent runs on these errors, from reading the insight to asserting on the result with an `instant()` test. The `Learn more` link resolves to a per-error page under [`/docs/messages`](https://nextjs.org/docs/messages/blocking-prerender-dynamic) written for agents to read. Each page follows the same shape, with the canonical patterns for every fix, the trade-offs against the other fixes, and the gotchas an agent is likely to miss on a first attempt. The [Instant navigation guide](/docs/app/guides/instant-navigation#ai-workflow) walks through the full loop an agent runs on these errors, from reading the insight to writing an `instant()` test that fails before the fix and passes once it's in place.
## Step 4: Hand multi-step workflows to skills ## Step 4: Hand multi-step workflows to Skills
Framework knowledge comes from the bundled docs, not from skills. [Benchmark results](https://nextjs.org/evals) show that always-available context outperforms on-demand retrieval. Skills cover the tasks that are workflows rather than lookups, such as adopting Cache Components or Partial Prefetching across an app. [Next.js skills](https://www.skills.sh/vercel/next.js) package these as structured instructions an agent installs and follows, sequencing the work and pointing at the relevant docs and [runtime tooling](#step-2-give-agents-runtime-visibility) at each step. Framework knowledge comes from the bundled docs, not from Skills. [Benchmark results](https://nextjs.org/evals) show that always-available context outperforms on-demand retrieval. Skills cover the tasks that are workflows rather than lookups, such as adopting Cache Components or Partial Prefetching across an app. Next.js Skills package these as structured instructions an agent installs and follows, sequencing the work and pointing at the relevant docs and [runtime tooling](#step-2-give-agents-runtime-visibility) along the way.
You can [browse the source for these Skills](https://github.com/vercel/next.js/tree/canary/skills) in the Next.js repository and [find them on skills.sh](https://www.skills.sh/vercel/next.js).
The Skills serve three different workflow types:
- **Runtime foundations** such as `next-dev-loop` give any coding task a repeatable inspect, edit, and verify cycle.
- **Interactive workflows** make broader changes with user checkpoints, such as adopting Cache Components or Partial Prefetching across an app.
- **Unattended loops** work toward a verifiable goal and stop only for genuine decisions.
### `next-dev-loop` ### `next-dev-loop`
The [`next-dev-loop`](https://github.com/vercel/next.js/tree/canary/skills/next-dev-loop) skill verifies a change actually works at runtime against a running dev server, combining the [MCP server](/docs/app/guides/mcp)'s view with the browser's. The [`next-dev-loop`](https://www.skills.sh/vercel/next.js/next-dev-loop) runtime foundation verifies changes against a running dev server using the [MCP server](/docs/app/guides/mcp) and browser.
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-dev-loop npx skills add vercel/next.js --skill next-dev-loop
...@@ -167,12 +175,12 @@ npx skills add vercel/next.js --skill next-dev-loop ...@@ -167,12 +175,12 @@ npx skills add vercel/next.js --skill next-dev-loop
Then give the agent this prompt: Then give the agent this prompt:
```prompt ```prompt
After every edit, verify the page still works at runtime using the next-dev-loop skill. After every edit, verify the page still works at runtime using the next-dev-loop Skill.
``` ```
### `next-cache-components-adoption` ### `next-cache-components-adoption`
The [`next-cache-components-adoption`](https://github.com/vercel/next.js/tree/canary/skills/next-cache-components-adoption) skill turns on [Cache Components](/docs/app/getting-started/caching) and walks the app to a passing build, resolving each blocking route the flag surfaces. The [`next-cache-components-adoption`](https://www.skills.sh/vercel/next.js/next-cache-components-adoption) Skill turns on [Cache Components](/docs/app/getting-started/caching) and resolves blocking routes until the app builds.
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-cache-components-adoption npx skills add vercel/next.js --skill next-cache-components-adoption
...@@ -181,26 +189,26 @@ npx skills add vercel/next.js --skill next-cache-components-adoption ...@@ -181,26 +189,26 @@ npx skills add vercel/next.js --skill next-cache-components-adoption
Then give the agent this prompt: Then give the agent this prompt:
```prompt ```prompt
Adopt Cache Components in this project using the next-cache-components-adoption skill. Adopt Cache Components in this project using the next-cache-components-adoption Skill.
``` ```
### `next-cache-components-optimizer` ### `next-cache-components-optimizer`
The [`next-cache-components-optimizer`](https://github.com/vercel/next.js/tree/canary/skills/next-cache-components-optimizer) skill drives a route to instant navigation with a failing `@next/playwright` `instant()` test worked to green, then shipped as a regression guard. The [`next-cache-components-optimizer`](https://www.skills.sh/vercel/next.js/next-cache-components-optimizer) Skill maximizes the meaningful UI available on an exact navigation and guards it with an `@next/playwright` `instant()` test.
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-cache-components-optimizer npx skills add vercel/next.js --skill next-cache-components-optimizer
``` ```
Then give the agent this prompt: For example, give the agent this prompt:
```prompt ```prompt
Make the navigation from the dashboard to settings instant using the next-cache-components-optimizer skill. Make the navigation to `/settings` instant using the next-cache-components-optimizer Skill.
``` ```
### `next-partial-prefetching-adoption` ### `next-partial-prefetching-adoption`
The [`next-partial-prefetching-adoption`](https://github.com/vercel/next.js/tree/canary/skills/next-partial-prefetching-adoption) skill turns on [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) and works through the insights it surfaces until every link reuses a shared App Shell. The [`next-partial-prefetching-adoption`](https://www.skills.sh/vercel/next.js/next-partial-prefetching-adoption) Skill turns on [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) and resolves its insights until all routes reuse a shared App Shell.
```bash filename="Terminal" ```bash filename="Terminal"
npx skills add vercel/next.js --skill next-partial-prefetching-adoption npx skills add vercel/next.js --skill next-partial-prefetching-adoption
...@@ -209,5 +217,5 @@ npx skills add vercel/next.js --skill next-partial-prefetching-adoption ...@@ -209,5 +217,5 @@ npx skills add vercel/next.js --skill next-partial-prefetching-adoption
Then give the agent this prompt: Then give the agent this prompt:
```prompt ```prompt
Adopt Partial Prefetching in this project using the next-partial-prefetching-adoption skill. Adopt Partial Prefetching in this project using the next-partial-prefetching-adoption Skill.
``` ```
...@@ -454,15 +454,16 @@ Use the [DevTools](#visualize-loading-states-with-the-nextjs-devtools) to see wh ...@@ -454,15 +454,16 @@ Use the [DevTools](#visualize-loading-states-with-the-nextjs-devtools) to see wh
## AI workflow ## AI workflow
The observe-fix-iterate loop is well suited to AI coding agents: An AI coding agent can run this workflow to make a navigation instant:
- **Observe**: read validation insights in the dev overlay and dev server console. - **Observe**: read validation insights and choose the exact navigation and UI that should appear immediately.
- **Fix**: validation errors name a specific component and suggest a fix (`use cache` or `<Suspense>`). The agent applies the fix and re-runs validation, whether that's in dev or a build. - **Test**: confirm the target UI renders normally, then write an `instant()` test and verify that it fails before changing the route.
- **Iterate**: run an `instant()` test to check what appears in the shell. Because the output is deterministic, the agent can assert on it without flaky retries. - **Fix**: validation errors name a specific component and suggest a fix (`use cache` or `<Suspense>`). The agent applies the fix and re-runs validation.
- **Verify**: run the test against a production-like build and keep the passing test as a regression guard.
The agent doesn't need to understand the full caching model. It follows the insights and errors until they're gone. The agent doesn't need to understand the full caching model, only to follow the insights and errors until they're gone. It does need your app-specific intent, though. Tell it what should appear immediately, what can stream in, and what must stay fresh. When a caching decision is unclear, keep the data fresh behind `<Suspense>` rather than guessing a cache lifetime.
For [iterating on loading states](#iterate-on-loading-states), a prompt like "maximize my content, and reduce the amount that needs to be behind a spinner" works well for pushing boundaries down. You can hint at what data needs to be fresh on load and what can be cached, and the agent will move the `<Suspense>` and `use cache` placement accordingly. For [iterating on loading states](#iterate-on-loading-states), a prompt like "maximize my content, and reduce the amount that needs to be behind a spinner" works well for pushing boundaries down.
Agents working on a Cache Components route typically reach for three levers: Agents working on a Cache Components route typically reach for three levers:
...@@ -474,7 +475,7 @@ Each refactor should pair with a before/after capture to verify the change actua ...@@ -474,7 +475,7 @@ Each refactor should pair with a before/after capture to verify the change actua
For agents to see what their changes actually render, pair this with [agent-browser](https://github.com/vercel-labs/agent-browser). With React DevTools enabled it reports the component tree and which `<Suspense>` boundaries are still pending, so an agent can make a change, snapshot the shell, check what landed, and adjust. See [Runtime visibility](/docs/app/guides/ai-agents#step-2-give-agents-runtime-visibility) in the AI agents guide for the setup. For agents to see what their changes actually render, pair this with [agent-browser](https://github.com/vercel-labs/agent-browser). With React DevTools enabled it reports the component tree and which `<Suspense>` boundaries are still pending, so an agent can make a change, snapshot the shell, check what landed, and adjust. See [Runtime visibility](/docs/app/guides/ai-agents#step-2-give-agents-runtime-visibility) in the AI agents guide for the setup.
The [`next-cache-components-optimizer`](/docs/app/guides/ai-agents#next-cache-components-optimizer) skill packages this loop: it encodes the goal as a failing `@next/playwright` `instant()` test and works it to green one route at a time, for both initial load (hard navigation) and client-side navigation (soft navigation), then ships the test as a regression guard. The [`next-cache-components-optimizer`](/docs/app/guides/ai-agents#next-cache-components-optimizer) Skill packages this loop. It confirms the target UI renders normally, writes an `instant()` test that fails before the fix, then works it to green against a production-like build and ships it as a regression guard. Use it for the initial load (hard navigation), client-side navigation (soft navigation), or both.
## Opting out ## Opting out
......
// @ts-nocheck
// Keep this route on the Edge runtime.
// See: https://nextjs.org/docs/app/guides/adopting-partial-prefetching
export const runtime = 'edge', prefetch = 'partial';
export default function Page() {
return <p>hello world</p>;
}
// @ts-nocheck
// Keep this route on the Edge runtime.
export const runtime = 'edge';
export default function Page() {
return <p>hello world</p>;
}
// @ts-nocheck
import { Suspense } from 'react';
// TODO(runtime-prefetch): assess whether this link should prefetch URL data.
// See: https://nextjs.org/docs/app/guides/runtime-prefetching
// See: https://nextjs.org/docs/app/guides/adopting-partial-prefetching
export const prefetch = 'partial';
export default function Page() {
return <p>hello world</p>;
}
// @ts-nocheck
import { Suspense } from 'react';
// TODO(runtime-prefetch): assess whether this link should prefetch URL data.
// See: https://nextjs.org/docs/app/guides/runtime-prefetching
export default function Page() {
return <p>hello world</p>;
}
...@@ -5,6 +5,21 @@ import { createParserFromPath } from '../lib/parser' ...@@ -5,6 +5,21 @@ import { createParserFromPath } from '../lib/parser'
// Route Segment Config name and the only value this codemod strips. // Route Segment Config name and the only value this codemod strips.
const CONFIG_NAME = 'prefetch' const CONFIG_NAME = 'prefetch'
const TARGET_VALUE = 'partial' const TARGET_VALUE = 'partial'
const GENERATED_GUIDE_COMMENT =
'See: https://nextjs.org/docs/app/guides/adopting-partial-prefetching'
function isGeneratedGuideComment(comment: any): boolean {
return comment.value.trim() === GENERATED_GUIDE_COMMENT
}
function removeGeneratedGuideComment(node: any) {
for (const target of [node, node.declaration]) {
if (!target?.comments) continue
target.comments = target.comments.filter(
(comment: any) => !isGeneratedGuideComment(comment)
)
}
}
// Unwrap `'partial' as const` / `'partial' satisfies T` so the value guard // Unwrap `'partial' as const` / `'partial' satisfies T` so the value guard
// still matches when the export is annotated. // still matches when the export is annotated.
...@@ -53,7 +68,9 @@ function stripTargetDeclarators( ...@@ -53,7 +68,9 @@ function stripTargetDeclarators(
// leading comments to the next statement (or the previous one when the // leading comments to the next statement (or the previous one when the
// removed statement is last) so they survive the removal. // removed statement is last) so they survive the removal.
function preserveLeadingComments(path: any) { function preserveLeadingComments(path: any) {
const comments = path.node.comments?.filter((comment: any) => comment.leading) const comments = path.node.comments?.filter(
(comment: any) => comment.leading && !isGeneratedGuideComment(comment)
)
if (!comments?.length) { if (!comments?.length) {
return return
} }
...@@ -108,6 +125,7 @@ export default function transformer(file: FileInfo, _api: API) { ...@@ -108,6 +125,7 @@ export default function transformer(file: FileInfo, _api: API) {
) )
}) })
.forEach((path) => { .forEach((path) => {
removeGeneratedGuideComment(path.node)
const declaration = path.node.declaration as VariableDeclaration const declaration = path.node.declaration as VariableDeclaration
const remaining = stripTargetDeclarators(j, declaration) const remaining = stripTargetDeclarators(j, declaration)
// Remove the whole export only when nothing else was declared with it. // Remove the whole export only when nothing else was declared with it.
...@@ -172,6 +190,7 @@ export default function transformer(file: FileInfo, _api: API) { ...@@ -172,6 +190,7 @@ export default function transformer(file: FileInfo, _api: API) {
return path.node.declarations.some((decl) => isTargetPrefetch(j, decl)) return path.node.declarations.some((decl) => isTargetPrefetch(j, decl))
}) })
.forEach((path) => { .forEach((path) => {
removeGeneratedGuideComment(path.node)
const remaining = stripTargetDeclarators(j, path.node) const remaining = stripTargetDeclarators(j, path.node)
if (remaining === 0) { if (remaining === 0) {
preserveLeadingComments(path) preserveLeadingComments(path)
......
...@@ -118,10 +118,8 @@ Before invoking the codemod, fix the two classes of blocker it can't. ...@@ -118,10 +118,8 @@ Before invoking the codemod, fix the two classes of blocker it can't.
The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. Common false positive: if you recently upgraded Next.js, `package.json` and the lockfile will already be dirty — commit those first. The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. Common false positive: if you recently upgraded Next.js, `package.json` and the lockfile will already be dirty — commit those first.
Use the `@canary` channel, not `@latest`. The `cache-components-instant-false` transform isn't in the stable `@next/codemod` release; `@next/codemod@latest` errors with `Invalid transform choice`.
```bash ```bash
npx @next/codemod@canary cache-components-instant-false ./app npx @next/codemod@latest cache-components-instant-false ./app
``` ```
Inserts `export const instant = false` (with a `// TODO: Cache Components adoption` comment) into every `app/**/{page,layout,default}` file, skipping files that already declare `instant` and any module marked `"use client"` or `"use server"`. Then set `cacheComponents: true`. The TODO comments are the work queue for the loop. Inserts `export const instant = false` (with a `// TODO: Cache Components adoption` comment) into every `app/**/{page,layout,default}` file, skipping files that already declare `instant` and any module marked `"use client"` or `"use server"`. Then set `cacheComponents: true`. The TODO comments are the work queue for the loop.
...@@ -196,6 +194,7 @@ Per route: ...@@ -196,6 +194,7 @@ Per route:
- The [three blocker classes from background](#background) often get missed when fixing in place. Caching a downstream fetch (`getThing(id)`) doesn't clear an `await params` at the top of the page body — push the param promise into the `<Suspense>`-wrapped child. - The [three blocker classes from background](#background) often get missed when fixing in place. Caching a downstream fetch (`getThing(id)`) doesn't clear an `await params` at the top of the page body — push the param promise into the `<Suspense>`-wrapped child.
- Ambiguous calls are user check-ins, not agent judgment. When you're not sure which fix fits, the blocking code looks security-sensitive, or the user might want to keep the route blocking on purpose — read [references/per-page-decisions.md](./references/per-page-decisions.md) before editing. Show the route while you ask: the `next-dev-loop` session runs the browser headed, so drive to the page and leave it on screen so the user is looking at the thing they're deciding about, with a screenshot as the fallback when a headed browser isn't possible. "Should this stay blocking?" is much easier to answer while looking at the page than at a file path. - Ambiguous calls are user check-ins, not agent judgment. When you're not sure which fix fits, the blocking code looks security-sensitive, or the user might want to keep the route blocking on purpose — read [references/per-page-decisions.md](./references/per-page-decisions.md) before editing. Show the route while you ask: the `next-dev-loop` session runs the browser headed, so drive to the page and leave it on screen so the user is looking at the thing they're deciding about, with a screenshot as the fallback when a headed browser isn't possible. "Should this stay blocking?" is much easier to answer while looking at the page than at a file path.
- Don't narrate the refactor with comments. The only comment the codemod (or you) should leave is `// TODO: Cache Components adoption` on opt-outs, and the user's existing comments. Don't annotate every `<Suspense>` boundary or `"use cache"` call with what it does — the code says that. Drop a comment only when the _why_ isn't clear from the code (e.g. a deliberate Block with a reason). - Don't narrate the refactor with comments. The only comment the codemod (or you) should leave is `// TODO: Cache Components adoption` on opt-outs, and the user's existing comments. Don't annotate every `<Suspense>` boundary or `"use cache"` call with what it does — the code says that. Drop a comment only when the _why_ isn't clear from the code (e.g. a deliberate Block with a reason).
- For many routes with the same mechanical fix, verify one representative route first. Then batch disjoint route groups using the same recipe, and run the shared build and browser checks together.
Keep a todo list of the feature's routes. When every route in the feature is clean, move to step 3. Keep a todo list of the feature's routes. When every route in the feature is clean, move to step 3.
...@@ -206,6 +205,7 @@ Checklist before checking in with the user: ...@@ -206,6 +205,7 @@ Checklist before checking in with the user:
- `next build` completes without blocking-route errors. - `next build` completes without blocking-route errors.
- No bare TODOs in the feature: `grep -rn "TODO: Cache Components adoption"` finds both the codemod's opt-out comments and the sync-IO unblocks from the pre-step. Any `instant = false` left behind is a deliberate, documented Block — comment rewritten to a reason (see [references/per-page-decisions.md](./references/per-page-decisions.md) → "when to leave a Block in place"). Any `await connection()` left behind has been reviewed and kept on purpose, not left over from the pre-step. - No bare TODOs in the feature: `grep -rn "TODO: Cache Components adoption"` finds both the codemod's opt-out comments and the sync-IO unblocks from the pre-step. Any `instant = false` left behind is a deliberate, documented Block — comment rewritten to a reason (see [references/per-page-decisions.md](./references/per-page-decisions.md) → "when to leave a Block in place"). Any `await connection()` left behind has been reviewed and kept on purpose, not left over from the pre-step.
- Each route visited in the browser: confirm the static shell renders first and every `<Suspense>` fallback resolves to its real content. Capture both states if you can — the fallback (mid-stream) and the final paint — so you have a streaming-experience demo to show the user. Throttle the network in the browser if streaming is too fast to observe. - Each route visited in the browser: confirm the static shell renders first and every `<Suspense>` fallback resolves to its real content. Capture both states if you can — the fallback (mid-stream) and the final paint — so you have a streaming-experience demo to show the user. Throttle the network in the browser if streaming is too fast to observe.
- If runtime verification fails, reproduce the same route on the pre-adoption branch or with its opt-out restored. A failure that already exists is an environment or data problem, not an adoption regression.
Then check in with the user. Same rule as the pre-step: speak their language. Don't say "feature-by-feature loop" or other internal labels; talk about the feature you adopted and what the user will see. Then check in with the user. Same rule as the pre-step: speak their language. Don't say "feature-by-feature loop" or other internal labels; talk about the feature you adopted and what the user will see.
......
...@@ -37,9 +37,9 @@ command, platform, or env var below as a requirement. ...@@ -37,9 +37,9 @@ command, platform, or env var below as a requirement.
production-like build and must not be able to pass vacuously. Stand the loop production-like build and must not be able to pass vacuously. Stand the loop
up once; every later optimization is then verifiable by construction. The up once; every later optimization is then verifiable by construction. The
loop is the deliverable, not any one route. loop is the deliverable, not any one route.
- **The mechanism: `@next/playwright` `instant()`.** This skill locks with - **The mechanism: `@next/playwright` `instant()`.** This skill uses
[`instant()`](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/instant#testing-instant-navigation): [`instant()`](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests)
a ruler, not a stopwatch (phase A). It comes from as a ruler, not a stopwatch (phase A). It comes from
`@next/playwright` (installed alongside `@playwright/test`, on the same `@next/playwright` (installed alongside `@playwright/test`, on the same
release line as `next`), so it isn't tied to any host. Keep it. Timing a release line as `next`), so it isn't tied to any host. Keep it. Timing a
navigation by hand is too flaky to trust, and is the failure mode this skill navigation by hand is too flaky to trust, and is the failure mode this skill
...@@ -88,10 +88,12 @@ trustworthy. ...@@ -88,10 +88,12 @@ trustworthy.
## Reporting to the user ## Reporting to the user
This loop is meant to run unattended — ideally across many navigations in one This loop is meant to run unattended — ideally across many navigations in one
pass — so it doesn't stop to ask after each route. What matters is how you word pass — so it doesn't stop to ask after each route. If the user names one route,
and present the results, not how often you interrupt. The mechanics below — the finish it and stop. If they ask to make the app or its navigations instant, work
rig, RED, GREEN, the gates — are your scaffolding; the user never needs to hear the whole route queue without pausing between routes. What matters is how you
those words. word and present the results, not how often you
interrupt. The mechanics below — the rig, RED, GREEN, the gates — are your
scaffolding; the user never needs to hear those words.
- **Speak their language.** Describe the gap and the result in terms of what the - **Speak their language.** Describe the gap and the result in terms of what the
user sees: "navigating to the dashboard waited on the charts query before user sees: "navigating to the dashboard waited on the charts query before
...@@ -101,8 +103,9 @@ those words. ...@@ -101,8 +103,9 @@ those words.
before/after screenshots) so the user watches the shell commit immediately and before/after screenshots) so the user watches the shell commit immediately and
the data stream in, rather than reading a claim. Identical before and after the data stream in, rather than reading a claim. Identical before and after
means the fix did nothing — roll it back. means the fix did nothing — roll it back.
- **Present a run as a list of results,** one line per navigation — which route, - **Present a run as a list of results the user can click through** — one line
what's now instant, what streams — not a transcript of the loop. per navigation: the route, what commits instantly, and what streams in — not a
transcript of the loop.
- **Only surface a question for a genuine fork:** a fix that would change - **Only surface a question for a genuine fork:** a fix that would change
behavior, a security-sensitive read, or a route that's dynamic by design (a behavior, a security-sensitive read, or a route that's dynamic by design (a
runtime-prefetch candidate, not a shell to grow). A clean instant fix is not a runtime-prefetch candidate, not a shell to grow). A clean instant fix is not a
...@@ -230,6 +233,10 @@ Wrap the same navigation in `instant()`; assert the shell commits under the ...@@ -230,6 +233,10 @@ Wrap the same navigation in `instant()`; assert the shell commits under the
lock. A RED here is the gap. **This is the test that ships** lock. A RED here is the gap. **This is the test that ships**
(`test-template.md`). (`test-template.md`).
Prefer the self-validating variant when the route has deferred content. If the
route cannot build while blocked, or a cookie/session read stays GREEN, use the
RED recipes in `reference/red-test-robustness.md`.
> **C-gate: do not start optimizing until the RED is verified trustworthy.** A > **C-gate: do not start optimizing until the RED is verified trustworthy.** A
> RED that is red for the wrong reason sends you optimizing a route that was > RED that is red for the wrong reason sends you optimizing a route that was
> never broken. > never broken.
...@@ -340,6 +347,9 @@ layout: it duplicates structure, drifts as the page changes, and pulls the ...@@ -340,6 +347,9 @@ layout: it duplicates structure, drifts as the page changes, and pulls the
design back toward a single coarse boundary. Reusing the component's own design back toward a single coarse boundary. Reusing the component's own
skeleton also keeps the prefetched shell consistent with the loaded UI. skeleton also keeps the prefetched shell consistent with the loaded UI.
See: [Streaming](https://nextjs.org/docs/app/guides/streaming#push-dynamic-access-down)
and [loading states](https://nextjs.org/docs/app/guides/instant-navigation#iterate-on-loading-states).
Exception: if the deferred component renders `null` for some users (for Exception: if the deferred component renders `null` for some users (for
example, a flag-gated control), `fallback={null}` is correct, since a skeleton example, a flag-gated control), `fallback={null}` is correct, since a skeleton
would flash and then collapse. would flash and then collapse.
...@@ -385,6 +395,9 @@ now commits instantly. Verify: ...@@ -385,6 +395,9 @@ now commits instantly. Verify:
- **Client state survives.** Because the layout UI is hoisted into the stable - **Client state survives.** Because the layout UI is hoisted into the stable
shell rather than swapped on resolve, open menus, scroll position, focus, shell rather than swapped on resolve, open menus, scroll position, focus,
and input state persist across the stream. and input state persist across the stream.
- **Pre-existing failures stay separate.** If the route errors after the
change, reproduce it on the base branch. The same failure there is an
environment or data problem, not an optimizer regression.
If anything other than whether the route is instant changed, reduce the refactor. If anything other than whether the route is instant changed, reduce the refactor.
...@@ -405,6 +418,7 @@ PR-specific items: ...@@ -405,6 +418,7 @@ PR-specific items:
- [ ] **Parity confirmed (E)**: same content, redirects, and state. - [ ] **Parity confirmed (E)**: same content, redirects, and state.
- [ ] **Existing loading UI reused (D1)**: no new page-mirroring skeleton. - [ ] **Existing loading UI reused (D1)**: no new page-mirroring skeleton.
- [ ] **Shell matches the real render at desktop and mobile widths (D2)**. - [ ] **Shell matches the real render at desktop and mobile widths (D2)**.
- [ ] **Baseline removed**: only the locked test from C remains.
**Stop condition for the whole workflow:** the locked test from C is GREEN on **Stop condition for the whole workflow:** the locked test from C is GREEN on
the rig, the differential (F) holds, and every item above is checked. Until all the rig, the differential (F) holds, and every item above is checked. Until all
......
...@@ -16,6 +16,21 @@ spend a few minutes verifying the RED is trustworthy first. ...@@ -16,6 +16,21 @@ spend a few minutes verifying the RED is trustworthy first.
Everything below serves answering that question honestly. Everything below serves answering that question honestly.
## When the blocked route will not build
With Cache Components, a top-level blocking read can fail the build before the
test can produce a RED. Add `export const instant = false` to the target route
as part of the temporary RED scaffold. It lets the known blocker build without
making the navigation instant. Remove the opt-out with the fix, and include it
when reverting the fix for the differential.
## Cookie and session reads are not lock probes
Do not manufacture a RED with `cookies()` or a session read alone. The testing
lock restricts the navigation to its shell; it does not make request cookies
unavailable. Use the route's real blocking uncached data, and prefer the
self-validating test variant when deferred content exists.
## The robustness checklist (all must hold) ## The robustness checklist (all must hold)
1. **Red on baseline**: fails on the unfixed route. 1. **Red on baseline**: fails on the unfixed route.
...@@ -80,6 +95,8 @@ sees the differential knows the test measures the property. ...@@ -80,6 +95,8 @@ sees the differential knows the test measures the property.
## `instant()` is not a stopwatch ## `instant()` is not a stopwatch
See: [`instant()`](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests).
The test does not measure how fast a navigation is. `instant()` gates dynamic data so the content The test does not measure how fast a navigation is. `instant()` gates dynamic data so the content
of the static shell can be asserted; the signal is presence, not speed. Under the lock, an instant of the static shell can be asserted; the signal is presence, not speed. Under the lock, an instant
route's shell is present, and a blocking route's content never commits, regardless of wait time. route's shell is present, and a blocking route's content never commits, regardless of wait time.
......
...@@ -62,7 +62,9 @@ build/run obstacles, accumulated as you first hit them). ...@@ -62,7 +62,9 @@ build/run obstacles, accumulated as you first hit them).
`/healthz` route or a response header, or fall back to polling the deploy `/healthz` route or a response header, or fall back to polling the deploy
platform's API for the deployment whose `commitSha === HEAD`. Record the platform's API for the deployment whose `commitSha === HEAD`. Record the
chosen mechanism. For a local `build && start` rig the artifact is the one chosen mechanism. For a local `build && start` rig the artifact is the one
freshly built, so no probe is needed. freshly built, so no SHA probe is needed. Record the port, stop the previous
server before starting, fail the loop on `EADDRINUSE`, and verify the newly
started process owns the port before running the test.
## The file: copy, fill, commit as `instant-nav.rig.md` ## The file: copy, fill, commit as `instant-nav.rig.md`
......
# Test template: the instant() guard # Test template: the instant() guard
See: [`@next/playwright` `instant()`](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests).
Ship one test per navigation type you are guarding: under `instant()`, assert that the Ship one test per navigation type you are guarding: under `instant()`, assert that the
destination's static shell appears. `instant()` gates dynamic data, so a correctly instant route destination's static shell appears. `instant()` gates dynamic data, so a correctly instant route
commits its shell under the lock and a blocking route does not. `instant()` is a ruler, not a commits its shell under the lock and a blocking route does not. `instant()` is a ruler, not a
......
...@@ -61,16 +61,24 @@ Enumerate the prefetch sites across the whole source tree, not only `app/` — t ...@@ -61,16 +61,24 @@ Enumerate the prefetch sites across the whole source tree, not only `app/` — t
Then, for each one: Then, for each one:
1. **Click each `<Link>` in `next dev`.** The insight fires at navigation time, not when the link prefetches, so a link sitting in the viewport won't trip it — you have to navigate through it. This click is _verification_: it confirms the insight fires before you adopt and clears after. Imperative `router.prefetch()` sites have no equivalent insight, so audit them from source and verify them in production ([step 4](#step-4-verify)). Without a browser, skip the click and adopt from [`link-prefetch-partial`](https://nextjs.org/docs/messages/instant-link-prefetch-partial) and the audit table below — the destination's structure tells you the row, and type-check gates the edit — then leave the live confirmation for the hand-off. 1. **Click each `<Link>` in `next dev`.** The insight fires at navigation time, not when the link prefetches, so a link sitting in the viewport won't trip it — you have to navigate through it. This click is _verification_: it confirms the insight fires before you adopt and clears after. Imperative `router.prefetch()` sites have no equivalent insight, so audit them from source and verify them in production ([step 4](#step-4-verify)). Without a browser, skip the click and adopt from [`link-prefetch-partial`](https://nextjs.org/docs/messages/instant-link-prefetch-partial) and the audit table below — the destination's structure tells you the row, and type-check gates the edit — then leave the live confirmation for the hand-off.
2. **Adopt the destination.** Add `export const prefetch = 'partial'`. That clears the insight for every link pointing at it. If the route reads URL data (`params`, `searchParams`), the default link still warms only its skeleton (the guide's [URL data](https://nextjs.org/docs/app/guides/adopting-partial-prefetching#url-data) section), so it's a runtime-prefetch candidate for step 5, not a finished adoption. Keep `prefetch={true}` on its links and mark the route: 2. **Adopt the destination.** Add the temporary route config with a link to the migration guide. That clears the insight for every link pointing at it:
```tsx
// See: https://nextjs.org/docs/app/guides/adopting-partial-prefetching
export const prefetch = 'partial'
```
If the route reads URL data (`params`, `searchParams`), the default link still warms only its skeleton (the guide's [URL data](https://nextjs.org/docs/app/guides/adopting-partial-prefetching#url-data) section), so it's a runtime-prefetch candidate for step 5, not a finished adoption. Keep `prefetch={true}` on its links and mark the route:
```tsx ```tsx
// TODO(runtime-prefetch): assess with the user whether URL data should resolve before click. // TODO(runtime-prefetch): assess with the user whether URL data should resolve before click.
// See: https://nextjs.org/docs/app/guides/runtime-prefetching
export const prefetch = 'partial' export const prefetch = 'partial'
``` ```
Use that exact prefix so step 5 can grep them back. Don't cache or decide anything for these routes now. Use that exact prefix so step 5 can grep them back. Don't cache or decide anything for these routes now.
3. **Preserve what that prefetch delivered.** The guide's [audit table](https://nextjs.org/docs/app/guides/adopting-partial-prefetching#auditing-link-prefetchtrue-calls) is the canonical decision — fetch it and apply the matching row rather than re-deriving it. Caching uncached content is the judgment call in that table: trace where the data comes from and what freshness and revalidation it needs, per the [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache) docs, and ask the user when the answer isn't clear-cut. The URL-data routes you marked in the previous item wait for step 5. 3. **Preserve what that prefetch delivered.** The guide's [audit table](https://nextjs.org/docs/app/guides/adopting-partial-prefetching#auditing-link-prefetchtrue-calls) is the canonical decision — fetch it and apply the matching row. Caching uncached content is the judgment call in that table: trace where the data comes from and what freshness and revalidation it needs, per the [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache) docs, and ask the user when the answer isn't clear-cut. The URL-data routes you marked in the previous item wait for step 5.
> **If you add `use cache`, verify under `next start`, not only the build.** A `cookies()`/`headers()`/session read anywhere in the cached call tree throws at request time while `next build` passes clean. See [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache). > **If you add `use cache`, verify under `next start`, not only the build.** A `cookies()`/`headers()`/session read anywhere in the cached call tree throws at request time while `next build` passes clean. See [`use cache`](https://nextjs.org/docs/app/api-reference/directives/use-cache).
...@@ -79,15 +87,13 @@ Then, for each one: ...@@ -79,15 +87,13 @@ Then, for each one:
Once every audited destination has `prefetch = 'partial'`, finish in two moves. Once every audited destination has `prefetch = 'partial'`, finish in two moves.
1. **Enable the flag globally.** Set `partialPrefetching: true` in `next.config.ts` (alongside `cacheComponents: true`). Every route is adopted now, so every link is good. 1. **Enable the flag globally.** Set `partialPrefetching: true` in `next.config.ts` (alongside `cacheComponents: true`). Every route is adopted now, so every link is good.
2. **Strip the redundant `prefetch = 'partial'` exports.** Run the first-party `remove-partial-prefetch` codemod rather than a text find-and-replace. It removes only `export const prefetch = 'partial'` and leaves other values such as `prefetch = 'force-disabled'` in place, along with your `TODO(runtime-prefetch)` markers, which wait for step 5. 2. **Strip the redundant `prefetch = 'partial'` exports.** Run the first-party `remove-partial-prefetch` codemod rather than a text find-and-replace. It removes only `export const prefetch = 'partial'` and its generated Partial Prefetching guide comment. It leaves other values such as `prefetch = 'force-disabled'` in place, along with your `TODO(runtime-prefetch)` markers and their Runtime Prefetching guide links, which wait for step 5.
Use the `@canary` channel, not `@latest`. The `remove-partial-prefetch` transform isn't in the stable `@next/codemod` release yet, and `@next/codemod@latest` errors with `Invalid transform choice`.
```bash ```bash
npx @next/codemod@canary remove-partial-prefetch ./app npx @next/codemod@latest remove-partial-prefetch ./app
``` ```
The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. If the codemod isn't available (older `@next/codemod`, sandboxed environment, offline run), reproduce it by hand by removing `export const prefetch = 'partial'` from every `app/**/{page,layout}.{js,jsx,ts,tsx}` — leave other `prefetch` values in place, and leave the `TODO(runtime-prefetch)` markers where they are. Don't hand-edit when the codemod can run. The codemod refuses to run on a dirty working tree. Commit or stash unrelated work first, or pass `--force` to let its edits land alongside your WIP. If the codemod isn't available (older `@next/codemod`, sandboxed environment, offline run), reproduce it by hand by removing `export const prefetch = 'partial'` and its generated Partial Prefetching guide comment from every `app/**/{page,layout}.{js,jsx,ts,tsx}` — leave other `prefetch` values in place, and leave the `TODO(runtime-prefetch)` markers and Runtime Prefetching guide links where they are. Don't hand-edit when the codemod can run.
## step 3: sweep for URL-data insights (after enabling) ## step 3: sweep for URL-data insights (after enabling)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment