Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 188 additions & 0 deletions .agents/skills/next-dev-loop/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
---
name: next-dev-loop
description: >
Verify Next.js runtime behavior after editing app code. Use this
skill to confirm a change actually works in a running app — not
just that it compiles or type-checks. Combines /_next/mcp
(Next.js's view) with agent-browser (the browser's view).
Requires a running `next dev`.
---

# next-dev-loop

The edit/verify rhythm during `next dev` — make a change, then
confirm it actually works at runtime, not only that the types or
the build are happy.

You verify through two views of the same running app:

- **`/_next/mcp`** — an HTTP endpoint Next.js exposes about itself.
Knows framework-specific things: routes, segments, RSC, server
actions, server logs, and errors as Next.js saw them. Call
`tools/list` for the current surface.
- **`agent-browser`** — a CLI that drives a real Chrome. Knows
framework-agnostic browser things: DOM, console, network, React
fiber, vitals. Before driving it, run `agent-browser skills get core`
once for the version-matched usage guide — don't guess subcommands
from memory.

The two views cross-check each other.

## requires

- Next.js **16.3+** with **Turbopack** — `/_next/mcp` plus the
proactive compile check via `get_compilation_issues`.
- `agent-browser` **>= 0.31.1** — React introspection, worktree-scoped
`session id`, idempotent `--restore`, and launch flag reconciliation.

These are hard floors, not soft preferences. If anything is missing,
tell the user how to upgrade and stop. Don't fall back to grepping
source or to a weaker probe — this skill assumes both views are live
at the versions above.

- Upgrade Next.js: `pnpm next upgrade` (or `npx next upgrade`).
Docs: https://nextjs.org/docs/app/getting-started/upgrading
(version-16 guide:
https://nextjs.org/docs/app/guides/upgrading/version-16)
- Install or upgrade `agent-browser`: `npm i -g agent-browser@latest`.
If the CLI isn't on `PATH`, install it before continuing — preflight
expects to invoke it directly.

## preflight

Once per session, confirm both views are live.

1. **Open `agent-browser` at the target URL, restoring saved
login state when present.** First derive one stable session id for
this checkout and use it for every `agent-browser` command:

```bash
SESSION="$(agent-browser session id --scope worktree --prefix next-dev-loop)"
export AGENT_BROWSER_SESSION="$SESSION"
export AGENT_BROWSER_RESTORE="$SESSION"
```

Then open the target URL:

```bash
agent-browser --session "$SESSION" --restore --headed --enable react-devtools open <url>
```

`--scope worktree` keeps parallel worktrees and copied checkouts
from colliding. Bare `--restore` uses the session id as the
persistence key, loads saved cookies/localStorage before navigation
when present, and auto-saves state on close. Always pass the desired
launch flags on `open`; agent-browser will reuse, relaunch, or restart
its scoped background state as needed.

The browser is the user's. If state was not restored (first run,
expired session) and the page is gated, the user drives the login —
pause until they confirm. After login, continue using the same session
and restore context; `agent-browser close` saves the cookie state so
the next `open` restores it.

2. Probe `/_next/mcp` (`tools/list`) — confirm it's reachable and
lists `get_compilation_issues`:
- Unreachable → either `next dev` isn't running, or Next.js is
below 16.3. Check `package.json` to disambiguate, then refuse.
- `get_compilation_issues` not in the list → Next.js below 16.3.
Refuse and tell the user to upgrade.
3. `get_compilation_issues` doubles as a Turbopack probe. An error
response of `"Turbopack project is not available..."` means the
user is on webpack. Refuse — Turbopack is required.
4. `get_routes` → your route map for the rest of the session.

## loop

### before the edit — narrow the scope

Ask the running app, not the codebase. `/_next/mcp` knows which
files rendered the current route; use those as your search scope.
Runtime introspection stays cheap as the codebase grows; agentic
search doesn't.

### after the edit — verify

Four failure modes. Check each:

- **Compiles** — `get_compilation_issues`.
- **Runs without errors** — `/_next/mcp` (server and bubbled-up
browser errors both surface here).
- **Behaves as intended** — `agent-browser` drives the page; assert
what the user actually sees.
- **React-level behavior** — `agent-browser` with react-devtools
enabled exposes the component tree, props, state, and render
counts. Anchor framework-level checks here (extra renders,
server/client boundary shifts, suspense fallbacks) — DOM asserts
alone miss them.

