Unverified Commit 393de1eb authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

skill: add Partial Prefetching optimizer (#96471)

## Summary

- add a Partial Prefetching optimizer Skill for selected source Links
and destinations
- keep prefetch stages and Link policy in the public [Optimizing
prefetching
guide](https://nextjs.org/docs/app/guides/optimizing-prefetching), and
rely on the same static-shell documentation as the Cache Components
optimizer for cache placement, Suspense, loading UI, and authorization
- keep the Skill focused on the product decision, production `instant()`
loop, differential verification, and mutation freshness when an
optimization adds a cache around mutable data
- reference the canonical
[`unstable_prefetch()`](https://nextjs.org/docs/app/api-reference/functions/prefetch)
and
[`unstable_navigation()`](https://nextjs.org/docs/app/api-reference/functions/navigation)
docs instead of explaining the APIs again in the Skill
- link cache-writing optimizations to the canonical
[Revalidating](https://nextjs.org/docs/app/getting-started/caching-and-revalidating#revalidating)
documentation and verify a populated-cache mutation in the Skill and
eval
- bundle a self-contained production rig aligned with the related
adoption and optimizer Skills, tuned to record each source-link and
prefetch-stage contract
- add an eval that compares baseline, the bundled guide, and the local
Skill against the same prefetched-UI and cache-freshness goal
- document the optimizer in the AI agents guide

This follows the same guide/Skill split as #97737. Partial Prefetching
adoption preserves existing behavior; this optimizer is the later
decision about what is worth preparing before a click and what should
wait for navigation.

Related: #97712, #97737, #97759, #98122, #98175

## Eval

One run per treatment with Claude Opus 4.8 and Claude Sonnet 4.5, using
a fixed Claude Haiku 4.5 judge. The bundled-guide and Skill treatments
use a local Next.js tarball containing the new guide and API references.

| Model | Treatment | Criteria | Score change | Overall | Duration |
Tokens processed | Total run cost | Cost change |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| Opus 4.8 | Baseline | 10/10 (100%) | — | Pass | 18m 42s | 3.39M |
$3.46 | — |
| Opus 4.8 | Bundled guide | 9/10 (90%) | -10 pp | Fail | 13m 37s |
3.02M | $2.84 | -18.0% |
| Opus 4.8 | Local Skill | 10/10 (100%) | +10 pp | Pass | 17m 22s |
2.80M | $2.54 | -10.6% |
| Sonnet 4.5 | Baseline | 2/10 (20%) | — | Fail | 15m 55s | 1.97M |
$1.06 | — |
| Sonnet 4.5 | Bundled guide | 5/10 (50%) | +30 pp | Fail | 15m 49s |
2.17M | $1.11 | +4.5% |
| Sonnet 4.5 | Local Skill | 8/10 (80%) | +30 pp | Fail | 15m 31s |
1.41M | $0.77 | -30.4% |

Token totals count each unique model message once and include uncached
input, cache creation, cache reads, and output. Cache reads account for
most of the total in every treatment. Total run cost applies the current
AI Gateway base rates to each token category: Opus 4.8 costs $5/M input,
$6.25/M cache writes, $0.50/M cache reads, and $25/M output; Sonnet 4.5
costs $3/M input, $3.75/M cache writes, $0.30/M cache reads, and $15/M
output. The six agent runs cost $11.78 in total.

Compared with baseline, the Opus Skill run maintained a 100% criteria
pass rate while reducing cost by 26.7%. The Sonnet Skill run improved
the criteria pass rate from 20% to 80%, a 60 percentage-point increase,
while reducing cost by 27.3%.

The stronger model could solve the fixture without the Skill, although
it independently searched the bundled Next.js documentation and took
slightly longer than the Skill treatment. The Opus guide-only run
implemented the correct behavior but missed the required
RED-before-GREEN proof.

The Sonnet treatments show a clearer progression. Baseline did not
implement the required caching, navigation stage, `instant()` contract,
or cache invalidation. The bundled guide added the cached summary and
production test, but missed the navigation stage, deferred-state
assertions, tag invalidation, and RED-before-GREEN proof. The Skill
treatment completed the `instant()` RED-to-GREEN loop and final
production behavior, but left `connection()` in the related-sessions
read and used path revalidation instead of tagging the cached read. It
therefore passed 8 of 10 criteria but failed the overall eval.

All six measured runs completed through grading. Chromium and its system
dependencies are provisioned before the agent starts, so missing browser
libraries did not determine these results.

## Verification

- `pnpm --filter=next build`
- `pnpm prettier --check` for the changed guide, prompt, Skill, and eval
fixture
- `pnpm exec tsc -p
evals/evals/agent-051-optimize-partial-prefetching/tsconfig.json
--noEmit`
- `node --check run-evals.js`
- `git diff --check`
- packed a local Next.js tarball and confirmed it contains the optimizer
guide plus the `navigation()` and `prefetch()` references
- verified the `navigation()` contract in the minimal reproduction and
NextBeats on Next.js 16.4.0-canary.22
- merged the latest `canary`, preserving both generic fixture setup and
Playwright provisioning

<!-- NEXT_JS_LLM -->
parent 6fbba169
......@@ -47,7 +47,7 @@ The [`use cache`](/docs/app/api-reference/directives/use-cache) directive caches
- **Data-level**: Cache a function that fetches or computes data (e.g., `getProducts()`, `getUser(id)`)
- **UI-level**: Cache an entire component or page (e.g., `async function BlogPosts()`)
A cache directive gives a result a lifetime, information Next.js uses to apply rendering optimizations. See [Prerendering](#prerendering) for how cached results become part of the static shell and may be included in a [prefetch](#prefetching).
A cache directive gives a result a lifetime, which Next.js uses for time-based revalidation and rendering optimizations. For on-demand revalidation after a mutation, see [Revalidating](/docs/app/getting-started/revalidating). See [Prerendering](#prerendering) for how cached results become part of the static shell and may be included in a [prefetch](#prefetching).
> **Good to know:** We recommend pairing every cache directive with a [`cacheLife`](/docs/app/api-reference/functions/cacheLife). Without one, the implicit `default` profile applies.
......
......@@ -89,7 +89,30 @@ A legacy full prefetch can include more UI than the navigation needs. In most ca
### Verify prefetched UI with tests
To verify the migration programmatically, an [`instant()`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) test can capture the UI that should stay available from an existing full prefetch. Run this baseline against a production build with `partialPrefetching` disabled because automatic prefetching doesn't run in `next dev`. Then rerun the same assertions after adopting the destination. A failure identifies UI the App Shell no longer carries, so you can cache the data or subtree that restores it. The passing test provides regression coverage.
To verify the migration programmatically, an [`instant()`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) test can capture the UI that should stay available from an existing full prefetch. Test the exact source link because different links to the same destination can use different prefetch settings:
```ts filename="e2e/product-navigation.test.ts" highlight={7-16}
import { expect, test } from '@playwright/test'
import { instant } from '@next/playwright'
test('preserves the prefetched product summary', async ({ page }) => {
await page.goto('/products')
await instant(page, async () => {
const link = page.getByRole('link', { name: 'Baseball Cap' })
await expect(link).toBeVisible()
await link.click()
await page.waitForURL((url) => url.pathname === '/products/baseball-cap')
await expect(
page.getByRole('heading', { name: 'Baseball Cap' })
).toBeVisible()
await expect(page.getByTestId('product-summary')).toBeVisible()
})
})
```
Run this baseline against a production build with `partialPrefetching` disabled because automatic prefetching doesn't run in `next dev`. Then rerun the same test after adopting the destination. If it fails, the selected UI is no longer prefetched. Cache the reusable data or subtree that should stay available, then keep the passing test as regression coverage.
### Static or cached content
......
......@@ -237,3 +237,23 @@ Then give the agent this prompt:
```prompt
Adopt Partial Prefetching in this project using the next-partial-prefetching-adoption Skill.
```
### `next-partial-prefetching-optimizer`
The [`next-partial-prefetching-optimizer`](https://www.skills.sh/vercel/next.js/next-partial-prefetching-optimizer) Skill takes a target navigation or set of navigations and works toward the UI you want ready before each click:
1. Turns the requested behavior for each navigation into a contract for what is prefetched, what waits for navigation, and when prefetching begins.
2. Captures each contract in an [`instant()`](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) test.
3. Applies the [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) patterns and keeps the passing tests as regression coverage.
It needs Cache Components and Partial Prefetching already adopted.
```bash filename="Terminal"
npx skills add vercel/next.js --skill next-partial-prefetching-optimizer
```
Then give the agent a prompt like:
```prompt
Make the product title instant when navigating from /products to /products/[id]. Use the next-partial-prefetching-optimizer Skill.
```
......@@ -61,7 +61,15 @@ export default function Home() {
}
```
The destination renders a static heading and a `<Results>` list whose contents depend on the query. Each query is cached, computed once and reused.
`'auto'` is equivalent to omitting `prefetch` or passing `undefined`. In a conditional expression, return `'auto'` for links that should keep the default App Shell prefetch:
```tsx filename="app/page.tsx"
<Link href={href} prefetch={isFeatured ? true : 'auto'} />
```
Use `prefetch={false}` only when you want to disable prefetching for a link.
The `/search` page renders a static heading and a `<Results>` list based on the query. The `search()` function caches results by query so later requests can reuse them.
```tsx filename="app/search/page.tsx"
import { Suspense } from 'react'
......@@ -215,6 +223,40 @@ Without it, keeping a subtree out of a prefetch means leaving it uncached, which
For a subtree that would otherwise sit in the App Shell, but that a `<Link prefetch={true}>` should still resolve before the click, use [`unstable_prefetch()`](/docs/app/api-reference/functions/prefetch) instead.
Unlike [`connection()`](/docs/app/api-reference/functions/connection), `unstable_navigation()` does not make the subtree request-dependent. This lets reusable content keep its cache lifetime while waiting for navigation. See [How `unstable_navigation()` differs from `connection()`](/docs/app/api-reference/functions/navigation#how-unstable_navigation-differs-from-connection) for the full comparison.
## Test prefetched and deferred content
The [Instant navigation guide](/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests) explains how to install and configure `@next/playwright`. For a client navigation, use `instant()` to inspect the destination's prefetched UI.
When [adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching#verify-prefetched-ui-with-tests), run this test before enabling the feature and rerun the same assertions afterward. This preserves the UI selected from the legacy full prefetch while its implementation moves to the App Shell or a per-link prefetch.
Inside the callback, click the link, wait for the destination URL, and assert which content is available. After the callback releases the navigation, assert that deferred content eventually renders:
```ts filename="e2e/product-navigation.test.ts" highlight={8-15,17}
import { expect, test } from '@playwright/test'
import { instant } from '@next/playwright'
test('prefetches the product summary but not reviews', async ({ page }) => {
await page.goto('/products')
await instant(page, async () => {
await page.click('a[href="/products/baseball-cap"]')
await page.waitForURL((url) => url.pathname === '/products/baseball-cap')
await expect(
page.getByRole('heading', { name: 'Baseball Cap' })
).toBeVisible()
await expect(page.getByTestId('product-summary')).toBeVisible()
await expect(page.getByTestId('reviews')).toHaveCount(0)
})
await expect(page.getByTestId('reviews')).toBeVisible()
})
```
While the `instant()` callback is running, dynamic content is paused. In this example, the product summary is part of the prefetched UI, while reviews wait for navigation. The final assertion confirms that the reviews render after the pause is released.
## Trade-offs
Use `prefetch={true}` on routes where:
......@@ -223,6 +265,8 @@ Use `prefetch={true}` on routes where:
- That part of the tree has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`)
- The traffic justifies the per-link server invocation
Prefetching cached data does not change its freshness behavior. If a mutation can update the data, [tag and invalidate the cached result](/docs/app/getting-started/revalidating).
Skip it when the prefetch can't produce a better UI than the App Shell. Each visible `<Link prefetch={true}>` can wake a server, and that cost only pays off if more of the page is ready before the click:
- The route has little or no URL-data dependency. The App Shell already makes the navigation instant.
......
......@@ -5,6 +5,7 @@ version: experimental
related:
links:
- app/api-reference/functions/prefetch
- app/api-reference/functions/connection
- app/guides/adopting-partial-prefetching
- app/api-reference/functions/io
- app/api-reference/config/next-config-js/partialPrefetching
......@@ -118,6 +119,14 @@ The slug and the cookie are both read below `unstable_navigation()` and passed a
Put the directive on a function called below it, as `getComments` does here. Awaiting `unstable_navigation()` inside a cached scope, such as [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), is not allowed.
## How `unstable_navigation()` differs from `connection()`
The [`connection()`](/docs/app/api-reference/functions/connection) function waits for a real request. It excludes the code that follows from prerendering and prefetching, making that work request-dependent.
`unstable_navigation()` only excludes the code that follows from route prefetches. It resolves when the user navigates without making that work request-dependent. A function called after `await unstable_navigation()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result during prefetching.
Use `connection()` when the work must run for a real request. Use `unstable_navigation()` when the work is reusable but should wait until the user navigates.
## When to use it
Reach for it when the content below `unstable_navigation()` is expensive to produce, in compute, in upstream requests, or in latency, and you do not want every prefetch of the route to generate it.
......@@ -158,7 +167,6 @@ async function Stories() {
## Good to know
- The function has no effect on the initial load of a page.
- Unlike [`connection()`](/docs/app/api-reference/functions/connection), it does not mark the subtree as request-dependent. Content below `await unstable_navigation()` stays fully cacheable and can be wrapped in [`use cache`](/docs/app/api-reference/directives/use-cache). It also keeps its cache lifetime.
- Reading `cookies()` or `headers()` below `unstable_navigation()` does not make the route's prefetches render per request, so they can still be served from static output. Those accesses are ignored, because they would not have resolved in a prefetch either.
- A call outside a `<Suspense>` boundary surfaces a validation insight in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell.
- Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws.
......
......@@ -5,6 +5,7 @@ version: experimental
related:
links:
- app/api-reference/functions/navigation
- app/api-reference/functions/connection
- app/guides/adopting-partial-prefetching
- app/api-reference/functions/io
- app/api-reference/config/next-config-js/partialPrefetching
......@@ -122,6 +123,14 @@ The greeting reads the session and stays in the App Shell. The recommendations r
Put the directive on a function called below it, as `getRecommendations` does here. Awaiting `unstable_prefetch()` inside a cached scope, such as [`use cache`](/docs/app/api-reference/directives/use-cache) or [`use cache: private`](/docs/app/api-reference/directives/use-cache-private), is not allowed.
## How `unstable_prefetch()` differs from `connection()`
The [`connection()`](/docs/app/api-reference/functions/connection) function waits for a real request. It excludes the code that follows from prerendering and prefetching, making that work request-dependent.
`unstable_prefetch()` only excludes the code that follows from the App Shell. It can resolve during a per-link prefetch without making that work request-dependent. A function called after `await unstable_prefetch()` can therefore use [`"use cache"`](/docs/app/api-reference/directives/use-cache) and keep its cache lifetime without generating its result for every link into the route.
Use `connection()` when the work must run for a real request. Use `unstable_prefetch()` when the work is reusable but should only run for a selected per-link prefetch or a navigation.
## When to use it
Reach for it when the content below `unstable_prefetch()` is expensive to produce, in compute, in upstream requests, or in latency, and you do not want it generated in the App Shell that every `<Link>` into the route prefetches.
......@@ -139,7 +148,6 @@ When every read of [`cookies()`](/docs/app/api-reference/functions/cookies) and
## Good to know
- The function has no effect on the initial load of a page.
- Unlike [`connection()`](/docs/app/api-reference/functions/connection), it does not mark the subtree as request-dependent. Content below `await unstable_prefetch()` stays fully cacheable and can be wrapped in [`use cache`](/docs/app/api-reference/directives/use-cache).
- A call outside a `<Suspense>` boundary surfaces a validation insight in development. It is reported even on a page that is currently prerendered in full, because the same page starts deferring content as soon as it switches to a runtime shell.
- Calling it inside `use cache`, `use cache: private`, [`unstable_cache()`](/docs/app/api-reference/functions/unstable_cache), [`after()`](/docs/app/api-reference/functions/after), [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), or a Client Component throws.
......
......@@ -7,6 +7,10 @@
"skills": ["next-cache-components-adoption"],
"timeout": 1800
},
"agent-051-optimize-partial-prefetching": {
"skills": ["next-partial-prefetching-optimizer"],
"timeout": 1800
},
"agent-054-cache-components-empty-static-params": {
"skills": ["next-cache-components-adoption"],
"timeout": 1800
......
/**
* Optimize one Partial Prefetching navigation
*
* The fixture starts after Cache Components and Partial Prefetching adoption.
* The agent must turn one accepted, URL-specific product goal into an
* instant() RED-to-GREEN loop without expanding the cost to every card.
*/
import { expect, test } from 'vitest'
import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
import { environment, transcript } from '@vercel/agent-eval/eval'
const IGNORE_DIRS = new Set([
'.git',
'.next',
'node_modules',
'dist',
'build',
'coverage',
])
function readSourceFiles(dir: string): string[] {
if (!existsSync(dir)) return []
return readdirSync(dir).flatMap((entry) => {
if (IGNORE_DIRS.has(entry)) return []
const path = join(dir, entry)
if (statSync(path).isDirectory()) return readSourceFiles(path)
if (entry === 'EVAL.ts' || !/\.(ts|tsx|js|jsx)$/.test(entry)) return []
return readFileSync(path, 'utf-8')
})
}
const source = readSourceFiles(process.cwd()).join('\n')
test('keeps Cache Components and Partial Prefetching enabled', () => {
const config = readFileSync(join(process.cwd(), 'next.config.ts'), 'utf-8')
expect(config).toMatch(/cacheComponents\s*:\s*true/)
expect(config).toMatch(/partialPrefetching\s*:\s*true/)
})
test('adds a click-driven instant navigation regression test', () => {
expect(source).toMatch(/from\s+['"]@next\/playwright['"]/)
expect(source).toMatch(/\binstant\s*\(/)
expect(source).toMatch(/\.click\s*\(/)
})
test('adds reusable cached work', () => {
expect(source).toMatch(/['"]use cache['"]/)
})
test('uses the navigation stage', () => {
expect(source).toMatch(/\b(?:unstable_)?navigation\s*\(/)
})
test('optimizes only the selected featured navigation', async () => {
await expect(environment).toSatisfyCriterion(
`Only the featured Aurora keynote Link from /sessions opts into per-link prefetching with prefetch={true} or the equivalent bare prefetch prop. The other session-card Links retain the default or auto prefetch behavior. The solution does not add prefetch={false} or enable per-link prefetching for every card.`
)
})
test('assigns the destination UI to the intended stages', async () => {
await expect(environment).toSatisfyCriterion(
`The final /sessions/aurora-keynote implementation makes the public title "Aurora Keynote", speaker "Mina Park", and summary reusable through a focused use-cache function. An explicit cacheLife is optional because the fixture has no existing time-based freshness contract; this does not remove the separate on-demand invalidation requirement for edits. The result varies by session slug, and the cache does not contain connection(), cookies(), headers(), or live audience questions. Related sessions are also reusable cached data, but an await navigation() boundary runs before that cached work is called. Live audience questions remain uncached request-time content and continue streaming after navigation.`
)
})
test('invalidates cached session data after an edit', async () => {
await expect(environment).toSatisfyCriterion(
`The cached session read has a cache tag that identifies the edited session, and saveSessionSummary invalidates the same tag after updateSessionSummary succeeds. The invalidation provides read-your-own-writes behavior for the Server Action; cacheLife alone is not treated as sufficient.`
)
})
test('ships the exact positive instant contract', async () => {
await expect(environment).toSatisfyCriterion(
`The project retains a production-mode @next/playwright instant() test that starts at /sessions and clicks the featured Aurora keynote Link. While instant() holds dynamic writes, the test asserts the Aurora Keynote title, Mina Park speaker, and session summary are visible, while related sessions and live audience questions are absent. After the lock releases, the deferred regions are allowed to render. The testing API is exposed only for the measured production test build.`
)
})
test('completed a verified RED-to-GREEN optimizer loop', async () => {
await expect(transcript).toSatisfyCriterion(
`The agent verified the exact featured-Link navigation in a production build. Before changing the implementation, it proved the destination content rendered normally and that the locked instant() contract failed while the route shell remained available. It then applied the targeted optimization and reran the same locked test successfully. Merely writing the test, running only a development server, or describing commands for the user does not satisfy this criterion.`
)
})
test('verified session summary freshness after a write', async () => {
await expect(transcript).toSatisfyCriterion(
`The agent ran a behavioral freshness check that first populated the cache for a session, then updated its summary through the existing mutation, and finally read the session again and observed the updated summary. Source inspection, merely adding invalidation code, or testing the mutation before the cache was populated does not satisfy this criterion.`
)
})
Make the navigation from `/sessions` through the featured Aurora keynote card include its title, speaker, and summary in the instant UI. Related sessions must wait for navigation and stream in after the click, but should stay reusable. Live audience questions must stay fresh. Keep the other session cards on the default prefetch behavior. Session editors use the existing summary form, and the updated summary must appear on the next read. Preserve the result with regression coverage and finish the production verification.
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<nav aria-label="Conference">
<a href="/sessions">Sessions</a>
</nav>
{children}
</body>
</html>
)
}
import Link from 'next/link'
export default function HomePage() {
return <Link href="/sessions">Browse conference sessions</Link>
}
'use server'
import { updateSessionSummary } from '@/lib/sessions'
export async function saveSessionSummary(formData: FormData) {
const slug = String(formData.get('slug'))
const summary = String(formData.get('summary'))
await updateSessionSummary(slug, summary)
}
import { notFound } from 'next/navigation'
import { Suspense } from 'react'
import {
getLiveQuestions,
getRelatedSessions,
getSession,
} from '@/lib/sessions'
import { saveSessionSummary } from './actions'
export default function SessionPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<main>
<Suspense fallback={<p>Loading session…</p>}>
<SessionSummary params={params} />
</Suspense>
<Suspense fallback={<p>Loading related sessions…</p>}>
<RelatedSessions params={params} />
</Suspense>
<Suspense fallback={<p>Loading live questions…</p>}>
<LiveQuestions params={params} />
</Suspense>
</main>
)
}
async function SessionSummary({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const session = await getSession(slug)
if (!session) notFound()
return (
<header data-testid="session-summary">
<h1>{session.title}</h1>
<p>{session.speaker}</p>
<p data-testid="session-summary-text">{session.summary}</p>
<form action={saveSessionSummary}>
<input name="slug" type="hidden" value={slug} />
<label htmlFor="summary">Summary</label>
<input defaultValue={session.summary} id="summary" name="summary" />
<button type="submit">Save summary</button>
</form>
</header>
)
}
async function RelatedSessions({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const sessions = await getRelatedSessions(slug)
return (
<section data-testid="related-sessions">
<h2>Related sessions</h2>
{sessions.map((session) => (
<p key={session.slug}>{session.title}</p>
))}
</section>
)
}
async function LiveQuestions({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const questions = await getLiveQuestions(slug)
return (
<section data-testid="live-questions">
<h2>Live audience questions</h2>
{questions.map((question) => (
<p key={question}>{question}</p>
))}
</section>
)
}
import Link from 'next/link'
import { getSessions } from '@/lib/sessions'
export default async function SessionsPage() {
const sessions = await getSessions()
return (
<main>
<h1>Conference sessions</h1>
<ul>
{sessions.map((session, index) => (
<li key={session.slug}>
<Link
href={`/sessions/${session.slug}`}
data-testid={index === 0 ? 'featured-session' : undefined}
>
{session.title}
</Link>
</li>
))}
</ul>
</main>
)
}
import { connection } from 'next/server'
export type Session = {
slug: string
title: string
speaker: string
summary: string
}
const sessions: Session[] = [
{
slug: 'aurora-keynote',
title: 'Aurora Keynote',
speaker: 'Mina Park',
summary: 'Building resilient interfaces for distributed teams.',
},
{
slug: 'designing-for-delay',
title: 'Designing for Delay',
speaker: 'Theo Grant',
summary: 'Making asynchronous systems feel immediate.',
},
{
slug: 'operational-calm',
title: 'Operational Calm',
speaker: 'Rhea Stone',
summary: 'Keeping incident response focused and humane.',
},
]
export async function getSessions() {
return sessions
}
export async function getSession(slug: string) {
await connection()
await new Promise((resolve) => setTimeout(resolve, 150))
return sessions.find((session) => session.slug === slug) ?? null
}
export async function updateSessionSummary(slug: string, summary: string) {
await connection()
const index = sessions.findIndex((candidate) => candidate.slug === slug)
if (index === -1) return false
sessions[index] = { ...sessions[index], summary }
return true
}
export async function getRelatedSessions(slug: string) {
await connection()
await new Promise((resolve) => setTimeout(resolve, 350))
return sessions.filter((session) => session.slug !== slug)
}
export async function getLiveQuestions(slug: string) {
await connection()
await new Promise((resolve) => setTimeout(resolve, 500))
return [`What should teams try first after ${slug}?`]
}
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
{
"private": true,
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^16",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@next/playwright": "canary",
"@playwright/test": "1.61.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5",
"vitest": "^3.1.3",
"@vitejs/plugin-react": "^4.4.1",
"vite-tsconfig-paths": "^5.1.4"
}
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules", "EVAL.ts"]
}
......@@ -65,6 +65,91 @@ export async function installNextJs(sandbox: Sandbox): Promise<void> {
console.log(' Installed local Next.js tarball')
}
/**
* Install Chromium and its Linux dependencies for fixtures that exercise
* Playwright. The fixture declares @playwright/test so unrelated evals do not
* pay this setup cost.
*/
export async function installPlaywright(sandbox: Sandbox): Promise<void> {
const pkg = JSON.parse(await sandbox.readFile('package.json'))
const usesPlaywright = Boolean(
pkg.dependencies?.['@playwright/test'] ??
pkg.devDependencies?.['@playwright/test']
)
if (!usesPlaywright) return
console.log(' Installing Chromium and system dependencies...')
const hasDnf = (await sandbox.runCommand('which', ['dnf'])).exitCode === 0
if (hasDnf) {
const systemDeps = [
'nss',
'nspr',
'libxkbcommon',
'atk',
'at-spi2-atk',
'at-spi2-core',
'libXcomposite',
'libXdamage',
'libXrandr',
'libXfixes',
'libXcursor',
'libXi',
'libXtst',
'libXScrnSaver',
'libXext',
'mesa-libgbm',
'libdrm',
'mesa-libGL',
'mesa-libEGL',
'cups-libs',
'alsa-lib',
'pango',
'cairo',
'gtk3',
'dbus-libs',
]
const deps = await sandbox.runCommand('sudo', [
'dnf',
'install',
'-y',
'--skip-broken',
...systemDeps,
])
if (deps.exitCode !== 0) {
throw new Error(
`Chromium system dependency installation failed (exit ${deps.exitCode}):\n${deps.stderr}`
)
}
}
const browserArgs = [
'playwright',
'install',
...(hasDnf ? [] : ['--with-deps']),
'chromium',
]
const browser = await sandbox.runCommand('npx', browserArgs)
if (browser.exitCode !== 0) {
throw new Error(
`playwright install chromium failed (exit ${browser.exitCode}):\n${browser.stderr}`
)
}
const smoke = await sandbox.runCommand('node', [
'--input-type=module',
'--eval',
"import { chromium } from '@playwright/test'; const browser = await chromium.launch(); await browser.close()",
])
if (smoke.exitCode !== 0) {
throw new Error(
`Chromium launch check failed (exit ${smoke.exitCode}):\n${smoke.stderr}`
)
}
console.log(' Installed Chromium and system dependencies')
}
/**
* Run optional fixture-specific setup after dependencies are installed but
* before the coding agent starts.
......
......@@ -42,13 +42,13 @@ const EVAL_CONFIG = JSON.parse(fs.readFileSync(EVAL_CONFIG_PATH, 'utf-8'))
const BASE_VARIANTS = [
{
suffix: 'baseline',
imports: `import { installNextJs, prepareFixture } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await prepareFixture(sandbox)`,
imports: `import { installNextJs, installPlaywright, prepareFixture } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await installPlaywright(sandbox)\n await prepareFixture(sandbox)`,
},
{
suffix: 'agents-md',
imports: `import { installNextJs, prepareFixture, writeAgentsMd } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await prepareFixture(sandbox)\n await writeAgentsMd(sandbox)`,
imports: `import { installNextJs, installPlaywright, prepareFixture, writeAgentsMd } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await installPlaywright(sandbox)\n await prepareFixture(sandbox)\n await writeAgentsMd(sandbox)`,
},
]
......@@ -159,8 +159,8 @@ function getExperimentSettings(evalName) {
const multipleSkillGroups = skillGroups.size > 1
const skillVariants = [...skillGroups.values()].map(({ skills, evals }) => ({
suffix: multipleSkillGroups ? `skills-${skills.join('-')}` : 'skills',
imports: `import { installLocalSkills, installNextJs, prepareFixture } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await prepareFixture(sandbox)\n await installLocalSkills(sandbox, ${JSON.stringify(skills)})`,
imports: `import { installLocalSkills, installNextJs, installPlaywright, prepareFixture } from '../lib/setup.js'`,
setup: `await installNextJs(sandbox)\n await installPlaywright(sandbox)\n await prepareFixture(sandbox)\n await installLocalSkills(sandbox, ${JSON.stringify(skills)})`,
evals,
}))
......
......@@ -54,7 +54,7 @@ In both, the per-route success bar is the same: **dev loop reports no errors AND
`cacheComponents: true` requires every route to be prerenderable. A route that reads request-time data outside `<Suspense>` is "blocking" and fails the build. `export const instant = false` marks a route as allowed to block, which clears it in both dev and build; on a layout it covers the whole subtree during the build, but client navigations still validate each descendant segment on its own. Reads wrapped in a [`"use cache"`](https://nextjs.org/docs/app/api-reference/directives/use-cache) function count as cache boundaries, not blocking reads.
When a fix introduces `"use cache"`, follow the Caching guide for [choosing a data-level or UI-level boundary and setting its lifetime](https://nextjs.org/docs/app/getting-started/caching#usage). Use the [`use cache` cache-key reference](https://nextjs.org/docs/app/api-reference/directives/use-cache#cache-keys) when the result varies by arguments or captured values.
When a fix introduces `"use cache"`, follow the Caching guide for [choosing a data-level or UI-level boundary and setting its lifetime](https://nextjs.org/docs/app/getting-started/caching#usage) and [revalidating after mutations](https://nextjs.org/docs/app/getting-started/revalidating). Use the [`use cache` cache-key reference](https://nextjs.org/docs/app/api-reference/directives/use-cache#cache-keys) when the result varies by arguments or captured values.
Three classes of blocker come up, usually in this order:
......@@ -219,6 +219,7 @@ Checklist before checking in with the user:
- `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 io()` or `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.
- After populating any new cache whose data can be updated, a mutation check confirms the next read returns the expected data.
- 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.
......
......@@ -167,9 +167,8 @@ yours. On first use in a repository, discover how the project builds, deploys,
authenticates, and tests (inspect the repository first, and ask the user only
what it cannot answer), then write the answers to a committed
`instant-nav.rig.md`. Every later run reads that file instead of
rediscovering. The six questions (BUILD / EXPOSE / RUN / TEST USER / DRIFT /
LOOP), the file template, and filled examples (local-only, generic CI +
container, preview deploy) are in **`rig-template.md`**.
rediscovering. The required build, test context, navigation contracts,
iteration loop, and file template are in **`rig-template.md`**.
If the repo has no Playwright e2e harness yet, standing up a minimal one
(`@next/playwright`, a config with `baseURL`, one authenticated path) is part
......@@ -206,12 +205,12 @@ every platform:
The rig is any production-like build that exposes the testing API: a local
`next build && next start`, a CI/staging container, and a preview deploy are
all equally valid; the verdict comes from the build, not the platform. See
`rig-template.md` for filled examples.
`rig-template.md` for the setup requirements.
For any deployed or remote build, poll the rig's LIVENESS probe to confirm the
artifact contains `HEAD` before trusting a verdict (a stale deploy reads as a
false RED or GREEN); a local `next build && next start` needs none. The probe
mechanism is in `rig-template.md` (question 6).
mechanism is in `rig-template.md`.
## B. BASELINE (unlocked): development scaffold, do not ship
......@@ -367,6 +366,10 @@ this gate is as machine-checkable as the others. Detail:
> under the lock on the production-build rig**, not when the code compiles. That
> GREEN is the deterministic stop for the fix loop; proceed to E.
If the optimization adds or expands a cache boundary, follow
[Revalidating](https://nextjs.org/docs/app/getting-started/revalidating).
A passing `instant()` test proves shell readiness, not mutation freshness.
**When URL data can't be pushed down** (for example, the whole page depends on
`params`, `searchParams`, or the full URL), there may be no meaningful static
shell to grow. Don't force one. Per-link prefetching can make the soft
......@@ -414,6 +417,9 @@ PR-specific items:
- [ ] **Differential shown**: RED without the fix, GREEN with it, runs linked.
- [ ] **Parity confirmed (E)**: same content, redirects, and state.
- [ ] **Mutations verified when applicable**: after populating any cache whose
data can be updated, a mutation test confirms the next read returns the
expected data.
- [ ] **Existing loading UI reused (D1)**: no new page-mirroring skeleton.
- [ ] **Shell matches the real render at desktop and mobile widths (D2)**.
- [ ] **Baseline removed**: only the locked test from C remains.
......@@ -435,9 +441,8 @@ three hold, you are not done.
## Files
- `rig-template.md`: phase 0, the six-question rig discovery, the
`instant-nav.rig.md` template, and filled examples (local-only, generic CI,
preview deploy).
- `rig-template.md`: phase 0 production build, test context, navigation
contract, and unattended loop discovery.
- `test-template.md`: the shipped `instant()` specs for both navigation
types (phase C), and the delete-before-PR baseline scaffold (phase B).
- `reference/red-test-robustness.md`: the C-gate and phase F. The taxonomy of
......
......@@ -112,7 +112,7 @@ Use that exact prefix so step 7 can grep them back. Do not select new target UI
For test-backed preservation, rerun the affected **unchanged** tests after each destination changes and treat failures as the work queue. Run the complete suite and record its passing exit status before enabling the global flag. For manual preservation, compare the adopted production navigation with the selected target and document anything not yet restored. Apply the guide's matching preservation pattern for caching and Link-prop changes, and ask the user before making an unclear freshness or caching decision. New URL-data candidates marked above wait for step 7.
When restoring the target changes caching or invalidation, follow the project's existing verification approach. Reuse or extend an applicable suite for the affected lifecycle, such as freshness after mutations, cache scope, or generated values. If the project doesn't test this type of behavior, do not introduce new test infrastructure during adoption; verify it manually in production and record the expected and observed results. A green `instant()` test proves readiness, not cache correctness. Ask the user only when the intended behavior is unclear.
When restoring the target changes caching or invalidation, follow the project's existing verification approach and the [Revalidating](https://nextjs.org/docs/app/getting-started/revalidating) guide. Reuse or extend an applicable suite for the affected lifecycle. If the project doesn't test this type of behavior, do not introduce new test infrastructure during adoption; verify it manually in production and record the expected and observed results. A green `instant()` test proves readiness, not cache correctness. Ask the user only when the intended behavior is unclear.
> **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).
......@@ -153,7 +153,7 @@ Checklist before checking in with the user:
- The App Shells are real: for each route you changed, confirm the first paint after a navigation shows the intended shared content, not an empty shell or a stuck fallback. A `<Suspense>` around the whole page body passes validation with an empty shell, which defeats the point.
- The insights validate shell _structure_, not that a prefetch actually happened. Confirm on the production run (automatic prefetching runs only in production) that navigating a changed link lands on the shared shell instantly.
- For test-backed preservation, every locked `instant()` test for an audited `<Link prefetch={true}>` passes against the production run. For manual preservation, the before/after inventory and any deferred test follow-ups are recorded.
- Any caching or invalidation changed to preserve the target is verified through an applicable existing test suite or a recorded manual check when the project has no such coverage.
- After populating any new or expanded cache whose data can be updated, a mutation check verifies the next read through an applicable existing test suite or a recorded manual check when the project has no such coverage.
- **If the app prefetches imperatively**, the insight sweep does not cover it, so an empty sweep is not proof the prefetch survived the flag. Verify the call under `next start`: compare the `_rsc` prefetch response or resource timing before/after, and make sure any intentionally preserved full prefetch still carries the data the old call was warming. If it now returns only the App Shell, migrate that call site using the same decision as the nearest `<Link prefetch={true}>` destination — cache the data, or move per-link-prefetch behavior to a docs-supported `<Link prefetch={true}>`.
- **Before blaming a broken route on the flag, reproduce it with `partialPrefetching` off** (or on the pre-flag branch). The flag surfaces existing issues — a fragile request-time auth gate, a rewrite, deployment skew — earlier and more visibly, but rarely causes them. If it breaks flag-off too, it isn't a Partial Prefetching problem; fix it there, not here.
- `next build` still passes.
......
......@@ -148,14 +148,16 @@ Place this file at the repository root or next to the end-to-end configuration:
- RUN: <focused Playwright command and how it receives BASE_URL>
- TEST USER: <public/no auth, or account and login>; state: <flags, role, data, locale>
- DRIFT: <differences that could change the asserted UI>
- CONTRACTS: <audited source Link, destination, and prefetched UI to preserve>
- LOOP: <local build → start → test, or push → deploy → test>; agent limits: <...>
- LIVENESS: <deployed SHA check, or n/a for a local build and start>
- WALLS: <project-specific obstacles and their resolutions>
```
Every field needs a concrete value. `n/a` is valid only with a reason, such as
`TEST USER: public; no authentication` or `LIVENESS: n/a; local build and
start`.
`CONTRACTS` may list more than one audited navigation, but each contract needs
its own test. Every field needs a concrete value. `n/a` is valid only with a
reason, such as `TEST USER: public; no authentication` or
`LIVENESS: n/a; local build and start`.
## Check the rig before writing the baseline
......
This diff is collapsed.
# Trustworthy RED and differential
Change the implementation only after the RED proves a genuine prefetch-contract
gap for one exact link. A failing assertion alone is not enough.
## Verification gate
Require this sequence on the same production artifact and as the same test
user:
1. **Unlocked:** click the exact source link; exact pathname/query, shell, and
expected URL-derived target content all render.
2. **Locked diagnostic:** click the same link; destination URL changes,
`SHELL_MARKER` is visible, and the current result differs from the selected
target/navigation-only contract.
3. **After release:** every marker selected from the loaded page is visible.
Only then restore the selected contract assertions and change the
implementation.
## What each signal rules out
- **Destination URL wait** rules out matching the source page or clicking a
nested element that never navigates. Match relevant search params too, not
only `pathname`.
- **Shell visible under lock** proves the route already has an App Shell and is
not wholly blocking.
- **Target visible unlocked** rules out auth, flags, empty data, typoed
selectors, and redirects hiding the region.
- **Target absent locked, visible after release** proves it is outside the
prefetched result rather than absent altogether.
## The trigger is part of the test
Do not replace the real link with `router.push`, `page.goto`, or another link
to the same URL. The testing lock reenacts the clicked link's fetch strategy.
It intentionally restricts a default Partial Prefetching link to the App Shell
even if a sibling `prefetch={true}` link already warmed a concrete-param cache
entry.
For an intent policy, hover or focus the exact link inside `instant()` before
clicking. Click without a fixed delay and assert the prefetched UI after the
destination URL changes. Do not warm outside the scope or inspect private
request headers to decide when the prefetch is ready. For viewport policy, do
not hover: the test should prove the link's declared eager strategy.
Reusing a browser worker does not require aggregating several contracts into
one test. Separate tests prevent navigation cache and interaction state from
leaking between routes, and their failures identify the exact contract that
regressed.
## Common false REDs
- The target is URL-specific but the test user's record/query returns empty.
- The target is behind a flag, role, plan, locale, or experiment absent in CI.
- Auth redirects to a page where the shell selector happens to exist.
- A shared selector matches the source before the destination commits.
- The test clicks a default link while the code change modified a different
link to the same URL.
- Session-only UI was assumed to need a per-link prefetch without proving the
default/per-link exact-link differential.
- The pathname matches but the query or parameter-derived content is wrong.
- The production build does not have the testing API exposed.
- A remote test ran against a stale deployment.
- A local start failed with `EADDRINUSE` and the test hit the previous build.
## Contract already GREEN
Run the locked diagnostic against the exact link as it exists. If the shell and
target are visible, navigation-only markers are absent, and the lock is
engaged, the current link already meets the contract. It is not an optimizer
candidate, even if setting `prefetch={false}` would make it RED. Never add that
prop as a test control; the optimizer compares automatic prefetching with no
prop against `prefetch={true}`.
## Lock engagement
`experimental.exposeTestingApiInProductionBuild` must be true on the measured
artifact. A marker that is absent under lock and visible after release is the
in-band proof that the lock engaged. A vacuous no-op cannot satisfy both
halves.
Never enable this flag for real production traffic. For a remote rig, verify
the deployed commit before trusting RED or GREEN.
## What `instant()` can verify
See: [`instant()`](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests).
The public helper accepts a page, callback, and optional `baseURL`:
```ts
instant(page, callback, { baseURL? })
```
It does not accept a requested stage such as `shell` or `max`. A failed test
also does not identify the data read where the prefetch stopped. Compare the
same exact link before and after the optimization:
- existing exact-link policy -> current committed UI;
- accepted policy change -> the selected prefetch stages may commit.
If the optimization does not change the locked result, inspect `params`,
`searchParams`, Suspense boundaries, and cache directives using the
[Optimizing prefetching guide](https://nextjs.org/docs/app/guides/optimizing-prefetching).
Do not compensate with timing.
`instant()` does not expose a public request classifier for App Shell,
per-link, and navigation requests. Internal request headers and segment URLs
can change between Next.js versions, so do not use them as product regression
assertions. Use `instant()` for the visible contract and record network or
platform cost data separately when the task calls for it.
## Differential
After the test passes:
1. Record the build/commit under test.
2. Remove only the stage, per-link prefetch trigger, and cache boundary
introduced for the contract.
3. Rebuild and rerun. The shell should stay available, but the selected
prefetch contract should fail.
4. Reapply the optimization, rebuild, and rerun. The complete contract should
pass again.
5. Confirm the unlocked loaded page is identical in both versions.
If removing the optimization also removes the shell, the change mixed Cache
Components work into this loop. Split it. If the contract remains GREEN,
another policy still controls the clicked link or the changed boundary does
not own the asserted content; the test does not guard the intended
optimization. Do not replace the unchanged automatic policy with
`prefetch={false}` to force this step RED.
# Production `instant()` rig
The optimizer suite needs a production build that exposes the Next.js
testing API, a stable URL for that build, and a Playwright command that can
drive the selected source Links. Discover this setup once, record it in
`instant-nav.rig.md`, and reuse it across optimization runs.
Read an existing `instant-nav.rig.md` before creating one. Inspect the
repository before asking the user:
- `package.json` scripts for build, start, and end-to-end tests
- `playwright.config.*` for `baseURL`, `webServer`, projects, and authentication
- `next.config.*` for existing `experimental` options
- CI, preview deployment, container, and hosting configuration
- test helpers for login, `storageState`, fixtures, flags, and seeded data
Ask only for details the repository cannot answer, such as unavailable
credentials or which remote environment may expose the testing API.
## What the rig must define
### Production build and server
Use `next build` followed by `next start`, or a remote artifact produced by the
same production build. Automatic prefetching does not run in `next dev`, so a
development server cannot verify the prefetched result.
Record separate build and start commands. For a local rig, record the port,
stop any previous server before starting, fail on `EADDRINUSE`, and confirm the
new process owns the port before running Playwright. `next start` can fork a
`next-server` child, so the launcher process ID may not own the port. Start the
server in a process group that the rig can stop as a unit, or discover and stop
the process listening on the recorded port before the next build.
### Testing API
An `instant()` test against a production build requires
`experimental.exposeTestingApiInProductionBuild`. Gate it so real production
builds do not expose the API:
```ts filename="next.config.ts" highlight={3,8-10}
import type { NextConfig } from 'next'
const exposeTestingApi = process.env.EXPOSE_TESTING_API === '1'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
exposeTestingApiInProductionBuild: exposeTestingApi,
},
}
export default nextConfig
```
Merge the option into an existing `experimental` object instead of replacing
the project's other experimental options.
Set the condition while running `next build`. Setting it only for `next start`
is too late because the testing API is compiled into the production artifact.
When the artifact was built without it, Next.js does not activate the
navigation lock, so the test cannot distinguish prefetched UI from streamed
dynamic content. Rebuild with the condition enabled before interpreting the
results. Use the project's existing environment naming when it already
distinguishes test, staging, preview, and production builds.
### Test command and base URL
Record the exact Playwright command and how it receives the measured build's
URL. Reuse the project's package manager, Playwright configuration, projects,
and reporters. The suite must import `instant()` from `@next/playwright`. If
the dependencies are absent, install `@next/playwright` on the same release
line as the project's `next`, alongside `@playwright/test`.
For a local rig, a typical sequence is:
```bash filename="Terminal"
EXPOSE_TESTING_API=1 pnpm build
pnpm start --port 3000
BASE_URL=http://localhost:3000 pnpm playwright test tests/prefetch-optimization.spec.ts
```
Adapt the script names and port to the project. Keep the production server
running while the test command executes. Follow the public
[client-navigation test](https://nextjs.org/docs/app/guides/instant-navigation#prevent-regressions-with-e2e-tests): load the source route, confirm the real
Link is visible, then enter `instant()`, click, wait for the destination URL,
and assert the prefetched UI.
### Test context
Record the state required to reach the selected source Link and destination UI:
- Use `public; no authentication` when the navigation is public.
- Otherwise record the test account and login mechanism, including a fixture,
`storageState`, API login, or seeded session.
- Record flags, plan, role, locale, seeded data, and other state that can change
which UI the test sees.
A test user is not required. The field exists to make authenticated and
state-dependent tests reproducible when the app needs one.
### Drift
List differences between the state used to choose the navigation contract and
the state used by Playwright. Feature flags, permissions, empty test data, and
locale differences can make an assertion fail because the target is
unreachable, not because Partial Prefetching removed it. Write `none known`
only after checking the test context.
### Iteration loop
Record the complete loop the agent can repeat without rediscovering commands:
- Local: build with the testing API, start the new artifact, run the focused
suite, stop the server, edit, and repeat.
- Remote: push, wait for the measured artifact, verify it matches `HEAD`, run
the focused suite against its URL, edit, and repeat.
Note any step the agent cannot perform without the user, including deployment
approval, protected branches, secrets, or multi-factor authentication.
### Artifact liveness
For a remote rig, record how the test proves the deployment matches `HEAD`.
Prefer an endpoint or response header that exposes the deployed commit SHA. If
the app has neither, use the deployment provider's API to select the artifact
whose commit SHA matches `HEAD`.
A freshly completed local `build` followed by `start` does not need a SHA
probe. Record `n/a; local build and start`.
### Walls
Record build and run obstacles with their working resolution, such as required
environment variables, server-only imports that fail during prerendering,
unavailable credentials, or a process that keeps reclaiming the test port.
Reuse these notes on the next iteration.
## Write `instant-nav.rig.md`
Place this file at the repository root or next to the end-to-end configuration:
```md
# instant-nav rig: <project>
- BUILD: <commands or platform that builds and serves the measured production artifact>
- EXPOSE: <condition that enables exposeTestingApiInProductionBuild during build>
- RUN: <focused Playwright command and how it receives BASE_URL>
- TEST USER: <public/no auth, or account and login>; state: <flags, role, data, locale>
- DRIFT: <differences that could change the asserted UI>
- CONTRACTS: <source Link, destination, prefetched UI, navigation-only UI, and viewport or intent trigger>
- LOOP: <local build → start → test, or push → deploy → test>; agent limits: <...>
- LIVENESS: <deployed SHA check, or n/a for a local build and start>
- WALLS: <project-specific obstacles and their resolutions>
```
`CONTRACTS` may list more than one focused navigation, but each contract needs
its own test. Every field needs a concrete value. `n/a` is valid only with a
reason, such as `TEST USER: public; no authentication` or
`LIVENESS: n/a; local build and start`.
## Check the rig before writing the baseline
Before recording the prefetch contract:
1. Build with the testing API condition enabled.
2. Start or locate that exact artifact and confirm the base URL responds.
3. Run one focused `instant()` smoke test through a real `<Link>` navigation.
4. Confirm the test can reach its source Link and eventual destination UI in
the recorded test context.
Fix the rig before interpreting an optimizer failure. A missing testing API,
stale deployment, unreachable target, or wrong test state is an environment
failure rather than evidence that the optimization changed the prefetched UI.
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