avyvar commited on
Commit
4514571
·
verified ·
1 Parent(s): 94786da

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. nextjs-95375-instant-cookie-recovery/environment/Dockerfile +44 -0
  2. nextjs-95375-instant-cookie-recovery/solution/gold.patch +175 -0
  3. nextjs-95375-instant-cookie-recovery/solution/solve.sh +3 -0
  4. nextjs-95375-instant-cookie-recovery/tests/Dockerfile +42 -0
  5. nextjs-95375-instant-cookie-recovery/tests/test.patch +87 -0
  6. nextjs-95375-instant-cookie-recovery/tests/test.sh +98 -0
  7. nextjs-96250-turbopack-route-announcements/environment/Dockerfile +44 -0
  8. nextjs-96250-turbopack-route-announcements/solution/gold.patch +41 -0
  9. nextjs-96250-turbopack-route-announcements/solution/solve.sh +3 -0
  10. nextjs-96250-turbopack-route-announcements/tests/Dockerfile +42 -0
  11. nextjs-96250-turbopack-route-announcements/tests/test.patch +189 -0
  12. nextjs-96250-turbopack-route-announcements/tests/test.sh +98 -0
  13. nextjs-96390-not-found-adapter/environment/Dockerfile +44 -0
  14. nextjs-96390-not-found-adapter/solution/gold.patch +60 -0
  15. nextjs-96390-not-found-adapter/solution/solve.sh +3 -0
  16. nextjs-96390-not-found-adapter/tests/Dockerfile +42 -0
  17. nextjs-96390-not-found-adapter/tests/test.patch +160 -0
  18. nextjs-96390-not-found-adapter/tests/test.sh +98 -0
  19. nextjs-byte-exact-binary-fetch-cache-keys/environment/Dockerfile +44 -0
  20. nextjs-byte-exact-binary-fetch-cache-keys/solution/gold.patch +301 -0
  21. nextjs-byte-exact-binary-fetch-cache-keys/solution/solve.sh +3 -0
  22. nextjs-cache-components-dynamic-param-prerenders/environment/Dockerfile +44 -0
  23. nextjs-cache-components-dynamic-param-prerenders/solution/gold.patch +139 -0
  24. nextjs-cache-components-dynamic-param-prerenders/solution/solve.sh +3 -0
  25. nextjs-cache-components-dynamic-param-prerenders/tests/Dockerfile +42 -0
  26. nextjs-cache-components-dynamic-param-prerenders/tests/test.patch +440 -0
  27. nextjs-cache-components-dynamic-param-prerenders/tests/test.sh +98 -0
  28. nextjs-client-node-browser-variants/environment/Dockerfile +45 -0
  29. nextjs-client-node-browser-variants/solution/gold.patch +178 -0
  30. nextjs-client-node-browser-variants/solution/solve.sh +3 -0
  31. nextjs-client-node-browser-variants/tests/Dockerfile +43 -0
  32. nextjs-client-node-browser-variants/tests/test.patch +109 -0
  33. nextjs-client-node-browser-variants/tests/test.sh +98 -0
  34. nextjs-codemod-noninteractive-upgrade/environment/Dockerfile +44 -0
  35. nextjs-codemod-noninteractive-upgrade/solution/gold.patch +233 -0
  36. nextjs-codemod-noninteractive-upgrade/solution/solve.sh +3 -0
  37. nextjs-codemod-noninteractive-upgrade/tests/Dockerfile +42 -0
  38. nextjs-codemod-noninteractive-upgrade/tests/test.patch +283 -0
  39. nextjs-codemod-noninteractive-upgrade/tests/test.sh +98 -0
  40. nextjs-hybrid-router-adapter-not-found/environment/Dockerfile +44 -0
  41. nextjs-hybrid-router-adapter-not-found/solution/gold.patch +48 -0
  42. nextjs-hybrid-router-adapter-not-found/solution/solve.sh +3 -0
  43. nextjs-hybrid-router-adapter-not-found/tests/Dockerfile +42 -0
  44. nextjs-hybrid-router-adapter-not-found/tests/test.patch +209 -0
  45. nextjs-hybrid-router-adapter-not-found/tests/test.sh +98 -0
  46. nextjs-navigation-server-action-in-flight/environment/Dockerfile +44 -0
  47. nextjs-navigation-server-action-in-flight/solution/gold.patch +85 -0
  48. nextjs-navigation-server-action-in-flight/solution/solve.sh +3 -0
  49. nextjs-navigation-server-action-in-flight/tests/Dockerfile +42 -0
  50. nextjs-navigation-server-action-in-flight/tests/test.patch +385 -0