Pick the specific tool from `tools/list` or the agent-browser
manual rather than from memory.

## gotchas

- **Every `agent-browser` command must know your session and restore
key, or it may use an empty default browser or fail to save login
state.** Easiest: export both `AGENT_BROWSER_SESSION="$SESSION"` and
`AGENT_BROWSER_RESTORE="$SESSION"` at the top of each shell you run
agent-browser in. If you do not export them, pass
`--session "$SESSION" --restore` on every command.
- **When the two views disagree, suspect the tooling first.** If
`agent-browser` says a route is broken but `/_next/mcp` and the
server say it rendered cleanly, a stale or misdirected browser
session is the likelier cause than a real bug — reconcile the views
before debugging the app.
- Confirming a click or navigation: the page settles a beat later, so
wait with `wait --load networkidle` (no path to get wrong), then
snapshot/read to confirm the page. Avoid `wait --url` unless you pass
the link's exact href — a guessed or placeholder path won't match the
real URL and times out after 25s.
- A blank read, empty snapshot, `about:blank`, or a "no browser
session" error — right after `open` or after a click (even if `open`
reported the page) — is the browser dropping the page (a stale
session), not a broken route. Reopen your session at the URL with
`--session "$SESSION" --restore` and re-snapshot; if still blank,
run `agent-browser --session "$SESSION" --restore close`, then open
again. Don't fall back to `curl`; it bypasses the browser you're
testing.
- React introspection output is stale after navigation. Re-run.
- `/_next/mcp` replies are SSE — read the JSON off the `data:` line
with `sed -n 's/^data: //p'` (a plain `sed 's/^data: //'` leaves the
`event:` line and the parse fails).
- Non-3000 dev server: read the `next dev` banner; set
`NEXT_MCP_URL=http://localhost:<port>/_next/mcp`.
- `get_errors` and `get_page_metadata` need at least one navigation
to populate.

## reference

All tools below are present once preflight passes. If `tools/list`
is missing any of them, preflight should have refused — re-check.

```
# /_next/mcp notes
get_project_metadata projectPath, devServerUrl, bundler
get_routes fs-scan; no browser session needed
get_errors runtime + build; needs a browser session;
includes browser-side errors caught by the
dev server
get_page_metadata segment trie + routerType; needs a browser
session; use as a discovery shortcut for
which files power a route
get_logs returns logFilePath
get_server_action_by_id hashed id → file + functionName
get_compilation_issues Turbopack only; errors on webpack
("Turbopack project is not available")
```

## teardown

Close the session with the same session and restore context:
`agent-browser --session "$SESSION" --restore close`. `close` saves
that session's cookies and storage so the next loop's `--restore` open
keeps the user logged in. Leave `next dev` up for the next loop.

---

`next-dev-loop-<topic>` siblings (e.g. `next-dev-loop-rsc`, `next-dev-loop-debug`)
assume this preflight already ran; they pick up at the loop.
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know

This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@AGENTS.md
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Boundary } from '#/ui/boundary';
import { Mdx } from '#/ui/codehike';
import { CounterProvider } from 'app/context/counter-context';
import React from 'react';
import { CounterProvider } from './counter-context';
import ContextClickCounter from './context-click-counter';
import Readme from './readme.mdx';
const title = 'Client Context';
Expand Down
2 changes: 1 addition & 1 deletion app/context/page.tsx → app/(playground)/context/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ContextClickCounter from '#/app/context/context-click-counter';
import db from '#/lib/db';
import { Boundary } from '#/ui/boundary';
import { ProductCard } from '#/ui/product-card';
import ContextClickCounter from './context-click-counter';

export default function Page() {
const products = db.product.findMany({ limit: 9 });
Expand Down
File renamed without changes.
34 changes: 34 additions & 0 deletions app/(playground)/error-recovery/_lib/unstable-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import 'server-only';

import { connection } from 'next/server';

const attempts = new Map<string, number>();

export type BoundaryKind = 'catchError' | 'error.tsx';

export async function readTransientReport(boundary: BoundaryKind) {
await connection();
await new Promise((resolve) => setTimeout(resolve, 700));

const previousAttempts = attempts.get(boundary) ?? 0;
const nextAttempt = previousAttempts + 1;
attempts.set(boundary, nextAttempt);

if (previousAttempts === 0) {
throw new Error(`${boundary} report failed on attempt ${nextAttempt}`);
}

return {
boundary,
attempt: nextAttempt,
refreshedAt: new Date().toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
}),
};
}