nextjs-95375-instant-cookie-recovery/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build && pnpm exec playwright install --with-deps chromium' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-95375-instant-cookie-recovery/solution/gold.patch ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next-playwright/src/index.ts b/packages/next-playwright/src/index.ts
2
+ index 0267a1a716..291afa9ef0 100644
3
+ --- a/packages/next-playwright/src/index.ts
4
+ +++ b/packages/next-playwright/src/index.ts
5
+ @@ -29,6 +29,23 @@ interface PlaywrightPage {
6
+
7
+ const INSTANT_COOKIE = 'next-instant-navigation-testing'
8
+
9
+ +// Browser contexts that currently have an instant() scope executing. The
10
+ +// instant cookie is scoped to the browser context, so the context is the
11
+ +// natural granularity for the scope: two concurrent instant() calls on the same
12
+ +// context share one cookie and genuinely conflict, whereas calls on different
13
+ +// contexts (or different browsers) are independent and must not. Keying on the
14
+ +// context object preserves that isolation while giving a race-free nesting
15
+ +// signal.
16
+ +//
17
+ +// We track this in-process rather than inferring nesting from the cookie's
18
+ +// presence: a locked page asynchronously re-writes the instant cookie on every
19
+ +// MPA load (see navigation-testing-lock.ts), and that write can land right
20
+ +// after a prior scope's release deletes it, resurrecting the cookie once the
21
+ +// scope has already ended. Treating such a leftover as an active scope would
22
+ +// turn a benign residue into a cascading failure across every later test that
23
+ +// shares the browser context.
24
+ +const contextsWithActiveScope = new WeakSet<PlaywrightBrowserContext>()
25
+ +
26
+ /**
27
+ * Runs a function with instant navigation enabled. Within this scope,
28
+ * navigations render the prefetched UI immediately and wait for the
29
+ @@ -55,10 +72,8 @@ export async function instant<T>(
30
+ fn: () => Promise<T>,
31
+ options?: { baseURL?: string }
32
+ ): Promise<T> {
33
+ - // Check for nested instant() calls. The cookie is scoped to the browser
34
+ - // context, so we can detect nesting by checking if it's already set.
35
+ - const existingCookies = await page.context().cookies()
36
+ - if (existingCookies.some((c) => c.name === INSTANT_COOKIE)) {
37
+ + const context = page.context()
38
+ + if (contextsWithActiveScope.has(context)) {
39
+ throw new Error(
40
+ 'An instant() scope is already active. Nesting instant() ' +
41
+ 'calls is not supported. Did you forget to await the ' +
42
+ @@ -66,56 +81,86 @@ export async function instant<T>(
43
+ )
44
+ }
45
+
46
+ - // Acquire the lock by setting the cookie via the browser context. This
47
+ - // ensures the cookie is present even on the very first navigation.
48
+ - // The cookie triggers the CookieStore change event in
49
+ - // navigation-testing-lock.ts, which acquires the in-memory navigation lock.
50
+ + // Resolve the cookie's scope before touching any browser state, so misuse on
51
+ + // a fresh page (no baseURL and no prior navigation) fails with the
52
+ + // descriptive error from resolveURL rather than half-entering a scope.
53
+ const { hostname } = new URL(resolveURL(page, options))
54
+ - await step('Acquire Instant Lock', () =>
55
+ - page.context().addCookies([
56
+ - {
57
+ - name: INSTANT_COOKIE,
58
+ - value: JSON.stringify([0, `p${Math.random()}`]),
59
+ - domain: hostname,
60
+ - path: '/',
61
+ - },
62
+ - ])
63
+ - )
64
+ +
65
+ + contextsWithActiveScope.add(context)
66
+ try {
67
+ - return await fn()
68
+ + // A completed prior scope on this context can leave the cookie behind (its
69
+ + // client-side release races an in-flight captured-cookie write from a
70
+ + // locked MPA page load; see the note above). No scope is active for this
71
+ + // context, so a present cookie is always stale here — clear it before
72
+ + // acquiring so a completed prior scope never blocks this one.
73
+ + await releaseInstantCookie(context)
74
+ +
75
+ + // Acquire the lock by setting the cookie via the browser context. This
76
+ + // ensures the cookie is present even on the very first navigation. The
77
+ + // cookie triggers the CookieStore change event in
78
+ + // navigation-testing-lock.ts, which acquires the in-memory navigation lock.
79
+ + await step('Acquire Instant Lock', () =>
80
+ + context.addCookies([
81
+ + {
82
+ + name: INSTANT_COOKIE,
83
+ + value: JSON.stringify([0, `p${Math.random()}`]),
84
+ + domain: hostname,
85
+ + path: '/',
86
+ + },
87
+ + ])
88
+ + )
89
+ + try {
90
+ + return await fn()
91
+ + } finally {
92
+ + await step('Release Instant Lock', () => releaseInstantCookie(context))
93
+ + }
94
+ } finally {
95
+ - // Release the lock by expiring the instant cookie, leaving every other
96
+ - // cookie untouched.
97
+ - //
98
+ - // We must NOT use `context.clearCookies({ name: INSTANT_COOKIE })` here.
99
+ - // Playwright implements a filtered `clearCookies` by clearing the ENTIRE
100
+ - // cookie jar and then re-adding the cookies that don't match the filter.
101
+ - // That briefly removes the application's own cookies too. Next.js reacts
102
+ - // to the instant cookie's deletion by immediately re-rendering, and if
103
+ - // that render's request races the empty window it observes none of the
104
+ - // app's cookies (e.g. a navigated page renders as if no cookies were set).
105
+ - //
106
+ - // Instead we read the instant cookie's stored entries (Next.js may have
107
+ - // updated the value, e.g. from [0] to [1,null], but preserves the domain
108
+ - // and path) and re-add each with a past expiry, which deletes only those
109
+ - // entries without disturbing the rest of the jar.
110
+ - await step('Release Instant Lock', async () => {
111
+ - const instantCookies = (await page.context().cookies()).filter(
112
+ - (cookie) => cookie.name === INSTANT_COOKIE
113
+ - )
114
+ - if (instantCookies.length > 0) {
115
+ - await page.context().addCookies(
116
+ - instantCookies.map((cookie) => ({
117
+ - name: cookie.name,
118
+ - value: cookie.value,
119
+ - domain: cookie.domain,
120
+ - path: cookie.path,
121
+ - // A past expiry (Unix epoch seconds) deletes the cookie.
122
+ - expires: 1,
123
+ - }))
124
+ - )
125
+ - }
126
+ - })
127
+ + contextsWithActiveScope.delete(context)
128
+ + }
129
+ +}
130
+ +
131
+ +/**
132
+ + * Deletes the instant cookie, leaving every other cookie untouched.
133
+ + *
134
+ + * We must NOT use `context.clearCookies({ name: INSTANT_COOKIE })` here.
135
+ + * Playwright implements a filtered `clearCookies` by clearing the ENTIRE cookie
136
+ + * jar and then re-adding the cookies that don't match the filter. That briefly
137
+ + * removes the application's own cookies too. Next.js reacts to the instant
138
+ + * cookie's deletion by immediately re-rendering, and if that render's request
139
+ + * races the empty window it observes none of the app's cookies (e.g. a
140
+ + * navigated page renders as if no cookies were set).
141
+ + *
142
+ + * Instead we read the instant cookie's stored entries (Next.js may have updated
143
+ + * the value, e.g. from [0] to [1,null], but preserves the domain and path) and
144
+ + * re-add each with a past expiry, which deletes only those entries without
145
+ + * disturbing the rest of the jar.
146
+ + *
147
+ + * A locked MPA page load can asynchronously re-write (resurrect) the cookie
148
+ + * just after we delete it: the client only stops writing once it observes the
149
+ + * deletion, an event that races the pending write. We therefore re-read and
150
+ + * re-delete until the cookie stays gone, bounded so a cookie that some other
151
+ + * actor keeps re-setting can't loop forever.
152
+ + */
153
+ +async function releaseInstantCookie(
154
+ + context: PlaywrightBrowserContext
155
+ +): Promise<void> {
156
+ + for (let attempt = 0; attempt < 5; attempt++) {
157
+ + const instantCookies = (await context.cookies()).filter(
158
+ + (cookie) => cookie.name === INSTANT_COOKIE
159
+ + )
160
+ + if (instantCookies.length === 0) {
161
+ + return
162
+ + }
163
+ + await context.addCookies(
164
+ + instantCookies.map((cookie) => ({
165
+ + name: cookie.name,
166
+ + value: cookie.value,
167
+ + domain: cookie.domain,
168
+ + path: cookie.path,
169
+ + // A past expiry (Unix epoch seconds) deletes the cookie.
170
+ + expires: 1,
171
+ + }))
172
+ + )
173
+ }
174
+ }
175
+
nextjs-95375-instant-cookie-recovery/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-95375-instant-cookie-recovery/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build && pnpm exec playwright install --with-deps chromium' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-95375-instant-cookie-recovery/tests/test.patch ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts b/test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts
2
+ index 212d760f63..78f8bb2a1a 100644
3
+ --- a/test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts
4
+ +++ b/test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts
5
+ @@ -216,6 +216,82 @@ describe('instant-navigation-testing-api', () => {
6
+ })
7
+ })
8
+
9
+ + it('recovers from a stale instant cookie left by a prior scope', async () => {
10
+ + const page = await openPage(next, '/')
11
+ +
12
+ + // Simulate a cookie leaked by a previous instant() scope. A locked MPA page
13
+ + // load re-writes the cookie asynchronously and can resurrect it right after
14
+ + // a prior scope's release deletes it, leaving a captured-state entry in the
15
+ + // shared browser context. Because the context is reused across tests, a new
16
+ + // instant() call must treat that residue as stale (clearing it) rather than
17
+ + // reporting an active scope, or every following test would cascade-fail.
18
+ + const { hostname } = new URL(next.url)
19
+ + await page.context().addCookies([
20
+ + {
21
+ + name: 'next-instant-navigation-testing',
22
+ + value: JSON.stringify([1, 'c-stale', null]),
23
+ + domain: hostname,
24
+ + path: '/',
25
+ + },
26
+ + ])
27
+ +
28
+ + let ranCallback = false
29
+ + await instant(page, async () => {
30
+ + ranCallback = true
31
+ + await page.click('#link-to-target')
32
+ + const loadingShell = page.locator('[data-testid="loading-shell"]')
33
+ + await loadingShell.waitFor({ state: 'visible' })
34
+ + })
35
+ + expect(ranCallback).toBe(true)
36
+ +
37
+ + // After exiting the scope the cookie is gone again, so a normal navigation
38
+ + // is not locked and dynamic content streams in.
39
+ + const dynamicContent = page.locator('[data-testid="dynamic-content"]')
40
+ + await dynamicContent.waitFor({ state: 'visible' })
41
+ + })
42
+ +
43
+ + it('allows concurrent instant scopes across separate browser contexts', async () => {
44
+ + const page = await openPage(next, '/')
45
+ +
46
+ + // A second, independent browser context. Its cookie jar and its page's
47
+ + // navigation lock are separate from the first context's, so a concurrent
48
+ + // instant() scope here must not be reported as already active against the
49
+ + // first. This guards against tracking the active scope per-process instead
50
+ + // of per-context.
51
+ + const browser = page.context().browser()
52
+ + if (!browser) {
53
+ + throw new Error('Expected the page context to expose a browser instance')
54
+ + }
55
+ + const otherContext = await browser.newContext()
56
+ + try {
57
+ + const otherPage = await otherContext.newPage()
58
+ + await otherPage.goto(next.url)
59
+ +
60
+ + let ranFirst = false
61
+ + let ranSecond = false
62
+ + await Promise.all([
63
+ + instant(page, async () => {
64
+ + ranFirst = true
65
+ + await page.click('#link-to-target')
66
+ + await page
67
+ + .locator('[data-testid="loading-shell"]')
68
+ + .waitFor({ state: 'visible' })
69
+ + }),
70
+ + instant(otherPage, async () => {
71
+ + ranSecond = true
72
+ + await otherPage.click('#link-to-target')
73
+ + await otherPage
74
+ + .locator('[data-testid="loading-shell"]')
75
+ + .waitFor({ state: 'visible' })
76
+ + }),
77
+ + ])
78
+ + expect(ranFirst).toBe(true)
79
+ + expect(ranSecond).toBe(true)
80
+ + } finally {
81
+ + await otherContext.close()
82
+ + }
83
+ + })
84
+ +
85
+ it('renders shell on page reload', async () => {
86
+ const page = await openPage(next, '/target-page')
87
+
nextjs-95375-instant-cookie-recovery/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts' --exclude='test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'pnpm --filter @next/playwright build && pnpm test-dev-webpack '"'"'test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'pnpm --filter @next/playwright build && pnpm test-dev-webpack '"'"'test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'true'; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-96250-turbopack-route-announcements/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps chromium' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-96250-turbopack-route-announcements/solution/gold.patch ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/server/dev/hot-reloader-turbopack.ts b/packages/next/src/server/dev/hot-reloader-turbopack.ts
2
+ index 2aaf1e65fe..d0b5d7b8ef 100644
3
+ --- a/packages/next/src/server/dev/hot-reloader-turbopack.ts
4
+ +++ b/packages/next/src/server/dev/hot-reloader-turbopack.ts
5
+ @@ -789,6 +789,9 @@ export async function createHotReloaderTurbopack(
6
+ // advancing there would both churn the hash without an edit and fail to
7
+ // advance it at all when no client is connected.
8
+ let hmrHash = 0
9
+ + // Undefined until the first entrypoints emission. That one has nothing to
10
+ + // compare against, so every route it lists would look added.
11
+ + let previousRouteKeys: Set<string> | undefined
12
+
13
+ // HACK: Defer sending `building` messages. Turbopack emits a compile pass for every
14
+ // foreground-job cycle, including empty no-op recompiles scheduled by
15
+ @@ -1041,18 +1044,14 @@ export async function createHotReloaderTurbopack(
16
+ }
17
+
18
+ const routes = entrypoints.routes
19
+ - const existingRoutes = [
20
+ - ...currentEntrypoints.app.keys(),
21
+ - ...currentEntrypoints.page.keys(),
22
+ - ]
23
+ - const newRoutes = [...routes.keys()]
24
+ -
25
+ - const addedRoutes = newRoutes.filter(
26
+ - (route) =>
27
+ - !currentEntrypoints.app.has(route) &&
28
+ - !currentEntrypoints.page.has(route)
29
+ - )
30
+ - const removedRoutes = existingRoutes.filter((route) => !routes.has(route))
31
+ + const prevRouteKeys = previousRouteKeys
32
+ + const addedRoutes = prevRouteKeys
33
+ + ? [...routes.keys()].filter((route) => !prevRouteKeys.has(route))
34
+ + : []
35
+ + const removedRoutes = prevRouteKeys
36
+ + ? [...prevRouteKeys].filter((route) => !routes.has(route))
37
+ + : []
38
+ + previousRouteKeys = new Set(routes.keys())
39
+
40
+ await handleEntrypoints({
41
+ entrypoints: entrypoints as any,
nextjs-96250-turbopack-route-announcements/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-96250-turbopack-route-announcements/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps chromium' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-96250-turbopack-route-announcements/tests/test.patch ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/development/app-dir/route-change-refetch/fixtures/app/app/counted/page.tsx b/test/development/app-dir/route-change-refetch/fixtures/app/app/counted/page.tsx
2
+ new file mode 100644
3
+ index 00000000..214d82c0
4
+ --- /dev/null
5
+ +++ b/test/development/app-dir/route-change-refetch/fixtures/app/app/counted/page.tsx
6
+ @@ -0,0 +1,3 @@
7
+ +export default function Page() {
8
+ + return <p id="counted">counted</p>
9
+ +}
10
+ diff --git a/test/development/app-dir/route-change-refetch/fixtures/app/app/existing/page.tsx b/test/development/app-dir/route-change-refetch/fixtures/app/app/existing/page.tsx
11
+ new file mode 100644
12
+ index 00000000..03b551f3
13
+ --- /dev/null
14
+ +++ b/test/development/app-dir/route-change-refetch/fixtures/app/app/existing/page.tsx
15
+ @@ -0,0 +1,3 @@
16
+ +export default function Page() {
17
+ + return <p id="existing">existing</p>
18
+ +}
19
+ diff --git a/test/development/app-dir/route-change-refetch/fixtures/app/app/layout.tsx b/test/development/app-dir/route-change-refetch/fixtures/app/app/layout.tsx
20
+ new file mode 100644
21
+ index 00000000..e7077399
22
+ --- /dev/null
23
+ +++ b/test/development/app-dir/route-change-refetch/fixtures/app/app/layout.tsx
24
+ @@ -0,0 +1,7 @@
25
+ +export default function Root({ children }: { children: React.ReactNode }) {
26
+ + return (
27
+ + <html>
28
+ + <body>{children}</body>
29
+ + </html>
30
+ + )
31
+ +}
32
+ diff --git a/test/development/app-dir/route-change-refetch/fixtures/app/app/page.tsx b/test/development/app-dir/route-change-refetch/fixtures/app/app/page.tsx
33
+ new file mode 100644
34
+ index 00000000..56c1adc4
35
+ --- /dev/null
36
+ +++ b/test/development/app-dir/route-change-refetch/fixtures/app/app/page.tsx
37
+ @@ -0,0 +1,3 @@
38
+ +export default function Page() {
39
+ + return <p id="home">home</p>
40
+ +}
41
+ diff --git a/test/development/app-dir/route-change-refetch/fixtures/app/app/posts/[id]/page.tsx b/test/development/app-dir/route-change-refetch/fixtures/app/app/posts/[id]/page.tsx
42
+ new file mode 100644
43
+ index 00000000..20fd68f1
44
+ --- /dev/null
45
+ +++ b/test/development/app-dir/route-change-refetch/fixtures/app/app/posts/[id]/page.tsx
46
+ @@ -0,0 +1,4 @@
47
+ +export default async function Page(props: { params: Promise<{ id: string }> }) {
48
+ + const { id } = await props.params
49
+ + return <p id="dynamic">dynamic {id}</p>
50
+ +}
51
+ diff --git a/test/development/app-dir/route-change-refetch/fixtures/app/app/renamed-a/page.tsx b/test/development/app-dir/route-change-refetch/fixtures/app/app/renamed-a/page.tsx
52
+ new file mode 100644
53
+ index 00000000..4ebc2313
54
+ --- /dev/null
55
+ +++ b/test/development/app-dir/route-change-refetch/fixtures/app/app/renamed-a/page.tsx
56
+ @@ -0,0 +1,3 @@
57
+ +export default function Page() {
58
+ + return <p id="renamed">renamed</p>
59
+ +}
60
+ diff --git a/test/development/app-dir/route-change-refetch/route-change-refetch.test.ts b/test/development/app-dir/route-change-refetch/route-change-refetch.test.ts
61
+ new file mode 100644
62
+ index 00000000..2bb4715a
63
+ --- /dev/null
64
+ +++ b/test/development/app-dir/route-change-refetch/route-change-refetch.test.ts
65
+ @@ -0,0 +1,124 @@
66
+ +import { nextTestSetup } from 'e2e-utils'
67
+ +import { retry, waitFor } from 'next-test-utils'
68
+ +import type { Page } from 'playwright'
69
+ +import * as nodeFs from 'node:fs'
70
+ +import * as nodePath from 'node:path'
71
+ +
72
+ +type RouteAnnouncement = {
73
+ + type: 'addedPage' | 'removedPage'
74
+ + route: string
75
+ +}
76
+ +
77
+ +function recordRouteAnnouncements(announcements: RouteAnnouncement[]) {
78
+ + return (page: Page) => {
79
+ + page.on('websocket', (ws) => {
80
+ + if (new URL(ws.url()).pathname !== '/_next/hmr') return
81
+ + ws.on('framereceived', (frame) => {
82
+ + const payload =
83
+ + typeof frame.payload === 'string'
84
+ + ? frame.payload
85
+ + : frame.payload.toString('utf8')
86
+ + let message: { type?: string; data?: unknown[] }
87
+ + try {
88
+ + message = JSON.parse(payload)
89
+ + } catch {
90
+ + return
91
+ + }
92
+ + const route = message.data?.[0]
93
+ + if (
94
+ + (message.type === 'addedPage' || message.type === 'removedPage') &&
95
+ + typeof route === 'string'
96
+ + ) {
97
+ + announcements.push({ type: message.type, route })
98
+ + }
99
+ + })
100
+ + })
101
+ + }
102
+ +}
103
+ +
104
+ +describe('Turbopack route change announcements', () => {
105
+ + const { next } = nextTestSetup({
106
+ + files: nodePath.join(__dirname, 'fixtures/app'),
107
+ + })
108
+ +
109
+ + async function cleanupAddedPage() {
110
+ + if (nodeFs.existsSync(nodePath.join(next.testDir, 'app/zz-added'))) {
111
+ + await next.deleteFile('app/zz-added/page.tsx')
112
+ + await retry(async () => {
113
+ + expect((await next.fetch('/zz-added')).status).toBe(404)
114
+ + }, 15_000)
115
+ + }
116
+ + }
117
+ +
118
+ + it('announces only the newly added route under its route name', async () => {
119
+ + const announcements: RouteAnnouncement[] = []
120
+ + const browser = await next.browser('/existing', {
121
+ + beforePageLoad: recordRouteAnnouncements(announcements),
122
+ + })
123
+ + expect(await browser.elementById('existing').text()).toBe('existing')
124
+ +
125
+ + try {
126
+ + // Connecting to an already-running app establishes the baseline. None of
127
+ + // its routes are changes, so they must not be announced.
128
+ + await waitFor(1000)
129
+ + expect(announcements).toEqual([])
130
+ +
131
+ + await next.patchFile(
132
+ + 'app/zz-added/page.tsx',
133
+ + 'export default function Page() { return <p>added</p> }'
134
+ + )
135
+ + await retry(async () => {
136
+ + expect((await next.fetch('/zz-added')).status).toBe(200)
137
+ + }, 15_000)
138
+ + await retry(async () => {
139
+ + expect(announcements).toEqual([
140
+ + { type: 'addedPage', route: '/zz-added' },
141
+ + ])
142
+ + }, 15_000)
143
+ + await waitFor(1000)
144
+ + expect(announcements).toEqual([
145
+ + { type: 'addedPage', route: '/zz-added' },
146
+ + ])
147
+ + } finally {
148
+ + await cleanupAddedPage()
149
+ + await browser.close()
150
+ + }
151
+ + })
152
+ +
153
+ + it('announces only the removed route under its route name', async () => {
154
+ + const announcements: RouteAnnouncement[] = []
155
+ + const browser = await next.browser('/existing', {
156
+ + beforePageLoad: recordRouteAnnouncements(announcements),
157
+ + })
158
+ + expect(await browser.elementById('existing').text()).toBe('existing')
159
+ +
160
+ + try {
161
+ + await waitFor(1000)
162
+ + expect(announcements).toEqual([])
163
+ +
164
+ + await next.renameFile('app/existing/page.tsx', 'app/existing/page.bak')
165
+ + await retry(async () => {
166
+ + expect((await next.fetch('/existing')).status).toBe(404)
167
+ + }, 15_000)
168
+ + await retry(async () => {
169
+ + expect(announcements).toEqual([
170
+ + { type: 'removedPage', route: '/existing' },
171
+ + ])
172
+ + }, 15_000)
173
+ + await waitFor(1000)
174
+ + expect(announcements).toEqual([
175
+ + { type: 'removedPage', route: '/existing' },
176
+ + ])
177
+ + } finally {
178
+ + if (
179
+ + nodeFs.existsSync(nodePath.join(next.testDir, 'app/existing/page.bak'))
180
+ + ) {
181
+ + await next.renameFile('app/existing/page.bak', 'app/existing/page.tsx')
182
+ + await retry(async () => {
183
+ + expect((await next.fetch('/existing')).status).toBe(200)
184
+ + }, 15_000)
185
+ + }
186
+ + await browser.close()
187
+ + }
188
+ + })
189
+ +})
nextjs-96250-turbopack-route-announcements/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/development/app-dir/route-change-refetch/route-change-refetch.test.ts' --exclude='test/development/app-dir/route-change-refetch/route-change-refetch.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/development/app-dir/route-change-refetch/route-change-refetch.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/development/app-dir/route-change-refetch/route-change-refetch.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/test/development/app-dir/route-change-refetch/route-change-refetch.test.ts'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'pnpm --filter next build && pnpm test-dev-turbo '"'"'test/development/app-dir/route-change-refetch/route-change-refetch.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'pnpm --filter next build && pnpm test-dev-turbo '"'"'test/development/app-dir/route-change-refetch/route-change-refetch.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'true'; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-96390-not-found-adapter/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && pnpm install --frozen-lockfile && NEXT_TELEMETRY_DISABLED=1 pnpm build' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-96390-not-found-adapter/solution/gold.patch ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/build/adapter/build-complete.ts b/packages/next/src/build/adapter/build-complete.ts
2
+ index 131605cac3..00b7db3879 100644
3
+ --- a/packages/next/src/build/adapter/build-complete.ts
4
+ +++ b/packages/next/src/build/adapter/build-complete.ts
5
+ @@ -1387,12 +1387,6 @@ export async function handleBuildComplete({
6
+ const isAppPage =
7
+ Boolean(appOutputMap[srcRoute]) || srcRoute === '/_not-found'
8
+
9
+ - // if we already have 404.html favor that instead of
10
+ - // _not-found prerender
11
+ - if (srcRoute === '/_not-found' && hasStatic404) {
12
+ - continue
13
+ - }
14
+ -
15
+ const isNotFoundTrue = prerenderManifest.notFoundRoutes.includes(route)
16
+
17
+ let allowQuery: string[] | undefined
18
+ @@ -1458,6 +1452,13 @@ export async function handleBuildComplete({
19
+
20
+ const meta = await getAppRouteMeta(route, isAppPage)
21
+
22
+ + // If we already have a complete 404.html, favor that instead of the
23
+ + // _not-found prerender. A route with postponed state only produced a
24
+ + // shell, so preserve its prerender output in order to resume it.
25
+ + if (srcRoute === '/_not-found' && hasStatic404 && !meta.postponed) {
26
+ + continue
27
+ + }
28
+ +
29
+ let htmlAllowQuery = allowQuery
30
+ let dataAllowQuery = allowQuery
31
+ const dataInitialHeaders: Record<string, string> = {}
32
+ diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts
33
+ index da2f222113..b4e175cd34 100644
34
+ --- a/packages/next/src/build/index.ts
35
+ +++ b/packages/next/src/build/index.ts
36
+ @@ -2983,8 +2983,6 @@ export default async function build(
37
+ !hasPages500 && !hasNonStaticErrorPage && !customAppGetInitialProps
38
+
39
+ const combinedPages = [...staticPages, ...ssgPages]
40
+ - const isApp404Static = staticPaths.has(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY)
41
+ - const hasStaticApp404 = hasApp404 && isApp404Static
42
+ const isAppGlobalErrorStatic = staticPaths.has(
43
+ UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY
44
+ )
45
+ @@ -3960,7 +3958,14 @@ export default async function build(
46
+ })
47
+ }
48
+
49
+ - // If there's /not-found inside app, we prefer it over the pages 404
50
+ + // If there's a fully static /not-found inside app, we prefer it over
51
+ + // the pages 404. A partially prerendered not-found is only a shell,
52
+ + // so it must remain associated with its resumable prerender output.
53
+ + const hasStaticApp404 =
54
+ + hasApp404 &&
55
+ + staticPaths.has(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY) &&
56
+ + !pageInfos.get(UNDERSCORE_NOT_FOUND_ROUTE)?.hasPostponed
57
+ +
58
+ if (hasStaticApp404) {
59
+ await moveExportedAppNotFoundTo404()
60
+ } else {
nextjs-96390-not-found-adapter/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-96390-not-found-adapter/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && pnpm install --frozen-lockfile && NEXT_TELEMETRY_DISABLED=1 pnpm build' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-96390-not-found-adapter/tests/test.patch ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/e2e/app-dir/not-found-non-document-dynamic/app/layout.tsx b/test/e2e/app-dir/not-found-non-document-dynamic/app/layout.tsx
2
+ index c9606f1555..0b374ba091 100644
3
+ --- a/test/e2e/app-dir/not-found-non-document-dynamic/app/layout.tsx
4
+ +++ b/test/e2e/app-dir/not-found-non-document-dynamic/app/layout.tsx
5
+ @@ -3,7 +3,7 @@ import { connection } from 'next/server'
6
+
7
+ async function Dynamic() {
8
+ await connection()
9
+ - return null
10
+ + return <p id="dynamic-layout">dynamic layout content</p>
11
+ }
12
+
13
+ export default function Root({ children }: { children: ReactNode }) {
14
+ diff --git a/test/e2e/app-dir/not-found-non-document-dynamic/my-adapter.mjs b/test/e2e/app-dir/not-found-non-document-dynamic/my-adapter.mjs
15
+ new file mode 100644
16
+ index 0000000000..23c2d2f097
17
+ --- /dev/null
18
+ +++ b/test/e2e/app-dir/not-found-non-document-dynamic/my-adapter.mjs
19
+ @@ -0,0 +1,9 @@
20
+ +import fs from 'fs/promises'
21
+ +
22
+ +/** @type {import('next').NextAdapter} */
23
+ +export default {
24
+ + name: 'not-found-non-document-dynamic',
25
+ + async onBuildComplete(ctx) {
26
+ + await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
27
+ + },
28
+ +}
29
+ diff --git a/test/e2e/app-dir/not-found-non-document-dynamic/next.config.js b/test/e2e/app-dir/not-found-non-document-dynamic/next.config.js
30
+ index 807126e4cf..d0451f0268 100644
31
+ --- a/test/e2e/app-dir/not-found-non-document-dynamic/next.config.js
32
+ +++ b/test/e2e/app-dir/not-found-non-document-dynamic/next.config.js
33
+ @@ -3,4 +3,8 @@
34
+ */
35
+ const nextConfig = {}
36
+
37
+ +if (!process.env.NEXT_ADAPTER_PATH) {
38
+ + nextConfig.adapterPath = require.resolve('./my-adapter.mjs')
39
+ +}
40
+ +
41
+ module.exports = nextConfig
42
+ diff --git a/test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts b/test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts
43
+ index 4c5140fd77..b6a85b661c 100644
44
+ --- a/test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts
45
+ +++ b/test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts
46
+ @@ -1,4 +1,5 @@
47
+ -import { isNextDeploy, nextTestSetup } from 'e2e-utils'
48
+ +import { isNextDeploy, isNextStart, nextTestSetup } from 'e2e-utils'
49
+ +import type { NextAdapter } from 'next'
50
+
51
+ describe('not-found-non-document-dynamic', () => {
52
+ const { next } = nextTestSetup({
53
+ @@ -48,7 +49,9 @@ describe('not-found-non-document-dynamic', () => {
54
+ })
55
+ expect(res.status).toBe(404)
56
+ expect(res.headers.get('content-type')).toContain('text/html')
57
+ - expect(await res.text()).toContain('custom not found page')
58
+ + const html = await res.text()
59
+ + expect(html).toContain('custom not found page')
60
+ + expect(html).toContain('dynamic layout content')
61
+ })
62
+
63
+ it('renders the not-found page for fetch requests to unknown paths', async () => {
64
+ @@ -61,6 +64,49 @@ describe('not-found-non-document-dynamic', () => {
65
+ })
66
+ expect(res.status).toBe(404)
67
+ expect(res.headers.get('content-type')).toContain('text/html')
68
+ - expect(await res.text()).toContain('custom not found page')
69
+ + const html = await res.text()
70
+ + expect(html).toContain('custom not found page')
71
+ + expect(html).toContain('dynamic layout content')
72
+ })
73
+ +
74
+ + it('renders dynamic not-found content when selected by a rewrite', async () => {
75
+ + const res = await next.fetch('/rewritten-not-found')
76
+ + const html = await res.text()
77
+ +
78
+ + expect(res.status).toBe(404)
79
+ + expect(res.headers.get('content-type')).toContain('text/html')
80
+ + expect(html).toContain('custom not found page')
81
+ + expect(html).toContain('dynamic layout content')
82
+ + })
83
+ +
84
+ + if (isNextStart && process.env.__NEXT_CACHE_COMPONENTS) {
85
+ + it('publishes the partial not-found shell as a resumable prerender', async () => {
86
+ + expect(await next.hasFile('.next/server/pages/404.html')).toBe(false)
87
+ +
88
+ + const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
89
+ + await next.readJSON('build-complete.json')
90
+ + const notFoundPrerender = outputs.prerenders.find(
91
+ + (output) => output.pathname === '/_not-found'
92
+ + )
93
+ +
94
+ + expect(notFoundPrerender).toMatchObject({
95
+ + route: '/_not-found',
96
+ + routeType: 'page',
97
+ + response: 'initial',
98
+ + compute: 'resuming',
99
+ + pprChain: {
100
+ + headers: {
101
+ + 'next-resume': '1',
102
+ + },
103
+ + },
104
+ + config: {
105
+ + renderingMode: 'PARTIALLY_STATIC',
106
+ + },
107
+ + fallback: {
108
+ + postponedState: expect.any(String),
109
+ + initialStatus: 404,
110
+ + },
111
+ + })
112
+ + })
113
+ + }
114
+ })
115
+ diff --git a/test/e2e/app-dir/not-found-non-document-dynamic/proxy.ts b/test/e2e/app-dir/not-found-non-document-dynamic/proxy.ts
116
+ new file mode 100644
117
+ index 0000000000..52c8d6880b
118
+ --- /dev/null
119
+ +++ b/test/e2e/app-dir/not-found-non-document-dynamic/proxy.ts
120
+ @@ -0,0 +1,9 @@
121
+ +import { NextRequest, NextResponse } from 'next/server'
122
+ +
123
+ +export function proxy(request: NextRequest) {
124
+ + if (request.nextUrl.pathname === '/rewritten-not-found') {
125
+ + return NextResponse.rewrite(new URL('/_not-found', request.url), {
126
+ + status: 404,
127
+ + })
128
+ + }
129
+ +}
130
+ diff --git a/test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts b/test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts
131
+ index 2922744e8f..e9877dcd5a 100644
132
+ --- a/test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts
133
+ +++ b/test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts
134
+ @@ -228,6 +228,17 @@ describe('adapter-prerender-metadata', () => {
135
+ expect(staticPage.htmlSize).toBeGreaterThan(0)
136
+ })
137
+
138
+ + it('uses 404.html for a fully static not-found', async () => {
139
+ + const prerenders = await getPrerenders()
140
+ +
141
+ + expect(
142
+ + prerenders.find((output) => output.pathname === '/_not-found')
143
+ + ).toBeUndefined()
144
+ + expect(await next.readFile('.next/server/pages/404.html')).toContain(
145
+ + 'Not Found'
146
+ + )
147
+ + })
148
+ +
149
+ it('classifies an upgradable app template as fallback', async () => {
150
+ const prerenders = await getPrerenders()
151
+ const template = prerenders.find(
152
+ diff --git a/test/production/app-dir/adapter-prerender-metadata/app/not-found.tsx b/test/production/app-dir/adapter-prerender-metadata/app/not-found.tsx
153
+ new file mode 100644
154
+ index 0000000000..9db9e67b29
155
+ --- /dev/null
156
+ +++ b/test/production/app-dir/adapter-prerender-metadata/app/not-found.tsx
157
+ @@ -0,0 +1,3 @@
158
+ +export default function NotFound() {
159
+ + return <p>Not Found</p>
160
+ +}
nextjs-96390-not-found-adapter/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts' --exclude='test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts/*' --exclude='test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts' --exclude='test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts' 'test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts' 'test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts' '/app/test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'pnpm build && NEXT_TELEMETRY_DISABLED=1 pnpm test-start-experimental-turbo '"'"'test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'pnpm build && NEXT_TELEMETRY_DISABLED=1 pnpm test-start-experimental-turbo '"'"'test/e2e/app-dir/not-found-non-document-dynamic/not-found-non-document-dynamic.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'pnpm build && NEXT_TELEMETRY_DISABLED=1 pnpm test-start-experimental-turbo '"'"'test/production/app-dir/adapter-prerender-metadata/adapter-prerender-metadata.test.ts'"'"''; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-byte-exact-binary-fetch-cache-keys/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-byte-exact-binary-fetch-cache-keys/solution/gold.patch ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/errors.json b/packages/next/errors.json
2
+ index 6cf757d5c2..bc70516553 100644
3
+ --- a/packages/next/errors.json
4
+ +++ b/packages/next/errors.json
5
+ @@ -1440,5 +1440,6 @@
6
+ "1439": "Route \"%s\": Next.js encountered URL data during prerendering or a navigation.\\n\\n\\`params\\` or \\`searchParams\\` accessed outside of \\`<Suspense>\\` may prevent the navigation from being instant, leading to a slower user experience.\\n\\nWays to fix this:\\n - [stream] Provide a placeholder with \\`<Suspense fallback={...}>\\` around the data access\\n - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\nLearn more: https://nextjs.org/docs/messages/instant-shell-url-data",
7
+ "1440": "Route \"%s\": Next.js encountered uncached data during prerendering.\\n\\n\\`fetch(...)\\` or \\`connection()\\` accessed outside of \\`<Suspense>\\` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.\\n\\nWays to fix this:\\n - [stream] Provide a placeholder with \\`<Suspense fallback={...}>\\` around the data access\\n - [cache] Cache the data access with \\`\"use cache\"\\` (does not apply to \\`connection()\\`)\\n - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\nLearn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic",
8
+ "1441": "DevValidationScheduler requires at least one active validation",
9
+ - "1442": "The Server Reference ID did not match the expected format. Received %s.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action"
10
+ + "1442": "The Server Reference ID did not match the expected format. Received %s.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
11
+ + "1443": "Unsupported body type: %s"
12
+ }
13
+ diff --git a/packages/next/src/server/lib/incremental-cache/index.ts b/packages/next/src/server/lib/incremental-cache/index.ts
14
+ index 918f5583fb..31f100be25 100644
15
+ --- a/packages/next/src/server/lib/incremental-cache/index.ts
16
+ +++ b/packages/next/src/server/lib/incremental-cache/index.ts
17
+ @@ -55,6 +55,50 @@ export interface CacheHandlerValue {
18
+ value: IncrementalCacheValue | null
19
+ }
20
+
21
+ +function toHex(buffer: ArrayBufferView | ArrayBuffer): string {
22
+ + // Hex-encode body bytes losslessly: decoding as UTF-8 would collapse
23
+ + // distinct bytes (0xff/0xfe to U+FFFD) and collide; Buffer isn't on edge.
24
+ + const bytes = isArrayBuffer(buffer)
25
+ + ? new Uint8Array(buffer)
26
+ + : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
27
+ + let hex = ''
28
+ + for (const byte of bytes) {
29
+ + hex += byte.toString(16).padStart(2, '0')
30
+ + }
31
+ + return hex
32
+ +}
33
+ +
34
+ +type Body = NonNullable<RequestInit['body'] | Request['body']>
35
+ +
36
+ +// Duck typing to support Edge runtime
37
+ +// TODO: Switch to instanceof checks once Edge runtime is removed.
38
+ +
39
+ +function isArrayBuffer(
40
+ + buffer: ArrayBuffer | ArrayBufferView
41
+ +): buffer is ArrayBuffer {
42
+ + return !('buffer' in buffer)
43
+ +}
44
+ +
45
+ +function isBodyByteSequence(
46
+ + body: Body
47
+ +): body is ArrayBufferView<ArrayBuffer> | ArrayBuffer {
48
+ + return typeof body === 'object' && 'byteLength' in body
49
+ +}
50
+ +
51
+ +function isBodyReadableStream(body: Body): body is ReadableStream {
52
+ + return typeof (body as any).getReader === 'function'
53
+ +}
54
+ +
55
+ +function isBodyFormDataOrURLSearchParams(
56
+ + body: Body
57
+ +): body is FormData | URLSearchParams {
58
+ + return typeof (body as any).keys === 'function'
59
+ +}
60
+ +
61
+ +function isBodyBlob(body: Body): body is Blob {
62
+ + return typeof (body as any).arrayBuffer === 'function'
63
+ +}
64
+ +
65
+ export class CacheHandler {
66
+ // eslint-disable-next-line
67
+ constructor(_ctx: CacheHandlerContext) {}
68
+ @@ -80,6 +124,21 @@ export class CacheHandler {
69
+ public resetRequestCache(): void {}
70
+ }
71
+
72
+ +async function hashString(cacheString: string): Promise<string> {
73
+ + if (process.env.NEXT_RUNTIME === 'edge') {
74
+ + const encoder = new TextEncoder()
75
+ + const buffer = encoder.encode(cacheString)
76
+ + return toHex(await crypto.subtle.digest('SHA-256', buffer))
77
+ + } else {
78
+ + const crypto = require('crypto') as typeof import('crypto')
79
+ + return crypto.createHash('sha256').update(cacheString).digest('hex')
80
+ + }
81
+ +}
82
+ +
83
+ +// this should be bumped anytime a fix is made to cache entries
84
+ +// that should bust the cache
85
+ +const MAIN_KEY_PREFIX = 'v4'
86
+ +
87
+ export class IncrementalCache implements IncrementalCacheType {
88
+ readonly dev?: boolean
89
+ readonly disableForTestmode?: boolean
90
+ @@ -288,28 +347,34 @@ export class IncrementalCache implements IncrementalCacheType {
91
+ return this.cacheHandler?.revalidateTag(tags, durations)
92
+ }
93
+
94
+ + async generateSimpleCacheKey(input: string): Promise<string> {
95
+ + const cacheString = JSON.stringify([
96
+ + MAIN_KEY_PREFIX,
97
+ + this.fetchCacheKeyPrefix || '',
98
+ + input,
99
+ + ])
100
+ +
101
+ + return hashString(cacheString)
102
+ + }
103
+ +
104
+ // x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23
105
+ async generateCacheKey(
106
+ url: string,
107
+ init: RequestInit | Request = {}
108
+ ): Promise<string> {
109
+ - // this should be bumped anytime a fix is made to cache entries
110
+ - // that should bust the cache
111
+ - const MAIN_KEY_PREFIX = 'v3'
112
+ -
113
+ const bodyChunks: string[] = []
114
+
115
+ const encoder = new TextEncoder()
116
+ - const decoder = new TextDecoder()
117
+
118
+ - if (init.body) {
119
+ - // handle Uint8Array body
120
+ - if (init.body instanceof Uint8Array) {
121
+ - bodyChunks.push(decoder.decode(init.body))
122
+ - ;(init as any)._ogBody = init.body
123
+ - } // handle ReadableStream body
124
+ - else if (typeof (init.body as any).getReader === 'function') {
125
+ - const readableBody = init.body as ReadableStream<Uint8Array | string>
126
+ + // Will be set implementing https://fetch.spec.whatwg.org/#concept-bodyinit-extract
127
+ + let bodyType: string | null = null
128
+ + const body = init.body
129
+ + if (body) {
130
+ + if (isBodyByteSequence(body)) {
131
+ + bodyChunks.push(`bytes:${toHex(body)}`)
132
+ + ;(init as any)._ogBody = body
133
+ + } else if (isBodyReadableStream(body)) {
134
+ + const readableBody = body
135
+
136
+ const chunks: Uint8Array[] = []
137
+
138
+ @@ -317,20 +382,13 @@ export class IncrementalCache implements IncrementalCacheType {
139
+ await readableBody.pipeTo(
140
+ new WritableStream({
141
+ write(chunk) {
142
+ - if (typeof chunk === 'string') {
143
+ - chunks.push(encoder.encode(chunk))
144
+ - bodyChunks.push(chunk)
145
+ - } else {
146
+ - chunks.push(chunk)
147
+ - bodyChunks.push(decoder.decode(chunk, { stream: true }))
148
+ - }
149
+ + chunks.push(
150
+ + typeof chunk === 'string' ? encoder.encode(chunk) : chunk
151
+ + )
152
+ },
153
+ })
154
+ )
155
+
156
+ - // Flush the decoder.
157
+ - bodyChunks.push(decoder.decode())
158
+ -
159
+ // Create a new buffer with all the chunks.
160
+ const length = chunks.reduce((total, arr) => total + arr.length, 0)
161
+ const arrayBuffer = new Uint8Array(length)
162
+ @@ -342,46 +400,54 @@ export class IncrementalCache implements IncrementalCacheType {
163
+ offset += chunk.length
164
+ }
165
+
166
+ + bodyChunks.push(`bytes:${toHex(arrayBuffer)}`)
167
+ ;(init as any)._ogBody = arrayBuffer
168
+ } catch (err) {
169
+ console.error('Problem reading body', err)
170
+ }
171
+ - } // handle FormData or URLSearchParams bodies
172
+ - else if (typeof (init.body as any).keys === 'function') {
173
+ - const formData = init.body as FormData
174
+ - ;(init as any)._ogBody = init.body
175
+ - for (const key of new Set([...formData.keys()])) {
176
+ - const values = formData.getAll(key)
177
+ - bodyChunks.push(
178
+ - `${key}=${(
179
+ - await Promise.all(
180
+ - values.map(async (val) => {
181
+ - if (typeof val === 'string') {
182
+ - return val
183
+ - } else {
184
+ - return await val.text()
185
+ - }
186
+ - })
187
+ - )
188
+ - ).join(',')}`
189
+ - )
190
+ + } else if (isBodyFormDataOrURLSearchParams(body)) {
191
+ + bodyType =
192
+ + String(body) === '[object FormData]'
193
+ + ? // We don't need a boundary because we're not actually using this for a Content-Type header
194
+ + 'multipart/form-data; boundary='
195
+ + : 'application/x-www-form-urlencoded;charset=UTF-8'
196
+ + const iterable = body
197
+ + ;(init as any)._ogBody = body
198
+ + // Separate, tagged chunks so `["a","b"]` can't collide with `["a,b"]`.
199
+ + for (const [key, val] of iterable.entries()) {
200
+ + bodyChunks.push(`key:${key}`)
201
+ + if (typeof val === 'string') {
202
+ + bodyChunks.push(`str:${val}`)
203
+ + } else {
204
+ + bodyChunks.push(
205
+ + 'file',
206
+ + val.name,
207
+ + val.type,
208
+ + `bytes:${toHex(await val.arrayBuffer())}`
209
+ + )
210
+ + }
211
+ }
212
+ // handle blob body
213
+ - } else if (typeof (init.body as any).arrayBuffer === 'function') {
214
+ - const blob = init.body as Blob
215
+ + } else if (isBodyBlob(body)) {
216
+ + const blob = body
217
+ const arrayBuffer = await blob.arrayBuffer()
218
+ - bodyChunks.push(await blob.text())
219
+ + bodyChunks.push('blob', blob.type, `bytes:${toHex(arrayBuffer)}`)
220
+ ;(init as any)._ogBody = new Blob([arrayBuffer], { type: blob.type })
221
+ - } else if (typeof init.body === 'string') {
222
+ - bodyChunks.push(init.body)
223
+ - ;(init as any)._ogBody = init.body
224
+ + bodyType = blob.type
225
+ + } else if (typeof body === 'string') {
226
+ + bodyChunks.push(`str:${body}`)
227
+ + ;(init as any)._ogBody = body
228
+ + bodyType = 'text/plain;charset=UTF-8'
229
+ + } else {
230
+ + body satisfies never
231
+ + throw new Error(`Unsupported body type: ${typeof body}`)
232
+ }
233
+ }
234
+
235
+ const headers =
236
+ typeof (init.headers || {}).keys === 'function'
237
+ ? Object.fromEntries(init.headers as Headers)
238
+ - : Object.assign({}, init.headers)
239
+ + : Object.assign({} as Record<string, string>, init.headers)
240
+
241
+ // w3c trace context headers can break request caching and deduplication
242
+ // so we remove them from the cache key
243
+ @@ -393,6 +459,9 @@ export class IncrementalCache implements IncrementalCacheType {
244
+ this.fetchCacheKeyPrefix || '',
245
+ url,
246
+ init.method,
247
+ + // Ensures default Content-Type is part of the cache key
248
+ + // TODO: Only necessary when headers are not used from the Request instance
249
+ + bodyType,
250
+ headers,
251
+ init.mode,
252
+ init.redirect,
253
+ @@ -404,18 +473,7 @@ export class IncrementalCache implements IncrementalCacheType {
254
+ bodyChunks,
255
+ ])
256
+
257
+ - if (process.env.NEXT_RUNTIME === 'edge') {
258
+ - function bufferToHex(buffer: ArrayBuffer): string {
259
+ - return Array.prototype.map
260
+ - .call(new Uint8Array(buffer), (b) => b.toString(16).padStart(2, '0'))
261
+ - .join('')
262
+ - }
263
+ - const buffer = encoder.encode(cacheString)
264
+ - return bufferToHex(await crypto.subtle.digest('SHA-256', buffer))
265
+ - } else {
266
+ - const crypto = require('crypto') as typeof import('crypto')
267
+ - return crypto.createHash('sha256').update(cacheString).digest('hex')
268
+ - }
269
+ + return hashString(cacheString)
270
+ }
271
+
272
+ async get(
273
+ diff --git a/packages/next/src/server/lib/patch-fetch.ts b/packages/next/src/server/lib/patch-fetch.ts
274
+ index 4be72496f1..b7e8b124c4 100644
275
+ --- a/packages/next/src/server/lib/patch-fetch.ts
276
+ +++ b/packages/next/src/server/lib/patch-fetch.ts
277
+ @@ -820,8 +820,8 @@ export function createPatchedFetcher(
278
+ fetchUrl,
279
+ isRequestInput ? (input as RequestInit) : init
280
+ )
281
+ - } catch (err) {
282
+ - console.error(`Failed to generate cache key for`, input)
283
+ + } catch (cause) {
284
+ + console.error(`Failed to generate cache key for`, input, cause)
285
+ }
286
+ }
287
+
288
+ diff --git a/packages/next/src/server/web/spec-extension/unstable-cache.ts b/packages/next/src/server/web/spec-extension/unstable-cache.ts
289
+ index 9027330881..5c3aac47c7 100644
290
+ --- a/packages/next/src/server/web/spec-extension/unstable-cache.ts
291
+ +++ b/packages/next/src/server/web/spec-extension/unstable-cache.ts
292
+ @@ -134,7 +134,8 @@ export function unstable_cache<T extends Callback>(
293
+ // @TODO stringify is likely not safe here. We will coerce undefined to null which will make
294
+ // the keyspace smaller than the execution space
295
+ const invocationKey = `${fixedKey}-${JSON.stringify(args)}`
296
+ - const cacheKey = await incrementalCache.generateCacheKey(invocationKey)
297
+ + const cacheKey =
298
+ + await incrementalCache.generateSimpleCacheKey(invocationKey)
299
+ // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse
300
+ const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`
301
+ const fetchIdx =
nextjs-byte-exact-binary-fetch-cache-keys/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-cache-components-dynamic-param-prerenders/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-cache-components-dynamic-param-prerenders/solution/gold.patch ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/build/adapter/build-complete.ts b/packages/next/src/build/adapter/build-complete.ts
2
+ index 48757853f6..167adb54b5 100644
3
+ --- a/packages/next/src/build/adapter/build-complete.ts
4
+ +++ b/packages/next/src/build/adapter/build-complete.ts
5
+ @@ -1585,6 +1585,7 @@ export async function handleBuildComplete({
6
+ const canEmitPartialFallback =
7
+ partialFallback && fallbackRootParams?.length === 0
8
+ let htmlAllowQuery = allowQuery
9
+ + let didFilterBlockingAllowQuery = false
10
+
11
+ // We only want to vary on the shell contents if there is a fallback
12
+ // present and able to be served.
13
+ @@ -1615,6 +1616,35 @@ export async function handleBuildComplete({
14
+ )
15
+ : []
16
+ }
17
+ + } else if (
18
+ + fallback === null &&
19
+ + isAppPage &&
20
+ + renderingMode === RenderingMode.PARTIALLY_STATIC &&
21
+ + routesManifest.rsc.clientParamParsing &&
22
+ + remainingPrerenderableParams !== undefined
23
+ + ) {
24
+ + // BLOCKING entries (no servable fallback) still cache their
25
+ + // on-demand renders, so the same cache-key contract applies as for
26
+ + // partial fallbacks: only params that `generateStaticParams` can
27
+ + // still provide may partition the cache — root params (which are
28
+ + // always provided) and the remaining prerenderable params.
29
+ + // Including a never-prerenderable param would create a cache entry
30
+ + // per param value and resolve the param into the cached content,
31
+ + // so it must be stripped from the request instead, which defers it
32
+ + // to a per-request resume.
33
+ + const prerenderableQueryKeys = new Set<string>()
34
+ + for (const paramName of fallbackRootParams ?? []) {
35
+ + prerenderableQueryKeys.add(`${NEXT_QUERY_PARAM_PREFIX}${paramName}`)
36
+ + }
37
+ + for (const param of remainingPrerenderableParams) {
38
+ + prerenderableQueryKeys.add(
39
+ + `${NEXT_QUERY_PARAM_PREFIX}${param.paramName}`
40
+ + )
41
+ + }
42
+ + htmlAllowQuery = allowQuery.filter((routeKey) =>
43
+ + prerenderableQueryKeys.has(routeKey)
44
+ + )
45
+ + didFilterBlockingAllowQuery = true
46
+ }
47
+
48
+ const initialOutput: AdapterOutput['PRERENDER'] = {
49
+ @@ -1699,6 +1729,12 @@ export async function handleBuildComplete({
50
+ if (routesManifest.rsc.clientParamParsing) {
51
+ dataAllowQuery = htmlAllowQuery
52
+ }
53
+ + } else if (didFilterBlockingAllowQuery) {
54
+ + // Blocking entries have no fallback shell whose presence could
55
+ + // make the data route vary differently from the HTML route: the
56
+ + // on-demand data render is cached under the same
57
+ + // prerenderable-params-only contract.
58
+ + dataAllowQuery = htmlAllowQuery
59
+ }
60
+
61
+ if (renderingMode === RenderingMode.PARTIALLY_STATIC) {
62
+ diff --git a/packages/next/src/build/templates/app-page.ts b/packages/next/src/build/templates/app-page.ts
63
+ index 227259ded5..beed2e5216 100644
64
+ --- a/packages/next/src/build/templates/app-page.ts
65
+ +++ b/packages/next/src/build/templates/app-page.ts
66
+ @@ -585,6 +585,7 @@ export async function handler(
67
+ (prerenderInfo.fallbackRootParams?.length ?? 0) > 0
68
+
69
+ let ssgCacheKey: string | null = null
70
+ + let usesCompletedShellCacheKey = false
71
+ if (
72
+ !isDraftMode &&
73
+ isSSG &&
74
+ @@ -597,17 +598,19 @@ export async function handler(
75
+ // partial fallbacks we instead derive the cache key from the shell
76
+ // that matched this request so `/prefix/[one]/[two]` can specialize into
77
+ // `/prefix/c/[two]` without promoting all the way to `/prefix/c/foo`.
78
+ + // This includes entries with unresolved ROOT params: those requests are
79
+ + // served blocking (no shell can be shared across root branches), but
80
+ + // the entry they produce is still keyed by the completed shell — root
81
+ + // params and any other prerenderable params resolve into the key while
82
+ + // params that `generateStaticParams` can never provide stay as
83
+ + // placeholders and must not partition the cache.
84
+ const fallbackPathname = prerenderMatch
85
+ ? typeof prerenderInfo?.fallback === 'string'
86
+ ? prerenderInfo.fallback
87
+ : prerenderMatch.source
88
+ : null
89
+
90
+ - if (
91
+ - fallbackPathname &&
92
+ - prerenderInfo?.fallbackRouteParams?.length &&
93
+ - !hasUnresolvedRootFallbackParams
94
+ - ) {
95
+ + if (fallbackPathname && prerenderInfo?.fallbackRouteParams?.length) {
96
+ if (remainingPrerenderableParams.length > 0) {
97
+ const completedShellCacheKey = buildCompletedShellCacheKey(
98
+ fallbackPathname,
99
+ @@ -618,10 +621,10 @@ export async function handler(
100
+ // If applying the current request params doesn't make the shell any
101
+ // more complete, then this shell is already at its most complete
102
+ // form and should remain shared rather than creating a new cache entry.
103
+ - ssgCacheKey =
104
+ - completedShellCacheKey !== fallbackPathname
105
+ - ? completedShellCacheKey
106
+ - : null
107
+ + if (completedShellCacheKey !== fallbackPathname) {
108
+ + ssgCacheKey = completedShellCacheKey
109
+ + usesCompletedShellCacheKey = true
110
+ + }
111
+ }
112
+ } else {
113
+ ssgCacheKey = resolvedPathname
114
+ @@ -1494,9 +1497,22 @@ export async function handler(
115
+ effectiveFallbackRouteParams.length <
116
+ (prerenderInfo?.fallbackRouteParams?.length ?? 0)
117
+ ? createOpaqueFallbackRouteParams(effectiveFallbackRouteParams)
118
+ - : isDebugFallbackShell
119
+ - ? getFallbackRouteParams(normalizedSrcPage, routeModule)
120
+ - : null
121
+ + : // A render cached under a completed shell cache key must keep
122
+ + // deferring the params the key leaves as placeholders (the
123
+ + // ones `generateStaticParams` can never provide) so they
124
+ + // resume per request instead of baking into the shared entry.
125
+ + // This is the blocking analog of the background shell
126
+ + // upgrade above and is likewise self-hosted only: in minimal
127
+ + // mode the platform proxy owns this contract by stripping
128
+ + // never-prerenderable params from the request, which defers
129
+ + // them through the placeholder handling instead.
130
+ + !isMinimalMode &&
131
+ + usesCompletedShellCacheKey &&
132
+ + remainingFallbackRouteParams.length > 0
133
+ + ? createOpaqueFallbackRouteParams(remainingFallbackRouteParams)
134
+ + : isDebugFallbackShell
135
+ + ? getFallbackRouteParams(normalizedSrcPage, routeModule)
136
+ + : null
137
+
138
+ // For staged dynamic rendering (Cached Navigations) and debug static
139
+ // shell rendering, pass the fallback params via request meta so the
nextjs-cache-components-dynamic-param-prerenders/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-cache-components-dynamic-param-prerenders/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile && pnpm build' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-cache-components-dynamic-param-prerenders/tests/test.patch ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/e2e/app-dir/partial-fallback-root-blocking/next.config.js b/test/e2e/app-dir/partial-fallback-root-blocking/next.config.js
2
+ index e64bae22..5e50f0b7 100644
3
+ --- a/test/e2e/app-dir/partial-fallback-root-blocking/next.config.js
4
+ +++ b/test/e2e/app-dir/partial-fallback-root-blocking/next.config.js
5
+ @@ -3,6 +3,7 @@
6
+ */
7
+ const nextConfig = {
8
+ cacheComponents: true,
9
+ + partialPrefetching: true,
10
+ }
11
+
12
+ module.exports = nextConfig
13
+ diff --git a/test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts b/test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts
14
+ index 76293240..bfe46a4a 100644
15
+ --- a/test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts
16
+ +++ b/test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts
17
+ @@ -42,22 +42,29 @@ describe('partial-fallback-root-blocking', () => {
18
+
19
+ // TODO: Re-enable once infra supports multiple layers of fallbacks
20
+ if (!isNextDeploy) {
21
+ - it('should not reuse a shared shell cache entry for unknown root branches', async () => {
22
+ + it('should serve unknown root branches with the root param resolved and other params deferred', async () => {
23
+ const firstResult = await fetchSplitHTML('/fr/two')
24
+
25
+ expect(firstResult.response.status).toBe(200)
26
+ expect(firstResult.static$('#lang-fallback').length).toBe(0)
27
+ expect(firstResult.static$('#lang').text()).toBe('fr')
28
+ - expect(firstResult.static$('#slug').text()).toBe('two')
29
+ - expect(firstResult.dynamicPart).toBe('')
30
+ +
31
+ + expect(firstResult.static$('#slug-fallback').text()).toBe(
32
+ + 'loading slug...'
33
+ + )
34
+ + expect(firstResult.static$('#slug').length).toBe(0)
35
+ + expect(firstResult.dynamicPart).toContain('<div id="slug">two</div>')
36
+
37
+ const secondResult = await fetchSplitHTML('/fr/other')
38
+
39
+ expect(secondResult.response.status).toBe(200)
40
+ expect(secondResult.static$('#lang-fallback').length).toBe(0)
41
+ expect(secondResult.static$('#lang').text()).toBe('fr')
42
+ - expect(secondResult.static$('#slug').text()).toBe('other')
43
+ - expect(secondResult.dynamicPart).toBe('')
44
+ + expect(secondResult.static$('#slug-fallback').text()).toBe(
45
+ + 'loading slug...'
46
+ + )
47
+ + expect(secondResult.static$('#slug').length).toBe(0)
48
+ + expect(secondResult.dynamicPart).toContain('<div id="slug">other</div>')
49
+ })
50
+ }
51
+
52
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts b/test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts
53
+ new file mode 100644
54
+ index 00000000..acdfa239
55
+ --- /dev/null
56
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts
57
+ @@ -0,0 +1,132 @@
58
+ +import { nextTestSetup } from 'e2e-utils'
59
+ +import type { NextAdapter } from 'next'
60
+ +
61
+ +describe('adapter-partial-fallback-blocking', () => {
62
+ + const { next } = nextTestSetup({
63
+ + files: __dirname,
64
+ + })
65
+ +
66
+ + function expectAllowedParams(allowQuery: string[], expected: string[]) {
67
+ + // Adapter query allowlists are sets. Their serialized order is not part
68
+ + // of the build output contract.
69
+ + expect(new Set(allowQuery)).toEqual(new Set(expected))
70
+ + }
71
+ +
72
+ + it('should exclude never-prerenderable params from allowQuery for blocking routes with empty shells', async () => {
73
+ + const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
74
+ + await next.readJSON('build-complete.json')
75
+ +
76
+ + const genericEmptyShellPrerender = outputs.prerenders.find(
77
+ + (output) => output.pathname === '/empty-shell/[one]/[two]'
78
+ + )
79
+ + const genericEmptyShellDataPrerender = outputs.prerenders.find(
80
+ + (output) => output.pathname === '/empty-shell/[one]/[two].rsc'
81
+ + )
82
+ + const genericEmptyShellSegmentPrerenders = outputs.prerenders.filter(
83
+ + (output) =>
84
+ + output.pathname.startsWith('/empty-shell/[one]/[two].segments/')
85
+ + )
86
+ + const generatedEmptyShellPrerender = outputs.prerenders.find(
87
+ + (output) => output.pathname === '/empty-shell/a/[two]'
88
+ + )
89
+ +
90
+ + expect(genericEmptyShellPrerender).toBeDefined()
91
+ + expect(genericEmptyShellDataPrerender).toBeDefined()
92
+ + expect(genericEmptyShellSegmentPrerenders.length).toBeGreaterThan(0)
93
+ + expect(generatedEmptyShellPrerender).toBeDefined()
94
+ +
95
+ + expectAllowedParams(genericEmptyShellPrerender.config.allowQuery, [
96
+ + 'nxtPone',
97
+ + ])
98
+ + expectAllowedParams(genericEmptyShellDataPrerender.config.allowQuery, [
99
+ + 'nxtPone',
100
+ + ])
101
+ + for (const output of genericEmptyShellSegmentPrerenders) {
102
+ + expectAllowedParams(output.config.allowQuery, ['nxtPone'])
103
+ + }
104
+ +
105
+ + expect(generatedEmptyShellPrerender.config.partialFallback).toBeUndefined()
106
+ + expectAllowedParams(generatedEmptyShellPrerender.config.allowQuery, [])
107
+ + })
108
+ +
109
+ + it('should exclude never-prerenderable params from allowQuery for entries with a resolved root param', async () => {
110
+ + const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
111
+ + await next.readJSON('build-complete.json')
112
+ +
113
+ + const emptyShellPrerender = outputs.prerenders.find(
114
+ + (output) =>
115
+ + output.pathname === '/with-root-param/en/empty-shell/[category]/[id]'
116
+ + )
117
+ + const emptyShellDataPrerender = outputs.prerenders.find(
118
+ + (output) =>
119
+ + output.pathname ===
120
+ + '/with-root-param/en/empty-shell/[category]/[id].rsc'
121
+ + )
122
+ + const nonEmptyShellPrerender = outputs.prerenders.find(
123
+ + (output) =>
124
+ + output.pathname ===
125
+ + '/with-root-param/en/non-empty-shell/[category]/[id]'
126
+ + )
127
+ + const emptyShellLeafPrerender = outputs.prerenders.find(
128
+ + (output) =>
129
+ + output.pathname === '/with-root-param/en/empty-shell/shoes/[id]'
130
+ + )
131
+ +
132
+ + expect(emptyShellPrerender).toBeDefined()
133
+ + expect(emptyShellDataPrerender).toBeDefined()
134
+ + expect(nonEmptyShellPrerender).toBeDefined()
135
+ + expect(emptyShellLeafPrerender).toBeDefined()
136
+ +
137
+ + expectAllowedParams(emptyShellPrerender.config.allowQuery, [
138
+ + 'nxtPcategory',
139
+ + ])
140
+ + expectAllowedParams(emptyShellDataPrerender.config.allowQuery, [
141
+ + 'nxtPcategory',
142
+ + ])
143
+ +
144
+ + expectAllowedParams(nonEmptyShellPrerender.config.allowQuery, [
145
+ + 'nxtPcategory',
146
+ + ])
147
+ + expect(nonEmptyShellPrerender.config.partialFallback).toBe(true)
148
+ +
149
+ + expectAllowedParams(emptyShellLeafPrerender.config.allowQuery, [])
150
+ + })
151
+ +
152
+ + it('should exclude never-prerenderable params from allowQuery for entries with an unresolved root param', async () => {
153
+ + const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
154
+ + await next.readJSON('build-complete.json')
155
+ +
156
+ + const emptyShellBasePrerender = outputs.prerenders.find(
157
+ + (output) =>
158
+ + output.pathname ===
159
+ + '/with-root-param/[lang]/empty-shell/[category]/[id]'
160
+ + )
161
+ + const emptyShellBaseDataPrerender = outputs.prerenders.find(
162
+ + (output) =>
163
+ + output.pathname ===
164
+ + '/with-root-param/[lang]/empty-shell/[category]/[id].rsc'
165
+ + )
166
+ + const nonEmptyShellBasePrerender = outputs.prerenders.find(
167
+ + (output) =>
168
+ + output.pathname ===
169
+ + '/with-root-param/[lang]/non-empty-shell/[category]/[id]'
170
+ + )
171
+ +
172
+ + expect(emptyShellBasePrerender).toBeDefined()
173
+ + expect(emptyShellBaseDataPrerender).toBeDefined()
174
+ + expect(nonEmptyShellBasePrerender).toBeDefined()
175
+ +
176
+ + expectAllowedParams(emptyShellBasePrerender.config.allowQuery, [
177
+ + 'nxtPlang',
178
+ + 'nxtPcategory',
179
+ + ])
180
+ + expectAllowedParams(emptyShellBaseDataPrerender.config.allowQuery, [
181
+ + 'nxtPlang',
182
+ + 'nxtPcategory',
183
+ + ])
184
+ + expectAllowedParams(nonEmptyShellBasePrerender.config.allowQuery, [
185
+ + 'nxtPlang',
186
+ + 'nxtPcategory',
187
+ + ])
188
+ + })
189
+ +})
190
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx
191
+ new file mode 100644
192
+ index 00000000..65d28a99
193
+ --- /dev/null
194
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx
195
+ @@ -0,0 +1,27 @@
196
+ +// This route intentionally produces EMPTY build-time shells: the params are
197
+ +// read outside of any Suspense boundary (and there is no loading.tsx), so the
198
+ +// postpone propagates to the root. `instant = false` opts the route out of
199
+ +// requiring an instant (non-empty) shell.
200
+ +//
201
+ +// The empty shells downgrade the generic route to a blocking route, but `two`
202
+ +// is still never provided by `generateStaticParams`: an on-demand render may
203
+ +// only complete `one`, so only `one` may participate in the cache key.
204
+ +export function generateStaticParams() {
205
+ + return [{ one: 'a' }]
206
+ +}
207
+ +
208
+ +export const instant = false
209
+ +
210
+ +export default async function Page({
211
+ + params,
212
+ +}: {
213
+ + params: Promise<{ one: string; two: string }>
214
+ +}) {
215
+ + const { one, two } = await params
216
+ +
217
+ + return (
218
+ + <div>
219
+ + {one}:{two}
220
+ + </div>
221
+ + )
222
+ +}
223
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx
224
+ new file mode 100644
225
+ index 00000000..e7a42507
226
+ --- /dev/null
227
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx
228
+ @@ -0,0 +1,11 @@
229
+ +import { ReactNode } from 'react'
230
+ +
231
+ +// Root layout for the (standard) branch: all params in this branch are
232
+ +// below the root layout, so none of them are root params.
233
+ +export default function Root({ children }: { children: ReactNode }) {
234
+ + return (
235
+ + <html>
236
+ + <body>{children}</body>
237
+ + </html>
238
+ + )
239
+ +}
240
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx
241
+ new file mode 100644
242
+ index 00000000..d2b6d1b1
243
+ --- /dev/null
244
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx
245
+ @@ -0,0 +1,38 @@
246
+ +// Empty-shell variant under a root param: the params are read outside of
247
+ +// any Suspense boundary, so the postpone propagates to the root and every
248
+ +// build-time shell is empty. `instant = false` opts the route out of
249
+ +// requiring an instant (non-empty) shell.
250
+ +//
251
+ +// `generateStaticParams` provides `lang` in every entry (required for root
252
+ +// params) and partially covers `category`; `id` is never provided, so `id`
253
+ +// must never be resolved into a cached shell and must never be part of a
254
+ +// cache key — including for requests whose `lang` value was not enumerated
255
+ +// (e.g. /fr/...), which match the base route entry where `lang` is an
256
+ +// unresolved root param.
257
+ +export async function generateStaticParams() {
258
+ + return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
259
+ +}
260
+ +
261
+ +export const instant = false
262
+ +
263
+ +export default async function Page({
264
+ + params,
265
+ +}: {
266
+ + params: Promise<{ lang: string; category: string; id: string }>
267
+ +}) {
268
+ + const { lang, category, id } = await params
269
+ +
270
+ + // Per-render marker (prerenderable): must be re-rendered per request and
271
+ + // never repeat across fetches — a repeated value proves a stored render
272
+ + // is being replayed from the cache.
273
+ + const renderedAt = performance.now()
274
+ +
275
+ + return (
276
+ + <div>
277
+ + <div id="lang">{lang}</div>
278
+ + <div id="category">{category}</div>
279
+ + <div id="id">{id}</div>
280
+ + <div id="rendered-at">{renderedAt}</div>
281
+ + </div>
282
+ + )
283
+ +}
284
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx
285
+ new file mode 100644
286
+ index 00000000..bc155c67
287
+ --- /dev/null
288
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx
289
+ @@ -0,0 +1,19 @@
290
+ +// The ROOT layout lives inside [lang], making `lang` a ROOT param: the
291
+ +// document itself (the html tag) varies by lang with no Suspense boundary.
292
+ +// Root params must be provided by every generateStaticParams result — the
293
+ +// build enforces this — so `lang` is always a prerenderable param.
294
+ +export default async function RootLayout({
295
+ + children,
296
+ + params,
297
+ +}: {
298
+ + children: React.ReactNode
299
+ + params: Promise<{ lang: string }>
300
+ +}) {
301
+ + const { lang } = await params
302
+ +
303
+ + return (
304
+ + <html lang={lang}>
305
+ + <body>{children}</body>
306
+ + </html>
307
+ + )
308
+ +}
309
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx
310
+ new file mode 100644
311
+ index 00000000..ba731670
312
+ --- /dev/null
313
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx
314
+ @@ -0,0 +1,49 @@
315
+ +import { Suspense } from 'react'
316
+ +
317
+ +// Non-empty-shell variant under a root param: static page content plus
318
+ +// Suspense boundaries around the non-root param reads, so shells contain
319
+ +// static content and no empty-shell downgrade happens.
320
+ +//
321
+ +// `generateStaticParams` provides `lang` in every entry (required for root
322
+ +// params) and partially covers `category`; `id` is never provided and must
323
+ +// never resolve into a cached shell nor participate in a cache key.
324
+ +export async function generateStaticParams() {
325
+ + return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
326
+ +}
327
+ +
328
+ +async function Id({ params }: { params: Promise<{ id: string }> }) {
329
+ + const { id } = await params
330
+ +
331
+ + // Per-render marker (prerenderable), read after `await params` so it
332
+ + // belongs to the deferred region: it must be re-rendered (resumed) per
333
+ + // request and never repeat across fetches.
334
+ + const renderedAt = performance.now()
335
+ +
336
+ + return (
337
+ + <>
338
+ + <div id="id">{id}</div>
339
+ + <div id="rendered-at">{renderedAt}</div>
340
+ + </>
341
+ + )
342
+ +}
343
+ +
344
+ +export default function Page({
345
+ + params,
346
+ +}: {
347
+ + params: Promise<{ lang: string; category: string; id: string }>
348
+ +}) {
349
+ + return (
350
+ + <div>
351
+ + <div id="static">static page content</div>
352
+ + <Suspense
353
+ + fallback={
354
+ + <div id="id-fallback" data-fallback>
355
+ + loading id...
356
+ + </div>
357
+ + }
358
+ + >
359
+ + <Id params={params} />
360
+ + </Suspense>
361
+ + </div>
362
+ + )
363
+ +}
364
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx
365
+ new file mode 100644
366
+ index 00000000..a0da238a
367
+ --- /dev/null
368
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx
369
+ @@ -0,0 +1,40 @@
370
+ +import { Suspense, type ReactNode } from 'react'
371
+ +
372
+ +// `category` is read in its own Suspense boundary: shells where it is
373
+ +// concrete render it statically, and generic shells show
374
+ +// `#category-fallback`. This makes the served shell's specialization
375
+ +// observable from the static part of the response. (`lang` is a root param
376
+ +// and is part of the document itself, rendered by the root layout.)
377
+ +async function LayoutImpl({
378
+ + children,
379
+ + params,
380
+ +}: {
381
+ + children: ReactNode
382
+ + params: Promise<{ category: string }>
383
+ +}) {
384
+ + const { category } = await params
385
+ +
386
+ + return (
387
+ + <div>
388
+ + <div id="category">{category}</div>
389
+ + {children}
390
+ + </div>
391
+ + )
392
+ +}
393
+ +
394
+ +export default function Layout(props: {
395
+ + children: ReactNode
396
+ + params: Promise<{ category: string }>
397
+ +}) {
398
+ + return (
399
+ + <Suspense
400
+ + fallback={
401
+ + <div id="category-fallback" data-fallback>
402
+ + loading category...
403
+ + </div>
404
+ + }
405
+ + >
406
+ + <LayoutImpl {...props} />
407
+ + </Suspense>
408
+ + )
409
+ +}
410
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs b/test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs
411
+ new file mode 100644
412
+ index 00000000..548129ec
413
+ --- /dev/null
414
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs
415
+ @@ -0,0 +1,9 @@
416
+ +import fs from 'fs/promises'
417
+ +
418
+ +/** @type {import('next').NextAdapter } */
419
+ +export default {
420
+ + name: 'adapter-partial-fallback-blocking',
421
+ + async onBuildComplete(ctx) {
422
+ + await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
423
+ + },
424
+ +}
425
+ diff --git a/test/production/app-dir/adapter-partial-fallback-blocking/next.config.js b/test/production/app-dir/adapter-partial-fallback-blocking/next.config.js
426
+ new file mode 100644
427
+ index 00000000..39584cc1
428
+ --- /dev/null
429
+ +++ b/test/production/app-dir/adapter-partial-fallback-blocking/next.config.js
430
+ @@ -0,0 +1,10 @@
431
+ +/**
432
+ + * @type {import('next').NextConfig}
433
+ + */
434
+ +const nextConfig = {
435
+ + cacheComponents: true,
436
+ + partialPrefetching: true,
437
+ + adapterPath: require.resolve('./my-adapter.mjs'),
438
+ +}
439
+ +
440
+ +module.exports = nextConfig
nextjs-cache-components-dynamic-param-prerenders/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/e2e/app-dir/partial-fallback-root-blocking/next.config.js' --exclude='test/e2e/app-dir/partial-fallback-root-blocking/next.config.js/*' --exclude='test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts' --exclude='test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs/*' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/next.config.js' --exclude='test/production/app-dir/adapter-partial-fallback-blocking/next.config.js/*' /opt/selfbench/agent.patch || patch_applied=0
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/partial-fallback-root-blocking/next.config.js' 'test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts' 'test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts' 'test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs' 'test/production/app-dir/adapter-partial-fallback-blocking/next.config.js' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/e2e/app-dir/partial-fallback-root-blocking/next.config.js' 'test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts' 'test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts' 'test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx' 'test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs' 'test/production/app-dir/adapter-partial-fallback-blocking/next.config.js' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/test/e2e/app-dir/partial-fallback-root-blocking/next.config.js' '/app/test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts' '/app/test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/empty-shell/[one]/[two]/page.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/(standard)/layout.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/empty-shell/[category]/[id]/page.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/layout.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/[id]/page.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/app/with-root-param/[lang]/non-empty-shell/[category]/layout.tsx' '/app/test/production/app-dir/adapter-partial-fallback-blocking/my-adapter.mjs' '/app/test/production/app-dir/adapter-partial-fallback-blocking/next.config.js'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'pnpm build && pnpm test-start-webpack '"'"'test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts'"'"' '"'"'test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'pnpm build && pnpm test-start-webpack '"'"'test/e2e/app-dir/partial-fallback-root-blocking/partial-fallback-root-blocking.test.ts'"'"' '"'"'test/production/app-dir/adapter-partial-fallback-blocking/adapter-partial-fallback-blocking.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'pnpm build && pnpm test-start-webpack '"'"'test/e2e/app-dir/partial-fallback-shell-upgrade/partial-fallback-shell-upgrade.test.ts'"'"''; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-client-node-browser-variants/environment/Dockerfile ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | env RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo sh -s -- -y --no-modify-path --profile minimal --default-toolchain 1.90.0
21
+ RUN useradd --create-home --shell /bin/bash agent
22
+ COPY repo.tar.gz /tmp/repo.tar.gz
23
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
24
+ && git -C /app init -q \
25
+ && git -C /app config user.email selfbench@local \
26
+ && git -C /app config user.name selfbench \
27
+ && git -C /app add -A \
28
+ && git -C /app commit -qm base
29
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
30
+ && cd '/app/.' \
31
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm swc-build-native && pnpm build' \
32
+ && chmod -R a+rwX /opt/uv-cache
33
+ RUN git -C /app reset --hard -q HEAD \
34
+ && git -C /app clean -fdq \
35
+ && mkdir -p /opt/selfbench \
36
+ && cp -a /app/.git /opt/selfbench/base.git \
37
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
38
+ && chown -R root:root /opt/selfbench \
39
+ && chmod 700 /opt/selfbench \
40
+ && mkdir -p /home/agent/.cache/uv \
41
+ && chown -R agent:agent /home/agent/.cache
42
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
43
+ UV_NO_BUILD_ISOLATION=1
44
+ USER agent
45
+ WORKDIR /app
nextjs-client-node-browser-variants/solution/gold.patch ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/crates/next-core/src/browser_variant_modules.rs b/crates/next-core/src/browser_variant_modules.rs
2
+ index 1e1b9295b4..133ef25ace 100644
3
+ --- a/crates/next-core/src/browser_variant_modules.rs
4
+ +++ b/crates/next-core/src/browser_variant_modules.rs
5
+ @@ -11,6 +11,8 @@
6
+ #[rustfmt::skip]
7
+ pub static BROWSER_VARIANT_MODULES: &[&str] = &[
8
+ "client/components/client-boundary-params",
9
+ + "client/components/instant-samples",
10
+ + "client/components/instant-validation/impl",
11
+ "client/components/navigation-dynamic-rendering",
12
+ "client/components/server-async-storage",
13
+ "client/components/unstable-rethrow",
14
+ diff --git a/packages/next/src/build/browser-variant-modules.ts b/packages/next/src/build/browser-variant-modules.ts
15
+ index bf7685e857..45563cf715 100644
16
+ --- a/packages/next/src/build/browser-variant-modules.ts
17
+ +++ b/packages/next/src/build/browser-variant-modules.ts
18
+ @@ -7,6 +7,8 @@
19
+ // `packages/next/dist` (extension omitted).
20
+ export const browserVariantModules = [
21
+ 'client/components/client-boundary-params',
22
+ + 'client/components/instant-samples',
23
+ + 'client/components/instant-validation/impl',
24
+ 'client/components/navigation-dynamic-rendering',
25
+ 'client/components/server-async-storage',
26
+ 'client/components/unstable-rethrow',
27
+ diff --git a/packages/next/src/client/components/instant-samples.browser.ts b/packages/next/src/client/components/instant-samples.browser.ts
28
+ new file mode 100644
29
+ index 0000000000..35c2fbf65a
30
+ --- /dev/null
31
+ +++ b/packages/next/src/client/components/instant-samples.browser.ts
32
+ @@ -0,0 +1,3 @@
33
+ +export const instrumentParamsForClientValidation = undefined
34
+ +export const expectCompleteParamsInClientValidation = undefined
35
+ +export const instrumentSearchParamsForClientValidation = undefined
36
+ diff --git a/packages/next/src/server/app-render/instant-validation/instant-samples-client.ts b/packages/next/src/client/components/instant-samples.ts
37
+ similarity index 88%
38
+ rename from packages/next/src/server/app-render/instant-validation/instant-samples-client.ts
39
+ rename to packages/next/src/client/components/instant-samples.ts
40
+ index 15101787cb..7bd30ba8b1 100644
41
+ --- a/packages/next/src/server/app-render/instant-validation/instant-samples-client.ts
42
+ +++ b/packages/next/src/client/components/instant-samples.ts
43
+ @@ -1,13 +1,13 @@
44
+ -import type { Params } from '../../request/params'
45
+ -import type { ReadonlyURLSearchParams } from '../../../client/components/readonly-url-search-params'
46
+ -import { workUnitAsyncStorage } from '../work-unit-async-storage.external'
47
+ -import { workAsyncStorage } from '../work-async-storage.external'
48
+ +import type { Params } from '../../server/request/params'
49
+ +import type { ReadonlyURLSearchParams } from './readonly-url-search-params'
50
+ +import { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'
51
+ +import { workAsyncStorage } from '../../server/app-render/work-async-storage.external'
52
+ import {
53
+ createExhaustiveParamsProxy,
54
+ createExhaustiveURLSearchParamsProxy,
55
+ trackMissingSampleErrorAndThrow,
56
+ -} from './instant-samples'
57
+ -import { InstantValidationError } from './instant-validation-error'
58
+ +} from '../../server/app-render/instant-validation/instant-samples'
59
+ +import { InstantValidationError } from '../../server/app-render/instant-validation/instant-validation-error'
60
+
61
+ export function instrumentParamsForClientValidation<TPArams extends Params>(
62
+ underlyingParams: TPArams
63
+ diff --git a/packages/next/src/client/components/instant-validation/boundary.tsx b/packages/next/src/client/components/instant-validation/boundary.tsx
64
+ index cf39318c3a..8ed8ccd7fe 100644
65
+ --- a/packages/next/src/client/components/instant-validation/boundary.tsx
66
+ +++ b/packages/next/src/client/components/instant-validation/boundary.tsx
67
+ @@ -1,29 +1,9 @@
68
+ 'use client'
69
+ -
70
+ -// This facade ensures that the boundary code is DCE'd in browser bundles.
71
+ -//
72
+ -// It also exists to satisfy `browser-chunks.test.ts`, which looks for
73
+ -// references to code in `packages/next/src/server` in browser bundles and errors if it finds any.
74
+ -// A "use client" module seems to always have always have an entry in the browser bundle,
75
+ -// so this module cannot be colocated with the rest of the instant validation code,
76
+ -// because it ends up looking like it's importing server code in the browser
77
+ -// even though all the server code inside is actually DCE'd.
78
+ -
79
+ -const {
80
+ - InstantValidationBoundaryContext,
81
+ - PlaceValidationBoundaryBelowThisLevel,
82
+ - RenderValidationBoundaryAtThisLevel,
83
+ - SlotMarker,
84
+ -} =
85
+ - typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS
86
+ - ? // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
87
+ - // ast-grep-ignore: no-typeof-window-require-tsx
88
+ - (require('../../../server/app-render/instant-validation/boundary-impl') as typeof import('../../../server/app-render/instant-validation/boundary-impl'))
89
+ - : ({} as typeof import('../../../server/app-render/instant-validation/boundary-impl'))
90
+ -
91
+ +// We can't fork a `use client` boundary based on node-client vs browser-client.
92
+ +// We need to fork one level deeper.
93
+ export {
94
+ InstantValidationBoundaryContext,
95
+ PlaceValidationBoundaryBelowThisLevel,
96
+ RenderValidationBoundaryAtThisLevel,
97
+ SlotMarker,
98
+ -}
99
+ +} from './impl'
100
+ diff --git a/packages/next/src/client/components/instant-validation/impl.browser.tsx b/packages/next/src/client/components/instant-validation/impl.browser.tsx
101
+ new file mode 100644
102
+ index 0000000000..fad4049807
103
+ --- /dev/null
104
+ +++ b/packages/next/src/client/components/instant-validation/impl.browser.tsx
105
+ @@ -0,0 +1,4 @@
106
+ +export const InstantValidationBoundaryContext = null
107
+ +export const PlaceValidationBoundaryBelowThisLevel = null
108
+ +export const RenderValidationBoundaryAtThisLevel = null
109
+ +export const SlotMarker = null
110
+ diff --git a/packages/next/src/client/components/instant-validation/impl.tsx b/packages/next/src/client/components/instant-validation/impl.tsx
111
+ new file mode 100644
112
+ index 0000000000..62e291f209
113
+ --- /dev/null
114
+ +++ b/packages/next/src/client/components/instant-validation/impl.tsx
115
+ @@ -0,0 +1,6 @@
116
+ +export {
117
+ + InstantValidationBoundaryContext,
118
+ + PlaceValidationBoundaryBelowThisLevel,
119
+ + RenderValidationBoundaryAtThisLevel,
120
+ + SlotMarker,
121
+ +} from '../../../server/app-render/instant-validation/boundary-impl'
122
+ diff --git a/packages/next/src/client/components/layout-router.tsx b/packages/next/src/client/components/layout-router.tsx
123
+ index efdd8d9187..52019013c5 100644
124
+ --- a/packages/next/src/client/components/layout-router.tsx
125
+ +++ b/packages/next/src/client/components/layout-router.tsx
126
+ @@ -33,6 +33,10 @@ import { ErrorBoundary } from './error-boundary'
127
+ import { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/router/utils/disable-smooth-scroll'
128
+ import { RedirectBoundary } from './redirect-boundary'
129
+ import { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'
130
+ +import {
131
+ + InstantValidationBoundaryContext,
132
+ + RenderValidationBoundaryAtThisLevel,
133
+ +} from './instant-validation/boundary'
134
+ import { createRouterCacheKey } from './router-reducer/create-router-cache-key'
135
+ import {
136
+ useRouterBFCache,
137
+ @@ -670,10 +674,6 @@ export default function OuterLayoutRouter({
138
+
139
+ let maybeValidationBoundaryId: string | null = null
140
+ if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {
141
+ - const { InstantValidationBoundaryContext } =
142
+ - // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
143
+ - // ast-grep-ignore: no-typeof-window-require-tsx
144
+ - require('./instant-validation/boundary') as typeof import('./instant-validation/boundary')
145
+ maybeValidationBoundaryId = use(InstantValidationBoundaryContext)
146
+ }
147
+
148
+ @@ -812,10 +812,6 @@ export default function OuterLayoutRouter({
149
+ process.env.__NEXT_CACHE_COMPONENTS &&
150
+ typeof maybeValidationBoundaryId === 'string'
151
+ ) {
152
+ - const { RenderValidationBoundaryAtThisLevel } =
153
+ - // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
154
+ - // ast-grep-ignore: no-typeof-window-require-tsx
155
+ - require('./instant-validation/boundary') as typeof import('./instant-validation/boundary')
156
+ templateValue = (
157
+ <RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>
158
+ {templateValue}
159
+ diff --git a/packages/next/src/client/components/navigation.ts b/packages/next/src/client/components/navigation.ts
160
+ index 0c7dc84d32..2e1df203d8 100644
161
+ --- a/packages/next/src/client/components/navigation.ts
162
+ +++ b/packages/next/src/client/components/navigation.ts
163
+ @@ -27,12 +27,9 @@ const {
164
+ instrumentParamsForClientValidation,
165
+ instrumentSearchParamsForClientValidation,
166
+ expectCompleteParamsInClientValidation,
167
+ -} =
168
+ - typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS
169
+ - ? // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs
170
+ - // ast-grep-ignore: no-typeof-window-require
171
+ - (require('../../server/app-render/instant-validation/instant-samples-client') as typeof import('../../server/app-render/instant-validation/instant-samples-client'))
172
+ - : {}
173
+ +} = process.env.__NEXT_CACHE_COMPONENTS
174
+ + ? (require('./instant-samples') as typeof import('./instant-samples'))
175
+ + : {}
176
+
177
+ /**
178
+ * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
nextjs-client-node-browser-variants/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-client-node-browser-variants/tests/Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | env RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo sh -s -- -y --no-modify-path --profile minimal --default-toolchain 1.90.0
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && pnpm swc-build-native && pnpm build' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+
33
+ RUN useradd --create-home --shell /bin/bash verifier \
34
+ && chown -R verifier:verifier /app /opt/uv-cache \
35
+ && mkdir -p /opt/selfbench \
36
+ && chmod 700 /opt/selfbench \
37
+ && mkdir -p /home/verifier/.cache/uv \
38
+ && chown -R verifier:verifier /home/verifier/.cache
39
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
40
+ UV_NO_BUILD_ISOLATION=1
41
+ COPY test.patch test.sh /tests/
42
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
43
+ WORKDIR /app
nextjs-client-node-browser-variants/tests/test.patch ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/production/app-dir/browser-chunks/browser-chunks.test.ts b/test/production/app-dir/browser-chunks/browser-chunks.test.ts
2
+ index 041a813ad0..ecf810fcb3 100644
3
+ --- a/test/production/app-dir/browser-chunks/browser-chunks.test.ts
4
+ +++ b/test/production/app-dir/browser-chunks/browser-chunks.test.ts
5
+ @@ -22,6 +22,14 @@ function normalizeSource(source: string): string {
6
+ describe('browser-chunks', () => {
7
+ const { next } = nextTestSetup({
8
+ files: __dirname,
9
+ + dependencies: {
10
+ + react: '19.2.7',
11
+ + 'react-dom': '19.2.7',
12
+ + '@types/react': '19.2.2',
13
+ + '@types/react-dom': '19.2.1',
14
+ + typescript: '6.0.2',
15
+ + '@types/node': '20.17.6',
16
+ + },
17
+ })
18
+
19
+ let sources: string[] = []
20
+ @@ -45,13 +53,11 @@ describe('browser-chunks', () => {
21
+ )
22
+ })
23
+
24
+ - // These snapshots document which matching modules currently reach browser
25
+ - // chunks. Some of these we don't intend to act on yet, so we snapshot the
26
+ - // normalized paths (rather than hard-fail) to surface regressions on review.
27
+ it('must not bundle any server modules into browser chunks', () => {
28
+ const serverSources = Array.from(
29
+ new Set(
30
+ sources
31
+ + // normalizing in case we regress and want to keep track of the regression
32
+ .map(normalizeSource)
33
+ .filter(
34
+ (source) =>
35
+ @@ -63,46 +69,7 @@ describe('browser-chunks', () => {
36
+ )
37
+ ).sort()
38
+
39
+ - // This set varies along two axes, so snapshot each combination separately
40
+ - // rather than forcing them to agree:
41
+ - // - bundler: webpack's browser chunks contain none of these; Turbopack
42
+ - // still pulls in a set we haven't acted on yet.
43
+ - // - cache components: enabling it pulls additional server modules
44
+ - // (instant-validation, async storage, dynamic rendering) into the
45
+ - // client render path. CI runs this suite both with and without it
46
+ - // (see test/cache-components-tests-manifest.json).
47
+ - const cacheComponents = process.env.__NEXT_CACHE_COMPONENTS === 'true'
48
+ - if (process.env.IS_TURBOPACK_TEST) {
49
+ - if (cacheComponents) {
50
+ - expect(serverSources).toMatchInlineSnapshot(`
51
+ - [
52
+ - "src/server/app-render/async-local-storage.ts",
53
+ - "src/server/app-render/instant-validation/boundary-constants.ts",
54
+ - "src/server/app-render/instant-validation/boundary-impl.tsx",
55
+ - "src/server/app-render/instant-validation/instant-samples-client.ts",
56
+ - "src/server/app-render/instant-validation/instant-samples.ts",
57
+ - "src/server/app-render/instant-validation/instant-validation-error.ts",
58
+ - "src/server/app-render/staged-rendering.ts",
59
+ - "src/server/app-render/work-async-storage-instance.ts",
60
+ - "src/server/app-render/work-async-storage.external.ts",
61
+ - "src/server/app-render/work-unit-async-storage-instance.ts",
62
+ - "src/server/app-render/work-unit-async-storage.external.ts",
63
+ - "src/server/web/spec-extension/adapters/headers.ts",
64
+ - "src/server/web/spec-extension/adapters/reflect.ts",
65
+ - "src/server/web/spec-extension/adapters/request-cookies.ts",
66
+ - "src/server/web/spec-extension/cookies.ts",
67
+ - ]
68
+ - `)
69
+ - } else {
70
+ - expect(serverSources).toMatchInlineSnapshot(`[]`)
71
+ - }
72
+ - } else {
73
+ - if (cacheComponents) {
74
+ - expect(serverSources).toMatchInlineSnapshot(`[]`)
75
+ - } else {
76
+ - expect(serverSources).toMatchInlineSnapshot(`[]`)
77
+ - }
78
+ - }
79
+ + expect(serverSources).toEqual([])
80
+ })
81
+
82
+ it('must not bundle any dev overlay into browser chunks', () => {
83
+ diff --git a/test/production/app-dir/browser-chunks/browser-runtime.test.ts b/test/production/app-dir/browser-chunks/browser-runtime.test.ts
84
+ new file mode 100644
85
+ index 0000000000..1891353f1f
86
+ --- /dev/null
87
+ +++ b/test/production/app-dir/browser-chunks/browser-runtime.test.ts
88
+ @@ -0,0 +1,21 @@
89
+ +import { nextTestSetup } from 'e2e-utils'
90
+ +
91
+ +describe('browser runtime', () => {
92
+ + const { next } = nextTestSetup({
93
+ + files: __dirname,
94
+ + dependencies: {
95
+ + react: '19.2.7',
96
+ + 'react-dom': '19.2.7',
97
+ + '@types/react': '19.2.2',
98
+ + '@types/react-dom': '19.2.1',
99
+ + typescript: '6.0.2',
100
+ + '@types/node': '20.17.6',
101
+ + },
102
+ + })
103
+ +
104
+ + it('serves the client application in production', async () => {
105
+ + const response = await next.fetch('/')
106
+ +
107
+ + expect(response.status).toBe(200)
108
+ + })
109
+ +})
nextjs-client-node-browser-variants/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/production/app-dir/browser-chunks/browser-chunks.test.ts' --exclude='test/production/app-dir/browser-chunks/browser-chunks.test.ts/*' --exclude='test/production/app-dir/browser-chunks/browser-runtime.test.ts' --exclude='test/production/app-dir/browser-chunks/browser-runtime.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/production/app-dir/browser-chunks/browser-chunks.test.ts' 'test/production/app-dir/browser-chunks/browser-runtime.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/production/app-dir/browser-chunks/browser-chunks.test.ts' 'test/production/app-dir/browser-chunks/browser-runtime.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/test/production/app-dir/browser-chunks/browser-chunks.test.ts' '/app/test/production/app-dir/browser-chunks/browser-runtime.test.ts'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'pnpm swc-build-native && pnpm build && pnpm test-start-experimental-turbo '"'"'test/production/app-dir/browser-chunks/browser-chunks.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'pnpm swc-build-native && pnpm build && pnpm test-start-experimental-turbo '"'"'test/production/app-dir/browser-chunks/browser-chunks.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'pnpm swc-build-native && pnpm build && pnpm test-start-experimental-turbo '"'"'test/production/app-dir/browser-chunks/browser-runtime.test.ts'"'"''; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-codemod-noninteractive-upgrade/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack pnpm@10.33.0 install --frozen-lockfile && corepack pnpm@10.33.0 turbo build --filter=next --filter=@next/codemod' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-codemod-noninteractive-upgrade/solution/gold.patch ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next-codemod/bin/next-codemod.ts b/packages/next-codemod/bin/next-codemod.ts
2
+ index d49ecb8e4762baeb6e02e4dc68f175a1f42de629..367412ee26feeca267d03c2e0050d2ea355fc55b 100644
3
+ --- a/packages/next-codemod/bin/next-codemod.ts
4
+ +++ b/packages/next-codemod/bin/next-codemod.ts
5
+ @@ -65,6 +65,11 @@ program
6
+ )
7
+ .usage('[revision] [options]')
8
+ .option('--verbose', 'Verbose output', false)
9
+ + .option(
10
+ + '-y, --yes',
11
+ + 'Skip every interactive prompt and accept its default. Also auto-enabled when stdin is not a TTY (e.g. running under an agent or in CI).',
12
+ + false
13
+ + )
14
+ .action(async (revision, options) => {
15
+ try {
16
+ await runUpgrade(revision, options)
17
+ diff --git a/packages/next-codemod/bin/upgrade.ts b/packages/next-codemod/bin/upgrade.ts
18
+ index b7de97ce5cb1640afb7dd2fb93028d6055330801..2cb91c140a49348bb8bbd0335a14021c0441a7cd 100644
19
+ --- a/packages/next-codemod/bin/upgrade.ts
20
+ +++ b/packages/next-codemod/bin/upgrade.ts
21
+ @@ -112,9 +112,15 @@ function resolveSemanticRevision(
22
+
23
+ export async function runUpgrade(
24
+ revision: string | undefined,
25
+ - options: { verbose: boolean }
26
+ + options: { verbose: boolean; yes?: boolean }
27
+ ): Promise<void> {
28
+ const { verbose } = options
29
+ + const nonInteractive = options.yes === true || !process.stdin.isTTY
30
+ + if (nonInteractive) {
31
+ + console.log(
32
+ + ` Running in non-interactive mode. Every prompt will accept its default.`
33
+ + )
34
+ + }
35
+ const appPackageJsonPath = path.resolve(cwd, 'package.json')
36
+ let appPackageJson = JSON.parse(fs.readFileSync(appPackageJsonPath, 'utf8'))
37
+
38
+ @@ -221,22 +227,27 @@ export async function runUpgrade(
39
+ // We'll recommend to upgrade in the prompt but users can decide to try 18.
40
+ !isPureAppRouter
41
+ ) {
42
+ - const shouldStayOnReact18Res = await prompts(
43
+ - {
44
+ - type: 'confirm',
45
+ - name: 'shouldStayOnReact18',
46
+ - message:
47
+ - `Do you prefer to stay on React 18?` +
48
+ - (isMixedApp
49
+ - ? " Since you're using both pages/ and app/, we recommend upgrading React to use a consistent version throughout your app."
50
+ - : ''),
51
+ - initial: false,
52
+ - active: 'Yes',
53
+ - inactive: 'No',
54
+ - },
55
+ - { onCancel }
56
+ - )
57
+ - shouldStayOnReact18 = shouldStayOnReact18Res.shouldStayOnReact18
58
+ + if (nonInteractive) {
59
+ + // Default: upgrade React past 18.
60
+ + shouldStayOnReact18 = false
61
+ + } else {
62
+ + const shouldStayOnReact18Res = await prompts(
63
+ + {
64
+ + type: 'confirm',
65
+ + name: 'shouldStayOnReact18',
66
+ + message:
67
+ + `Do you prefer to stay on React 18?` +
68
+ + (isMixedApp
69
+ + ? " Since you're using both pages/ and app/, we recommend upgrading React to use a consistent version throughout your app."
70
+ + : ''),
71
+ + initial: false,
72
+ + active: 'Yes',
73
+ + inactive: 'No',
74
+ + },
75
+ + { onCancel }
76
+ + )
77
+ + shouldStayOnReact18 = shouldStayOnReact18Res.shouldStayOnReact18
78
+ + }
79
+ }
80
+
81
+ // We're resolving a specific version here to avoid including "ugly" version queries
82
+ @@ -254,12 +265,13 @@ export async function runUpgrade(
83
+ compareVersions(targetNextVersion, '15.0.0-canary') >= 0 &&
84
+ compareVersions(targetNextVersion, '16.0.0-canary') < 0
85
+ ) {
86
+ - await suggestTurbopack(appPackageJson, targetNextVersion)
87
+ + await suggestTurbopack(appPackageJson, targetNextVersion, nonInteractive)
88
+ }
89
+
90
+ const codemods = await suggestCodemods(
91
+ installedNextVersion,
92
+ - targetNextVersion
93
+ + targetNextVersion,
94
+ + nonInteractive
95
+ )
96
+ const packageManager: PackageManager = getPkgManager(cwd)
97
+
98
+ @@ -272,8 +284,9 @@ export async function runUpgrade(
99
+ compareVersions(targetReactVersion, '19.0.0-0') >= 0 &&
100
+ compareVersions(installedReactVersion, '19.0.0-0') < 0
101
+ ) {
102
+ - shouldRunReactCodemods = await suggestReactCodemods()
103
+ - shouldRunReactTypesCodemods = await suggestReactTypesCodemods()
104
+ + shouldRunReactCodemods = await suggestReactCodemods(nonInteractive)
105
+ + shouldRunReactTypesCodemods =
106
+ + await suggestReactTypesCodemods(nonInteractive)
107
+
108
+ execCommand = getNpxCommand(packageManager)
109
+ }
110
+ @@ -400,10 +413,12 @@ export async function runUpgrade(
111
+ // understanding of the codemods, we run all of the applicable codemods.
112
+ if (shouldRunReactCodemods) {
113
+ // https://react.dev/blog/2024/04/25/react-19-upgrade-guide#run-all-react-19-codemods
114
+ + // `--no-interactive` skips the interactive prompt that asks for confirmation
115
+ + // https://github.com/codemod-com/codemod/blob/c0cf00d13161a0ec0965b6cc6bc5d54076839cc8/apps/cli/src/flags.ts#L160
116
+ + // `--allow-dirty` is required because the upgrade above modified package.json
117
+ + // and the lockfile; the recipe refuses to run on a dirty tree otherwise.
118
+ execSync(
119
+ - // `--no-interactive` skips the interactive prompt that asks for confirmation
120
+ - // https://github.com/codemod-com/codemod/blob/c0cf00d13161a0ec0965b6cc6bc5d54076839cc8/apps/cli/src/flags.ts#L160
121
+ - `${execCommand} codemod@latest react/19/migration-recipe --no-interactive`,
122
+ + `${execCommand} codemod@latest react/19/migration-recipe --no-interactive --allow-dirty`,
123
+ { stdio: 'inherit' }
124
+ )
125
+ }
126
+ @@ -486,7 +501,8 @@ function isUsingAppDir(projectPath: string): boolean {
127
+ */
128
+ async function suggestTurbopack(
129
+ packageJson: any,
130
+ - targetNextVersion: string
131
+ + targetNextVersion: string,
132
+ + nonInteractive: boolean
133
+ ): Promise<void> {
134
+ const devScript: string | undefined = packageJson.scripts?.['dev']
135
+ // Turbopack flag was changed from `--turbo` to `--turbopack` in v15.0.1-canary.3
136
+ @@ -518,17 +534,21 @@ async function suggestTurbopack(
137
+ return
138
+ }
139
+
140
+ - const responseTurbopack = await prompts(
141
+ - {
142
+ - type: 'confirm',
143
+ - name: 'enable',
144
+ - message: `Enable Turbopack for ${pc.bold('next dev')}?`,
145
+ - initial: true,
146
+ - },
147
+ - { onCancel }
148
+ - )
149
+ + let enable = true
150
+ + if (!nonInteractive) {
151
+ + const responseTurbopack = await prompts(
152
+ + {
153
+ + type: 'confirm',
154
+ + name: 'enable',
155
+ + message: `Enable Turbopack for ${pc.bold('next dev')}?`,
156
+ + initial: true,
157
+ + },
158
+ + { onCancel }
159
+ + )
160
+ + enable = responseTurbopack.enable
161
+ + }
162
+
163
+ - if (!responseTurbopack.enable) {
164
+ + if (!enable) {
165
+ return
166
+ }
167
+
168
+ @@ -543,6 +563,12 @@ async function suggestTurbopack(
169
+ `${pc.yellow('⚠')} Could not find "${pc.bold('next dev')}" in your dev script.`
170
+ )
171
+
172
+ + if (nonInteractive) {
173
+ + // Without a TTY we can't ask the user for a replacement script.
174
+ + // Keep the existing dev script untouched.
175
+ + return
176
+ + }
177
+ +
178
+ const responseCustomDevScript = await prompts(
179
+ {
180
+ type: 'text',
181
+ @@ -559,7 +585,8 @@ async function suggestTurbopack(
182
+
183
+ async function suggestCodemods(
184
+ initialNextVersion: string,
185
+ - targetNextVersion: string
186
+ + targetNextVersion: string,
187
+ + nonInteractive: boolean
188
+ ): Promise<string[]> {
189
+ // example:
190
+ // codemod version: 15.0.0-canary.45
191
+ @@ -594,6 +621,16 @@ async function suggestCodemods(
192
+ return []
193
+ }
194
+
195
+ + if (nonInteractive) {
196
+ + // Default: apply every recommended codemod, matching `selected: true` below.
197
+ + const all = relevantCodemods.map(({ value }) => value)
198
+ + console.log(
199
+ + ` Applying all ${pc.blue('codemods')} recommended for your upgrade:\n` +
200
+ + all.map((value) => ` - ${value}`).join('\n')
201
+ + )
202
+ + return all
203
+ + }
204
+ +
205
+ const { codemods } = await prompts(
206
+ {
207
+ type: 'multiselect',
208
+ @@ -614,7 +651,10 @@ async function suggestCodemods(
209
+ return codemods
210
+ }
211
+
212
+ -async function suggestReactCodemods(): Promise<boolean> {
213
+ +async function suggestReactCodemods(nonInteractive: boolean): Promise<boolean> {
214
+ + if (nonInteractive) {
215
+ + return true
216
+ + }
217
+ const { runReactCodemod } = await prompts(
218
+ {
219
+ type: 'confirm',
220
+ @@ -628,7 +668,12 @@ async function suggestReactCodemods(): Promise<boolean> {
221
+ return runReactCodemod
222
+ }
223
+
224
+ -async function suggestReactTypesCodemods(): Promise<boolean> {
225
+ +async function suggestReactTypesCodemods(
226
+ + nonInteractive: boolean
227
+ +): Promise<boolean> {
228
+ + if (nonInteractive) {
229
+ + return true
230
+ + }
231
+ const { runReactTypesCodemod } = await prompts(
232
+ {
233
+ type: 'confirm',
nextjs-codemod-noninteractive-upgrade/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-codemod-noninteractive-upgrade/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack pnpm@10.33.0 install --frozen-lockfile && corepack pnpm@10.33.0 turbo build --filter=next --filter=@next/codemod' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-codemod-noninteractive-upgrade/tests/test.patch ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js b/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js
2
+ new file mode 100644
3
+ index 00000000..54ca42d2
4
+ --- /dev/null
5
+ +++ b/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js
6
+ @@ -0,0 +1,277 @@
7
+ +/* global jest */
8
+ +
9
+ +jest.autoMockOff()
10
+ +
11
+ +const fs = require('fs')
12
+ +const os = require('os')
13
+ +const path = require('path')
14
+ +const { spawnSync } = require('child_process')
15
+ +
16
+ +const codemodRoot = path.resolve(__dirname, '../..')
17
+ +const tsx = path.resolve(codemodRoot, '../../node_modules/.bin/tsx')
18
+ +const projects = []
19
+ +
20
+ +// The verifier setup builds the base revision before applying a candidate patch.
21
+ +// Run a source snapshot of the current package so tests see candidate changes
22
+ +// instead of stale generated JavaScript while still reusing the prebuilt
23
+ +// transforms. Copy the whole package rather than assuming that an implementation
24
+ +// must live in bin/ and lib/: a CLI may legitimately import a new source folder,
25
+ +// a JavaScript-only helper, or package metadata added by the candidate.
26
+ +function createSourceCli() {
27
+ + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'next-codemod-cli-'))
28
+ + projects.push(root)
29
+ +
30
+ + const sourceFile = (file) => {
31
+ + const relative = path.relative(codemodRoot, file)
32
+ + const topLevel = relative.split(path.sep)[0]
33
+ + if (topLevel === 'node_modules' || topLevel === 'transforms') return false
34
+ +
35
+ + // Ignore a generated artifact only when its source sibling exists. This
36
+ + // keeps candidate-authored JavaScript modules while ensuring tsx loads a
37
+ + // changed TypeScript source file instead of JavaScript built from HEAD.
38
+ + const sourceBase = file.replace(/(?:\.js(?:\.map)?|\.d\.ts(?:\.map)?)$/, '')
39
+ + if (sourceBase !== file) {
40
+ + if (fs.existsSync(`${sourceBase}.ts`)) return false
41
+ + if (fs.existsSync(`${sourceBase}.tsx`)) return false
42
+ + }
43
+ + return true
44
+ + }
45
+ + fs.cpSync(codemodRoot, root, { recursive: true, filter: sourceFile })
46
+ +
47
+ + for (const entry of ['node_modules', 'transforms']) {
48
+ + fs.symlinkSync(
49
+ + path.join(codemodRoot, entry),
50
+ + path.join(root, entry),
51
+ + 'dir'
52
+ + )
53
+ + }
54
+ +
55
+ + return path.join(root, 'bin', 'next-codemod.ts')
56
+ +}
57
+ +
58
+ +function writeJson(file, value) {
59
+ + fs.mkdirSync(path.dirname(file), { recursive: true })
60
+ + fs.writeFileSync(file, JSON.stringify(value, null, 2))
61
+ +}
62
+ +
63
+ +function createProject({
64
+ + installedNext,
65
+ + installedReact,
66
+ + targetNext,
67
+ + targetReact,
68
+ + devScript,
69
+ + pages = false,
70
+ +}) {
71
+ + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'next-codemod-upgrade-'))
72
+ + projects.push(dir)
73
+ +
74
+ + writeJson(path.join(dir, 'package.json'), {
75
+ + private: true,
76
+ + scripts: { dev: devScript },
77
+ + dependencies: {
78
+ + next: installedNext,
79
+ + react: installedReact,
80
+ + 'react-dom': installedReact,
81
+ + },
82
+ + })
83
+ + writeJson(path.join(dir, 'package-lock.json'), {})
84
+ + for (const dependency of ['next', 'react', 'react-dom']) {
85
+ + writeJson(path.join(dir, 'node_modules', dependency, 'package.json'), {
86
+ + name: dependency,
87
+ + version: dependency === 'next' ? installedNext : installedReact,
88
+ + })
89
+ + }
90
+ + if (pages) {
91
+ + fs.mkdirSync(path.join(dir, 'pages'), { recursive: true })
92
+ + fs.writeFileSync(
93
+ + path.join(dir, 'pages', 'index.js'),
94
+ + 'export default () => null\n'
95
+ + )
96
+ + }
97
+ +
98
+ + const fakeBin = path.join(dir, 'fake-bin')
99
+ + fs.mkdirSync(fakeBin)
100
+ + const npm = `#!/usr/bin/env node
101
+ +const fs = require('fs')
102
+ +const args = process.argv.slice(2)
103
+ +const query = args.find((arg) => arg.includes('@')) || ''
104
+ +if (args.includes('view')) {
105
+ + if (query.startsWith('next@') && args.includes('version')) {
106
+ + console.log(JSON.stringify(process.env.TEST_TARGET_NEXT))
107
+ + } else if (query.startsWith('next@')) {
108
+ + console.log(JSON.stringify({ version: process.env.TEST_TARGET_NEXT, peerDependencies: { react: process.env.TEST_REACT_RANGE } }))
109
+ + } else {
110
+ + console.log(JSON.stringify(process.env.TEST_TARGET_REACT))
111
+ + }
112
+ +} else {
113
+ + fs.appendFileSync(process.env.TEST_COMMAND_LOG, 'npm ' + args.join(' ') + '\\n')
114
+ +}
115
+ +`
116
+ + const npx = `#!/usr/bin/env node
117
+ +require('fs').appendFileSync(process.env.TEST_COMMAND_LOG, 'npx ' + process.argv.slice(2).join(' ') + '\\n')
118
+ +`
119
+ + for (const [name, contents] of [
120
+ + ['npm', npm],
121
+ + ['npx', npx],
122
+ + ]) {
123
+ + const file = path.join(fakeBin, name)
124
+ + fs.writeFileSync(file, contents)
125
+ + fs.chmodSync(file, 0o755)
126
+ + }
127
+ +
128
+ + return {
129
+ + dir,
130
+ + cli: createSourceCli(),
131
+ + commandLog: path.join(dir, 'commands.log'),
132
+ + env: {
133
+ + ...process.env,
134
+ + PATH: `${fakeBin}${path.delimiter}${process.env.PATH}`,
135
+ + TEST_TARGET_NEXT: targetNext,
136
+ + TEST_TARGET_REACT: targetReact,
137
+ + TEST_REACT_RANGE: `^${targetReact}`,
138
+ + TEST_COMMAND_LOG: path.join(dir, 'commands.log'),
139
+ + FORCE_COLOR: '0',
140
+ + },
141
+ + }
142
+ +}
143
+ +
144
+ +function runUpgrade(project, args, { tty = false, input } = {}) {
145
+ + if (!tty) {
146
+ + return spawnSync(tsx, [project.cli, 'upgrade', ...args], {
147
+ + cwd: project.dir,
148
+ + env: project.env,
149
+ + encoding: 'utf8',
150
+ + timeout: 15_000,
151
+ + })
152
+ + }
153
+ +
154
+ + const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`
155
+ + const command = [tsx, project.cli, 'upgrade', ...args].map(quote).join(' ')
156
+ + return spawnSync('script', ['-q', '-e', '-c', command, '/dev/null'], {
157
+ + cwd: project.dir,
158
+ + env: project.env,
159
+ + encoding: 'utf8',
160
+ + timeout: 15_000,
161
+ + input,
162
+ + })
163
+ +}
164
+ +
165
+ +function outputOf(result) {
166
+ + return `${result.stdout || ''}\n${result.stderr || ''}`
167
+ +}
168
+ +
169
+ +afterEach(() => {
170
+ + while (projects.length) {
171
+ + fs.rmSync(projects.pop(), { recursive: true, force: true })
172
+ + }
173
+ +})
174
+ +
175
+ +test('upgrade help exposes both non-interactive option spellings', () => {
176
+ + const cli = createSourceCli()
177
+ + const result = spawnSync(tsx, [cli, 'upgrade', '--help'], {
178
+ + encoding: 'utf8',
179
+ + timeout: 15_000,
180
+ + })
181
+ +
182
+ + expect(result.status).toBe(0)
183
+ + expect(outputOf(result)).toMatch(/-y, --yes\b/)
184
+ +})
185
+ +
186
+ +test('TTY use without --yes remains interactive', () => {
187
+ + const project = createProject({
188
+ + installedNext: '15.0.0-canary.90',
189
+ + installedReact: '19.0.0',
190
+ + targetNext: '15.0.0-canary.100',
191
+ + targetReact: '19.0.0',
192
+ + devScript: 'next dev',
193
+ + })
194
+ +
195
+ + // Reject the default Turbopack suggestion. A command that incorrectly forces
196
+ + // non-interactive defaults would update this script instead.
197
+ + const result = runUpgrade(project, ['15.0.0-canary.100'], {
198
+ + tty: true,
199
+ + input: 'n\n',
200
+ + })
201
+ + expect(outputOf(result)).toContain('Enable Turbopack')
202
+ + expect(result.status).toBe(0)
203
+ +
204
+ + const manifest = JSON.parse(
205
+ + fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
206
+ + )
207
+ + expect(manifest.scripts.dev).toBe('next dev')
208
+ +})
209
+ +
210
+ +test('--yes accepts prompt defaults even when the command has a TTY', () => {
211
+ + const project = createProject({
212
+ + installedNext: '15.0.0-canary.90',
213
+ + installedReact: '18.2.0',
214
+ + targetNext: '15.0.0-canary.100',
215
+ + targetReact: '19.0.0',
216
+ + devScript: 'next dev',
217
+ + pages: true,
218
+ + })
219
+ +
220
+ + const result = runUpgrade(project, ['15.0.0-canary.100', '--yes'], {
221
+ + tty: true,
222
+ + })
223
+ + expect(result.status).toBe(0)
224
+ +
225
+ + const manifest = JSON.parse(
226
+ + fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
227
+ + )
228
+ + expect(manifest.scripts.dev).toContain('next dev --turbo')
229
+ + expect(manifest.dependencies.next).toBe('15.0.0-canary.100')
230
+ + expect(manifest.dependencies.react).toBe('19.0.0')
231
+ + expect(manifest.dependencies['react-dom']).toBe('19.0.0')
232
+ +
233
+ + const commands = fs.readFileSync(project.commandLog, 'utf8')
234
+ + expect(commands).toContain('react/19/migration-recipe')
235
+ + expect(commands).toContain('types-react-codemod@latest')
236
+ +})
237
+ +
238
+ +test('piped stdin automatically leaves an unrecognized custom dev script unchanged', () => {
239
+ + const devScript = 'node scripts/start-development.js --inspect'
240
+ + const project = createProject({
241
+ + installedNext: '15.0.0-canary.90',
242
+ + installedReact: '19.0.0',
243
+ + targetNext: '15.0.0-canary.100',
244
+ + targetReact: '19.0.0',
245
+ + devScript,
246
+ + })
247
+ +
248
+ + const result = runUpgrade(project, ['15.0.0-canary.100'])
249
+ + expect(result.status).toBe(0)
250
+ + const manifest = JSON.parse(
251
+ + fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
252
+ + )
253
+ + expect(manifest.scripts.dev).toBe(devScript)
254
+ + expect(manifest.dependencies.next).toBe('15.0.0-canary.100')
255
+ +})
256
+ +
257
+ +test('piped stdin applies every recommended Next.js codemod', () => {
258
+ + const project = createProject({
259
+ + installedNext: '13.5.0',
260
+ + installedReact: '18.2.0',
261
+ + targetNext: '14.2.0',
262
+ + targetReact: '18.3.1',
263
+ + devScript: 'next dev',
264
+ + })
265
+ + const page = path.join(project.dir, 'app', 'page.tsx')
266
+ + fs.mkdirSync(path.dirname(page), { recursive: true })
267
+ + fs.writeFileSync(
268
+ + page,
269
+ + `import { ImageResponse } from 'next/server'\n\nexport const metadata = {\n title: 'Keep this title',\n viewport: { width: 'device-width' },\n themeColor: 'black',\n}\n\nexport default function Page() { return null }\n`
270
+ + )
271
+ +
272
+ + const result = runUpgrade(project, ['14.2.0'])
273
+ + expect(result.status).toBe(0)
274
+ +
275
+ + const output = outputOf(result)
276
+ + expect(output).toContain('metadata-to-viewport-export')
277
+ + expect(output).toContain('next-og-import')
278
+ +
279
+ + const transformed = fs.readFileSync(page, 'utf8')
280
+ + expect(transformed).toMatch(/from ['"]next\/og['"]/)
281
+ + expect(transformed).toContain('export const viewport')
282
+ + expect(transformed).toContain("title: 'Keep this title'")
283
+ +})
nextjs-codemod-noninteractive-upgrade/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ git -C /app apply --binary --whitespace=nowarn --exclude='packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js' --exclude='packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js/*' /opt/selfbench/agent.patch || patch_applied=0
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'corepack pnpm@10.33.0 test-webpack '"'"'packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'corepack pnpm@10.33.0 test-webpack '"'"'packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'corepack pnpm@10.33.0 test-webpack '"'"'packages/next-codemod/transforms/__tests__/remove-unstable-prefix.test.js'"'"''; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-hybrid-router-adapter-not-found/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-hybrid-router-adapter-not-found/solution/gold.patch ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/server/request-meta.ts b/packages/next/src/server/request-meta.ts
2
+ index 0521765ea2..e8a421f992 100644
3
+ --- a/packages/next/src/server/request-meta.ts
4
+ +++ b/packages/next/src/server/request-meta.ts
5
+ @@ -155,10 +155,13 @@ export interface RequestMeta {
6
+ isNextDataReq?: true
7
+
8
+ /**
9
+ - * Postponed state to use for resumption. If present it's assumed that the
10
+ - * request is for a page that has postponed (there are no guarantees that the
11
+ - * page actually has postponed though as it would incur an additional cache
12
+ - * lookup).
13
+ + * Postponed state to use for resumption. When absent, the request is not a
14
+ + * resume request. A non-empty string contains the state to resume, while an
15
+ + * empty string represents a resume request without postponed state and
16
+ + * signals that the renderer should perform a full dynamic render.
17
+ + *
18
+ + * There are no guarantees that the page actually postponed, as verifying
19
+ + * that would incur an additional cache lookup.
20
+ */
21
+ postponed?: string
22
+
23
+ diff --git a/packages/next/src/server/route-modules/pages/pages-handler.ts b/packages/next/src/server/route-modules/pages/pages-handler.ts
24
+ index 72dd63c22f..627c5747e6 100644
25
+ --- a/packages/next/src/server/route-modules/pages/pages-handler.ts
26
+ +++ b/packages/next/src/server/route-modules/pages/pages-handler.ts
27
+ @@ -116,6 +116,21 @@ export const getHandler = ({
28
+ const render404 = async () => {
29
+ // TODO: should route-module itself handle rendering the 404
30
+ if (routerServerContext?.render404) {
31
+ + // When the Pages and App Routers coexist, a Pages Router 404 renders
32
+ + // the App Router not-found page. A direct route-module invocation
33
+ + // cannot provide the postponed state needed to resume that App Router
34
+ + // output, so an empty postponed state signals that the renderer must
35
+ + // perform a complete dynamic render instead.
36
+ + //
37
+ + // TODO: Re-enter routing with the App Router not-found output so its
38
+ + // prerender and postponed state can be selected and resumed.
39
+ + if (
40
+ + nextConfig.cacheComponents &&
41
+ + !routerServerContext.isWrappedByNextServer &&
42
+ + typeof getRequestMeta(req, 'postponed') !== 'string'
43
+ + ) {
44
+ + addRequestMeta(req, 'postponed', '')
45
+ + }
46
+ await routerServerContext.render404(req, res, parsedUrl, false)
47
+ } else {
48
+ res.end('This page could not be found')
nextjs-hybrid-router-adapter-not-found/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-hybrid-router-adapter-not-found/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && NEXT_SKIP_NATIVE_POSTINSTALL=0 pnpm install --frozen-lockfile' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-hybrid-router-adapter-not-found/tests/test.patch ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/e2e/app-dir/pages-router-app-not-found/adapter-launcher.js b/test/e2e/app-dir/pages-router-app-not-found/adapter-launcher.js
2
+ new file mode 100644
3
+ index 00000000..068d62ae
4
+ --- /dev/null
5
+ +++ b/test/e2e/app-dir/pages-router-app-not-found/adapter-launcher.js
6
+ @@ -0,0 +1,46 @@
7
+ +// Mimics an adapter invoking a Pages output and handing its 404 render to the
8
+ +// separately compiled App Router not-found output.
9
+ +const http = require('http')
10
+ +const path = require('path')
11
+ +
12
+ +require('next/dist/build/adapter/setup-node-env.external')
13
+ +
14
+ +const dir = process.cwd()
15
+ +const port = Number(process.env.PORT)
16
+ +const pagesRoute = require(path.join(
17
+ + dir,
18
+ + '.next/server/pages/pages-route/[...slug].js'
19
+ +))
20
+ +const appNotFound = require(path.join(
21
+ + dir,
22
+ + '.next/server/app/_not-found/page.js'
23
+ +))
24
+ +
25
+ +http
26
+ + .createServer((req, res) => {
27
+ + const requestMeta = {
28
+ + minimalMode: true,
29
+ + relativeProjectDir: '.',
30
+ + initURL: `https://localhost${req.url}`,
31
+ + render404: async (notFoundReq, notFoundRes) => {
32
+ + await appNotFound.handler(notFoundReq, notFoundRes, {
33
+ + waitUntil: undefined,
34
+ + requestMeta,
35
+ + })
36
+ + },
37
+ + }
38
+ +
39
+ + Promise.resolve(
40
+ + pagesRoute.handler(req, res, {
41
+ + waitUntil: undefined,
42
+ + requestMeta,
43
+ + })
44
+ + ).catch((err) => {
45
+ + console.error('handler error', err)
46
+ + if (!res.writableEnded) {
47
+ + res.statusCode = 500
48
+ + res.end('internal error')
49
+ + }
50
+ + })
51
+ + })
52
+ + .listen(port, () => console.log('adapter launcher ready'))
53
+ diff --git a/test/e2e/app-dir/pages-router-app-not-found/app/layout.tsx b/test/e2e/app-dir/pages-router-app-not-found/app/layout.tsx
54
+ new file mode 100644
55
+ index 00000000..888614de
56
+ --- /dev/null
57
+ +++ b/test/e2e/app-dir/pages-router-app-not-found/app/layout.tsx
58
+ @@ -0,0 +1,8 @@
59
+ +import { ReactNode } from 'react'
60
+ +export default function Root({ children }: { children: ReactNode }) {
61
+ + return (
62
+ + <html>
63
+ + <body>{children}</body>
64
+ + </html>
65
+ + )
66
+ +}
67
+ diff --git a/test/e2e/app-dir/pages-router-app-not-found/app/not-found.tsx b/test/e2e/app-dir/pages-router-app-not-found/app/not-found.tsx
68
+ new file mode 100644
69
+ index 00000000..5c587676
70
+ --- /dev/null
71
+ +++ b/test/e2e/app-dir/pages-router-app-not-found/app/not-found.tsx
72
+ @@ -0,0 +1,20 @@
73
+ +import { Suspense } from 'react'
74
+ +import { cookies } from 'next/headers'
75
+ +
76
+ +async function DynamicNotFound() {
77
+ + const cookieStore = await cookies()
78
+ + const marker = cookieStore.get('not-found-marker')?.value ?? 'missing'
79
+ +
80
+ + return <p id="dynamic-not-found">{marker}</p>
81
+ +}
82
+ +
83
+ +export default function NotFound() {
84
+ + return (
85
+ + <main>
86
+ + <h1>App Router not found</h1>
87
+ + <Suspense fallback={<p>Loading not-found content...</p>}>
88
+ + <DynamicNotFound />
89
+ + </Suspense>
90
+ + </main>
91
+ + )
92
+ +}
93
+ diff --git a/test/e2e/app-dir/pages-router-app-not-found/app/page.tsx b/test/e2e/app-dir/pages-router-app-not-found/app/page.tsx
94
+ new file mode 100644
95
+ index 00000000..4f4d3de9
96
+ --- /dev/null
97
+ +++ b/test/e2e/app-dir/pages-router-app-not-found/app/page.tsx
98
+ @@ -0,0 +1,3 @@
99
+ +export default function Page() {
100
+ + return <p>App Router home</p>
101
+ +}
102
+ diff --git a/test/e2e/app-dir/pages-router-app-not-found/next.config.js b/test/e2e/app-dir/pages-router-app-not-found/next.config.js
103
+ new file mode 100644
104
+ index 00000000..e64bae22
105
+ --- /dev/null
106
+ +++ b/test/e2e/app-dir/pages-router-app-not-found/next.config.js
107
+ @@ -0,0 +1,8 @@
108
+ +/**
109
+ + * @type {import('next').NextConfig}
110
+ + */
111
+ +const nextConfig = {
112
+ + cacheComponents: true,
113
+ +}
114
+ +
115
+ +module.exports = nextConfig
116
+ diff --git a/test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts b/test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts
117
+ new file mode 100644
118
+ index 00000000..37a53015
119
+ --- /dev/null
120
+ +++ b/test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts
121
+ @@ -0,0 +1,65 @@
122
+ +import { spawn, type ChildProcess } from 'child_process'
123
+ +import path from 'path'
124
+ +import { nextTestSetup } from 'e2e-utils'
125
+ +import { findPort, retry } from 'next-test-utils'
126
+ +
127
+ +describe('pages-router-app-not-found', () => {
128
+ + const { next, skipped } = nextTestSetup({
129
+ + files: __dirname,
130
+ + skipDeployment: true,
131
+ + skipStart: true,
132
+ + })
133
+ +
134
+ + if (skipped) return
135
+ +
136
+ + let launcher: ChildProcess
137
+ + let port: number
138
+ +
139
+ + beforeAll(async () => {
140
+ + await next.build()
141
+ +
142
+ + port = await findPort()
143
+ + launcher = spawn('node', [path.join(next.testDir, 'adapter-launcher.js')], {
144
+ + cwd: next.testDir,
145
+ + env: { ...process.env, PORT: String(port) },
146
+ + stdio: 'pipe',
147
+ + })
148
+ + let output = ''
149
+ + launcher.stdout?.on('data', (chunk) => (output += chunk))
150
+ + launcher.stderr?.on('data', (chunk) => (output += chunk))
151
+ + await retry(async () => expect(output).toContain('adapter launcher ready'))
152
+ + })
153
+ +
154
+ + afterAll(() => launcher?.kill())
155
+ +
156
+ + it('fully renders dynamic app not-found content selected by a pages route through an adapter', async () => {
157
+ + for (const marker of ['not-found-first', 'not-found-second']) {
158
+ + const res = await fetch(`http://localhost:${port}/pages-route/${marker}`, {
159
+ + headers: {
160
+ + cookie: `not-found-marker=${marker}`,
161
+ + },
162
+ + })
163
+ + const html = await res.text()
164
+ +
165
+ + expect(res.status).toBe(404)
166
+ + expect(html).toContain('App Router not found')
167
+ + expect(html).toContain(marker)
168
+ + }
169
+ + })
170
+ +
171
+ + it('continues to render the dynamic app not-found content with next start', async () => {
172
+ + await next.start({ skipBuild: true })
173
+ +
174
+ + const marker = 'next-start-not-found'
175
+ + const res = await next.fetch(`/pages-route/${marker}`, {
176
+ + headers: {
177
+ + cookie: `not-found-marker=${marker}`,
178
+ + },
179
+ + })
180
+ + const html = await res.text()
181
+ +
182
+ + expect(res.status).toBe(404)
183
+ + expect(html).toContain('App Router not found')
184
+ + expect(html).toContain(marker)
185
+ + })
186
+ +})
187
+ diff --git a/test/e2e/app-dir/pages-router-app-not-found/pages/pages-route/[...slug].tsx b/test/e2e/app-dir/pages-router-app-not-found/pages/pages-route/[...slug].tsx
188
+ new file mode 100644
189
+ index 00000000..2df13cb6
190
+ --- /dev/null
191
+ +++ b/test/e2e/app-dir/pages-router-app-not-found/pages/pages-route/[...slug].tsx
192
+ @@ -0,0 +1,17 @@
193
+ +export function getStaticPaths() {
194
+ + return {
195
+ + paths: [],
196
+ + fallback: 'blocking',
197
+ + }
198
+ +}
199
+ +
200
+ +export function getStaticProps() {
201
+ + return {
202
+ + notFound: true,
203
+ + revalidate: 1,
204
+ + }
205
+ +}
206
+ +
207
+ +export default function PagesRoute() {
208
+ + return <p>This page should not render.</p>
209
+ +}
nextjs-hybrid-router-adapter-not-found/tests/test.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+ mkdir -p /logs/verifier
4
+ patch_applied=1
5
+ fail_to_pass=0
6
+ pass_to_pass=0
7
+ deterministic=0
8
+ setup_completed=0
9
+ fail_to_pass_exit_code=-1
10
+ fail_to_pass_repeat_exit_code=-1
11
+ pass_to_pass_exit_code=-1
12
+ verifier_cache=""
13
+
14
+ kill_verifier_processes() { pkill -KILL -u "$(id -u verifier)" 2>/dev/null || true; }
15
+ # Some toolchains fetch dependencies at test runtime (e.g. Next.js e2e installs),
16
+ # so a single registry connection reset must not be misread as a dead test. Retry
17
+ # only infrastructure-style failures with backoff; real assertion failures fail fast.
18
+ run_verifier_command() {
19
+ local logfile
20
+ logfile="$(mktemp /tmp/selfbench-verifier-command-XXXXXX.log)"
21
+ local attempt=1
22
+ local status=1
23
+ while [ "$attempt" -le 3 ]; do
24
+ : > "$logfile"
25
+ runuser -u verifier -- env PATH="/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin" UV_CACHE_DIR="$verifier_cache" UV_NO_BUILD_ISOLATION=1 bash -lc "$1" >"$logfile" 2>&1
26
+ status=$?
27
+ if [ "$status" -eq 0 ]; then
28
+ break
29
+ fi
30
+ if [ "$attempt" -lt 3 ] && grep -qE 'ECONNRESET|ETIMEDOUT|ESOCKETTIMEDOUT|ENOTFOUND|EAI_AGAIN|META_FETCH_FAIL|FetchError|EPIPE|EPERM|registry\.npmjs' "$logfile"; then
31
+ sleep "$((10 * attempt))"
32
+ attempt=$((attempt + 1))
33
+ continue
34
+ fi
35
+ break
36
+ done
37
+ cat "$logfile"
38
+ rm -f "$logfile"
39
+ kill_verifier_processes
40
+ return "$status"
41
+ }
42
+ protect_held_out_path() {
43
+ local path="$1"
44
+ chown -R root:root -- "$path"
45
+ chmod -R a-w,go+rX -- "$path"
46
+ }
47
+
48
+ if [ ! -f /opt/selfbench/agent.patch ]; then
49
+ patch_applied=0
50
+ elif [ -s /opt/selfbench/agent.patch ]; then
51
+ git -C /app apply --binary --whitespace=nowarn --exclude='test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts' --exclude='test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts/*' /opt/selfbench/agent.patch || patch_applied=0
52
+ fi
53
+
54
+ if [ "$patch_applied" -eq 1 ]; then setup_completed=1; fi
55
+
56
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
57
+ kill_verifier_processes
58
+ git -C /app restore --source=HEAD --staged --worktree -- 'test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts' 2>/dev/null || true
59
+ git -C /app clean -fd -- 'test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts' >/dev/null 2>&1 || true
60
+ git -C /app apply --binary --whitespace=nowarn /tests/test.patch || patch_applied=0
61
+ if [ "$patch_applied" -eq 1 ]; then
62
+ for protected_path in '/app/test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts'; do protect_held_out_path "$protected_path"; done
63
+ fi
64
+ rm -f /tests/test.patch
65
+ fi
66
+
67
+ if [ "$patch_applied" -eq 1 ] && [ "$setup_completed" -eq 1 ]; then
68
+ cd '/app/.'
69
+ verifier_cache="$(mktemp -d /tmp/selfbench-verifier-uv-XXXXXX)"
70
+ cp -a /opt/uv-cache/. "$verifier_cache"/
71
+ chown -R verifier:verifier "$verifier_cache"
72
+ if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-start-webpack '"'"'test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts'"'"''; then
73
+ fail_to_pass_exit_code=0
74
+ fail_to_pass=1
75
+ if run_verifier_command 'ANALYZE=1 pnpm build && pnpm test-start-webpack '"'"'test/e2e/app-dir/pages-router-app-not-found/pages-router-app-not-found.test.ts'"'"''; then
76
+ fail_to_pass_repeat_exit_code=0
77
+ deterministic=1
78
+ else
79
+ fail_to_pass_repeat_exit_code=$?
80
+ fi
81
+ else
82
+ fail_to_pass_exit_code=$?
83
+ fi
84
+ if run_verifier_command 'true'; then
85
+ pass_to_pass_exit_code=0
86
+ pass_to_pass=1
87
+ else
88
+ pass_to_pass_exit_code=$?
89
+ fi
90
+ rm -rf "$verifier_cache"
91
+ fi
92
+
93
+ reward=0
94
+ if [ "$patch_applied" -eq 1 ] && [ "$fail_to_pass" -eq 1 ] && [ "$pass_to_pass" -eq 1 ] && [ "$deterministic" -eq 1 ]; then reward=1; fi
95
+ cat > /logs/verifier/reward.json <<EOF
96
+ {"reward": $reward, "patch_applied": $patch_applied, "fail_to_pass": $fail_to_pass, "pass_to_pass": $pass_to_pass, "deterministic": $deterministic, "setup_completed": $setup_completed, "fail_to_pass_exit_code": $fail_to_pass_exit_code, "fail_to_pass_repeat_exit_code": $fail_to_pass_repeat_exit_code, "pass_to_pass_exit_code": $pass_to_pass_exit_code}
97
+ EOF
98
+ exit 0
nextjs-navigation-server-action-in-flight/environment/Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ RUN useradd --create-home --shell /bin/bash agent
21
+ COPY repo.tar.gz /tmp/repo.tar.gz
22
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
23
+ && git -C /app init -q \
24
+ && git -C /app config user.email selfbench@local \
25
+ && git -C /app config user.name selfbench \
26
+ && git -C /app add -A \
27
+ && git -C /app commit -qm base
28
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
29
+ && cd '/app/.' \
30
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps --only-shell chromium' \
31
+ && chmod -R a+rwX /opt/uv-cache
32
+ RUN git -C /app reset --hard -q HEAD \
33
+ && git -C /app clean -fdq \
34
+ && mkdir -p /opt/selfbench \
35
+ && cp -a /app/.git /opt/selfbench/base.git \
36
+ && chown -R agent:agent /app /home/agent /opt/uv-cache \
37
+ && chown -R root:root /opt/selfbench \
38
+ && chmod 700 /opt/selfbench \
39
+ && mkdir -p /home/agent/.cache/uv \
40
+ && chown -R agent:agent /home/agent/.cache
41
+ ENV UV_CACHE_DIR=/home/agent/.cache/uv \
42
+ UV_NO_BUILD_ISOLATION=1
43
+ USER agent
44
+ WORKDIR /app
nextjs-navigation-server-action-in-flight/solution/gold.patch ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/packages/next/src/client/components/app-router-instance.ts b/packages/next/src/client/components/app-router-instance.ts
2
+ index 420720a3cd..21a63aa2eb 100644
3
+ --- a/packages/next/src/client/components/app-router-instance.ts
4
+ +++ b/packages/next/src/client/components/app-router-instance.ts
5
+ @@ -67,26 +67,31 @@ export type ActionQueueNode = {
6
+
7
+ function runRemainingActions(
8
+ actionQueue: AppRouterActionQueue,
9
+ + settledAction: ActionQueueNode,
10
+ setState: DispatchStatePromise
11
+ ) {
12
+ - if (actionQueue.pending !== null) {
13
+ - actionQueue.pending = actionQueue.pending.next
14
+ + // Only advance the queue if the settled action is still at its head. If a
15
+ + // navigation discarded this action, the navigation took its place and is
16
+ + // still in flight — starting the next queued action now would run it
17
+ + // against router state that doesn't include the navigation yet.
18
+ + if (actionQueue.pending === settledAction) {
19
+ + actionQueue.pending = settledAction.next
20
+ if (actionQueue.pending !== null) {
21
+ runAction({
22
+ actionQueue,
23
+ action: actionQueue.pending,
24
+ setState,
25
+ })
26
+ - }
27
+ - } else {
28
+ - // Check for refresh when pending is already null
29
+ - // This handles the case where a discarded server action completes
30
+ - // after the navigation has already finished and the queue is empty
31
+ - if (actionQueue.needsRefresh) {
32
+ - actionQueue.needsRefresh = false
33
+ - actionQueue.dispatch({ type: ACTION_REFRESH }, setState)
34
+ + return
35
+ }
36
+ }
37
+ +
38
+ + if (actionQueue.pending === null && actionQueue.needsRefresh) {
39
+ + // The queue is idle; flush the refresh requested by a discarded server
40
+ + // action that revalidated data.
41
+ + actionQueue.needsRefresh = false
42
+ + actionQueue.dispatch({ type: ACTION_REFRESH }, setState)
43
+ + }
44
+ }
45
+
46
+ async function runAction({
47
+ @@ -117,22 +122,22 @@ async function runAction({
48
+ // mark that we need to refresh after all actions complete
49
+ actionQueue.needsRefresh = true
50
+ }
51
+ - // Still need to run remaining actions even for discarded actions
52
+ - // to potentially trigger the refresh
53
+ - runRemainingActions(actionQueue, setState)
54
+ + // This can't advance the queue (this action is no longer its head), but
55
+ + // if the queue has already drained, it flushes the refresh now.
56
+ + runRemainingActions(actionQueue, action, setState)
57
+ return
58
+ }
59
+
60
+ actionQueue.state = nextState
61
+
62
+ - runRemainingActions(actionQueue, setState)
63
+ + runRemainingActions(actionQueue, action, setState)
64
+ action.resolve(nextState)
65
+ }
66
+
67
+ // if the action is a promise, set up a callback to resolve it
68
+ if (isThenable(actionResult)) {
69
+ actionResult.then(handleResult, (err) => {
70
+ - runRemainingActions(actionQueue, setState)
71
+ + runRemainingActions(actionQueue, action, setState)
72
+ action.reject(err)
73
+ })
74
+ } else {
75
+ @@ -197,6 +202,10 @@ function dispatchAction(
76
+ // (Note that it can't contain any earlier navigations, because we always put those into `actionQueue.pending` by calling `runAction`)
77
+ newAction.next = actionQueue.pending.next
78
+
79
+ + if (actionQueue.last === actionQueue.pending) {
80
+ + actionQueue.last = newAction
81
+ + }
82
+ +
83
+ runAction({
84
+ actionQueue,
85
+ action: newAction,
nextjs-navigation-server-action-in-flight/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ git -C /app apply --binary --whitespace=nowarn /solution/gold.patch
nextjs-navigation-server-action-in-flight/tests/Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive \
3
+ UV_LINK_MODE=copy \
4
+ UV_CACHE_DIR=/opt/uv-cache \
5
+ UV_PYTHON_INSTALL_DIR=/usr/local/share/uv/python \
6
+ UV_PYTHON_BIN_DIR=/usr/local/bin \
7
+ RUSTUP_HOME=/usr/local/rustup \
8
+ CARGO_HOME=/usr/local/cargo \
9
+ COREPACK_HOME=/opt/corepack \
10
+ PATH=/usr/local/go/bin:/usr/local/cargo/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
11
+ RUN apt-get update && apt-get install -y --no-install-recommends \
12
+ bash build-essential ca-certificates curl git jq passwd pkg-config procps unzip xz-utils \
13
+ && rm -rf /var/lib/apt/lists/*
14
+ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
15
+ RUN mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" && chmod 755 "$PLAYWRIGHT_BROWSERS_PATH" \
16
+ && arch="$(dpkg --print-architecture)" && case "$arch" in arm64) node_arch=arm64 ;; amd64) node_arch=x64 ;; *) exit 1 ;; esac \
17
+ && curl -fsSL "https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-${node_arch}.tar.xz" | tar -C /usr/local --strip-components=1 -xJ \
18
+ && mkdir -p /opt/corepack && chmod 755 /opt/corepack \
19
+ && corepack enable
20
+ COPY repo.tar.gz /tmp/repo.tar.gz
21
+ RUN mkdir -p /app && tar -xzf /tmp/repo.tar.gz -C /app && rm /tmp/repo.tar.gz \
22
+ && git -C /app init -q \
23
+ && git -C /app config user.email selfbench@local \
24
+ && git -C /app config user.name selfbench \
25
+ && git -C /app add -A \
26
+ && git -C /app commit -qm base
27
+ RUN mkdir -p /opt/uv-cache && chmod 777 /opt/uv-cache \
28
+ && cd '/app/.' \
29
+ && bash -lc 'corepack enable && corepack prepare pnpm@10.33.0 --activate && pnpm install --frozen-lockfile && ANALYZE=1 pnpm build && pnpm exec playwright install --with-deps --only-shell chromium' \
30
+ && chmod -R a+rwX /opt/uv-cache
31
+
32
+ RUN useradd --create-home --shell /bin/bash verifier \
33
+ && chown -R verifier:verifier /app /opt/uv-cache \
34
+ && mkdir -p /opt/selfbench \
35
+ && chmod 700 /opt/selfbench \
36
+ && mkdir -p /home/verifier/.cache/uv \
37
+ && chown -R verifier:verifier /home/verifier/.cache
38
+ ENV UV_CACHE_DIR=/home/verifier/.cache/uv \
39
+ UV_NO_BUILD_ISOLATION=1
40
+ COPY test.patch test.sh /tests/
41
+ RUN chmod 700 /tests && chmod 600 /tests/test.patch && chmod +x /tests/test.sh
42
+ WORKDIR /app
nextjs-navigation-server-action-in-flight/tests/test.patch ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts b/test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts
2
+ new file mode 100644
3
+ index 00000000..bf1b09fa
4
+ --- /dev/null
5
+ +++ b/test/e2e/app-dir/actions-discarded-navigation-revert/actions-discarded-navigation-revert.test.ts
6
+ @@ -0,0 +1,167 @@
7
+ +import { nextTestSetup } from 'e2e-utils'
8
+ +import type * as Playwright from 'playwright'
9
+ +import { createRouterAct } from 'router-act'
10
+ +
11
+ +describe('discarded action settling while a navigation is pending (#86151)', () => {
12
+ + const { next } = nextTestSetup({ files: __dirname })
13
+ +
14
+ + // Navigating while a server action is in flight discards that action:
15
+ + // its result is never applied. These tests cover the window where the
16
+ + // discarded action's response arrives while the navigation is still
17
+ + // ongoing. The navigation must not be reverted, and later actions must
18
+ + // not run until it finishes — if one ran earlier, it would see the
19
+ + // pre-navigation page and undo the navigation.
20
+ + async function interleave(
21
+ + dispatchButton: string,
22
+ + options?: { allowErrorStatusCodes: number[] }
23
+ + ) {
24
+ + let page: Playwright.Page
25
+ + const browser = await next.browser('/', {
26
+ + beforePageLoad(p: Playwright.Page) {
27
+ + page = p
28
+ + },
29
+ + })
30
+ + const act = createRouterAct(page, options)
31
+ +
32
+ + // data-render counts how many times the client received new data for
33
+ + // the root layout. Navigations preserve the root layout, so it only
34
+ + // changes when the router refreshes.
35
+ + const initialRender = await browser
36
+ + .elementById('stamp')
37
+ + .getAttribute('data-render')
38
+ +
39
+ + await act(
40
+ + async () => {
41
+ + // Start server action A. Its response is withheld, so it stays in
42
+ + // flight throughout this scope.
43
+ + await act(async () => {
44
+ + await browser.elementById(dispatchButton).click()
45
+ + }, 'block')
46
+ +
47
+ + // Start server action B. Actions run one at a time, so B waits for
48
+ + // A and no request is issued yet.
49
+ + await act(async () => {
50
+ + await browser.elementById('dispatch-b').click()
51
+ + }, 'no-requests')
52
+ +
53
+ + // Navigate before A or B finished. This discards A. The navigation
54
+ + // response is withheld too, so the navigation is still ongoing when
55
+ + // A's response arrives below.
56
+ + await act(
57
+ + async () => {
58
+ + await browser.elementById('go-dest').click()
59
+ + },
60
+ + { includes: 'Destination page', block: true }
61
+ + )
62
+ +
63
+ + // Exiting this scope delivers the withheld responses in the same
64
+ + // order: first A's, mid-navigation — the moment under test — then
65
+ + // the navigation's. Only then may B run.
66
+ + },
67
+ + // B ran and completed.
68
+ + { includes: 'b-result' }
69
+ + )
70
+ +
71
+ + // B completing means all three operations have settled.
72
+ + await browser.waitForElementByCss('#status-b[data-status="b-result"]')
73
+ +
74
+ + // If B ran too early, it saw the pre-navigation page — but that is not
75
+ + // necessarily visible yet. Running one more action makes it visible:
76
+ + // with the bug, the URL flips back to "/" here instead of staying
77
+ + // on /dest.
78
+ + await act(
79
+ + async () => {
80
+ + await browser.elementById('dispatch-c').click()
81
+ + },
82
+ + { includes: 'c-result' }
83
+ + )
84
+ + await browser.waitForElementByCss('#status-c[data-status="c-result"]')
85
+ +
86
+ + expect(new URL(await browser.url()).pathname).toBe('/dest')
87
+ + expect(await browser.elementById('dest').text()).toBe('Destination page')
88
+ +
89
+ + return { browser, initialRender }
90
+ + }
91
+ +
92
+ + it('keeps the navigation when the discarded action resolves', async () => {
93
+ + const { browser, initialRender } = await interleave('dispatch-resolve')
94
+ +
95
+ + // The discarded action didn't revalidate anything, so there must be
96
+ + // no refresh.
97
+ + expect(await browser.elementById('stamp').getAttribute('data-render')).toBe(
98
+ + initialRender
99
+ + )
100
+ + })
101
+ +
102
+ + // Same scenario, but the discarded action fails. Failure is handled
103
+ + // separately from success, so cover both.
104
+ + it('keeps the navigation when the discarded action rejects', async () => {
105
+ + const { browser, initialRender } = await interleave('dispatch-reject', {
106
+ + // A server action that throws responds with a 500.
107
+ + allowErrorStatusCodes: [500],
108
+ + })
109
+ +
110
+ + await browser.waitForElementByCss('#status-a[data-status="rejected"]')
111
+ + expect(await browser.elementById('stamp').getAttribute('data-render')).toBe(
112
+ + initialRender
113
+ + )
114
+ + })
115
+ +
116
+ + // An action can also be dispatched *while* the navigation is ongoing.
117
+ + // It must run once the navigation finishes. (At one point it never ran:
118
+ + // its caller never settled, and the router stopped applying updates
119
+ + // entirely — the URL never even changed to the navigation target.)
120
+ + it('runs an action dispatched during the navigation once it finishes', async () => {
121
+ + let page: Playwright.Page
122
+ + const browser = await next.browser('/', {
123
+ + beforePageLoad(p: Playwright.Page) {
124
+ + page = p
125
+ + },
126
+ + })
127
+ + const act = createRouterAct(page)
128
+ +
129
+ + await act(
130
+ + async () => {
131
+ + // Start server action A. Its response is withheld, so it stays in
132
+ + // flight throughout this scope.
133
+ + await act(async () => {
134
+ + await browser.elementById('dispatch-resolve').click()
135
+ + }, 'block')
136
+ +
137
+ + // Navigate before A finished. This discards A. The navigation
138
+ + // response is withheld too, so the navigation is still ongoing
139
+ + // when B is dispatched below.
140
+ + await act(
141
+ + async () => {
142
+ + await browser.elementById('go-dest').click()
143
+ + },
144
+ + { includes: 'Destination page', block: true }
145
+ + )
146
+ +
147
+ + // Dispatch server action B while the navigation is ongoing. It
148
+ + // must wait for the navigation, so no request is issued yet.
149
+ + await act(async () => {
150
+ + await browser.elementById('dispatch-b').click()
151
+ + }, 'no-requests')
152
+ + },
153
+ + // B ran once the withheld responses were delivered.
154
+ + { includes: 'b-result' }
155
+ + )
156
+ +
157
+ + await browser.waitForElementByCss('#status-b[data-status="b-result"]')
158
+ + expect(new URL(await browser.url()).pathname).toBe('/dest')
159
+ + expect(await browser.elementById('dest').text()).toBe('Destination page')
160
+ + })
161
+ +
162
+ + it('defers the refresh from a discarded revalidating action until the queue drains', async () => {
163
+ + const { browser, initialRender } = await interleave('dispatch-revalidate')
164
+ +
165
+ + // The discarded action revalidated, so a refresh must still happen —
166
+ + // after everything else, and without undoing the navigation.
167
+ + await browser.waitForElementByCss(
168
+ + `#stamp:not([data-render="${initialRender}"])`
169
+ + )
170
+ + expect(new URL(await browser.url()).pathname).toBe('/dest')
171
+ + expect(await browser.elementById('dest').text()).toBe('Destination page')
172
+ + })
173
+ +})
174
+ diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts b/test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts
175
+ new file mode 100644
176
+ index 00000000..eba7c318
177
+ --- /dev/null
178
+ +++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/actions.ts
179
+ @@ -0,0 +1,16 @@
180
+ +'use server'
181
+ +
182
+ +import { revalidatePath } from 'next/cache'
183
+ +
184
+ +export async function echo(value: string) {
185
+ + return value
186
+ +}
187
+ +
188
+ +export async function reject() {
189
+ + throw new Error('intentional test error')
190
+ +}
191
+ +
192
+ +export async function revalidate() {
193
+ + revalidatePath('/', 'layout')
194
+ + return 'revalidated'
195
+ +}
196
+ diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx
197
+ new file mode 100644
198
+ index 00000000..321086c5
199
+ --- /dev/null
200
+ +++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/controls.tsx
201
+ @@ -0,0 +1,91 @@
202
+ +'use client'
203
+ +
204
+ +import { useState } from 'react'
205
+ +import { useRouter } from 'next/navigation'
206
+ +import { echo, reject, revalidate } from './actions'
207
+ +
208
+ +// Rendered in the root layout so the statuses survive navigations.
209
+ +export function Controls() {
210
+ + const router = useRouter()
211
+ + const [a, setA] = useState('idle')
212
+ + const [b, setB] = useState('idle')
213
+ + const [c, setC] = useState('idle')
214
+ +
215
+ + async function dispatchResolve() {
216
+ + setA('pending')
217
+ + try {
218
+ + setA(await echo('a-result'))
219
+ + } catch {
220
+ + setA('rejected')
221
+ + }
222
+ + }
223
+ +
224
+ + async function dispatchReject() {
225
+ + setA('pending')
226
+ + try {
227
+ + await reject()
228
+ + setA('resolved')
229
+ + } catch {
230
+ + setA('rejected')
231
+ + }
232
+ + }
233
+ +
234
+ + async function dispatchRevalidate() {
235
+ + setA('pending')
236
+ + try {
237
+ + setA(await revalidate())
238
+ + } catch {
239
+ + setA('rejected')
240
+ + }
241
+ + }
242
+ +
243
+ + async function dispatchB() {
244
+ + setB('pending')
245
+ + try {
246
+ + setB(await echo('b-result'))
247
+ + } catch {
248
+ + setB('rejected')
249
+ + }
250
+ + }
251
+ +
252
+ + async function dispatchC() {
253
+ + setC('pending')
254
+ + try {
255
+ + setC(await echo('c-result'))
256
+ + } catch {
257
+ + setC('rejected')
258
+ + }
259
+ + }
260
+ +
261
+ + return (
262
+ + <div>
263
+ + <button id="dispatch-resolve" onClick={dispatchResolve}>
264
+ + dispatch resolving action
265
+ + </button>
266
+ + <button id="dispatch-reject" onClick={dispatchReject}>
267
+ + dispatch rejecting action
268
+ + </button>
269
+ + <button id="dispatch-revalidate" onClick={dispatchRevalidate}>
270
+ + dispatch revalidating action
271
+ + </button>
272
+ + <button id="dispatch-b" onClick={dispatchB}>
273
+ + dispatch queued action
274
+ + </button>
275
+ + <button id="go-dest" onClick={() => router.push('/dest')}>
276
+ + go to destination
277
+ + </button>
278
+ + <button id="dispatch-c" onClick={dispatchC}>
279
+ + dispatch probe action
280
+ + </button>
281
+ + <div id="status-a" data-status={a}>
282
+ + a:{a}
283
+ + </div>
284
+ + <div id="status-b" data-status={b}>
285
+ + b:{b}
286
+ + </div>
287
+ + <div id="status-c" data-status={c}>
288
+ + c:{c}
289
+ + </div>
290
+ + </div>
291
+ + )
292
+ +}
293
+ diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx
294
+ new file mode 100644
295
+ index 00000000..f40f1e5e
296
+ --- /dev/null
297
+ +++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/dest/page.tsx
298
+ @@ -0,0 +1,17 @@
299
+ +import { Suspense } from 'react'
300
+ +import { connection } from 'next/server'
301
+ +
302
+ +// connection() makes the page dynamic in all modes, so navigating here
303
+ +// always produces a router request.
304
+ +async function Content() {
305
+ + await connection()
306
+ + return <div id="dest">Destination page</div>
307
+ +}
308
+ +
309
+ +export default function DestPage() {
310
+ + return (
311
+ + <Suspense fallback={null}>
312
+ + <Content />
313
+ + </Suspense>
314
+ + )
315
+ +}
316
+ diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx
317
+ new file mode 100644
318
+ index 00000000..f387ca61
319
+ --- /dev/null
320
+ +++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/layout.tsx
321
+ @@ -0,0 +1,29 @@
322
+ +import { Suspense } from 'react'
323
+ +import { connection } from 'next/server'
324
+ +import { Controls } from './controls'
325
+ +import { RenderCounter } from './render-counter'
326
+ +
327
+ +// The stamp only changes when the router refreshes: navigations preserve the
328
+ +// root layout, so a new stamp on the client means a refresh happened.
329
+ +async function Stamp() {
330
+ + await connection()
331
+ + return <RenderCounter uuid={crypto.randomUUID()} />
332
+ +}
333
+ +
334
+ +export default function RootLayout({
335
+ + children,
336
+ +}: {
337
+ + children: React.ReactNode
338
+ +}) {
339
+ + return (
340
+ + <html lang="en">
341
+ + <body>
342
+ + <Suspense fallback={null}>
343
+ + <Stamp />
344
+ + </Suspense>
345
+ + <Controls />
346
+ + {children}
347
+ + </body>
348
+ + </html>
349
+ + )
350
+ +}
351
+ diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx
352
+ new file mode 100644
353
+ index 00000000..3e134694
354
+ --- /dev/null
355
+ +++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/page.tsx
356
+ @@ -0,0 +1,3 @@
357
+ +export default function Page() {
358
+ + return <div id="origin">Origin page</div>
359
+ +}
360
+ diff --git a/test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx b/test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx
361
+ new file mode 100644
362
+ index 00000000..7909f06b
363
+ --- /dev/null
364
+ +++ b/test/e2e/app-dir/actions-discarded-navigation-revert/app/render-counter.tsx
365
+ @@ -0,0 +1,20 @@
366
+ +'use client'
367
+ +
368
+ +import { useState } from 'react'
369
+ +
370
+ +// Counts how many times the client received new dynamic data for the root
371
+ +// layout. The count lives in client state: a server-side counter would break
372
+ +// in deploy tests, where the server is stateless.
373
+ +export function RenderCounter({ uuid }: { uuid: string }) {
374
+ + const [count, setCount] = useState(0)
375
+ + const [prevUuid, setPrevUuid] = useState(uuid)
376
+ + if (prevUuid !== uuid) {
377
+ + setPrevUuid(uuid)
378
+ + setCount(count + 1)
379
+ + }
380
+ + return (
381
+ + <div id="stamp" data-render={count}>
382
+ + renders:{count}
383
+ + </div>
384
+ + )
385
+ +}