export function resetTransientReport(boundary: BoundaryKind) {
attempts.delete(boundary);
}
14 changes: 14 additions & 0 deletions app/(playground)/error-recovery/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use server';

import { redirect } from 'next/navigation';
import { resetTransientReport } from './_lib/unstable-data';

export async function resetCatchErrorDemoAction() {
resetTransientReport('catchError');
redirect('/error-recovery/catch-error');
}

export async function resetErrorTsxDemoAction() {
resetTransientReport('error.tsx');
redirect('/error-recovery/error-tsx');
}
39 changes: 39 additions & 0 deletions app/(playground)/error-recovery/catch-error/error-boundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use client';

import Button from '#/ui/button';
import { Boundary } from '#/ui/boundary';
import { catchError, type ErrorInfo } from 'next/error';
import Link from 'next/link';

function ErrorFallback(
props: { title: string; backHref: string },
{ error, retry }: ErrorInfo,
) {
return (
<Boundary label="catchError fallback" color="red" size="small">
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<h1 className="text-lg font-semibold text-gray-300">{props.title}</h1>
<p className="text-sm leading-6 text-gray-400">
{error instanceof Error
? error.message
: 'The report failed to render.'}
</p>
</div>
<div className="flex flex-wrap gap-3">
<Button kind="error" onClick={() => retry()}>
Retry Server Component
</Button>
<Link
href={props.backHref}
className="rounded-md bg-gray-800 px-3 py-1 text-sm font-semibold text-gray-300 hover:bg-gray-700 hover:text-white"
>
Back
</Link>
</div>
</div>
</Boundary>
);
}

export default catchError(ErrorFallback);
9 changes: 9 additions & 0 deletions app/(playground)/error-recovery/catch-error/loading.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Boundary } from '#/ui/boundary';

export default function Loading() {
return (
<Boundary label="loading.tsx">
<div className="text-sm text-gray-400">Loading component demo...</div>
</Boundary>
);
}
78 changes: 78 additions & 0 deletions app/(playground)/error-recovery/catch-error/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { Boundary } from '#/ui/boundary';
import Button from '#/ui/button';
import { SkeletonText } from '#/ui/skeleton';
import Link from 'next/link';
import { Suspense } from 'react';
import { resetCatchErrorDemoAction } from '../actions';
import { readTransientReport } from '../_lib/unstable-data';
import ErrorBoundary from './error-boundary';

export default function Page() {
return (
<Boundary label="catch-error/page.tsx">
<div className="flex flex-col gap-6">
<Link
href="/error-recovery"
className="text-sm font-medium text-gray-400 hover:text-white"
>
Back to error recovery
</Link>
<ErrorBoundary
title="The analytics card crashed"
backHref="/error-recovery"
>
<Suspense fallback={<PanelSkeleton />}>
<UnstableAnalyticsPanel />
</Suspense>
</ErrorBoundary>
</div>
</Boundary>
);
}

async function UnstableAnalyticsPanel() {
const report = await readTransientReport('catchError');

return (
<Boundary
label="<UnstableAnalyticsPanel>"
size="small"
className="flex flex-col gap-4"
>
<h1 className="text-xl font-semibold text-gray-300">
Analytics recovered
</h1>
<div className="grid grid-cols-1 gap-3 text-sm text-gray-400 lg:grid-cols-3">
<Stat label="Boundary" value={report.boundary} />
<Stat label="Attempt" value={String(report.attempt)} />
<Stat label="Refreshed" value={report.refreshedAt} />
</div>
<form action={resetCatchErrorDemoAction}>
<Button type="submit">Reset demo</Button>
</form>
</Boundary>
);
}

function PanelSkeleton() {
return (
<Boundary label="<UnstableAnalyticsPanel>" size="small">
<SkeletonText
count={18}
seed="error-recovery-component"
className="text-gray-800"
/>
</Boundary>
);
}

function Stat({ label, value }: { label: string; value: string }) {
return (
<div className="bg-gray-900 p-4">
<div className="font-mono text-xs font-semibold tracking-wider text-gray-600 uppercase">
{label}
</div>
<div className="mt-2 text-lg font-semibold text-gray-300">{value}</div>
</div>
);
}
Loading