From c5b3a7a6163c73cac86252b11223ced67d3f158d Mon Sep 17 00:00:00 2001 From: Jiwon Choi Date: Mon, 28 Sep 2026 08:15:06 +0900 Subject: [PATCH 1/7] Use focused npm advisories and nudge only for ready upgrades (#99222) Stacked on #99230. ### Why? Simplify the advisory check by querying only the versions we need instead of sending a bulk audit request. ### How? Query npm advisories for the installed version and relevant upgrade candidates. Remove the GHSA lookup and fallback. Only show a nudge when the assessment finds a ready target; otherwise, skip it. Closes NAR-948 --- evals/next-upgrade/future/assessment.mjs | 15 +- evals/next-upgrade/latest/assessment.mjs | 29 +- packages/next/src/lib/upgrade/nudge.ts | 98 +--- .../next/src/lib/upgrade/prepare-upgrade.ts | 358 ++++----------- test/unit/prepare-latest-upgrade.test.ts | 417 +++++++++--------- test/unit/security-upgrade-nudge.test.ts | 88 ++-- 6 files changed, 398 insertions(+), 607 deletions(-) diff --git a/evals/next-upgrade/future/assessment.mjs b/evals/next-upgrade/future/assessment.mjs index 189200280040..06c20c17ccb3 100644 --- a/evals/next-upgrade/future/assessment.mjs +++ b/evals/next-upgrade/future/assessment.mjs @@ -11,9 +11,18 @@ const { target } = JSON.parse( globalThis.fetch = async (input, init) => { const url = String(input) let value + let versions - if (url.startsWith('https://api.github.com/advisories?')) { - value = [] + if (url === 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk') { + versions = JSON.parse(init.body).next + if ( + !Array.isArray(versions) || + versions.length === 0 || + versions.some((version) => typeof version !== 'string') + ) { + throw new Error('Expected Next.js advisory versions') + } + value = {} } else if (url === 'https://registry.npmjs.org/next/latest') { value = { version: target, @@ -25,7 +34,7 @@ globalThis.fetch = async (input, init) => { appendFileSync( join(tools, 'assessment.jsonl'), - JSON.stringify({ url, value }) + '\n' + JSON.stringify({ url, versions, value }) + '\n' ) return Response.json(value) } diff --git a/evals/next-upgrade/latest/assessment.mjs b/evals/next-upgrade/latest/assessment.mjs index 50a8432917c2..06c20c17ccb3 100644 --- a/evals/next-upgrade/latest/assessment.mjs +++ b/evals/next-upgrade/latest/assessment.mjs @@ -10,22 +10,31 @@ const { target } = JSON.parse( globalThis.fetch = async (input, init) => { const url = String(input) + let value + let versions - if (url.startsWith('https://api.github.com/advisories?')) { - return Response.json([]) - } - - if (url !== 'https://registry.npmjs.org/next/latest') { + if (url === 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk') { + versions = JSON.parse(init.body).next + if ( + !Array.isArray(versions) || + versions.length === 0 || + versions.some((version) => typeof version !== 'string') + ) { + throw new Error('Expected Next.js advisory versions') + } + value = {} + } else if (url === 'https://registry.npmjs.org/next/latest') { + value = { + version: target, + engines: { node: '>=20.9.0' }, + } + } else { return realFetch(input, init) } - const value = { - version: target, - engines: { node: '>=20.9.0' }, - } appendFileSync( join(tools, 'assessment.jsonl'), - JSON.stringify({ url, value }) + '\n' + JSON.stringify({ url, versions, value }) + '\n' ) return Response.json(value) } diff --git a/packages/next/src/lib/upgrade/nudge.ts b/packages/next/src/lib/upgrade/nudge.ts index 1a885545690e..5f214158db7a 100644 --- a/packages/next/src/lib/upgrade/nudge.ts +++ b/packages/next/src/lib/upgrade/nudge.ts @@ -10,7 +10,7 @@ import type { NextConfigComplete } from '../../server/config-shared' import semver from 'next/dist/compiled/semver' import type { UpgradeAction } from './prompt' import { getAgentName } from '../../telemetry/agent-name' -import { futureDefaults, getPendingFutureDefaults } from './future-defaults' +import { getPendingFutureDefaults } from './future-defaults' import { isCI } from '../../server/ci-info' type NudgeOptions = { @@ -125,8 +125,7 @@ type UpgradeReminder = { | { kind: 'security' reference: string | null - targetVersion: string | null - unavailableReason: string | null + targetVersion: string } | { kind: 'latest'; latestVersion: string | null; names: string[] } | { kind: 'future'; targetVersion: string; names: string[] } @@ -186,24 +185,21 @@ export async function assessUpgrade( return null } const { upgrade } = assessment + if (upgrade.status !== 'ready') { + // TODO: Record affected and upgrade.status in telemetry so we can see when + // an advisory applies but no ready target was available to nudge. + return null + } if (assessment.affected) { return { kind: 'security', policy, installedVersion, reference: assessment.reference, - targetVersion: upgrade.status === 'ready' ? upgrade.targetVersion : null, - unavailableReason: - upgrade.status === 'ready' - ? null - : `${upgrade.status === 'unknown' ? 'Upgrade availability could not be checked.' : 'No safe newer target is available for the configured upgrade policy.'} ${upgrade.reason}`, + targetVersion: upgrade.targetVersion, } } - if ( - upgrade.status !== 'ready' || - policy === 'security' || - stopBefore === 'latest' - ) { + if (policy === 'security' || stopBefore === 'latest') { return null } const latestVersion = getLatestUpgradeVersion( @@ -248,8 +244,7 @@ export async function assessUpgrade( async function nudgeUpgradeForAgent( options: NudgeOptions, - reminder: UpgradeReminder, - preview: boolean + reminder: UpgradeReminder ): Promise { let summary: string let recommendation: string @@ -271,15 +266,11 @@ async function nudgeUpgradeForAgent( recommendation = 'We recommend you adopt these Future Defaults.' break } - const unavailableReason = - reminder.kind === 'security' ? reminder.unavailableReason : null - const command = unavailableReason - ? null - : `next upgrade --ai=${reminder.policy}` + const command = `next upgrade --ai=${reminder.policy}` const note = getRequestedUpgrade() ? `Note: This reminder is enabled by \`__NEXT_AGENTIC_AUTO_UPGRADE=${reminder.policy}\`.` : `Note: This reminder is enabled by \`experimental.agenticAutoUpgrade: '${reminder.policy}'\`.` - let message = `${summary} + const message = `${summary} **${recommendation}** @@ -287,20 +278,13 @@ This command stopped so the reminder you configured is not missed. Retry the sam When you report back to the user, include this upgrade recommendation even if the retry succeeds. -${ - command - ? `At the end of the task, ask the user whether they want you to run the upgrade using the configured '${reminder.policy}' policy in the background. If the app is in a Git repository, use a separate Git worktree unless they request otherwise. If the app is not in a Git repository, upgrade it in place. Run this command from this app's directory: +At the end of the task, ask the user whether they want you to run the upgrade using the configured '${reminder.policy}' policy in the background. If the app is in a Git repository, use a separate Git worktree unless they request otherwise. If the app is not in a Git repository, upgrade it in place. Run this command from this app's directory: \`\`\` ${command} -\`\`\`` - : unavailableReason -} +\`\`\` ${reference ? `Reference: ${reference}\n\n` : ''}${note}` - if (preview) { - message = `Forced preview: this reminder does not establish upgrade eligibility.\n\n${message}` - } let retryAllowed = false try { retryAllowed = await allowNudgeRetry( @@ -315,7 +299,7 @@ ${reference ? `Reference: ${reference}\n\n` : ''}${note}` } if (retryAllowed) { Log.warn( - `${summary} This command is continuing after the reminder you configured.${unavailableReason ? `\n${unavailableReason}` : ''}${reference ? `\nReference: ${reference}` : ''}` + `${summary} This command is continuing after the reminder you configured.${reference ? `\nReference: ${reference}` : ''}` ) return } @@ -389,18 +373,15 @@ async function getUpgradeDismissal( async function nudgeUpgradeForHuman( directory: string, reminder: UpgradeReminder, - signal: AbortSignal, - preview: boolean + signal: AbortSignal ): Promise { if (signal.aborted) { return 'skip' } let message: string - let canUpgrade = true if (reminder.kind === 'security') { message = `⚠ Installed Next.js version ${reminder.installedVersion} is affected by a known security vulnerability.` - canUpgrade = reminder.unavailableReason === null - message += `\n\n${reminder.unavailableReason ?? `Next.js security version upgrade available: ${reminder.installedVersion} -> ${reminder.targetVersion ?? '[target version]'}`}` + message += `\n\nNext.js security version upgrade available: ${reminder.installedVersion} -> ${reminder.targetVersion}` } else if (reminder.policy === 'future') { const targetVersion = reminder.kind === 'latest' @@ -419,11 +400,8 @@ async function nudgeUpgradeForHuman( } else { return 'skip' } - if (preview) { - message = `Forced preview: __NEXT_AGENTIC_AUTO_UPGRADE=${reminder.policy}. Upgrade eligibility has not been established.\n\n${message}` - } const { promptUpgrade } = require('./prompt') as typeof import('./prompt') - const action = await promptUpgrade(message, signal, canUpgrade) + const action = await promptUpgrade(message, signal, true) if (signal.aborted) { return 'skip' } @@ -495,56 +473,22 @@ export async function nudgeUpgrade( return } } - let reminder = await assessUpgrade( + const reminder = await assessUpgrade( directory, { ...config, experimental: { agenticAutoUpgrade: policy } }, installedVersion, stopBefore, requested !== null ) - const preview = !reminder && requested !== null - if (preview) { - // Exercise the real template without inventing an advisory or release. - // Update still runs the normal eligibility checks against this installation. - const context = { policy, installedVersion } - switch (requested) { - case 'security': - reminder = { - ...context, - kind: 'security', - reference: null, - targetVersion: null, - unavailableReason: null, - } - break - case 'latest': - reminder = { - ...context, - kind: 'latest', - latestVersion: null, - names: [], - } - break - case 'future': - reminder = { - ...context, - kind: 'future', - targetVersion: installedVersion, - names: futureDefaults.map((entry) => entry.name), - } - break - } - } if (!reminder || signal?.aborted) { return } if (agent) { await nudgeUpgradeForAgent( { directory, distDir: config.distDir, command }, - reminder, - preview + reminder ) } else if (signal) { - return nudgeUpgradeForHuman(directory, reminder, signal, preview) + return nudgeUpgradeForHuman(directory, reminder, signal) } } diff --git a/packages/next/src/lib/upgrade/prepare-upgrade.ts b/packages/next/src/lib/upgrade/prepare-upgrade.ts index aa86347a3ace..c8f0d9d3755c 100644 --- a/packages/next/src/lib/upgrade/prepare-upgrade.ts +++ b/packages/next/src/lib/upgrade/prepare-upgrade.ts @@ -129,8 +129,24 @@ export async function getUpgradeAssessment( } // Prerelease version ordering does not establish which security fixes it // contains, but stable promotion targets still need advisory validation. - const snapshot = - channel === 'canary' ? null : await readAdvisorySnapshot(installedVersion) + let snapshot: { ranges: string[]; reference: string } | null = null + if (channel !== 'canary') { + try { + snapshot = { + ranges: await readNpmAdvisories([installedVersion]), + reference: NPM_ADVISORIES, + } + } catch { + return { + affected: null, + reference: null, + upgrade: { + status: 'unknown', + reason: 'Could not check for security updates. Please try again.', + }, + } + } + } const affected = snapshot && !channel ? snapshot.ranges.some((range) => @@ -139,13 +155,6 @@ export async function getUpgradeAssessment( : null const assessment = { affected, reference: snapshot?.reference ?? null } - if (snapshot && snapshot.targetError !== null) { - return { - ...assessment, - upgrade: { status: 'unknown', reason: snapshot.targetError }, - } - } - // A dismissed release reminder still checks advisories, but does not need // target metadata unless an advisory applies. if ((policy === 'security' || onlyIfAffected) && !affected) { @@ -164,15 +173,22 @@ export async function getUpgradeAssessment( let references: string[] if (policy === 'security' && snapshot) { const registryURL = `${NPM_REGISTRY}next` - const registry = snapshot.registry ?? (await fetchJSON(registryURL)).value + const registry = (await fetchJSON(registryURL)).value const releases = parseReleases(registry) references = [snapshot.reference, registryURL] + const candidates = securityCandidates(installedVersion, releases) + const ranges = [ + ...snapshot.ranges, + ...(candidates.length + ? await readNpmAdvisories(candidates.map(({ version }) => version)) + : []), + ] try { - targetVersion = selectSecurityTarget(installedVersion, { - ranges: snapshot.ranges, + targetVersion = selectSecurityTarget( + installedVersion, releases, - references, - })!.version + ranges + )!.version } catch (error) { return { ...assessment, @@ -206,29 +222,12 @@ export async function getUpgradeAssessment( } } - // The tag can advance after npm's published-version snapshot was read. - // Include that exact target in the fallback query as well. + const targetRanges = + snapshot && targetVersion !== installedVersion + ? await readNpmAdvisories([targetVersion]) + : snapshot?.ranges if ( - snapshot && - snapshot.registry !== null && - !advisoryVersions(snapshot.registry, installedVersion).includes( - targetVersion - ) - ) { - snapshot.ranges = affectedRanges( - await readNpmAdvisories([ - ...advisoryVersions(snapshot.registry, installedVersion), - targetVersion, - ]) - ) - if (!channel) { - assessment.affected ||= snapshot.ranges.some((range) => - semver.satisfies(installedVersion, range) - ) - } - } - if ( - snapshot?.ranges.some((range) => semver.satisfies(targetVersion, range)) + targetRanges?.some((range) => semver.satisfies(targetVersion, range)) ) { return { ...assessment, @@ -268,33 +267,17 @@ export async function getUpgradeAssessment( } } -type Advisory = { - withdrawn_at: string | null - vulnerabilities: { - package: { ecosystem: string; name: string } - vulnerable_version_range: string - }[] -} - type PackageRelease = { version: string } -type SecuritySnapshot = { - ranges: string[] - releases: PackageRelease[] - references: string[] -} - -const ADVISORIES = - 'https://api.github.com/advisories?ecosystem=npm&affects=next&type=reviewed&per_page=100' const NPM_REGISTRY = 'https://registry.npmjs.org/' const NPM_ADVISORIES = `${NPM_REGISTRY}-/npm/v1/security/advisories/bulk` async function fetchJSON( url: string, init: RequestInit | undefined = undefined -): Promise<{ value: unknown; headers: Headers }> { +): Promise<{ value: unknown }> { try { const response = await fetch(url, { ...init, @@ -307,7 +290,7 @@ async function fetchJSON( throw new Error(`HTTP ${response.status}`) } - return { value: await response.json(), headers: response.headers } + return { value: await response.json() } } catch (error) { throw new Error('Could not fetch upgrade metadata. Please try again.', { cause: error, @@ -325,7 +308,7 @@ export function getPrereleaseChannel(version: string): string | null { : null } -function parseReleases(value: unknown): SecuritySnapshot['releases'] { +function parseReleases(value: unknown): PackageRelease[] { const data = value as { versions: | Record< @@ -354,58 +337,6 @@ function parseReleases(value: unknown): SecuritySnapshot['releases'] { }) } -function affectedRanges(advisories: Advisory[]): string[] { - const ranges: string[] = [] - - for (const advisory of advisories) { - if ( - !advisory || - !Array.isArray(advisory.vulnerabilities) || - !('withdrawn_at' in advisory) - ) { - throw new Error('Could not check for security updates.') - } - - if (advisory.withdrawn_at) { - continue - } - - for (const finding of advisory.vulnerabilities) { - if ( - !finding.package || - typeof finding.package.name !== 'string' || - typeof finding.package.ecosystem !== 'string' - ) { - throw new Error('Could not check for security updates.') - } - - if ( - finding.package.ecosystem !== 'npm' || - finding.package.name !== 'next' - ) { - continue - } - - if ( - typeof finding.vulnerable_version_range !== 'string' || - !finding.vulnerable_version_range.trim() - ) { - throw new Error('Could not check for security updates.') - } - - const range = finding.vulnerable_version_range.replace(/,\s*/g, ' ') - - if (!semver.validRange(range)) { - throw new Error('Could not check for security updates.') - } - - ranges.push(range) - } - } - - return ranges -} - export function getLatestUpgradeVersion( version: string, targetVersion: string @@ -459,61 +390,23 @@ async function fetchLatestRelease(installedVersion: string): Promise<{ return { version: release.version, reference } } -async function readGitHubAdvisories(version: string | null) { - const advisories: Advisory[] = [] - const visited = new Set() - const affects = version === null ? 'next' : `next@${version}` - const firstPage = new URL(ADVISORIES) - firstPage.searchParams.set('affects', affects) - let url: string | undefined = firstPage.href - - for (let page = 0; url; page++) { - if (page === 100) { - throw new Error('Could not check for security updates.') - } - - visited.add(url) - const { value, headers } = await fetchJSON(url) - - if (!Array.isArray(value)) { - throw new Error('Could not check for security updates.') - } - - advisories.push(...value) - const next = headers - .get('link') - ?.split(',') - .find((part) => /rel="next"/.test(part)) - ?.match(/<([^>]+)>/)?.[1] - - if (next) { - const parsed = new URL(next) - - if ( - parsed.origin !== 'https://api.github.com' || - parsed.pathname !== '/advisories' || - parsed.searchParams.get('ecosystem') !== 'npm' || - parsed.searchParams.get('affects') !== affects || - parsed.searchParams.get('type') !== 'reviewed' || - visited.has(next) - ) { - throw new Error('Could not check for security updates.') - } - } - - url = next +// TODO: Record whether each advisory lookup succeeded or failed in upgrade telemetry. +async function readNpmAdvisories(versions: string[]): Promise { + let value: unknown + try { + value = ( + await fetchJSON(NPM_ADVISORIES, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ next: versions }), + }) + ).value + } catch (error) { + throw new Error('Could not check for security updates. Please try again.', { + cause: error, + }) } - return { advisories, reference: firstPage.href } -} - -async function readNpmAdvisories(versions: string[]): Promise { - const { value } = await fetchJSON(NPM_ADVISORIES, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ next: versions }), - }) - if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error('Could not check for security updates.') } @@ -533,136 +426,55 @@ async function readNpmAdvisories(versions: string[]): Promise { throw new Error('Could not check for security updates.') } - const advisories: Advisory[] = data.next.map((finding) => { - if (!finding || typeof finding.vulnerable_versions !== 'string') { + return data.next.map((finding) => { + if ( + !finding || + typeof finding.vulnerable_versions !== 'string' || + !finding.vulnerable_versions.trim() + ) { throw new Error('Could not check for security updates.') } - - return { - // npm's active advisory feed does not expose withdrawal metadata. - withdrawn_at: null, - vulnerabilities: [ - { - package: { ecosystem: 'npm', name: 'next' }, - vulnerable_version_range: finding.vulnerable_versions, - }, - ], + const range = finding.vulnerable_versions.replace(/,\s*/g, ' ') + if (!semver.validRange(range)) { + throw new Error('Could not check for security updates.') } + return range }) - return advisories -} - -function advisoryVersions(value: unknown, checkedVersion: string): string[] { - const data = value as { versions: Record | undefined } - if ( - !data?.versions || - typeof data.versions !== 'object' || - Array.isArray(data.versions) - ) { - throw new Error('Could not check for security updates.') - } - - // Include all published versions to retrieve advisories affecting candidates, - // not only the installed version. - const versions = Object.keys(data.versions).filter((version) => - semver.valid(version) - ) - if (!versions.includes(checkedVersion)) { - versions.push(checkedVersion) - } - return versions -} - -// TODO: Replace provider-specific requests with a Next.js-maintained endpoint -// that returns advisory ranges and exact safe targets for each major. -async function readAdvisorySnapshot(installedVersion: string): Promise<{ - ranges: string[] - reference: string - registry: unknown | null - targetError: string | null -}> { - // Accept GitHub evidence only after every page and range validates. On - // failure, npm replaces the entire set, including candidate advisories. - try { - const { advisories, reference } = await readGitHubAdvisories(null) - return { - ranges: affectedRanges(advisories), - reference, - registry: null, - targetError: null, - } - } catch (githubFailure) { - try { - const { value } = await fetchJSON(`${NPM_REGISTRY}next`) - const ranges = affectedRanges( - await readNpmAdvisories(advisoryVersions(value, installedVersion)) - ) - return { - ranges, - reference: NPM_ADVISORIES, - registry: value, - targetError: null, - } - } catch (error) { - // A source-only response can still establish a warning, but cannot - // establish target safety. - try { - const ranges = affectedRanges( - await readNpmAdvisories([installedVersion]) - ) - if (ranges.some((range) => semver.satisfies(installedVersion, range))) { - return { - ranges, - reference: NPM_ADVISORIES, - registry: null, - targetError: 'Could not assess upgrade targets. Please try again.', - } - } - } catch { - // Neither provider could establish even a source-only warning. - } - throw new Error( - 'Could not check for security updates. Please try again.', - { cause: [githubFailure, error] } - ) - } - } } -function selectSecurityTarget( +function securityCandidates( source: string, - snapshot: SecuritySnapshot -): PackageRelease | undefined { - const ranges = snapshot.ranges - - if (!ranges.some((range) => semver.satisfies(source, range))) { - return - } - - const releases = snapshot.releases - // Consider only the latest stable release of each major, not an older safe patch. + releases: PackageRelease[] +): PackageRelease[] { + // Only the newest stable release of each eligible major is considered. const latest = new Map() - for (const release of releases) { const major = semver.major(release.version) const previous = latest.get(major) - if (!previous || semver.gt(release.version, previous.version)) { latest.set(major, release) } } + return [...latest.entries()] + .sort(([a], [b]) => a - b) + .filter( + ([major, release]) => + major >= semver.major(source) && semver.gt(release.version, source) + ) + .map(([, release]) => release) +} - for (const major of [...latest.keys()].sort((a, b) => a - b)) { - if (major < semver.major(source)) { - continue - } - - const candidate = latest.get(major)! +function selectSecurityTarget( + source: string, + releases: PackageRelease[], + ranges: string[] +): PackageRelease | undefined { + if (!ranges.some((range) => semver.satisfies(source, range))) { + return + } - if ( - semver.gt(candidate.version, source) && - !ranges.some((range) => semver.satisfies(candidate.version, range)) - ) { + for (const candidate of securityCandidates(source, releases)) { + if (!ranges.some((range) => semver.satisfies(candidate.version, range))) { return candidate } } diff --git a/test/unit/prepare-latest-upgrade.test.ts b/test/unit/prepare-latest-upgrade.test.ts index bcb0f7978ad4..01570edf0580 100644 --- a/test/unit/prepare-latest-upgrade.test.ts +++ b/test/unit/prepare-latest-upgrade.test.ts @@ -32,21 +32,16 @@ describe('prepare latest upgrade', () => { } function mockLatestVersion(version: string) { - global.fetch = jest.fn(async (input) => - String(input).startsWith('https://api.github.com/') - ? Response.json([]) - : new Response( - JSON.stringify({ - version, - engines: { node: '>=18' }, - }), - { status: 200 } - ) - ) + global.fetch = jest.fn(async (input) => { + if (String(input).includes('/security/advisories/bulk')) { + return Response.json({}) + } + return Response.json({ version, engines: { node: '>=18' } }) + }) } function mockFutureMetadata(vulnerableVersions: string) { - global.fetch = jest.fn(async (input) => { + global.fetch = jest.fn(async (input, init) => { const url = String(input) if (url === 'https://registry.npmjs.org/next/latest') { @@ -56,31 +51,25 @@ describe('prepare latest upgrade', () => { }) } - if (url.startsWith('https://api.github.com/advisories?')) { - return new Response(null, { status: 500 }) - } - - if (url === 'https://registry.npmjs.org/next') { - return Response.json({ - versions: { - '16.2.0': { version: '16.2.0' }, - '16.4.0': { version: '16.4.0' }, - }, - }) - } - if ( url === 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk' ) { + const { next: versions } = JSON.parse(String(init?.body)) as { + next: string[] + } return Response.json({ - next: [ - { - id: 1, - url: 'https://github.com/advisories/GHSA-next-test', - severity: 'high', - vulnerable_versions: vulnerableVersions, - }, - ], + next: versions.some((version) => + semver.satisfies(version, vulnerableVersions) + ) + ? [ + { + id: 1, + url: 'https://github.com/advisories/GHSA-next-test', + severity: 'high', + vulnerable_versions: vulnerableVersions, + }, + ] + : [], }) } @@ -98,26 +87,10 @@ describe('prepare latest upgrade', () => { ranges = ['>=17.2.0-canary.0 <17.2.0-canary.5'], target = '17.2.0-canary.5' as string | null, published = ['17.2.0', '17.2.0-canary.5', '17.3.0-canary.0'], - fallback = false, npmFailure = false, } = {}) { global.fetch = jest.fn(async (input, init) => { const url = String(input) - if (url.startsWith('https://api.github.com/advisories?')) { - return fallback - ? new Response(null, { status: 500 }) - : Response.json( - ranges.map((range) => ({ - withdrawn_at: null, - vulnerabilities: [ - { - package: { ecosystem: 'npm', name: 'next' }, - vulnerable_version_range: range, - }, - ], - })) - ) - } if (url === 'https://registry.npmjs.org/next') { return Response.json({ 'dist-tags': target === null ? {} : { canary: target }, @@ -175,10 +148,15 @@ describe('prepare latest upgrade', () => { expect(global.fetch).toHaveBeenCalledTimes(0) }) - it('does not treat failed stable advisory providers as an unaffected version', async () => { + it('does not treat a failed advisory request as an unaffected version', async () => { const directory = await createApp('17.2.0') - mockSecurityMetadata({ fallback: true, npmFailure: true }) - await expect(getUpgradeAssessment('17.2.0', 'security')).rejects.toThrow() + mockSecurityMetadata({ npmFailure: true }) + await expect( + getUpgradeAssessment('17.2.0', 'security') + ).resolves.toMatchObject({ + affected: null, + upgrade: { status: 'unknown' }, + }) await expect(prepareUpgrade(directory, 'security')).rejects.toThrow( 'Could not check for security updates.' ) @@ -219,7 +197,7 @@ describe('prepare latest upgrade', () => { }) expect( jest.mocked(global.fetch).mock.calls.map(([url]) => String(url)) - ).toEqual([expect.stringContaining('https://api.github.com/advisories?')]) + ).toEqual(['https://registry.npmjs.org/-/npm/v1/security/advisories/bulk']) }) describe('shared stable eligibility', () => { @@ -297,7 +275,7 @@ describe('prepare latest upgrade', () => { 'retains npm advisory warnings without release metadata for %s', async (policy) => { const directory = await createApp(installed) - mockSecurityMetadata({ fallback: true, ranges: [installed] }) + mockSecurityMetadata({ ranges: [installed] }) const fetchMetadata = global.fetch global.fetch = jest.fn(async (input, init) => { if (String(input).startsWith('https://registry.npmjs.org/next')) { @@ -314,17 +292,16 @@ describe('prepare latest upgrade', () => { upgrade: { status: 'unknown' }, }) await expect(prepareUpgrade(directory, policy)).rejects.toThrow( - 'Could not assess upgrade targets.' + 'Could not fetch upgrade metadata.' ) } ) }) - it('includes a newly published tag in npm fallback assessment', async () => { + it('checks a newly published target tag', async () => { const target = '17.3.0' const directory = await createApp('17.2.0') mockSecurityMetadata({ - fallback: true, ranges: [target], target, published: ['17.2.0'], @@ -343,31 +320,27 @@ describe('prepare latest upgrade', () => { ) }) - it.each([false, true])( - 'assesses the configured policy rather than a different safe security target, fallback=%s', - async (fallback) => { - const directory = await createApp('17.2.0') - mockSecurityMetadata({ - fallback, - ranges: ['17.2.0', '17.3.0'], - target: '17.3.0', - published: ['17.2.0', '17.3.0', '18.0.0'], - }) + it('assesses the configured policy rather than a different safe security target', async () => { + const directory = await createApp('17.2.0') + mockSecurityMetadata({ + ranges: ['17.2.0', '17.3.0'], + target: '17.3.0', + published: ['17.2.0', '17.3.0', '18.0.0'], + }) + await expect( + getUpgradeAssessment('17.2.0', 'security') + ).resolves.toMatchObject({ + upgrade: { status: 'ready', targetVersion: '18.0.0' }, + }) + for (const policy of ['latest', 'future'] as const) { await expect( - getUpgradeAssessment('17.2.0', 'security') - ).resolves.toMatchObject({ - upgrade: { status: 'ready', targetVersion: '18.0.0' }, - }) - for (const policy of ['latest', 'future'] as const) { - await expect( - getUpgradeAssessment('17.2.0', policy) - ).resolves.toMatchObject({ upgrade: { status: 'blocked' } }) - await expect(prepareUpgrade(directory, policy)).rejects.toThrow( - '17.3.0 is affected by an active advisory' - ) - } + getUpgradeAssessment('17.2.0', policy) + ).resolves.toMatchObject({ upgrade: { status: 'blocked' } }) + await expect(prepareUpgrade(directory, policy)).rejects.toThrow( + '17.3.0 is affected by an active advisory' + ) } - ) + }) it('preserves stable security target selection', async () => { const directory = await createApp('17.2.0') @@ -380,6 +353,69 @@ describe('prepare latest upgrade', () => { ) }) + it('queries only the installed version and newest eligible release per major', async () => { + mockSecurityMetadata({ + ranges: ['17.2.0', '17.3.0'], + published: [ + '16.9.0', + '17.2.0', + '17.2.1', + '17.3.0', + '18.0.0', + '18.0.1', + '18.1.0-canary.0', + ], + }) + + await expect( + getUpgradeAssessment('17.2.0', 'security') + ).resolves.toMatchObject({ + affected: true, + upgrade: { status: 'ready', targetVersion: '18.0.1' }, + }) + + const requests = jest.mocked(global.fetch).mock.calls + expect(requests.map(([url]) => String(url))).toEqual([ + 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk', + 'https://registry.npmjs.org/next', + 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk', + ]) + expect(JSON.parse(String(requests[0][1]?.body))).toEqual({ + next: ['17.2.0'], + }) + expect(JSON.parse(String(requests[2][1]?.body))).toEqual({ + next: ['17.3.0', '18.0.1'], + }) + }) + + it('keeps a confirmed warning when the candidate advisory request fails', async () => { + mockSecurityMetadata({ + ranges: ['17.2.0'], + published: ['17.2.0', '17.2.1'], + }) + const fetchMetadata = global.fetch + let advisoryRequests = 0 + global.fetch = jest.fn(async (input, init) => { + if (String(input).includes('/security/advisories/bulk')) { + advisoryRequests++ + if (advisoryRequests === 2) { + return new Response(null, { status: 503 }) + } + } + return fetchMetadata(input, init) + }) + + await expect( + getUpgradeAssessment('17.2.0', 'security') + ).resolves.toMatchObject({ + affected: true, + upgrade: { + status: 'unknown', + reason: 'Could not check for security updates. Please try again.', + }, + }) + }) + it.each(['17.2.0-rc.1', '17.2.0-beta.1', '17.2.0-preview.1'])( 'blocks security upgrades for prereleases without querying advisories: %s', async (version) => { @@ -448,13 +484,7 @@ describe('prepare latest upgrade', () => { async (channel, installed) => { const target = '17.2.0' const directory = await createApp(installed) - global.fetch = jest.fn(async (input) => { - if (String(input).startsWith('https://api.github.com/advisories?')) { - return Response.json([]) - } - expect(String(input)).toBe('https://registry.npmjs.org/next/latest') - return Response.json({ version: target }) - }) + mockLatestVersion(target) await expect( getUpgradeAssessment(installed, 'latest') ).resolves.toMatchObject({ @@ -469,44 +499,54 @@ describe('prepare latest upgrade', () => { references: ['https://registry.npmjs.org/next/latest'], }) ) - expect(global.fetch).toHaveBeenCalledTimes(4) + const advisoryRequests = jest + .mocked(global.fetch) + .mock.calls.filter(([url]) => + String(url).includes('/security/advisories/bulk') + ) + expect( + advisoryRequests.map(([, init]) => JSON.parse(String(init?.body))) + ).toEqual([ + { next: [installed] }, + { next: [target] }, + { next: [installed] }, + { next: [target] }, + ]) } ) - it.each([false, true])( - 'blocks an advised stable target for a prerelease with npm fallback=%s', - async (fallback) => { - const installed = '17.2.0-rc.1' - const target = '17.2.0' - const directory = await createApp(installed) - mockSecurityMetadata({ - fallback, - ranges: [target], - target, - published: fallback ? [installed] : [installed, target], - }) - await expect( - getUpgradeAssessment(installed, 'latest') - ).resolves.toMatchObject({ - affected: null, - upgrade: { - status: 'blocked', - reason: `Next.js ${target} is affected by an active advisory.`, - }, - }) - await expect(prepareUpgrade(directory, 'latest')).rejects.toThrow( - `Next.js ${target} is affected by an active advisory.` - ) - } - ) + it('blocks an advised stable target for a prerelease', async () => { + const installed = '17.2.0-rc.1' + const target = '17.2.0' + const directory = await createApp(installed) + mockSecurityMetadata({ ranges: [target], target }) + await expect( + getUpgradeAssessment(installed, 'latest') + ).resolves.toMatchObject({ + affected: null, + upgrade: { + status: 'blocked', + reason: `Next.js ${target} is affected by an active advisory.`, + }, + }) + await expect(prepareUpgrade(directory, 'latest')).rejects.toThrow( + `Next.js ${target} is affected by an active advisory.` + ) + }) it('does not offer stable latest when advisory validation fails for a prerelease', async () => { const installed = '17.2.0-rc.1' const directory = await createApp(installed) - mockSecurityMetadata({ fallback: true, npmFailure: true }) - await expect(getUpgradeAssessment(installed, 'latest')).rejects.toThrow( - 'Could not check for security updates.' - ) + mockSecurityMetadata({ npmFailure: true }) + await expect( + getUpgradeAssessment(installed, 'latest') + ).resolves.toMatchObject({ + affected: null, + upgrade: { + status: 'unknown', + reason: 'Could not check for security updates. Please try again.', + }, + }) await expect(prepareUpgrade(directory, 'latest')).rejects.toThrow( 'Could not check for security updates.' ) @@ -520,13 +560,7 @@ describe('prepare latest upgrade', () => { 'invalid', ])('rejects a prerelease or invalid stable dist-tag: %s', async (target) => { const directory = await createApp('17.2.0-rc.1') - global.fetch = jest.fn(async (input) => - Response.json( - String(input).startsWith('https://api.github.com/advisories?') - ? [] - : { version: target } - ) - ) + mockLatestVersion(target) await expect(prepareUpgrade(directory, 'latest')).rejects.toThrow( 'Could not determine the latest stable Next.js version.' ) @@ -536,13 +570,7 @@ describe('prepare latest upgrade', () => { 'does not downgrade %s when stable latest is older', async (installed) => { const directory = await createApp(installed) - global.fetch = jest.fn(async (input) => { - if (String(input).startsWith('https://api.github.com/advisories?')) { - return Response.json([]) - } - expect(String(input)).toBe('https://registry.npmjs.org/next/latest') - return Response.json({ version: '17.2.0' }) - }) + mockLatestVersion('17.2.0') await expect(prepareUpgrade(directory, 'latest')).resolves.toEqual({ status: 'unaffected', reason: `Next.js ${installed} is newer than the latest stable release 17.2.0.`, @@ -669,27 +697,23 @@ describe('prepare latest upgrade', () => { ) }) - it.each([false, true])( - 'assesses a retained Future version missing from registry metadata with npm fallback=%s', - async (fallback) => { - const directory = await createApp('17.2.9') - mockSecurityMetadata({ - fallback, - ranges: ['17.2.9'], - target: '17.2.1', - published: ['17.2.0', '17.2.1'], - }) - await expect(prepareUpgrade(directory, 'future')).rejects.toThrow( - '17.2.9 is affected by an active advisory.' - ) - } - ) + it('assesses a retained Future version missing from registry metadata', async () => { + const directory = await createApp('17.2.9') + mockSecurityMetadata({ + ranges: ['17.2.9'], + target: '17.2.1', + published: ['17.2.0', '17.2.1'], + }) + await expect(prepareUpgrade(directory, 'future')).rejects.toThrow( + '17.2.9 is affected by an active advisory.' + ) + }) it.each(['latest', 'future'] as const)( - 'fails a %s assessment when both advisory providers are unavailable', + 'fails a %s assessment when the advisory endpoint is unavailable', async (policy) => { const directory = await createApp('17.2.0') - mockSecurityMetadata({ fallback: true, npmFailure: true }) + mockSecurityMetadata({ npmFailure: true }) await expect(prepareUpgrade(directory, policy)).rejects.toThrow( 'Could not check for security updates.' ) @@ -708,7 +732,7 @@ describe('prepare latest upgrade', () => { references: ['https://registry.npmjs.org/next/latest'], }) ) - expect(global.fetch).toHaveBeenCalledTimes(2) + expect(global.fetch).toHaveBeenCalledTimes(3) expect(global.fetch).toHaveBeenCalledWith( 'https://registry.npmjs.org/next/latest', expect.any(Object) @@ -730,9 +754,9 @@ describe('prepare latest upgrade', () => { async (metadata) => { const directory = await createApp('17.1.0') global.fetch = jest.fn(async (input) => - Response.json( - String(input).startsWith('https://api.github.com/') ? [] : metadata - ) + String(input).includes('/security/advisories/bulk') + ? Response.json({}) + : Response.json(metadata) ) await expect(prepareUpgrade(directory, 'latest')).rejects.toThrow( @@ -750,8 +774,8 @@ describe('prepare latest upgrade', () => { it('preserves target lookup failures in the shared assessment and command', async () => { const directory = await createApp('17.1.0') global.fetch = jest.fn(async (input) => { - if (String(input).startsWith('https://api.github.com/')) { - return Response.json([]) + if (String(input).includes('/security/advisories/bulk')) { + return Response.json({}) } throw new Error('Network unavailable') }) @@ -789,55 +813,46 @@ describe('prepare latest upgrade', () => { }) }) - it.each([false, true])( - 'ignores an affected older latest target with npm fallback=%s', - async (fallback) => { - const directory = await createApp('17.3.0') - mockSecurityMetadata({ - fallback, - ranges: ['17.2.0'], - target: '17.2.0', - published: ['17.2.0', '17.3.0'], - }) + it('ignores an affected older latest target', async () => { + const directory = await createApp('17.3.0') + mockSecurityMetadata({ + ranges: ['17.2.0'], + target: '17.2.0', + published: ['17.2.0', '17.3.0'], + }) - await expect( - getUpgradeAssessment('17.3.0', 'latest') - ).resolves.toMatchObject({ - affected: false, - upgrade: { status: 'unaffected' }, - }) - await expect(prepareUpgrade(directory, 'latest')).resolves.toEqual({ - status: 'unaffected', - reason: - 'Next.js 17.3.0 is newer than the latest stable release 17.2.0.', - }) - } - ) + await expect( + getUpgradeAssessment('17.3.0', 'latest') + ).resolves.toMatchObject({ + affected: false, + upgrade: { status: 'unaffected' }, + }) + await expect(prepareUpgrade(directory, 'latest')).resolves.toEqual({ + status: 'unaffected', + reason: 'Next.js 17.3.0 is newer than the latest stable release 17.2.0.', + }) + }) - it.each([false, true])( - 'still blocks an affected equal latest target with npm fallback=%s', - async (fallback) => { - const directory = await createApp('17.3.0') - mockSecurityMetadata({ - fallback, - ranges: ['17.3.0'], - target: '17.3.0', - published: ['17.3.0'], - }) + it('still blocks an affected equal latest target', async () => { + const directory = await createApp('17.3.0') + mockSecurityMetadata({ + ranges: ['17.3.0'], + target: '17.3.0', + published: ['17.3.0'], + }) - await expect( - getUpgradeAssessment('17.3.0', 'latest') - ).resolves.toMatchObject({ - affected: true, - upgrade: { status: 'blocked' }, - }) - await expect(prepareUpgrade(directory, 'latest')).rejects.toThrow( - 'Next.js 17.3.0 is affected by an active advisory.' - ) - } - ) + await expect( + getUpgradeAssessment('17.3.0', 'latest') + ).resolves.toMatchObject({ + affected: true, + upgrade: { status: 'blocked' }, + }) + await expect(prepareUpgrade(directory, 'latest')).rejects.toThrow( + 'Next.js 17.3.0 is affected by an active advisory.' + ) + }) - it('allows a Future target outside npm fallback advisory ranges', async () => { + it('allows a Future target outside npm advisory ranges', async () => { const directory = await createApp('16.2.0') mockFutureMetadata('<16.3.0') @@ -850,7 +865,7 @@ describe('prepare latest upgrade', () => { ) }) - it('blocks a Future target inside npm fallback advisory ranges', async () => { + it('blocks a Future target inside npm advisory ranges', async () => { const directory = await createApp('16.2.0') mockFutureMetadata('<=16.4.0') diff --git a/test/unit/security-upgrade-nudge.test.ts b/test/unit/security-upgrade-nudge.test.ts index b1d1182641fb..d46960d2ea04 100644 --- a/test/unit/security-upgrade-nudge.test.ts +++ b/test/unit/security-upgrade-nudge.test.ts @@ -192,33 +192,15 @@ describe('security upgrade nudge', () => { }) it.each(['blocked', 'unknown'] as const)( - 'preserves the advisory and retry behavior when target eligibility is %s', + 'skips the security nudge when target eligibility is %s', async (status) => { jest.mocked(getUpgradeAssessment).mockResolvedValue({ reference: 'https://api.github.com/advisories?affects=next', affected: true, upgrade: { status, reason: 'Target assessment detail.' }, }) - let message = '' - try { - await run() - } catch (error) { - expect(error).toMatchObject({ name: 'SecurityFatalError', exitCode: 1 }) - message = (error as Error).message - } - expect(message).toContain('affected by a published security advisory') - expect(message).toContain('Target assessment detail.') - expect(message.includes('next upgrade --ai')).toBe(false) - expect(message.includes('can be automatically upgraded')).toBe(false) - expect(message).toContain( - status === 'unknown' - ? 'Upgrade availability could not be checked.' - : 'No safe newer target is available' - ) await expect(run()).resolves.toBeUndefined() - expect(warn).toHaveBeenCalledWith( - expect.stringContaining('Target assessment detail.') - ) + expect(warn).not.toHaveBeenCalled() } ) @@ -353,7 +335,9 @@ describe('latest nudge release selection', () => { ['17.2.0-canary.4', '17.3.0-rc.1', null], ['17.2.0-rc.1', '17.3.0', '17.3.0'], ['17.2.0-rc.1', '17.2.0', '17.2.0'], + ['17.2.0-rc.1', '17.2.0-rc.2', null], ['17.2.0-beta.1', '17.2.0', '17.2.0'], + ['17.2.0-beta.1', '18.0.0-beta.1', null], ['17.2.0-preview.1', '17.2.0', '17.2.0'], ['17.2.0-rc.1', '17.3.0-rc.1', null], ['17.2.0-beta.1', '17.3.0-beta.1', null], @@ -400,7 +384,7 @@ describe('latest upgrade nudge', () => { ) it.each(['rc', 'beta', 'preview'] as const)( - 'links a configured %s reminder to stable latest', + 'links a verified %s latest reminder to stable latest', async (channel) => { process.env.__NEXT_VERSION = `17.2.0-${channel}.1` mockUpgrade('17.2.0') @@ -412,6 +396,11 @@ describe('latest upgrade nudge', () => { 'Reference: https://registry.npmjs.org/next/latest' ), }) + expect(getUpgradeAssessment).toHaveBeenCalledWith( + `17.2.0-${channel}.1`, + 'latest', + false + ) } ) @@ -786,36 +775,37 @@ describe('human upgrade nudge', () => { ) it.each(['security', 'latest', 'future'] as const)( - 'forces a %s request without changing installed-version eligibility', + 'does not force a %s nudge without a valid installed version', async (policy) => { process.env.__NEXT_AGENTIC_AUTO_UPGRADE = policy - process.env.__NEXT_VERSION = '16.4.0-preview-test' + process.env.__NEXT_VERSION = 'not-a-version' processEnv([], directory) updateInitialEnv({ __NEXT_AGENTIC_AUTO_UPGRADE: policy }) - jest.mocked(promptUpgrade).mockResolvedValue('update') for (const configured of [false, 'future'] as const) { const original = config(configured) const context = getUpgradeContext(original) expect(context.experimental.agenticAutoUpgrade).toBe(policy) await expect( nudgeUpgrade(directory, context, 'dev', new AbortController().signal) - ).resolves.toBe('update') + ).resolves.toBeUndefined() } - expect(promptUpgrade).toHaveBeenCalledWith( - expect.stringContaining(`__NEXT_AGENTIC_AUTO_UPGRADE=${policy}`), - expect.any(AbortSignal), - true - ) + expect(promptUpgrade).not.toHaveBeenCalled() expect(getUpgradeAssessment).not.toHaveBeenCalled() - const message = jest.mocked(promptUpgrade).mock.calls[0][0] - expect(message).toContain('Forced preview:') - expect(message).not.toContain(`next upgrade --ai`) - expect(message).not.toContain('You requested') jest.mocked(getAgentName).mockResolvedValue('codex') - await expect(run(policy)).rejects.toMatchObject({ - message: expect.stringContaining(`next upgrade --ai=${policy}`), - }) + await expect(run(policy)).resolves.toBeUndefined() + } + ) + it.each(['security', 'latest', 'future'] as const)( + 'runs an explicitly requested %s upgrade', + async (policy) => { + process.env.__NEXT_AGENTIC_AUTO_UPGRADE = policy + process.env.__NEXT_VERSION = '16.4.0-preview-test' + processEnv([], directory) + updateInitialEnv({ + __NEXT_AGENTIC_AUTO_UPGRADE: policy, + __NEXT_VERSION: '16.4.0-preview-test', + }) jest.mocked(spawnNextUpgrade).mockImplementationOnce(async () => { expect(process.env.__NEXT_AGENTIC_AUTO_UPGRADE).toBeUndefined() // Future upgrade preparation reloads config and resets the environment. @@ -832,6 +822,22 @@ describe('human upgrade nudge', () => { } ) + it.each(['blocked', 'unknown'] as const)( + 'does not force a nudge when the target is %s', + async (status) => { + process.env.__NEXT_AGENTIC_AUTO_UPGRADE = 'security' + jest.mocked(getUpgradeAssessment).mockResolvedValue({ + affected: true, + reference: + 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk', + upgrade: { status, reason: 'No verified target.' }, + }) + await expect(run('security')).resolves.toBeUndefined() + expect(promptUpgrade).not.toHaveBeenCalled() + expect(warn).not.toHaveBeenCalled() + } + ) + it('lets an explicit request bypass a saved dismissal', async () => { jest.mocked(promptUpgrade).mockResolvedValue('dismiss') await run('security') @@ -1030,18 +1036,14 @@ describe('human upgrade nudge', () => { }) it.each(['blocked', 'unknown'] as const)( - 'omits Update when security target availability is %s', + 'does not prompt when security target availability is %s', async (status) => { jest.mocked(getUpgradeAssessment).mockResolvedValue({ ...securityAssessment, upgrade: { status, reason: 'No eligible target.' }, }) await run() - expect(promptUpgrade).toHaveBeenCalledWith( - expect.stringContaining('No eligible target.'), - expect.any(AbortSignal), - false - ) + expect(promptUpgrade).not.toHaveBeenCalled() } ) From 1a6a32cc1cbfd1549de2c0c88f7ba63a5503a174 Mon Sep 17 00:00:00 2001 From: Jiwon Choi Date: Mon, 28 Sep 2026 08:15:06 +0900 Subject: [PATCH 2/7] Show security upgrade insights in DevTools (#99002) Stacked on #99222. ### Why? Developers running `next dev` with `agenticAutoUpgrade` enabled need a browser reminder when their installed Next.js version is affected by a security advisory. ### How? Assess upgrades once during dev startup and share the result with the CLI nudge. The existing HMR `SYNC` message carries the security advisory to DevTools, which shows a Vulnerability Insight in the existing Insights overlay with a copyable upgrade prompt. The Insight applies to the `security`, `latest`, and `future` policies when the assessment finds an affected version and a safe target. A private test override previews the UI without a vulnerable fixture or live advisory data. ### Screenshots These show the badge and overlay layout. The current copied prompt runs `next upgrade --ai=security` from the app directory. **DevTools badge** ![DevTools badge](https://github.com/user-attachments/assets/d6af6daf-0501-497c-aa3f-fe0f95351bc1) | Light | Dark | | --- | --- | | ![Overlay in light mode](https://github.com/user-attachments/assets/e7a7e194-0595-41e6-97b6-b54c05c14aa7) | ![Overlay in dark mode](https://github.com/user-attachments/assets/1b80b7d7-376b-4883-a8d1-3ee7354c92ab) | Closes NAR-939 --- .../decorators/use-overlay-reducer.ts | 7 + .../dev/hot-reloader/app/hot-reloader-app.tsx | 7 + .../hot-reloader/pages/hot-reloader-pages.ts | 7 + packages/next/src/client/page-bootstrap.ts | 1 + packages/next/src/lib/upgrade/nudge.ts | 2 +- .../src/next-devtools/dev-overlay.browser.tsx | 7 + .../errors/error-overlay/error-overlay.tsx | 5 +- .../vulnerability-insight.tsx | 175 ++++++++++++++++++ .../dev-overlay/container/errors.tsx | 78 +++++--- .../next-devtools/dev-overlay/dev-overlay.tsx | 8 +- .../src/next-devtools/dev-overlay/shared.ts | 15 ++ .../next/src/server/dev/hot-middleware.ts | 14 +- .../src/server/dev/hot-reloader-turbopack.ts | 17 ++ .../next/src/server/dev/hot-reloader-types.ts | 8 + .../src/server/dev/hot-reloader-webpack.ts | 7 +- packages/next/src/server/lib/router-server.ts | 33 +++- .../lib/router-utils/setup-dev-bundler.ts | 2 + .../vulnerability-insight/app/layout.tsx | 9 + .../vulnerability-insight/app/page.tsx | 3 + .../vulnerability-insight.test.ts | 59 ++++++ test/unit/security-upgrade-nudge.test.ts | 4 +- 21 files changed, 430 insertions(+), 38 deletions(-) create mode 100644 packages/next/src/next-devtools/dev-overlay/components/vulnerability-insight/vulnerability-insight.tsx create mode 100644 test/development/app-dir/vulnerability-insight/app/layout.tsx create mode 100644 test/development/app-dir/vulnerability-insight/app/page.tsx create mode 100644 test/development/app-dir/vulnerability-insight/vulnerability-insight.test.ts diff --git a/packages/next/.storybook/decorators/use-overlay-reducer.ts b/packages/next/.storybook/decorators/use-overlay-reducer.ts index 90887abaa741..13d393051aef 100644 --- a/packages/next/.storybook/decorators/use-overlay-reducer.ts +++ b/packages/next/.storybook/decorators/use-overlay-reducer.ts @@ -34,6 +34,7 @@ import { ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_REJECTION, ACTION_VERSION_INFO, + ACTION_VULNERABILITY_INSIGHT, INITIAL_OVERLAY_STATE, } from '../../src/next-devtools/dev-overlay/shared' @@ -61,6 +62,12 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) { case ACTION_ERROR_OVERLAY_TOGGLE: { return { ...state, isErrorOverlayOpen: !state.isErrorOverlayOpen } } + case ACTION_VULNERABILITY_INSIGHT: { + return { + ...state, + hasVulnerabilityInsight: action.hasVulnerabilityInsight, + } + } case ACTION_DEVTOOLS_POSITION: { return { ...state, devToolsPosition: action.devToolsPosition } } diff --git a/packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx b/packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx index 63dfad8261dd..432f30a5c4b1 100644 --- a/packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx +++ b/packages/next/src/client/dev/hot-reloader/app/hot-reloader-app.tsx @@ -309,6 +309,10 @@ export function processMessage( } break } + case HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT: { + dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight) + break + } case HMR_MESSAGE_SENT_TO_BROWSER.BUILT: case HMR_MESSAGE_SENT_TO_BROWSER.SYNC: { dispatcher.buildingIndicatorHide() @@ -322,6 +326,9 @@ export function processMessage( // Is undefined when it's a 'built' event if ('versionInfo' in message) dispatcher.onVersionInfo(message.versionInfo) + if ('hasVulnerabilityInsight' in message) { + dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight) + } if ('debug' in message && message.debug) dispatcher.onDebugInfo(message.debug) if ('devIndicator' in message) diff --git a/packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts b/packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts index 81ea941a11f6..8e621645ac85 100644 --- a/packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts +++ b/packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts @@ -290,6 +290,10 @@ function processMessage(message: HmrMessageSentToBrowser) { } break } + case HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT: { + dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight) + break + } case HMR_MESSAGE_SENT_TO_BROWSER.BUILT: case HMR_MESSAGE_SENT_TO_BROWSER.SYNC: { dispatcher.buildingIndicatorHide() @@ -301,6 +305,9 @@ function processMessage(message: HmrMessageSentToBrowser) { // Is undefined when it's a 'built' event if ('versionInfo' in message) dispatcher.onVersionInfo(message.versionInfo) + if ('hasVulnerabilityInsight' in message) { + dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight) + } if ('devIndicator' in message) dispatcher.onDevIndicator(message.devIndicator) if ('devToolsConfig' in message) diff --git a/packages/next/src/client/page-bootstrap.ts b/packages/next/src/client/page-bootstrap.ts index b75799f7fc88..2744f81ab46e 100644 --- a/packages/next/src/client/page-bootstrap.ts +++ b/packages/next/src/client/page-bootstrap.ts @@ -121,6 +121,7 @@ export function pageBootstrap(assetPrefix: string) { case HMR_MESSAGE_SENT_TO_BROWSER.TURBOPACK_CONNECTED: case HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST: case HMR_MESSAGE_SENT_TO_BROWSER.DEVTOOLS_CONFIG: + case HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT: case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK: case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE: case HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS: diff --git a/packages/next/src/lib/upgrade/nudge.ts b/packages/next/src/lib/upgrade/nudge.ts index 5f214158db7a..2be1eda8017c 100644 --- a/packages/next/src/lib/upgrade/nudge.ts +++ b/packages/next/src/lib/upgrade/nudge.ts @@ -252,7 +252,7 @@ async function nudgeUpgradeForAgent( switch (reminder.kind) { case 'security': summary = - 'Your version of Next.js is affected by a published security advisory.' + 'Your version of Next.js is affected by a known security vulnerability.' recommendation = 'We strongly recommend you upgrade Next.js.' reference = reminder.reference break diff --git a/packages/next/src/next-devtools/dev-overlay.browser.tsx b/packages/next/src/next-devtools/dev-overlay.browser.tsx index c1a4856c6fff..d74fabdcc8d3 100644 --- a/packages/next/src/next-devtools/dev-overlay.browser.tsx +++ b/packages/next/src/next-devtools/dev-overlay.browser.tsx @@ -31,6 +31,7 @@ import { ACTION_INSTANT_NAVS_TOGGLE, ACTION_REQUEST_INSIGHTS_SNAPSHOT, ACTION_REQUEST_INSIGHTS_UPDATE, + ACTION_VULNERABILITY_INSIGHT, } from './dev-overlay/shared' import type { FlightRouterState } from '../shared/lib/app-router-types' @@ -67,6 +68,7 @@ export interface Dispatcher { onBuildOk(): void onBuildError(message: string): void onVersionInfo(versionInfo: VersionInfo): void + onVulnerabilityInsight(hasVulnerabilityInsight: boolean): void onDebugInfo(debugInfo: DebugInfo): void onBeforeRefresh(): void onRefresh(): void @@ -216,6 +218,11 @@ export const dispatcher: Dispatcher = { dispatch({ type: ACTION_VERSION_INFO, versionInfo }) } ), + onVulnerabilityInsight: createQueuable( + (dispatch: Dispatch, hasVulnerabilityInsight: boolean) => { + dispatch({ type: ACTION_VULNERABILITY_INSIGHT, hasVulnerabilityInsight }) + } + ), onCacheIndicator: createQueuable( (dispatch: Dispatch, status: CacheIndicatorState) => { dispatch({ type: ACTION_CACHE_INDICATOR, cacheIndicator: status }) diff --git a/packages/next/src/next-devtools/dev-overlay/components/errors/error-overlay/error-overlay.tsx b/packages/next/src/next-devtools/dev-overlay/components/errors/error-overlay/error-overlay.tsx index 2ff0f97a5c58..bccc309432fc 100644 --- a/packages/next/src/next-devtools/dev-overlay/components/errors/error-overlay/error-overlay.tsx +++ b/packages/next/src/next-devtools/dev-overlay/components/errors/error-overlay/error-overlay.tsx @@ -60,8 +60,8 @@ export function ErrorOverlay({ ) } - // No Runtime Errors. - if (!runtimeErrors.length) { + // No runtime errors or upgrade insight to display. + if (!runtimeErrors.length && !state.hasVulnerabilityInsight) { return null } @@ -83,6 +83,7 @@ export function ErrorOverlay({ debugInfo={state.debugInfo} getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails} runtimeErrors={runtimeErrors} + hasVulnerabilityInsight={state.hasVulnerabilityInsight} onClose={() => { dispatch({ type: ACTION_ERROR_OVERLAY_CLOSE }) }} diff --git a/packages/next/src/next-devtools/dev-overlay/components/vulnerability-insight/vulnerability-insight.tsx b/packages/next/src/next-devtools/dev-overlay/components/vulnerability-insight/vulnerability-insight.tsx new file mode 100644 index 000000000000..aab549876bd8 --- /dev/null +++ b/packages/next/src/next-devtools/dev-overlay/components/vulnerability-insight/vulnerability-insight.tsx @@ -0,0 +1,175 @@ +import * as React from 'react' +import type { ErrorBaseProps } from '../errors/error-overlay/error-overlay' +import type { ErrorOverlayTabBarRenderer } from '../errors/error-overlay-pagination/error-overlay-pagination' +import { ErrorOverlayNav } from '../errors/error-overlay-nav/error-overlay-nav' +import { ErrorOverlayOverlay } from '../errors/overlay/overlay' +import { ErrorOverlayDialog } from '../errors/dialog/dialog' +import { ErrorOverlayDialogHeader } from '../errors/dialog/header' +import { ErrorOverlayDialogBody } from '../errors/dialog/body' +import { OverlayBackdrop } from '../overlay' +import { DialogContent } from '../dialog' +import { Resizer } from '../resizer' +import { useFocusTrap } from '../errors/dev-tools-indicator/utils' +import { CopyButton } from '../copy-button' +import { CodeFrameShell } from '../code-frame/code-frame-shell' +import { css } from '../../utils/css' + +export function VulnerabilityInsight({ + renderTabBar, + canGoPrevious, + canGoNext, + onPrevious, + onNext, + onClose, + rendered, + transitionDurationMs, + versionInfo, +}: ErrorBaseProps & { + renderTabBar: ErrorOverlayTabBarRenderer | undefined + canGoPrevious: boolean + canGoNext: boolean + onPrevious: (() => void) | undefined + onNext: (() => void) | undefined + onClose: (() => void) | undefined +}) { + const prompt = 'Run `next upgrade --ai=security` and follow its instructions.' + const animationProps = { + 'data-rendered': rendered, + style: { + '--transition-duration': `${transitionDurationMs}ms`, + } as React.CSSProperties, + } + const [animating, setAnimating] = React.useState( + Boolean(transitionDurationMs) + ) + const dialogRef = React.useRef(null) + useFocusTrap(dialogRef, null, rendered) + + function onTransitionEnd({ propertyName, target }: React.TransitionEvent) { + if (propertyName === 'scale' && target === dialogRef.current) { + setAnimating(false) + } + } + + return ( + + +
+ + + + + +
+ + Vulnerability Insight + +

+ Upgrade Next.js to a safe version. +

+

+ Next.js {versionInfo.installed} is affected by a known + security vulnerability. We strongly recommend upgrading. +

+
+
+ +
+

+ Copy the prompt and paste it into your coding agent to + upgrade this app. +

+ + Upgrade prompt + + + } + > + {prompt} + +
+
+
+
+
+
+ +
+ ) +} + +const styles = css` + [data-nextjs-dialog-header]:has([data-nextjs-vulnerability-insight]) { + padding-bottom: 0; + } + [data-nextjs-vulnerability-insight] h2 { + margin: 16px 0 8px; + font-size: var(--size-20); + font-weight: 500; + color: var(--color-gray-1000); + } + [data-nextjs-vulnerability-insight] p, + [data-nextjs-vulnerability-action] > p { + margin: 8px 0; + font-size: var(--size-14); + line-height: var(--size-20); + color: var(--color-gray-900); + } + [data-nextjs-vulnerability-action] { + display: flex; + flex-direction: column; + gap: 8px; + } + [data-nextjs-vulnerability-action] .code-frame-lines { + min-width: 0; + white-space: pre-wrap; + overflow-wrap: anywhere; + } + [data-nextjs-vulnerability-copy] { + display: inline-flex; + align-items: center; + justify-content: center; + margin-left: auto; + width: var(--size-24); + height: var(--size-24); + padding: 4px; + border: none; + border-radius: var(--rounded-md-2); + background: transparent; + color: var(--color-gray-1000); + cursor: pointer; + } + [data-nextjs-vulnerability-copy]:hover { + background: var(--color-gray-alpha-100); + } + [data-nextjs-vulnerability-copy]:focus-visible { + outline: var(--focus-ring); + outline-offset: 2px; + } + [data-nextjs-vulnerability-copy][aria-disabled='true'] { + opacity: 0.5; + } +` diff --git a/packages/next/src/next-devtools/dev-overlay/container/errors.tsx b/packages/next/src/next-devtools/dev-overlay/container/errors.tsx index f97501d86640..1ed71d890cd3 100644 --- a/packages/next/src/next-devtools/dev-overlay/container/errors.tsx +++ b/packages/next/src/next-devtools/dev-overlay/container/errors.tsx @@ -6,6 +6,7 @@ import React, { useRef, useState, } from 'react' +import { VulnerabilityInsight } from '../components/vulnerability-insight/vulnerability-insight' import type { DebugInfo } from '../../shared/types' import { Overlay, OverlayBackdrop } from '../components/overlay' import { RuntimeError } from './runtime-error' @@ -51,6 +52,7 @@ interface ErrorsProps extends ErrorBaseProps { runtimeErrors: ReadyRuntimeError[] debugInfo: DebugInfo onClose: () => void + hasVulnerabilityInsight: boolean } function matchLinkType(text: string): string | null { @@ -632,6 +634,7 @@ export function Errors({ runtimeErrors, debugInfo, onClose, + hasVulnerabilityInsight, ...props }: ErrorsProps) { const dialogResizerRef = useRef(null) @@ -649,6 +652,8 @@ export function Errors({ return { normalErrors: normal, instantErrors: instant } }, [runtimeErrors]) + const insightCount = instantErrors.length + (hasVulnerabilityInsight ? 1 : 0) + const [activeTab, setActiveTab] = useState(() => normalErrors.length > 0 ? 'errors' : 'instant' ) @@ -661,7 +666,7 @@ export function Errors({ ? normalErrors.length > 0 ? 'errors' : 'instant' - : instantErrors.length > 0 + : insightCount > 0 ? 'instant' : 'errors' const activeErrors = @@ -672,7 +677,7 @@ export function Errors({ ) const instantActiveIdx = Math.max( 0, - Math.min(activeIndices.instant, Math.max(0, instantErrors.length - 1)) + Math.min(activeIndices.instant, Math.max(0, insightCount - 1)) ) const activeIdxForTab = effectiveActiveTab === 'instant' ? instantActiveIdx : errorActiveIdx @@ -707,29 +712,11 @@ export function Errors({ [activeError, errorType, props.versionInfo] ) - if (isLoading) { - // TODO: better loading state - return ( - - - - ) - } - - if (!activeError) { - return null - } - - const error = activeError.error - const isServerError = ['server', 'edge-server'].includes( - getErrorSource(error) || '' - ) - // Show the tab bar only when at least one Insight is present. When the only // bucket with content is Issues, the red pill already conveys the count and a // single-tab bar would be redundant. When Insights exist (alone or alongside // Issues), the bar is shown so the user can switch between buckets. - const showTabBar = instantErrors.length > 0 + const showTabBar = insightCount > 0 const renderTabBar = showTabBar ? ({ previousButton, @@ -744,7 +731,7 @@ export function Errors({ }) }} errorCount={normalErrors.length} - instantCount={instantErrors.length} + instantCount={insightCount} errorActiveIdx={errorActiveIdx} instantActiveIdx={instantActiveIdx} previousButton={previousButton} @@ -761,8 +748,8 @@ export function Errors({ : activeIdx > 0 const canGoNext = showTabBar ? effectiveActiveTab === 'errors' - ? errorActiveIdx < normalErrors.length - 1 || instantErrors.length > 0 - : instantActiveIdx < instantErrors.length - 1 + ? errorActiveIdx < normalErrors.length - 1 || insightCount > 0 + : instantActiveIdx < insightCount - 1 : activeIdx < activeErrors.length - 1 const handlePrevious = showTabBar @@ -800,7 +787,7 @@ export function Errors({ return } - if (instantErrors.length > 0) { + if (insightCount > 0) { setActiveTab('instant') setActiveIndices((previous) => ({ ...previous, @@ -810,13 +797,52 @@ export function Errors({ return } - if (instantActiveIdx < instantErrors.length - 1) { + if (instantActiveIdx < insightCount - 1) { setActiveIndex(instantActiveIdx + 1) } }) } : undefined + if ( + hasVulnerabilityInsight && + effectiveActiveTab === 'instant' && + instantActiveIdx === instantErrors.length + ) { + const hasServerError = runtimeErrors.some(({ error }) => + ['server', 'edge-server'].includes(getErrorSource(error) || '') + ) + return ( + + ) + } + + if (isLoading) { + // TODO: better loading state + return ( + + + + ) + } + + if (!activeError) { + return null + } + + const error = activeError.error + const isServerError = ['server', 'edge-server'].includes( + getErrorSource(error) || '' + ) + let errorMessage: React.ReactNode let maybeNotes: React.ReactNode = null let maybeDiff: React.ReactNode = null diff --git a/packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx b/packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx index 859b9203e79f..6ed03ea354f6 100644 --- a/packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx +++ b/packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx @@ -70,9 +70,13 @@ export function DevOverlay() { + readonly hasVulnerabilityInsight: boolean } type DevtoolsPanelName = string export type OverlayDispatch = React.Dispatch @@ -131,6 +132,7 @@ export const ACTION_INSTANT_NAVS_RESET = 'instant-navs-reset' export const ACTION_INSTANT_ERRORS_CLEAR = 'instant-errors-clear' export const ACTION_REQUEST_INSIGHTS_SNAPSHOT = 'request-insights-snapshot' export const ACTION_REQUEST_INSIGHTS_UPDATE = 'request-insights-update' +export const ACTION_VULNERABILITY_INSIGHT = 'vulnerability-insight' export function updateRequestInsights( currentRequests: readonly RequestInsight[], @@ -284,6 +286,11 @@ interface RequestInsightsUpdateAction { insight: RequestInsight } +interface VulnerabilityInsightAction { + type: typeof ACTION_VULNERABILITY_INSIGHT + hasVulnerabilityInsight: boolean +} + export type DispatcherEvent = | BuildOkAction | BuildErrorAction @@ -314,6 +321,7 @@ export type DispatcherEvent = | InstantErrorsClearAction | RequestInsightsSnapshotAction | RequestInsightsUpdateAction + | VulnerabilityInsightAction const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = // 1st group: new frame + v8 @@ -401,6 +409,7 @@ export const INITIAL_OVERLAY_STATE: Omit< instantNavs: hasInstantNavsCookie, requestInsights: [], requestInsightsConfig: { showInternal: false, verbose: false }, + hasVulnerabilityInsight: false, } function getInitialState( @@ -701,6 +710,12 @@ export function useErrorOverlayReducer( case ACTION_REQUEST_INSIGHTS_SNAPSHOT: { return { ...state, requestInsights: action.snapshot.requests } } + case ACTION_VULNERABILITY_INSIGHT: { + return { + ...state, + hasVulnerabilityInsight: action.hasVulnerabilityInsight, + } + } case ACTION_REQUEST_INSIGHTS_UPDATE: { return { ...state, diff --git a/packages/next/src/server/dev/hot-middleware.ts b/packages/next/src/server/dev/hot-middleware.ts index 3100504e07f6..6a527bdfbb4d 100644 --- a/packages/next/src/server/dev/hot-middleware.ts +++ b/packages/next/src/server/dev/hot-middleware.ts @@ -90,14 +90,25 @@ export class WebpackHotMiddleware { private middlewareLatestStats: { ts: number; stats: webpack.Stats } | null = null private serverLatestStats: { ts: number; stats: webpack.Stats } | null = null + private hasVulnerabilityInsight = false constructor( compilers: webpack.Compiler[], private versionInfo: VersionInfo, private devtoolsFrontendUrl: string | undefined, private config: NextConfigComplete, - private devToolsConfig: DevToolsConfig + private devToolsConfig: DevToolsConfig, + hasVulnerabilityInsight: Promise ) { + hasVulnerabilityInsight.then((enabled) => { + if (enabled) { + this.hasVulnerabilityInsight = true + this.publish({ + type: HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT, + hasVulnerabilityInsight: true, + }) + } + }) compilers[0].hooks.invalid.tap( 'webpack-hot-middleware', this.onClientInvalid @@ -220,6 +231,7 @@ export class WebpackHotMiddleware { ...(middlewareStats.warnings || []), ], versionInfo: this.versionInfo, + hasVulnerabilityInsight: this.hasVulnerabilityInsight, debug: { devtoolsFrontendUrl: this.devtoolsFrontendUrl, }, diff --git a/packages/next/src/server/dev/hot-reloader-turbopack.ts b/packages/next/src/server/dev/hot-reloader-turbopack.ts index d32f781f2afc..3fe4d3931756 100644 --- a/packages/next/src/server/dev/hot-reloader-turbopack.ts +++ b/packages/next/src/server/dev/hot-reloader-turbopack.ts @@ -891,6 +891,22 @@ export async function createHotReloaderTurbopack( client.send(data) } + let hasVulnerabilityInsight = false + opts.hasVulnerabilityInsight.then((enabled) => { + if (enabled) { + hasVulnerabilityInsight = true + for (const client of [ + ...clientsWithoutHtmlRequestId, + ...clientsByHtmlRequestId.values(), + ]) { + sendToClient(client, { + type: HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT, + hasVulnerabilityInsight: true, + }) + } + } + }) + let updateInProgress = false let pendingServerComponentChanges = false @@ -1757,6 +1773,7 @@ export async function createHotReloaderTurbopack( warnings: [], hash: '', versionInfo, + hasVulnerabilityInsight, debug: { devtoolsFrontendUrl, }, diff --git a/packages/next/src/server/dev/hot-reloader-types.ts b/packages/next/src/server/dev/hot-reloader-types.ts index b7740a94b328..dc45e592ae85 100644 --- a/packages/next/src/server/dev/hot-reloader-types.ts +++ b/packages/next/src/server/dev/hot-reloader-types.ts @@ -41,6 +41,7 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER { CACHE_INDICATOR = 'cacheIndicator', DEV_INDICATOR = 'devIndicator', DEVTOOLS_CONFIG = 'devtoolsConfig', + VULNERABILITY_INSIGHT = 'vulnerabilityInsight', REQUEST_CURRENT_ERROR_STATE = 'requestCurrentErrorState', RUNTIME_ERRORS = 'runtimeErrors', REQUEST_PAGE_METADATA = 'requestPageMetadata', @@ -88,6 +89,7 @@ export interface SyncMessage { errors: ReadonlyArray warnings: ReadonlyArray versionInfo: VersionInfo + hasVulnerabilityInsight: boolean updatedModules?: ReadonlyArray debug?: DebugInfo devIndicator: DevIndicatorServerState @@ -264,6 +266,11 @@ export interface RequestInsightsUpdateMessage { insight: RequestInsight } +export interface VulnerabilityInsightMessage { + type: HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT + hasVulnerabilityInsight: boolean +} + export type HmrMessageSentToBrowser = | TurbopackMessage | TurbopackConnectedMessage @@ -289,6 +296,7 @@ export type HmrMessageSentToBrowser = | RequestPageMetadataMessage | CacheIndicatorMessage | RequestInsightsUpdateMessage + | VulnerabilityInsightMessage export type BinaryHmrMessageSentToBrowser = Extract< HmrMessageSentToBrowser, diff --git a/packages/next/src/server/dev/hot-reloader-webpack.ts b/packages/next/src/server/dev/hot-reloader-webpack.ts index 4b9b685c4817..1d4542444959 100644 --- a/packages/next/src/server/dev/hot-reloader-webpack.ts +++ b/packages/next/src/server/dev/hot-reloader-webpack.ts @@ -266,6 +266,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { private reloadAfterInvalidation: boolean = false private isSrcDir: boolean private cacheStatusesByRequestId = new Map() + private hasVulnerabilityInsight: Promise public serverStats: webpack.Stats | null public edgeServerStats: webpack.Stats | null @@ -290,6 +291,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { resetFetch, lockfile, onDevServerCleanup, + hasVulnerabilityInsight, }: { config: NextConfigComplete isSrcDir: boolean @@ -304,6 +306,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { resetFetch: () => void lockfile: Lockfile | undefined onDevServerCleanup: ((listener: () => Promise) => void) | undefined + hasVulnerabilityInsight: Promise } ) { this.hasAppRouterEntrypoints = false @@ -323,6 +326,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { this.telemetry = telemetry this.resetFetch = resetFetch this.lockfile = lockfile + this.hasVulnerabilityInsight = hasVulnerabilityInsight this.config = config this.previewProps = previewProps @@ -1648,7 +1652,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { this.versionInfo, this.devtoolsFrontendUrl, this.config, - initialDevToolsConfig + initialDevToolsConfig, + this.hasVulnerabilityInsight ) let booted = false diff --git a/packages/next/src/server/lib/router-server.ts b/packages/next/src/server/lib/router-server.ts index 315d522bf0ac..bb6c43b84d28 100644 --- a/packages/next/src/server/lib/router-server.ts +++ b/packages/next/src/server/lib/router-server.ts @@ -68,6 +68,7 @@ import { isChromeDevtoolsWorkspaceUrl, } from './chrome-devtools-workspace' import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared' +import { isCI } from '../ci-info' import { getRequestInsightsSnapshot, isRequestInsightsEnabled, @@ -191,6 +192,7 @@ export async function initialize(opts: { | undefined = undefined let originalFetch = globalThis.fetch + let hasVulnerabilityInsight: Promise = Promise.resolve(false) if (opts.dev) { const { Telemetry } = @@ -223,10 +225,34 @@ export async function initialize(opts: { developmentConfig.experimental.agenticAutoUpgrade === 'security' || developmentConfig.experimental.agenticAutoUpgrade === 'latest' || developmentConfig.experimental.agenticAutoUpgrade === 'future' || - process.env.__NEXT_AGENTIC_AUTO_UPGRADE + process.env.__NEXT_AGENTIC_AUTO_UPGRADE || + process.env.__NEXT_AGENT_UPGRADE_FORCE_DEVTOOLS_FOR_TESTING === '1' ) { - const { nudgeUpgrade, getUpgradeContext } = + const { nudgeUpgrade, getUpgradeContext, assessUpgrade } = require('../../lib/upgrade/nudge') as typeof import('../../lib/upgrade/nudge') + const upgradeContext = getUpgradeContext(developmentConfig) + const installedVersion = process.env.__NEXT_VERSION || 'unknown' + const policy = upgradeContext.experimental.agenticAutoUpgrade + const forced = process.env.__NEXT_AGENTIC_AUTO_UPGRADE === policy + const forceDevToolsForTesting = + process.env.__NEXT_AGENT_UPGRADE_FORCE_DEVTOOLS_FOR_TESTING === '1' + const assessment: ReturnType = + isCI || forceDevToolsForTesting + ? Promise.resolve(null) + : assessUpgrade( + opts.dir, + upgradeContext, + installedVersion, + null, + forced + ) + hasVulnerabilityInsight = assessment.then( + (result) => result?.kind === 'security' || forceDevToolsForTesting, + (error) => { + Log.warn(`Could not check the DevTools security insight: ${error}`) + return false + } + ) if (process.env.NEXT_PRIVATE_UPGRADE_PROMPT === '1' && process.send) { // TODO: Do not block dev startup while prompting for an upgrade. // Preserve all logs for display after the prompt and stop dev before Update. @@ -242,7 +268,7 @@ export async function initialize(opts: { } process.on('message', resume) process.send!({ - nextUpgradeContext: getUpgradeContext(developmentConfig), + nextUpgradeContext: upgradeContext, }) }) } else { @@ -298,6 +324,7 @@ export async function initialize(opts: { onDevServerCleanup: opts.onDevServerCleanup, resetFetch, serverFastRefresh: effectiveServerFastRefresh, + hasVulnerabilityInsight, }) ) diff --git a/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts b/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts index 209d95248189..f43c7ad6818a 100644 --- a/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts +++ b/packages/next/src/server/lib/router-utils/setup-dev-bundler.ts @@ -141,6 +141,7 @@ export type SetupOpts = { onDevServerCleanup: ((listener: () => Promise) => void) | undefined resetFetch: () => void serverFastRefresh?: boolean + hasVulnerabilityInsight: Promise } export interface DevRoutesManifest { @@ -294,6 +295,7 @@ async function startWatcher( resetFetch, lockfile, onDevServerCleanup: opts.onDevServerCleanup, + hasVulnerabilityInsight: opts.hasVulnerabilityInsight, }) })() diff --git a/test/development/app-dir/vulnerability-insight/app/layout.tsx b/test/development/app-dir/vulnerability-insight/app/layout.tsx new file mode 100644 index 000000000000..7c3f422f0039 --- /dev/null +++ b/test/development/app-dir/vulnerability-insight/app/layout.tsx @@ -0,0 +1,9 @@ +import type { ReactNode } from 'react' + +export default function Root({ children }: { children: ReactNode }) { + return ( + + {children} + + ) +} diff --git a/test/development/app-dir/vulnerability-insight/app/page.tsx b/test/development/app-dir/vulnerability-insight/app/page.tsx new file mode 100644 index 000000000000..ff7159d9149f --- /dev/null +++ b/test/development/app-dir/vulnerability-insight/app/page.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

hello world

+} diff --git a/test/development/app-dir/vulnerability-insight/vulnerability-insight.test.ts b/test/development/app-dir/vulnerability-insight/vulnerability-insight.test.ts new file mode 100644 index 000000000000..73d3835a78b0 --- /dev/null +++ b/test/development/app-dir/vulnerability-insight/vulnerability-insight.test.ts @@ -0,0 +1,59 @@ +import { nextTestSetup, type Playwright } from 'e2e-utils' +import { retry } from 'next-test-utils' + +function portalText( + browser: Playwright, + selector: string +): Promise { + return browser.eval(`document.querySelector('nextjs-portal')?.shadowRoot + ?.querySelector(${JSON.stringify(selector)})?.textContent?.trim() ?? null`) +} + +function clickInPortal(browser: Playwright, selector: string): Promise { + return browser.eval(`document.querySelector('nextjs-portal')?.shadowRoot + ?.querySelector(${JSON.stringify(selector)})?.click()`) +} + +describe('vulnerability insight', () => { + const { next } = nextTestSetup({ + files: __dirname, + env: { __NEXT_AGENT_UPGRADE_FORCE_DEVTOOLS_FOR_TESTING: '1' }, + }) + + it('shows an insight, opens it, and copies the upgrade prompt', async () => { + const browser = await next.browser('/', { + beforePageLoad: async (page) => { + await page + .context() + .grantPermissions(['clipboard-read', 'clipboard-write']) + }, + }) + await retry(async () => { + expect(await portalText(browser, '[data-next-badge]')).toMatch( + /1\s*Insight/ + ) + }) + + await clickInPortal(browser, '[data-issues-open]') + await retry(async () => { + expect( + await portalText(browser, '[data-nextjs-vulnerability-label]') + ).toBe('Vulnerability Insight') + }) + const displayedPrompt = await portalText( + browser, + '[data-nextjs-vulnerability-prompt]' + ) + + await clickInPortal(browser, '[aria-label="Copy upgrade prompt"]') + let copiedPrompt = '' + await retry(async () => { + copiedPrompt = await browser.eval(() => navigator.clipboard.readText()) + expect(copiedPrompt).toBe(displayedPrompt) + }) + + expect(copiedPrompt).toMatchInlineSnapshot( + `"Run \`next upgrade --ai=security\` and follow its instructions."` + ) + }) +}) diff --git a/test/unit/security-upgrade-nudge.test.ts b/test/unit/security-upgrade-nudge.test.ts index d46960d2ea04..b4e7c0b18de4 100644 --- a/test/unit/security-upgrade-nudge.test.ts +++ b/test/unit/security-upgrade-nudge.test.ts @@ -162,7 +162,7 @@ describe('security upgrade nudge', () => { name: 'SecurityFatalError', exitCode: 1, message: expect.stringMatching( - /affected by a published security advisory[\s\S]*\*\*We strongly recommend you upgrade Next\.js\.\*\*[\s\S]*reminder you configured is not missed\. Retry the same command to continue the original task\.[\s\S]*include this upgrade recommendation even if the retry succeeds\.[\s\S]*If the app is in a Git repository, use a separate Git worktree unless they request otherwise\.[\s\S]*If the app is not in a Git repository, upgrade it in place\. Run this command from this app's directory:[\s\S]*```\nnext upgrade --ai=(?:security|latest|future)\n```/ + /affected by a known security vulnerability[\s\S]*\*\*We strongly recommend you upgrade Next\.js\.\*\*[\s\S]*reminder you configured is not missed\. Retry the same command to continue the original task\.[\s\S]*include this upgrade recommendation even if the retry succeeds\.[\s\S]*If the app is in a Git repository, use a separate Git worktree unless they request otherwise\.[\s\S]*If the app is not in a Git repository, upgrade it in place\. Run this command from this app's directory:[\s\S]*```\nnext upgrade --ai=(?:security|latest|future)\n```/ ), }) expect(warn).not.toHaveBeenCalled() @@ -185,7 +185,7 @@ describe('security upgrade nudge', () => { name: 'SecurityFatalError', exitCode: 1, message: expect.stringMatching( - /affected by a published security advisory[\s\S]*registry\.npmjs\.org/ + /affected by a known security vulnerability[\s\S]*registry\.npmjs\.org/ ), }) expect(warn).not.toHaveBeenCalled() From ffe5d5c2b429d2eae44f80cdeec2491933edcc3c Mon Sep 17 00:00:00 2001 From: "next-js-bot[bot]" <279046576+next-js-bot[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:23:04 +0000 Subject: [PATCH 3/7] v16.4.0-canary.51 --- lerna.json | 2 +- packages/create-next-app/package.json | 2 +- packages/devlow-bench/package.json | 2 +- packages/eslint-config-next/package.json | 4 ++-- packages/eslint-plugin-internal/package.json | 2 +- packages/eslint-plugin-next/package.json | 2 +- packages/font/package.json | 2 +- packages/next-bundle-analyzer/package.json | 2 +- packages/next-codemod/package.json | 2 +- packages/next-env/package.json | 2 +- packages/next-mdx/package.json | 2 +- packages/next-playwright/package.json | 2 +- packages/next-plugin-storybook/package.json | 2 +- packages/next-polyfill-module/package.json | 2 +- packages/next-polyfill-nomodule/package.json | 2 +- packages/next-routing/package.json | 2 +- packages/next-rspack/package.json | 2 +- packages/next-swc/package.json | 2 +- packages/next/package.json | 14 +++++++------- packages/react-refresh-utils/package.json | 2 +- packages/third-parties/package.json | 4 ++-- pnpm-lock.yaml | 16 ++++++++-------- 22 files changed, 37 insertions(+), 37 deletions(-) diff --git a/lerna.json b/lerna.json index 991567f765e4..f5e7253055bc 100644 --- a/lerna.json +++ b/lerna.json @@ -11,5 +11,5 @@ ] } }, - "version": "16.4.0-canary.50" + "version": "16.4.0-canary.51" } \ No newline at end of file diff --git a/packages/create-next-app/package.json b/packages/create-next-app/package.json index 2572101322c0..22ec92e582c8 100644 --- a/packages/create-next-app/package.json +++ b/packages/create-next-app/package.json @@ -1,6 +1,6 @@ { "name": "create-next-app", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "keywords": [ "react", "next", diff --git a/packages/devlow-bench/package.json b/packages/devlow-bench/package.json index d2f788aaa15d..3436a2c603e0 100644 --- a/packages/devlow-bench/package.json +++ b/packages/devlow-bench/package.json @@ -1,6 +1,6 @@ { "name": "@vercel/devlow-bench", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "description": "Benchmarking tool for the developer workflow", "repository": { "type": "git", diff --git a/packages/eslint-config-next/package.json b/packages/eslint-config-next/package.json index ae7d3ae04c7e..455f7039143f 100644 --- a/packages/eslint-config-next/package.json +++ b/packages/eslint-config-next/package.json @@ -1,6 +1,6 @@ { "name": "eslint-config-next", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "description": "ESLint configuration used by Next.js.", "license": "MIT", "repository": { @@ -12,7 +12,7 @@ "dist" ], "dependencies": { - "@next/eslint-plugin-next": "16.4.0-canary.50", + "@next/eslint-plugin-next": "16.4.0-canary.51", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", diff --git a/packages/eslint-plugin-internal/package.json b/packages/eslint-plugin-internal/package.json index 8bd422167ffd..7352c1605505 100644 --- a/packages/eslint-plugin-internal/package.json +++ b/packages/eslint-plugin-internal/package.json @@ -1,7 +1,7 @@ { "name": "@next/eslint-plugin-internal", "private": true, - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "description": "ESLint plugin for working on Next.js.", "exports": { ".": "./src/eslint-plugin-internal.js" diff --git a/packages/eslint-plugin-next/package.json b/packages/eslint-plugin-next/package.json index 028d65ff16f5..1974c3decc08 100644 --- a/packages/eslint-plugin-next/package.json +++ b/packages/eslint-plugin-next/package.json @@ -1,6 +1,6 @@ { "name": "@next/eslint-plugin-next", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "description": "ESLint plugin for Next.js.", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/font/package.json b/packages/font/package.json index 9fda9aa071b5..dd8b1ba70466 100644 --- a/packages/font/package.json +++ b/packages/font/package.json @@ -1,7 +1,7 @@ { "name": "@next/font", "private": true, - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "repository": { "url": "vercel/next.js", "directory": "packages/font" diff --git a/packages/next-bundle-analyzer/package.json b/packages/next-bundle-analyzer/package.json index c3584aebdce5..9946587bcea2 100644 --- a/packages/next-bundle-analyzer/package.json +++ b/packages/next-bundle-analyzer/package.json @@ -1,6 +1,6 @@ { "name": "@next/bundle-analyzer", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "main": "index.js", "types": "index.d.ts", "license": "MIT", diff --git a/packages/next-codemod/package.json b/packages/next-codemod/package.json index eb500c6a40a7..a188208753c4 100644 --- a/packages/next-codemod/package.json +++ b/packages/next-codemod/package.json @@ -1,6 +1,6 @@ { "name": "@next/codemod", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "license": "MIT", "repository": { "type": "git", diff --git a/packages/next-env/package.json b/packages/next-env/package.json index 5b9ca5937a76..33fe8739b1d0 100644 --- a/packages/next-env/package.json +++ b/packages/next-env/package.json @@ -1,6 +1,6 @@ { "name": "@next/env", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "keywords": [ "react", "next", diff --git a/packages/next-mdx/package.json b/packages/next-mdx/package.json index e9aff4b6a217..d4fb955cc67b 100644 --- a/packages/next-mdx/package.json +++ b/packages/next-mdx/package.json @@ -1,6 +1,6 @@ { "name": "@next/mdx", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "main": "index.js", "license": "MIT", "repository": { diff --git a/packages/next-playwright/package.json b/packages/next-playwright/package.json index da740972d6a1..4b0e55b4a1a5 100644 --- a/packages/next-playwright/package.json +++ b/packages/next-playwright/package.json @@ -1,6 +1,6 @@ { "name": "@next/playwright", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "repository": { "url": "vercel/next.js", "directory": "packages/next-playwright" diff --git a/packages/next-plugin-storybook/package.json b/packages/next-plugin-storybook/package.json index 6d7504caceb1..7167d1b0338c 100644 --- a/packages/next-plugin-storybook/package.json +++ b/packages/next-plugin-storybook/package.json @@ -1,6 +1,6 @@ { "name": "@next/plugin-storybook", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "repository": { "url": "vercel/next.js", "directory": "packages/next-plugin-storybook" diff --git a/packages/next-polyfill-module/package.json b/packages/next-polyfill-module/package.json index 6a4367039d09..add58c6f3a1e 100644 --- a/packages/next-polyfill-module/package.json +++ b/packages/next-polyfill-module/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-module", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)", "main": "dist/polyfill-module.js", "license": "MIT", diff --git a/packages/next-polyfill-nomodule/package.json b/packages/next-polyfill-nomodule/package.json index cdf2f55fbcdd..4cf4b06ba2a0 100644 --- a/packages/next-polyfill-nomodule/package.json +++ b/packages/next-polyfill-nomodule/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-nomodule", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "description": "A polyfill for non-dead, nomodule browsers.", "main": "dist/polyfill-nomodule.js", "license": "MIT", diff --git a/packages/next-routing/package.json b/packages/next-routing/package.json index 378e07473cb7..5e21122b4ec2 100644 --- a/packages/next-routing/package.json +++ b/packages/next-routing/package.json @@ -1,6 +1,6 @@ { "name": "@next/routing", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "keywords": [ "react", "next", diff --git a/packages/next-rspack/package.json b/packages/next-rspack/package.json index b7c2cab6280c..261b6d5cb0f6 100644 --- a/packages/next-rspack/package.json +++ b/packages/next-rspack/package.json @@ -1,6 +1,6 @@ { "name": "next-rspack", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "repository": { "url": "vercel/next.js", "directory": "packages/next-rspack" diff --git a/packages/next-swc/package.json b/packages/next-swc/package.json index 29206582b32b..4fdf0cf8f98c 100644 --- a/packages/next-swc/package.json +++ b/packages/next-swc/package.json @@ -1,6 +1,6 @@ { "name": "@next/swc", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "private": true, "files": [ "native/" diff --git a/packages/next/package.json b/packages/next/package.json index f92f0a5ccbe7..d63446d1a65c 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -1,6 +1,6 @@ { "name": "next", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "description": "The React Framework", "main": "./dist/server/next.js", "license": "MIT", @@ -100,7 +100,7 @@ ] }, "dependencies": { - "@next/env": "16.4.0-canary.50", + "@next/env": "16.4.0-canary.51", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -164,11 +164,11 @@ "@modelcontextprotocol/sdk": "1.18.1", "@mswjs/interceptors": "0.42.5", "@napi-rs/triples": "1.2.0", - "@next/font": "16.4.0-canary.50", - "@next/polyfill-module": "16.4.0-canary.50", - "@next/polyfill-nomodule": "16.4.0-canary.50", - "@next/react-refresh-utils": "16.4.0-canary.50", - "@next/swc": "16.4.0-canary.50", + "@next/font": "16.4.0-canary.51", + "@next/polyfill-module": "16.4.0-canary.51", + "@next/polyfill-nomodule": "16.4.0-canary.51", + "@next/react-refresh-utils": "16.4.0-canary.51", + "@next/swc": "16.4.0-canary.51", "@opentelemetry/api": "1.6.0", "@playwright/test": "1.61.0", "@rspack/core": "1.6.7", diff --git a/packages/react-refresh-utils/package.json b/packages/react-refresh-utils/package.json index c98473cddf18..5bd53a60030d 100644 --- a/packages/react-refresh-utils/package.json +++ b/packages/react-refresh-utils/package.json @@ -1,6 +1,6 @@ { "name": "@next/react-refresh-utils", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "description": "An experimental package providing utilities for React Refresh.", "repository": { "url": "vercel/next.js", diff --git a/packages/third-parties/package.json b/packages/third-parties/package.json index 6c01eb1567e1..76dafeba1da9 100644 --- a/packages/third-parties/package.json +++ b/packages/third-parties/package.json @@ -1,6 +1,6 @@ { "name": "@next/third-parties", - "version": "16.4.0-canary.50", + "version": "16.4.0-canary.51", "repository": { "url": "vercel/next.js", "directory": "packages/third-parties" @@ -26,7 +26,7 @@ "third-party-capital": "1.0.20" }, "devDependencies": { - "next": "16.4.0-canary.50", + "next": "16.4.0-canary.51", "outdent": "0.8.0", "prettier": "2.5.1", "typescript": "6.0.2" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cefb5746cf1e..d9f9b760e3d9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1027,7 +1027,7 @@ importers: packages/eslint-config-next: dependencies: '@next/eslint-plugin-next': - specifier: 16.4.0-canary.50 + specifier: 16.4.0-canary.51 version: link:../eslint-plugin-next eslint: specifier: '>=9.0.0' @@ -1110,7 +1110,7 @@ importers: packages/next: dependencies: '@next/env': - specifier: 16.4.0-canary.50 + specifier: 16.4.0-canary.51 version: link:../next-env '@swc/helpers': specifier: 0.5.23 @@ -1231,19 +1231,19 @@ importers: specifier: 1.2.0 version: 1.2.0 '@next/font': - specifier: 16.4.0-canary.50 + specifier: 16.4.0-canary.51 version: link:../font '@next/polyfill-module': - specifier: 16.4.0-canary.50 + specifier: 16.4.0-canary.51 version: link:../next-polyfill-module '@next/polyfill-nomodule': - specifier: 16.4.0-canary.50 + specifier: 16.4.0-canary.51 version: link:../next-polyfill-nomodule '@next/react-refresh-utils': - specifier: 16.4.0-canary.50 + specifier: 16.4.0-canary.51 version: link:../react-refresh-utils '@next/swc': - specifier: 16.4.0-canary.50 + specifier: 16.4.0-canary.51 version: link:../next-swc '@opentelemetry/api': specifier: 1.6.0 @@ -1986,7 +1986,7 @@ importers: version: 1.0.20 devDependencies: next: - specifier: 16.4.0-canary.50 + specifier: 16.4.0-canary.51 version: link:../next outdent: specifier: 0.8.0 From 2e2e5e0698ae8a25f0731040fde517f1b5a7c854 Mon Sep 17 00:00:00 2001 From: Jiwon Choi Date: Mon, 28 Sep 2026 11:10:54 +0900 Subject: [PATCH 4/7] [ai-upgrade] Ask user whether to start upgrade in worktree (#99232) ### Why? Let users choose whether an upgrade runs in a separate worktree. ### How? Ask in the existing agent's single upgrade question or before launching a new agent, then pass the choice into the upgrade instructions. Closes NAR-947 --- packages/next/src/cli/next-upgrade.ts | 6 +- packages/next/src/lib/upgrade/harness.ts | 48 ++++++++++-- packages/next/src/lib/upgrade/nudge.ts | 2 +- test/unit/agentic-upgrade-prompts.test.ts | 95 +++++++++++++++++++++-- test/unit/security-upgrade-nudge.test.ts | 4 +- 5 files changed, 138 insertions(+), 17 deletions(-) diff --git a/packages/next/src/cli/next-upgrade.ts b/packages/next/src/cli/next-upgrade.ts index 999c7cf05a6e..61e046b5c7cd 100644 --- a/packages/next/src/cli/next-upgrade.ts +++ b/packages/next/src/cli/next-upgrade.ts @@ -448,11 +448,13 @@ export async function spawnNextUpgrade( const taskSummary = needsVersionUpdate ? `We're upgrading the app in ${JSON.stringify(baseDir)} from Next.js ${result.installedVersion} to ${result.targetVersion} because ${reason}.` : `We're adopting the Future Defaults available to the app in ${JSON.stringify(baseDir)}, which already uses Next.js ${result.installedVersion}.` - const prompt = `Read and follow ${JSON.stringify(sharedGuidePath)} first. Attempt its applicable duplicate checks before changing files. If a check is unavailable, report it and continue. Stop only if you find equivalent work. Then read and follow every applicable instruction in ${JSON.stringify(guidePath)}. + const prompt = ( + useWorktree: boolean | null + ) => `Read and follow ${JSON.stringify(sharedGuidePath)} first. Attempt its applicable duplicate checks before changing files. If a check is unavailable, report it and continue. Stop only if you find equivalent work. Then read and follow every applicable instruction in ${JSON.stringify(guidePath)}. ${taskSummary} -If the app is in a Git repository, perform the upgrade in a separate Git worktree unless the user explicitly requests otherwise. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. +${useWorktree === null ? "Follow the user's worktree choice. If they do not specify, use a separate Git worktree when the app is in a Git repository. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place." : useWorktree ? "If the app is in a Git repository, perform the upgrade in a separate Git worktree. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place." : 'Perform the upgrade in the current checkout.'} Set \`experimental.agenticAutoUpgrade\` to ${JSON.stringify(upgradeType)} in the app's Next.js config as part of this upgrade. Preserve unrelated configuration. If the target Next.js version does not support this option, skip the setting and report why. diff --git a/packages/next/src/lib/upgrade/harness.ts b/packages/next/src/lib/upgrade/harness.ts index b17a9b9708e7..d8308ded108d 100644 --- a/packages/next/src/lib/upgrade/harness.ts +++ b/packages/next/src/lib/upgrade/harness.ts @@ -21,6 +21,27 @@ type UpgradeHarness = { path: string } +type UpgradePrompt = string | ((useWorktree: boolean | null) => string) + +function resolvePrompt( + prompt: UpgradePrompt, + useWorktree: boolean | null +): string { + return typeof prompt === 'string' ? prompt : prompt(useWorktree) +} + +async function chooseWorktree(): Promise { + Log.bootstrap(' Open the upgrade in a separate Git worktree?') + const { id } = await cliSelect({ + values: { yes: 'Yes', no: 'No' }, + defaultValue: 0, + selected: cyan('❯'), + unselected: ' ', + indentation: 2, + }) + return id === 'yes' +} + function getHarnessDisplayName(name: UpgradeHarness['name']): string { return name === 'codex' ? 'Codex' : 'Claude Code' } @@ -164,18 +185,18 @@ function launchHarness( } export async function handoffUpgrade( - prompt: string, + prompt: UpgradePrompt, directory: string ): Promise { // Existing agents keep their session, model and permissions. if (await getAgentName()) { - Log.bootstrap(prompt) + Log.bootstrap(resolvePrompt(prompt, null)) return } if (!process.stdin.isTTY || !process.stdout.isTTY) { Log.info('Copy this upgrade prompt into your coding agent:') - Log.bootstrap(prompt) + Log.bootstrap(resolvePrompt(prompt, null)) return } @@ -183,7 +204,7 @@ export async function handoffUpgrade( const installed = await findHarnesses() if (installed.length === 0) { - copyUpgradePrompt(prompt, true) + copyUpgradePrompt(resolvePrompt(prompt, null), true) return } @@ -191,7 +212,7 @@ export async function handoffUpgrade( const harness = await chooseHarness(installed) if (harness === 'copy') { - copyUpgradePrompt(prompt) + copyUpgradePrompt(resolvePrompt(prompt, null)) return } @@ -201,11 +222,26 @@ export async function handoffUpgrade( return } + let useWorktree: boolean + try { + useWorktree = await chooseWorktree() + } catch (error) { + if (error) { + throw error + } + process.exitCode = 1 + return + } + Log.bootstrap( ` Continuing with ${cyan(bold(getHarnessDisplayName(harness.name)))}...\n` ) try { - process.exitCode = await launchHarness(harness, prompt, directory) + process.exitCode = await launchHarness( + harness, + resolvePrompt(prompt, useWorktree), + directory + ) } catch { Log.error(`Could not start ${getHarnessDisplayName(harness.name)}.`) process.exitCode = 1 diff --git a/packages/next/src/lib/upgrade/nudge.ts b/packages/next/src/lib/upgrade/nudge.ts index 2be1eda8017c..f377878ffa82 100644 --- a/packages/next/src/lib/upgrade/nudge.ts +++ b/packages/next/src/lib/upgrade/nudge.ts @@ -278,7 +278,7 @@ This command stopped so the reminder you configured is not missed. Retry the sam When you report back to the user, include this upgrade recommendation even if the retry succeeds. -At the end of the task, ask the user whether they want you to run the upgrade using the configured '${reminder.policy}' policy in the background. If the app is in a Git repository, use a separate Git worktree unless they request otherwise. If the app is not in a Git repository, upgrade it in place. Run this command from this app's directory: +At the end of the task, ask the user once: "Would you like me to run the '${reminder.policy}' upgrade in the background in a separate Git worktree? I can use the current checkout if you prefer." If the app is not in Git, say it will run in place. Use their worktree choice and continue in this agent session. Run this command from this app's directory: \`\`\` ${command} diff --git a/test/unit/agentic-upgrade-prompts.test.ts b/test/unit/agentic-upgrade-prompts.test.ts index f9208ba289ee..884a90592477 100644 --- a/test/unit/agentic-upgrade-prompts.test.ts +++ b/test/unit/agentic-upgrade-prompts.test.ts @@ -1,4 +1,5 @@ import { EventEmitter } from 'events' +import { resolve } from 'path' import { access, cp, @@ -84,6 +85,16 @@ function normalizedBootstrapCalls(): string[][] { .mock.calls.map(([message]) => [String(message).replace(/\\+/g, '/')]) } +function expectedHarnessPath(name: string): string { + const extension = + process.platform === 'win32' + ? (process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM') + .split(';') + .filter(Boolean)[0] + : '' + return resolve('/agents', `${name}${extension}`) +} + function normalizedFileWriteCalls() { return jest .mocked(writeFile) @@ -105,7 +116,10 @@ function normalizedWriteFileCalls() { ) } -function overrideTTY(target: NodeJS.ReadStream | NodeJS.WriteStream): void { +function overrideTTY( + target: NodeJS.ReadStream | NodeJS.WriteStream, + value: boolean = true +): void { const descriptor = Object.getOwnPropertyDescriptor(target, 'isTTY') restoreDescriptors.push(() => { if (descriptor) { @@ -116,7 +130,7 @@ function overrideTTY(target: NodeJS.ReadStream | NodeJS.WriteStream): void { }) Object.defineProperty(target, 'isTTY', { configurable: true, - value: true, + value, }) } @@ -437,6 +451,75 @@ describe('agentic upgrade prompts', () => { ) }) + it.each([ + ['yes', true, 'Worktree prompt'], + ['no', false, 'Current checkout prompt'], + ])( + 'passes the %s worktree choice to the upgrade prompt', + async (choice, selected, expectedPrompt) => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' } as never) + .mockResolvedValueOnce({ id: choice } as never) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + const prompt = jest.fn((useWorktree: boolean | null) => + useWorktree ? 'Worktree prompt' : 'Current checkout prompt' + ) + + await handoffUpgrade(prompt, '/workspace/app') + + expect(prompt).toHaveBeenCalledWith(selected) + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + ['--model', 'gpt-5.6-terra', expectedPrompt], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + expect(jest.mocked(cliSelect).mock.calls[1][0].values).toEqual({ + yes: 'Yes', + no: 'No', + }) + } + ) + + it('keeps the existing agent in its session', async () => { + const prompt = jest.fn(() => 'Prepared upgrade prompt.') + + await handoffUpgrade(prompt, '/workspace/app') + + expect(prompt).toHaveBeenCalledWith(null) + expect(Log.bootstrap).toHaveBeenCalledWith('Prepared upgrade prompt.') + expect(cliSelect).not.toHaveBeenCalled() + expect(crossSpawn).not.toHaveBeenCalled() + }) + + it('leaves the worktree choice open outside a TTY', async () => { + overrideTTY(process.stdin, false) + overrideTTY(process.stdout, false) + jest.mocked(getAgentName).mockResolvedValue(null) + const prompt = jest.fn((useWorktree: boolean | null) => + useWorktree === null ? 'Choice pending prompt' : 'Selected prompt' + ) + + await handoffUpgrade(prompt, '/workspace/app') + + expect(prompt).toHaveBeenCalledWith(null) + expect(Log.bootstrap).toHaveBeenCalledWith( + expect.stringContaining('Choice pending prompt') + ) + expect(cliSelect).not.toHaveBeenCalled() + expect(crossSpawn).not.toHaveBeenCalled() + }) + it('passes the complete migration prompt to an existing agent', async () => { await spawnNextUpgrade('/workspace/app', { revision: 'latest', @@ -474,7 +557,7 @@ describe('agentic upgrade prompts', () => { We're upgrading the app in "/workspace/app" from Next.js 14.1.1 to 16.3.5 because the installed version is affected by a published security advisory. - If the app is in a Git repository, perform the upgrade in a separate Git worktree unless the user explicitly requests otherwise. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. + Follow the user's worktree choice. If they do not specify, use a separate Git worktree when the app is in a Git repository. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. Set \`experimental.agenticAutoUpgrade\` to "security" in the app's Next.js config as part of this upgrade. Preserve unrelated configuration. If the target Next.js version does not support this option, skip the setting and report why. @@ -571,7 +654,7 @@ describe('agentic upgrade prompts', () => { We're upgrading the app in "/workspace/app" from Next.js 16.2.12 to 16.3.5 because a newer stable Next.js release is available. - If the app is in a Git repository, perform the upgrade in a separate Git worktree unless the user explicitly requests otherwise. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. + Follow the user's worktree choice. If they do not specify, use a separate Git worktree when the app is in a Git repository. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. Set \`experimental.agenticAutoUpgrade\` to "latest" in the app's Next.js config as part of this upgrade. Preserve unrelated configuration. If the target Next.js version does not support this option, skip the setting and report why. @@ -780,7 +863,7 @@ describe('agentic upgrade prompts', () => { We're upgrading the app in "/workspace/app" from Next.js 16.2.0 to 16.4.0 because the Future policy applies the latest stable release and adopts its Future Defaults. - If the app is in a Git repository, perform the upgrade in a separate Git worktree unless the user explicitly requests otherwise. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. + Follow the user's worktree choice. If they do not specify, use a separate Git worktree when the app is in a Git repository. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. Set \`experimental.agenticAutoUpgrade\` to "future" in the app's Next.js config as part of this upgrade. Preserve unrelated configuration. If the target Next.js version does not support this option, skip the setting and report why. @@ -879,7 +962,7 @@ describe('agentic upgrade prompts', () => { We're adopting the Future Defaults available to the app in "/workspace/app", which already uses Next.js 16.4.0. - If the app is in a Git repository, perform the upgrade in a separate Git worktree unless the user explicitly requests otherwise. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. + Follow the user's worktree choice. If they do not specify, use a separate Git worktree when the app is in a Git repository. Run upgrade commands from this app's corresponding directory in that worktree. If the app is not in a Git repository, upgrade it in place. Set \`experimental.agenticAutoUpgrade\` to "future" in the app's Next.js config as part of this upgrade. Preserve unrelated configuration. If the target Next.js version does not support this option, skip the setting and report why. diff --git a/test/unit/security-upgrade-nudge.test.ts b/test/unit/security-upgrade-nudge.test.ts index b4e7c0b18de4..76fef62c0e2c 100644 --- a/test/unit/security-upgrade-nudge.test.ts +++ b/test/unit/security-upgrade-nudge.test.ts @@ -162,7 +162,7 @@ describe('security upgrade nudge', () => { name: 'SecurityFatalError', exitCode: 1, message: expect.stringMatching( - /affected by a known security vulnerability[\s\S]*\*\*We strongly recommend you upgrade Next\.js\.\*\*[\s\S]*reminder you configured is not missed\. Retry the same command to continue the original task\.[\s\S]*include this upgrade recommendation even if the retry succeeds\.[\s\S]*If the app is in a Git repository, use a separate Git worktree unless they request otherwise\.[\s\S]*If the app is not in a Git repository, upgrade it in place\. Run this command from this app's directory:[\s\S]*```\nnext upgrade --ai=(?:security|latest|future)\n```/ + /affected by a known security vulnerability[\s\S]*\*\*We strongly recommend you upgrade Next\.js\.\*\*[\s\S]*reminder you configured is not missed\. Retry the same command to continue the original task\.[\s\S]*include this upgrade recommendation even if the retry succeeds\.[\s\S]*ask the user once:[\s\S]*in a separate Git worktree\?[\s\S]*Use their worktree choice and continue in this agent session[\s\S]*Run this command from this app's directory:[\s\S]*```\nnext upgrade --ai=(?:security|latest|future)\n```/ ), }) expect(warn).not.toHaveBeenCalled() @@ -413,7 +413,7 @@ describe('latest upgrade nudge', () => { name: 'UpgradeNudgeError', exitCode: 1, message: expect.stringMatching( - /Next\.js 17\.0\.0 is available\.[\s\S]*\*\*We recommend you upgrade Next\.js\.\*\*[\s\S]*reminder you configured is not missed\. Retry the same command to continue the original task\.[\s\S]*include this upgrade recommendation even if the retry succeeds\.[\s\S]*If the app is in a Git repository, use a separate Git worktree unless they request otherwise\.[\s\S]*If the app is not in a Git repository, upgrade it in place\. Run this command from this app's directory:[\s\S]*```\nnext upgrade --ai=(?:security|latest|future)\n```[\s\S]*registry\.npmjs\.org[\s\S]*agenticAutoUpgrade: 'latest'/ + /Next\.js 17\.0\.0 is available\.[\s\S]*\*\*We recommend you upgrade Next\.js\.\*\*[\s\S]*reminder you configured is not missed\. Retry the same command to continue the original task\.[\s\S]*include this upgrade recommendation even if the retry succeeds\.[\s\S]*ask the user once:[\s\S]*in a separate Git worktree\?[\s\S]*Use their worktree choice and continue in this agent session[\s\S]*Run this command from this app's directory:[\s\S]*```\nnext upgrade --ai=(?:security|latest|future)\n```[\s\S]*registry\.npmjs\.org[\s\S]*agenticAutoUpgrade: 'latest'/ ), }) await expect( From 38c16c82b55de8d867a53b4d9efc140a32d71f78 Mon Sep 17 00:00:00 2001 From: Jiwon Choi Date: Mon, 28 Sep 2026 11:10:55 +0900 Subject: [PATCH 5/7] [ai-upgrade] Ask user to choose model and effort (#99235) Stacked on #99232. ### Why? Let users choose the model and effort for a new upgrade agent. ### How? Ask for model, then effort, in separate selectors and pass both to the CLI. Existing agents keep their settings. Closes NAR-947 --- packages/next/src/lib/upgrade/harness.ts | 178 ++++++++++++- test/unit/agentic-upgrade-prompts.test.ts | 310 ++++++++++++++++++++-- 2 files changed, 456 insertions(+), 32 deletions(-) diff --git a/packages/next/src/lib/upgrade/harness.ts b/packages/next/src/lib/upgrade/harness.ts index d8308ded108d..4c3c7b051b17 100644 --- a/packages/next/src/lib/upgrade/harness.ts +++ b/packages/next/src/lib/upgrade/harness.ts @@ -10,12 +10,68 @@ import { getAgentName } from '../../telemetry/agent-name' import { bold, cyan, dim } from '../picocolors' import { runChildProcess } from './run-child-process' -// Model defaults for newly launched sessions; existing agents keep their model. +const CODEX_EFFORTS = [ + 'low', + 'medium', + 'high', + 'xhigh', + 'max', + 'ultra', +] as const +const CLAUDE_EFFORTS = ['low', 'medium', 'high', 'max'] as const + const UPGRADE_MODELS = { - codex: 'gpt-5.6-terra', - claude: 'claude-sonnet-5[1m]', + codex: [ + { id: 'gpt-5.6-terra', label: 'GPT-5.6-Terra', efforts: CODEX_EFFORTS }, + { id: 'gpt-5.6-sol', label: 'GPT-5.6-Sol', efforts: CODEX_EFFORTS }, + { id: 'gpt-6-astra', label: 'GPT-6-Astra', efforts: CODEX_EFFORTS }, + ], + claude: [ + { + id: 'claude-sonnet-5[1m]', + label: 'Claude Sonnet 5 (1M)', + efforts: CLAUDE_EFFORTS, + }, + { id: 'opus', label: 'Claude Opus (latest)', efforts: CLAUDE_EFFORTS }, + { id: 'fable', label: 'Claude Fable (latest)', efforts: CLAUDE_EFFORTS }, + ], } as const +function getCodexModels(path: string) { + const result = spawn.sync(path, ['debug', 'models', '--bundled'], { + encoding: 'utf8', + timeout: 5000, + maxBuffer: 20 * 1024 * 1024, + }) + if (result.status !== 0) { + Log.warn( + 'Could not read the Codex model catalog; using the CLI defaults.', + result.error ?? (result.stderr?.trim() || `exit status ${result.status}`) + ) + return [] + } + + try { + const catalog = JSON.parse(result.stdout) as { + models?: Array<{ slug: string }> + } + if (!Array.isArray(catalog.models)) { + Log.warn( + 'Codex model catalog has an unexpected format; using the CLI defaults.' + ) + return [] + } + const available = new Set(catalog.models.map(({ slug }) => slug)) + return UPGRADE_MODELS.codex.filter(({ id }) => available.has(id)) + } catch (error) { + Log.warn( + 'Could not parse the Codex model catalog; using the CLI defaults.', + error + ) + return [] + } +} + type UpgradeHarness = { name: keyof typeof UPGRADE_MODELS path: string @@ -30,6 +86,34 @@ function resolvePrompt( return typeof prompt === 'string' ? prompt : prompt(useWorktree) } +async function chooseOption( + question: string, + values: Record, + defaultValue: number +): Promise { + Log.bootstrap('') + Log.bootstrap(` ${question}`) + Log.bootstrap(` ${dim('Use ↑/↓ to choose, then press Enter.')}\n`) + + try { + const { id } = await cliSelect({ + values: { ...values, cancel: 'Cancel' }, + defaultValue, + selected: cyan('❯'), + unselected: ' ', + indentation: 2, + valueRenderer: (value: string, selected: boolean) => + selected ? cyan(bold(value)) : value, + }) + return typeof id === 'string' && id !== 'cancel' ? id : undefined + } catch (error) { + if (error) { + throw error + } + return undefined + } +} + async function chooseWorktree(): Promise { Log.bootstrap(' Open the upgrade in a separate Git worktree?') const { id } = await cliSelect({ @@ -72,7 +156,20 @@ async function findHarnesses(): Promise { if ((await stat(file)).isFile()) { return { name, path: file } } - } catch {} + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if ( + code === 'ENOENT' || + code === 'EACCES' || + code === 'ENOTDIR' || + code === 'ELOOP' + ) { + continue + } + throw new Error(`Could not inspect coding agent at ${file}.`, { + cause: error, + }) + } } } @@ -170,25 +267,35 @@ function copyUpgradePrompt(prompt: string, noHarness = false): void { function launchHarness( harness: UpgradeHarness, prompt: string, - directory: string + directory: string, + model: string | null, + effort: string ): Promise { // Windows shell shims cannot carry literal line breaks in an argument. if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(harness.path)) { prompt = prompt.replace(/[\r\n]+/g, ' ') } - return runChildProcess( - harness.path, - ['--model', UPGRADE_MODELS[harness.name], prompt], - { cwd: directory, stdio: 'inherit' } - ) + const args = model === null ? [] : ['--model', model] + if (effort !== 'default') { + if (harness.name === 'codex') { + args.push('-c', `model_reasoning_effort=${effort}`) + } else { + args.push('--effort', effort) + } + } + args.push(prompt) + return runChildProcess(harness.path, args, { + cwd: directory, + stdio: 'inherit', + }) } export async function handoffUpgrade( prompt: UpgradePrompt, directory: string ): Promise { - // Existing agents keep their session, model and permissions. + // Existing agents keep their session and permissions. if (await getAgentName()) { Log.bootstrap(resolvePrompt(prompt, null)) return @@ -222,6 +329,51 @@ export async function handoffUpgrade( return } + const models = + harness.name === 'codex' + ? getCodexModels(harness.path) + : UPGRADE_MODELS.claude + if (models.length === 0 && harness.name !== 'codex') { + Log.error('No supported models were found for the selected coding agent.') + process.exitCode = 1 + return + } + let model: (typeof models)[number] | undefined + let effort = 'default' + if (models.length === 0) { + Log.warn('Could not verify Codex models; using the CLI defaults.') + } else { + const modelId = await chooseOption( + `Which ${getHarnessDisplayName(harness.name)} model should run the upgrade?`, + Object.fromEntries(models.map(({ id, label }) => [id, label])), + 0 + ) + model = models.find(({ id }) => id === modelId) + if (!model) { + Log.bootstrap(` ${dim('Upgrade cancelled.')}\n`) + process.exitCode = 1 + return + } + + const selectedEffort = await chooseOption( + 'Which reasoning effort should the upgrade use?', + { + default: 'Model default', + ...Object.fromEntries(model.efforts.map((value) => [value, value])), + }, + 0 + ) + if ( + !selectedEffort || + (selectedEffort !== 'default' && + !model.efforts.some((value) => value === selectedEffort)) + ) { + Log.bootstrap(` ${dim('Upgrade cancelled.')}\n`) + process.exitCode = 1 + return + } + effort = selectedEffort + } let useWorktree: boolean try { useWorktree = await chooseWorktree() @@ -240,7 +392,9 @@ export async function handoffUpgrade( process.exitCode = await launchHarness( harness, resolvePrompt(prompt, useWorktree), - directory + directory, + model?.id ?? null, + effort ) } catch { Log.error(`Could not start ${getHarnessDisplayName(harness.name)}.`) diff --git a/test/unit/agentic-upgrade-prompts.test.ts b/test/unit/agentic-upgrade-prompts.test.ts index 884a90592477..a7f7570bb100 100644 --- a/test/unit/agentic-upgrade-prompts.test.ts +++ b/test/unit/agentic-upgrade-prompts.test.ts @@ -40,12 +40,15 @@ jest.mock('next/dist/build/output/log', () => ({ bootstrap: jest.fn(), error: jest.fn(), info: jest.fn(), + warn: jest.fn(), })) jest.mock('next/dist/compiled/cli-select', () => ({ __esModule: true, default: jest.fn(), })) -jest.mock('next/dist/compiled/cross-spawn', () => jest.fn()) +jest.mock('next/dist/compiled/cross-spawn', () => + Object.assign(jest.fn(), { sync: jest.fn() }) +) jest.mock('next/dist/lib/find-pages-dir', () => ({ findDir: jest.fn(), })) @@ -73,9 +76,10 @@ jest.mock('next/dist/server/config-shared', () => ({ jest.mock('next/dist/telemetry/agent-name', () => ({ getAgentName: jest.fn(), })) - const createSpinner = require('next/dist/build/spinner').default as jest.Mock -const crossSpawn = require('next/dist/compiled/cross-spawn') as jest.Mock +const crossSpawn = require('next/dist/compiled/cross-spawn') as jest.Mock & { + sync: jest.Mock +} const cliVersion: string = require('next/package.json').version const restoreDescriptors: Array<() => void> = [] @@ -144,6 +148,7 @@ describe('agentic upgrade prompts', () => { beforeEach(() => { jest.resetAllMocks() + crossSpawn.sync.mockReturnValue({ status: 1, stdout: '' }) process.env.__NEXT_UPGRADE_USE_CURRENT_CLI = '1' process.env.__NEXT_UPGRADE_EXPECTED_CLI_VERSION = cliVersion global.fetch = jest.fn() @@ -439,7 +444,7 @@ describe('agentic upgrade prompts', () => { jest.mocked(getAgentName).mockResolvedValue(null) jest.mocked(access).mockImplementation(async (file) => { if (/[/\\]codex(?:\.(?:exe|cmd|bat|com))?$/i.test(String(file))) return - throw new Error('not found') + throw Object.assign(new Error('not found'), { code: 'ENOENT' }) }) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) jest.mocked(cliSelect).mockResolvedValue({ id: 'cancel' } as never) @@ -452,45 +457,270 @@ describe('agentic upgrade prompts', () => { }) it.each([ - ['yes', true, 'Worktree prompt'], - ['no', false, 'Current checkout prompt'], + [ + 'codex', + 'gpt-5.6-terra', + 'ultra', + ['--model', 'gpt-5.6-terra', '-c', 'model_reasoning_effort=ultra'], + ], + [ + 'codex', + 'gpt-5.6-sol', + 'max', + ['--model', 'gpt-5.6-sol', '-c', 'model_reasoning_effort=max'], + ], + [ + 'codex', + 'gpt-6-astra', + 'high', + ['--model', 'gpt-6-astra', '-c', 'model_reasoning_effort=high'], + ], + [ + 'claude', + 'claude-sonnet-5[1m]', + 'high', + ['--model', 'claude-sonnet-5[1m]', '--effort', 'high'], + ], + ['claude', 'opus', 'max', ['--model', 'opus', '--effort', 'max']], + ['claude', 'fable', 'medium', ['--model', 'fable', '--effort', 'medium']], ])( - 'passes the %s worktree choice to the upgrade prompt', - async (choice, selected, expectedPrompt) => { + 'passes selected %s model %s and effort %s', + async (agent, model, effort, flags) => { process.env.PATH = '/agents' overrideTTY(process.stdin) overrideTTY(process.stdout) jest.mocked(getAgentName).mockResolvedValue(null) jest.mocked(access).mockResolvedValue(undefined) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + if (agent === 'codex') { + crossSpawn.sync.mockReturnValue({ + status: 0, + stdout: JSON.stringify({ + models: [ + { slug: 'gpt-5.6-terra' }, + { slug: 'gpt-5.6-sol' }, + { slug: 'gpt-6-astra' }, + ], + }), + }) + } jest .mocked(cliSelect) - .mockResolvedValueOnce({ id: 'codex' } as never) - .mockResolvedValueOnce({ id: choice } as never) + .mockResolvedValueOnce({ id: agent } as never) + .mockResolvedValueOnce({ id: model } as never) + .mockResolvedValueOnce({ id: effort } as never) + .mockResolvedValueOnce({ id: 'no' } as never) crossSpawn.mockImplementation(() => { const child = new EventEmitter() process.nextTick(() => child.emit('close', 0, null)) return child }) + const prompt = jest.fn((useWorktree: boolean | null) => - useWorktree ? 'Worktree prompt' : 'Current checkout prompt' + useWorktree ? 'Worktree prompt' : 'In-place prompt' ) - await handoffUpgrade(prompt, '/workspace/app') - expect(prompt).toHaveBeenCalledWith(selected) + expect(prompt).toHaveBeenCalledWith(false) expect(crossSpawn).toHaveBeenCalledWith( - expectedHarnessPath('codex'), - ['--model', 'gpt-5.6-terra', expectedPrompt], + expectedHarnessPath(agent), + [...flags, 'In-place prompt'], { cwd: '/workspace/app', stdio: 'inherit' } ) - expect(jest.mocked(cliSelect).mock.calls[1][0].values).toEqual({ + const modelMenu = jest.mocked(cliSelect).mock.calls[1][0] + expect(modelMenu.values).toEqual( + agent === 'codex' + ? { + 'gpt-5.6-terra': 'GPT-5.6-Terra', + 'gpt-5.6-sol': 'GPT-5.6-Sol', + 'gpt-6-astra': 'GPT-6-Astra', + cancel: 'Cancel', + } + : { + 'claude-sonnet-5[1m]': 'Claude Sonnet 5 (1M)', + opus: 'Claude Opus (latest)', + fable: 'Claude Fable (latest)', + cancel: 'Cancel', + } + ) + const effortMenu = jest.mocked(cliSelect).mock.calls[2][0] + expect(Object.keys(effortMenu.values)).toEqual( + agent === 'claude' + ? ['default', 'low', 'medium', 'high', 'max', 'cancel'] + : [ + 'default', + 'low', + 'medium', + 'high', + 'xhigh', + 'max', + 'ultra', + 'cancel', + ] + ) + expect(effortMenu.defaultValue).toBe(0) + expect(jest.mocked(cliSelect).mock.calls[3][0].values).toEqual({ yes: 'Yes', no: 'No', }) + const questions = jest + .mocked(Log.bootstrap) + .mock.calls.map(([value]) => String(value)) + expect( + questions.findIndex((value) => value.includes('model should run')) + ).toBeLessThan( + questions.findIndex((value) => value.includes('reasoning effort')) + ) + } + ) + + it('uses the selected model default when no effort override is chosen', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + crossSpawn.sync.mockReturnValue({ + status: 0, + stdout: JSON.stringify({ models: [{ slug: 'gpt-5.6-terra' }] }), + }) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' } as never) + .mockResolvedValueOnce({ id: 'gpt-5.6-terra' } as never) + .mockResolvedValueOnce({ id: 'default' } as never) + .mockResolvedValueOnce({ id: 'no' } as never) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + ['--model', 'gpt-5.6-terra', 'Upgrade prompt'], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + }) + + it('omits Astra when the selected Codex catalog does not contain it', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + crossSpawn.sync.mockReturnValue({ + status: 0, + stdout: JSON.stringify({ + models: [{ slug: 'gpt-5.6-terra' }, { slug: 'gpt-5.6-sol' }], + }), + }) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' } as never) + .mockResolvedValueOnce({ id: 'gpt-5.6-sol' } as never) + .mockResolvedValueOnce({ id: 'default' } as never) + .mockResolvedValueOnce({ id: 'no' } as never) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect(jest.mocked(cliSelect).mock.calls[1][0].values).toEqual({ + 'gpt-5.6-terra': 'GPT-5.6-Terra', + 'gpt-5.6-sol': 'GPT-5.6-Sol', + cancel: 'Cancel', + }) + expect(crossSpawn.sync).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + ['debug', 'models', '--bundled'], + expect.objectContaining({ encoding: 'utf8' }) + ) + }) + + it.each([ + [ + 'unavailable', + { status: 1, stdout: '' }, + 'Could not read the Codex model catalog; using the CLI defaults.', + 'exit status 1', + ], + [ + 'invalid JSON', + { status: 0, stdout: '{' }, + 'Could not parse the Codex model catalog; using the CLI defaults.', + expect.any(SyntaxError), + ], + [ + 'unexpected format', + { status: 0, stdout: '{}' }, + 'Codex model catalog has an unexpected format; using the CLI defaults.', + null, + ], + [ + 'empty', + { status: 0, stdout: JSON.stringify({ models: [] }) }, + 'Could not verify Codex models; using the CLI defaults.', + null, + ], + ])( + 'uses Codex defaults when the model catalog is %s', + async (_, result, warning, cause) => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + crossSpawn.sync.mockReturnValue(result) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' } as never) + .mockResolvedValueOnce({ id: 'no' } as never) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect(cliSelect).toHaveBeenCalledTimes(2) + if (cause === null) { + expect(Log.warn).toHaveBeenCalledWith(warning) + } else { + expect(Log.warn).toHaveBeenCalledWith(warning, cause) + } + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + ['Upgrade prompt'], + { cwd: '/workspace/app', stdio: 'inherit' } + ) } ) + it('preserves unexpected agent probe errors as the cause', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + const cause = Object.assign(new Error('too many open files'), { + code: 'EMFILE', + }) + jest.mocked(access).mockRejectedValue(cause) + + await expect( + handoffUpgrade('Upgrade prompt', '/workspace/app') + ).rejects.toMatchObject({ cause }) + }) + it('keeps the existing agent in its session', async () => { const prompt = jest.fn(() => 'Prepared upgrade prompt.') @@ -498,8 +728,48 @@ describe('agentic upgrade prompts', () => { expect(prompt).toHaveBeenCalledWith(null) expect(Log.bootstrap).toHaveBeenCalledWith('Prepared upgrade prompt.') - expect(cliSelect).not.toHaveBeenCalled() - expect(crossSpawn).not.toHaveBeenCalled() + expect(cliSelect).toHaveBeenCalledTimes(0) + expect(crossSpawn).toHaveBeenCalledTimes(0) + }) + + it('passes the accepted worktree choice to the prompt factory', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + crossSpawn.sync.mockReturnValue({ + status: 0, + stdout: JSON.stringify({ models: [{ slug: 'gpt-5.6-terra' }] }), + }) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' } as never) + .mockResolvedValueOnce({ id: 'gpt-5.6-terra' } as never) + .mockResolvedValueOnce({ id: 'high' } as never) + .mockResolvedValueOnce({ id: 'yes' } as never) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + const prompt = jest.fn(() => 'Worktree prompt') + + await handoffUpgrade(prompt, '/workspace/app') + + expect(prompt).toHaveBeenCalledWith(true) + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + [ + '--model', + 'gpt-5.6-terra', + '-c', + 'model_reasoning_effort=high', + 'Worktree prompt', + ], + { cwd: '/workspace/app', stdio: 'inherit' } + ) }) it('leaves the worktree choice open outside a TTY', async () => { @@ -516,8 +786,8 @@ describe('agentic upgrade prompts', () => { expect(Log.bootstrap).toHaveBeenCalledWith( expect.stringContaining('Choice pending prompt') ) - expect(cliSelect).not.toHaveBeenCalled() - expect(crossSpawn).not.toHaveBeenCalled() + expect(cliSelect).toHaveBeenCalledTimes(0) + expect(crossSpawn).toHaveBeenCalledTimes(0) }) it('passes the complete migration prompt to an existing agent', async () => { From 543c5ec3b4494b62539e078282d6110785bf6327 Mon Sep 17 00:00:00 2001 From: Jiwon Choi Date: Mon, 28 Sep 2026 11:10:55 +0900 Subject: [PATCH 6/7] [ai-upgrade] Ask user to choose permission (#99291) Stacked on #99235. ### Why? Let users choose whether a new upgrade agent uses Auto permissions. ### How? Ask Yes/No after model and effort. No sets explicit approvals; CLIs without Auto use a supported approval mode. Existing agents keep their permissions. Closes NAR-947 --- packages/next/src/lib/upgrade/harness.ts | 87 ++++++- test/unit/agentic-upgrade-prompts.test.ts | 278 +++++++++++++++++++--- 2 files changed, 330 insertions(+), 35 deletions(-) diff --git a/packages/next/src/lib/upgrade/harness.ts b/packages/next/src/lib/upgrade/harness.ts index 4c3c7b051b17..c26e496a0a2c 100644 --- a/packages/next/src/lib/upgrade/harness.ts +++ b/packages/next/src/lib/upgrade/harness.ts @@ -72,6 +72,13 @@ function getCodexModels(path: string) { } } +const CODEX_APPROVAL_ARGS = [ + '--sandbox', + 'workspace-write', + '--ask-for-approval', + 'on-request', +] as const + type UpgradeHarness = { name: keyof typeof UPGRADE_MODELS path: string @@ -130,6 +137,38 @@ function getHarnessDisplayName(name: UpgradeHarness['name']): string { return name === 'codex' ? 'Codex' : 'Claude Code' } +function supportsCodexAutoReview(path: string): boolean { + const result = spawn.sync(path, ['--help'], { + encoding: 'utf8', + timeout: 5000, + }) + return result.status === 0 && /--approve-for-me\b/.test(result.stdout ?? '') +} + +function getClaudePermissionSupport(path: string) { + const result = spawn.sync(path, ['--help'], { + encoding: 'utf8', + timeout: 5000, + }) + const permissionModeHelp = + result.status === 0 + ? result.stdout?.match( + /--permission-mode[^\n]*(?:\n[ \t]{8,}[^\n]*){0,4}/ + )?.[0] + : null + const choices = permissionModeHelp?.match(/\(choices:\s*([^)]+)\)/)?.[1] + const supportedModes = new Set(choices?.match(/[A-Za-z]+/g) ?? []) + + return { + auto: supportedModes.has('auto'), + approvalMode: supportedModes.has('manual') + ? 'manual' + : supportedModes.has('default') + ? 'default' + : null, + } +} + async function findHarnesses(): Promise { const names: UpgradeHarness['name'][] = ['codex', 'claude'] const directories = (process.env.PATH ?? '').split(delimiter).filter(Boolean) @@ -269,7 +308,8 @@ function launchHarness( prompt: string, directory: string, model: string | null, - effort: string + effort: string, + permissionArgs: readonly string[] ): Promise { // Windows shell shims cannot carry literal line breaks in an argument. if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(harness.path)) { @@ -284,6 +324,7 @@ function launchHarness( args.push('--effort', effort) } } + args.push(...permissionArgs) args.push(prompt) return runChildProcess(harness.path, args, { cwd: directory, @@ -315,7 +356,7 @@ export async function handoffUpgrade( return } - // Let the selected agent take over the terminal with its existing permissions. + // Let the selected agent take over the terminal with the chosen permissions. const harness = await chooseHarness(installed) if (harness === 'copy') { @@ -374,6 +415,45 @@ export async function handoffUpgrade( } effort = selectedEffort } + let autoPermissionArgs: string[] | null + let approvalPermissionArgs: string[] + if (harness.name === 'codex') { + autoPermissionArgs = supportsCodexAutoReview(harness.path) + ? ['--approve-for-me'] + : null + approvalPermissionArgs = [...CODEX_APPROVAL_ARGS] + } else { + const { auto, approvalMode } = getClaudePermissionSupport(harness.path) + if (!approvalMode) { + Log.error('Could not determine a supported Claude approval mode.') + process.exitCode = 1 + return + } + autoPermissionArgs = auto ? ['--permission-mode', 'auto'] : null + approvalPermissionArgs = ['--permission-mode', approvalMode] + } + + let permissionArgs = approvalPermissionArgs + if (autoPermissionArgs) { + const useAuto = await chooseOption( + `Use Auto permission mode for ${getHarnessDisplayName(harness.name)}?`, + { yes: 'Yes', no: 'No, ask for approval' }, + 0 + ) + if (useAuto !== 'yes' && useAuto !== 'no') { + Log.bootstrap(` ${dim('Upgrade cancelled.')}\n`) + process.exitCode = 1 + return + } + if (useAuto === 'yes') { + permissionArgs = autoPermissionArgs + } + } else { + Log.info( + dim('Auto permission mode is unavailable; using approval requests.') + ) + } + let useWorktree: boolean try { useWorktree = await chooseWorktree() @@ -394,7 +474,8 @@ export async function handoffUpgrade( resolvePrompt(prompt, useWorktree), directory, model?.id ?? null, - effort + effort, + permissionArgs ) } catch { Log.error(`Could not start ${getHarnessDisplayName(harness.name)}.`) diff --git a/test/unit/agentic-upgrade-prompts.test.ts b/test/unit/agentic-upgrade-prompts.test.ts index a7f7570bb100..c26fd1667458 100644 --- a/test/unit/agentic-upgrade-prompts.test.ts +++ b/test/unit/agentic-upgrade-prompts.test.ts @@ -148,7 +148,25 @@ describe('agentic upgrade prompts', () => { beforeEach(() => { jest.resetAllMocks() - crossSpawn.sync.mockReturnValue({ status: 1, stdout: '' }) + crossSpawn.sync.mockImplementation((_path, args) => { + if (args[0] === 'debug') { + return { + status: 0, + stdout: JSON.stringify({ + models: [ + { slug: 'gpt-5.6-terra' }, + { slug: 'gpt-5.6-sol' }, + { slug: 'gpt-6-astra' }, + ], + }), + } + } + return { + status: 0, + stdout: + ' --approve-for-me Route approval requests through automatic review\n --permission-mode Permission mode to use for the session\n (choices: "acceptEdits", "auto", "manual")', + } + }) process.env.__NEXT_UPGRADE_USE_CURRENT_CLI = '1' process.env.__NEXT_UPGRADE_EXPECTED_CLI_VERSION = cliVersion global.fetch = jest.fn() @@ -492,23 +510,12 @@ describe('agentic upgrade prompts', () => { jest.mocked(getAgentName).mockResolvedValue(null) jest.mocked(access).mockResolvedValue(undefined) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) - if (agent === 'codex') { - crossSpawn.sync.mockReturnValue({ - status: 0, - stdout: JSON.stringify({ - models: [ - { slug: 'gpt-5.6-terra' }, - { slug: 'gpt-5.6-sol' }, - { slug: 'gpt-6-astra' }, - ], - }), - }) - } jest .mocked(cliSelect) .mockResolvedValueOnce({ id: agent } as never) .mockResolvedValueOnce({ id: model } as never) .mockResolvedValueOnce({ id: effort } as never) + .mockResolvedValueOnce({ id: 'yes' } as never) .mockResolvedValueOnce({ id: 'no' } as never) crossSpawn.mockImplementation(() => { const child = new EventEmitter() @@ -524,7 +531,13 @@ describe('agentic upgrade prompts', () => { expect(prompt).toHaveBeenCalledWith(false) expect(crossSpawn).toHaveBeenCalledWith( expectedHarnessPath(agent), - [...flags, 'In-place prompt'], + [ + ...flags, + ...(agent === 'codex' + ? ['--approve-for-me'] + : ['--permission-mode', 'auto']), + 'In-place prompt', + ], { cwd: '/workspace/app', stdio: 'inherit' } ) const modelMenu = jest.mocked(cliSelect).mock.calls[1][0] @@ -559,7 +572,14 @@ describe('agentic upgrade prompts', () => { ] ) expect(effortMenu.defaultValue).toBe(0) - expect(jest.mocked(cliSelect).mock.calls[3][0].values).toEqual({ + const permissionMenu = jest.mocked(cliSelect).mock.calls[3][0] + expect(permissionMenu.values).toEqual({ + yes: 'Yes', + no: 'No, ask for approval', + cancel: 'Cancel', + }) + expect(permissionMenu.defaultValue).toBe(0) + expect(jest.mocked(cliSelect).mock.calls[4][0].values).toEqual({ yes: 'Yes', no: 'No', }) @@ -571,6 +591,11 @@ describe('agentic upgrade prompts', () => { ).toBeLessThan( questions.findIndex((value) => value.includes('reasoning effort')) ) + expect( + questions.findIndex((value) => value.includes('reasoning effort')) + ).toBeLessThan( + questions.findIndex((value) => value.includes('permission mode')) + ) } ) @@ -581,15 +606,12 @@ describe('agentic upgrade prompts', () => { jest.mocked(getAgentName).mockResolvedValue(null) jest.mocked(access).mockResolvedValue(undefined) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) - crossSpawn.sync.mockReturnValue({ - status: 0, - stdout: JSON.stringify({ models: [{ slug: 'gpt-5.6-terra' }] }), - }) jest .mocked(cliSelect) .mockResolvedValueOnce({ id: 'codex' } as never) .mockResolvedValueOnce({ id: 'gpt-5.6-terra' } as never) .mockResolvedValueOnce({ id: 'default' } as never) + .mockResolvedValueOnce({ id: 'yes' } as never) .mockResolvedValueOnce({ id: 'no' } as never) crossSpawn.mockImplementation(() => { const child = new EventEmitter() @@ -601,7 +623,7 @@ describe('agentic upgrade prompts', () => { expect(crossSpawn).toHaveBeenCalledWith( expectedHarnessPath('codex'), - ['--model', 'gpt-5.6-terra', 'Upgrade prompt'], + ['--model', 'gpt-5.6-terra', '--approve-for-me', 'Upgrade prompt'], { cwd: '/workspace/app', stdio: 'inherit' } ) }) @@ -613,17 +635,23 @@ describe('agentic upgrade prompts', () => { jest.mocked(getAgentName).mockResolvedValue(null) jest.mocked(access).mockResolvedValue(undefined) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) - crossSpawn.sync.mockReturnValue({ - status: 0, - stdout: JSON.stringify({ - models: [{ slug: 'gpt-5.6-terra' }, { slug: 'gpt-5.6-sol' }], - }), + crossSpawn.sync.mockImplementation((_path, args) => { + if (args[0] === 'debug') { + return { + status: 0, + stdout: JSON.stringify({ + models: [{ slug: 'gpt-5.6-terra' }, { slug: 'gpt-5.6-sol' }], + }), + } + } + return { status: 0, stdout: ' --approve-for-me' } }) jest .mocked(cliSelect) .mockResolvedValueOnce({ id: 'codex' } as never) .mockResolvedValueOnce({ id: 'gpt-5.6-sol' } as never) .mockResolvedValueOnce({ id: 'default' } as never) + .mockResolvedValueOnce({ id: 'yes' } as never) .mockResolvedValueOnce({ id: 'no' } as never) crossSpawn.mockImplementation(() => { const child = new EventEmitter() @@ -679,10 +707,15 @@ describe('agentic upgrade prompts', () => { jest.mocked(getAgentName).mockResolvedValue(null) jest.mocked(access).mockResolvedValue(undefined) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) - crossSpawn.sync.mockReturnValue(result) + crossSpawn.sync.mockImplementation((_path, args) => + args[0] === 'debug' + ? result + : { status: 0, stdout: ' --approve-for-me' } + ) jest .mocked(cliSelect) .mockResolvedValueOnce({ id: 'codex' } as never) + .mockResolvedValueOnce({ id: 'yes' } as never) .mockResolvedValueOnce({ id: 'no' } as never) crossSpawn.mockImplementation(() => { const child = new EventEmitter() @@ -692,7 +725,7 @@ describe('agentic upgrade prompts', () => { await handoffUpgrade('Upgrade prompt', '/workspace/app') - expect(cliSelect).toHaveBeenCalledTimes(2) + expect(cliSelect).toHaveBeenCalledTimes(3) if (cause === null) { expect(Log.warn).toHaveBeenCalledWith(warning) } else { @@ -700,7 +733,7 @@ describe('agentic upgrade prompts', () => { } expect(crossSpawn).toHaveBeenCalledWith( expectedHarnessPath('codex'), - ['Upgrade prompt'], + ['--approve-for-me', 'Upgrade prompt'], { cwd: '/workspace/app', stdio: 'inherit' } ) } @@ -721,7 +754,181 @@ describe('agentic upgrade prompts', () => { ).rejects.toMatchObject({ cause }) }) - it('keeps the existing agent in its session', async () => { + it.each([ + ['codex', 'yes', ['--approve-for-me']], + [ + 'codex', + 'no', + ['--sandbox', 'workspace-write', '--ask-for-approval', 'on-request'], + ], + ['claude', 'yes', ['--permission-mode', 'auto']], + ['claude', 'no', ['--permission-mode', 'manual']], + ])('passes %s %s permission flags', async (agent, useAuto, flags) => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: agent } as never) + .mockResolvedValueOnce({ + id: agent === 'codex' ? 'gpt-5.6-terra' : 'opus', + } as never) + .mockResolvedValueOnce({ id: 'high' } as never) + .mockResolvedValueOnce({ id: useAuto } as never) + .mockResolvedValueOnce({ id: 'no' } as never) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath(agent), + [ + '--model', + agent === 'codex' ? 'gpt-5.6-terra' : 'opus', + ...(agent === 'codex' + ? ['-c', 'model_reasoning_effort=high'] + : ['--effort', 'high']), + ...flags, + 'Upgrade prompt', + ], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + }) + + it('defaults to approval requests when the Codex CLI lacks Auto review', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + crossSpawn.sync.mockImplementation((_path, args) => { + if (args[0] === 'debug') { + return { + status: 0, + stdout: JSON.stringify({ models: [{ slug: 'gpt-5.6-terra' }] }), + } + } + return { status: 0, stdout: ' --ask-for-approval ' } + }) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' } as never) + .mockResolvedValueOnce({ id: 'gpt-5.6-terra' } as never) + .mockResolvedValueOnce({ id: 'high' } as never) + .mockResolvedValueOnce({ id: 'no' } as never) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect(crossSpawn.sync).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + ['--help'], + expect.objectContaining({ encoding: 'utf8' }) + ) + expect(jest.mocked(cliSelect).mock.calls[3][0].values).toEqual({ + yes: 'Yes', + no: 'No', + }) + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + [ + '--model', + 'gpt-5.6-terra', + '-c', + 'model_reasoning_effort=high', + '--sandbox', + 'workspace-write', + '--ask-for-approval', + 'on-request', + 'Upgrade prompt', + ], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + }) + + it('uses explicit approval mode when the Claude CLI lacks Auto mode', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + crossSpawn.sync.mockReturnValue({ + status: 0, + stdout: + ' --permission-mode Permission mode to use for the session\n (choices: "default", "acceptEdits", "plan", "dontAsk", "bypassPermissions")', + }) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'claude' } as never) + .mockResolvedValueOnce({ id: 'opus' } as never) + .mockResolvedValueOnce({ id: 'high' } as never) + .mockResolvedValueOnce({ id: 'no' } as never) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect(crossSpawn.sync).toHaveBeenCalledWith( + expectedHarnessPath('claude'), + ['--help'], + expect.objectContaining({ encoding: 'utf8' }) + ) + expect(jest.mocked(cliSelect).mock.calls[3][0].values).toEqual({ + yes: 'Yes', + no: 'No', + }) + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('claude'), + [ + '--model', + 'opus', + '--effort', + 'high', + '--permission-mode', + 'default', + 'Upgrade prompt', + ], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + }) + + it('cancels the handoff when permission selection is cancelled', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' } as never) + .mockResolvedValueOnce({ id: 'gpt-5.6-terra' } as never) + .mockResolvedValueOnce({ id: 'high' } as never) + .mockResolvedValueOnce({ id: 'cancel' } as never) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect(process.exitCode).toBe(1) + expect(crossSpawn).not.toHaveBeenCalled() + }) + + it('uses the existing agent settings without prompting interactively', async () => { const prompt = jest.fn(() => 'Prepared upgrade prompt.') await handoffUpgrade(prompt, '/workspace/app') @@ -739,9 +946,14 @@ describe('agentic upgrade prompts', () => { jest.mocked(getAgentName).mockResolvedValue(null) jest.mocked(access).mockResolvedValue(undefined) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) - crossSpawn.sync.mockReturnValue({ - status: 0, - stdout: JSON.stringify({ models: [{ slug: 'gpt-5.6-terra' }] }), + crossSpawn.sync.mockImplementation((_path, args) => { + if (args[0] === 'debug') { + return { + status: 0, + stdout: JSON.stringify({ models: [{ slug: 'gpt-5.6-terra' }] }), + } + } + return { status: 0, stdout: ' --approve-for-me' } }) jest .mocked(cliSelect) @@ -749,6 +961,7 @@ describe('agentic upgrade prompts', () => { .mockResolvedValueOnce({ id: 'gpt-5.6-terra' } as never) .mockResolvedValueOnce({ id: 'high' } as never) .mockResolvedValueOnce({ id: 'yes' } as never) + .mockResolvedValueOnce({ id: 'yes' } as never) crossSpawn.mockImplementation(() => { const child = new EventEmitter() process.nextTick(() => child.emit('close', 0, null)) @@ -766,6 +979,7 @@ describe('agentic upgrade prompts', () => { 'gpt-5.6-terra', '-c', 'model_reasoning_effort=high', + '--approve-for-me', 'Worktree prompt', ], { cwd: '/workspace/app', stdio: 'inherit' } From 50199e6bce6275e231571bbbb9294b46bf9311f1 Mon Sep 17 00:00:00 2001 From: Jiwon Choi Date: Mon, 28 Sep 2026 11:10:55 +0900 Subject: [PATCH 7/7] [ai-upgrade] ESC to move back during prompt (#99319) Stacked on #99291. ### Why? Let users revisit upgrade choices before the new agent starts. ### How? Use the existing CLI selector with a dim hint above each menu. Esc goes back to the previous choice, or cancels from the first prompt; Ctrl+C cancels from any prompt. Remove the Cancel rows. --- packages/next/src/lib/upgrade/harness.ts | 390 ++++++++++++---------- test/unit/agentic-upgrade-prompts.test.ts | 225 +++++++++++-- 2 files changed, 419 insertions(+), 196 deletions(-) diff --git a/packages/next/src/lib/upgrade/harness.ts b/packages/next/src/lib/upgrade/harness.ts index c26e496a0a2c..90d412811dea 100644 --- a/packages/next/src/lib/upgrade/harness.ts +++ b/packages/next/src/lib/upgrade/harness.ts @@ -1,6 +1,7 @@ import { constants } from 'fs' import { access, stat } from 'fs/promises' import { delimiter, resolve } from 'path' +import type { Key } from 'readline' import cliSelect from 'next/dist/compiled/cli-select' import spawn from 'next/dist/compiled/cross-spawn' @@ -96,15 +97,25 @@ function resolvePrompt( async function chooseOption( question: string, values: Record, - defaultValue: number -): Promise { + defaultValue: number, + firstPrompt = false +): Promise { Log.bootstrap('') Log.bootstrap(` ${question}`) - Log.bootstrap(` ${dim('Use ↑/↓ to choose, then press Enter.')}\n`) + Log.bootstrap( + ` ${dim(`Use ↑/↓ to choose, Enter to confirm, or Esc to ${firstPrompt ? 'cancel' : 'go back'}.`)}\n` + ) + let interrupted = false + const onKeypress = (_text: string, key: Key) => { + if (key.ctrl && key.name === 'c') { + interrupted = true + } + } + process.stdin.on('keypress', onKeypress) try { const { id } = await cliSelect({ - values: { ...values, cancel: 'Cancel' }, + values, defaultValue, selected: cyan('❯'), unselected: ' ', @@ -112,25 +123,33 @@ async function chooseOption( valueRenderer: (value: string, selected: boolean) => selected ? cyan(bold(value)) : value, }) - return typeof id === 'string' && id !== 'cancel' ? id : undefined + return typeof id === 'string' ? id : undefined } catch (error) { - if (error) { + if (error !== undefined) { throw error } - return undefined + return interrupted ? null : undefined + } finally { + process.stdin.removeListener('keypress', onKeypress) } } -async function chooseWorktree(): Promise { - Log.bootstrap(' Open the upgrade in a separate Git worktree?') - const { id } = await cliSelect({ - values: { yes: 'Yes', no: 'No' }, - defaultValue: 0, - selected: cyan('❯'), - unselected: ' ', - indentation: 2, - }) - return id === 'yes' +async function chooseWorktree(): Promise { + const choice = await chooseOption( + 'Open the upgrade in a separate Git worktree?', + { yes: 'Yes', no: 'No' }, + 0 + ) + if (choice === null || choice === undefined) { + return choice + } + if (choice === 'yes') { + return true + } + if (choice === 'no') { + return false + } + throw new Error(`Unknown worktree choice: ${choice}`) } function getHarnessDisplayName(name: UpgradeHarness['name']): string { @@ -222,46 +241,32 @@ async function findHarnesses(): Promise { } async function chooseHarness( - harnesses: UpgradeHarness[] + harnesses: UpgradeHarness[], + previousName: UpgradeHarness['name'] | undefined ): Promise { const question = harnesses.length === 1 ? `${getHarnessDisplayName(harnesses[0].name)} detected. Would you like to proceed?` : 'Multiple coding agents detected. Which one would you like to use?' - Log.bootstrap('') - Log.bootstrap(` ${question}`) - Log.bootstrap(` ${dim('Use ↑/↓ to choose, then press Enter.')}\n`) - - try { - const { id } = await cliSelect({ - values: { - ...Object.fromEntries( - harnesses.map(({ name }) => [ - name, - `Continue with ${getHarnessDisplayName(name)}`, - ]) - ), - copy: 'Copy prompt for another coding agent', - cancel: 'Cancel', - }, - // cli-select indexes rows numerically, even when values is an object. - defaultValue: 0, - selected: cyan('❯'), - unselected: ' ', - indentation: 2, - valueRenderer: (value: string, selected: boolean) => - selected ? cyan(bold(value)) : value, - }) - return id === 'copy' ? 'copy' : harnesses.find(({ name }) => name === id) - } catch (error) { - // cli-select rejects without an error when Escape or Ctrl+C cancels the menu. - if (error) { - throw error - } - - return undefined - } + const id = await chooseOption( + question, + { + ...Object.fromEntries( + harnesses.map(({ name }) => [ + name, + `Continue with ${getHarnessDisplayName(name)}`, + ]) + ), + copy: 'Copy prompt for another coding agent', + }, + Math.max( + 0, + harnesses.findIndex(({ name }) => name === previousName) + ), + true + ) + return id === 'copy' ? 'copy' : harnesses.find(({ name }) => name === id) } function copyUpgradePrompt(prompt: string, noHarness = false): void { @@ -356,129 +361,170 @@ export async function handoffUpgrade( return } - // Let the selected agent take over the terminal with the chosen permissions. - const harness = await chooseHarness(installed) - - if (harness === 'copy') { - copyUpgradePrompt(resolvePrompt(prompt, null)) - return - } - - if (!harness) { - Log.bootstrap(` ${dim('Upgrade cancelled.')}\n`) - process.exitCode = 1 - return - } - - const models = - harness.name === 'codex' - ? getCodexModels(harness.path) - : UPGRADE_MODELS.claude - if (models.length === 0 && harness.name !== 'codex') { - Log.error('No supported models were found for the selected coding agent.') - process.exitCode = 1 - return - } - let model: (typeof models)[number] | undefined - let effort = 'default' - if (models.length === 0) { - Log.warn('Could not verify Codex models; using the CLI defaults.') - } else { - const modelId = await chooseOption( - `Which ${getHarnessDisplayName(harness.name)} model should run the upgrade?`, - Object.fromEntries(models.map(({ id, label }) => [id, label])), - 0 - ) - model = models.find(({ id }) => id === modelId) - if (!model) { - Log.bootstrap(` ${dim('Upgrade cancelled.')}\n`) - process.exitCode = 1 - return - } - - const selectedEffort = await chooseOption( - 'Which reasoning effort should the upgrade use?', - { - default: 'Model default', - ...Object.fromEntries(model.efforts.map((value) => [value, value])), - }, - 0 - ) - if ( - !selectedEffort || - (selectedEffort !== 'default' && - !model.efforts.some((value) => value === selectedEffort)) - ) { - Log.bootstrap(` ${dim('Upgrade cancelled.')}\n`) - process.exitCode = 1 - return - } - effort = selectedEffort - } - let autoPermissionArgs: string[] | null - let approvalPermissionArgs: string[] - if (harness.name === 'codex') { - autoPermissionArgs = supportsCodexAutoReview(harness.path) - ? ['--approve-for-me'] - : null - approvalPermissionArgs = [...CODEX_APPROVAL_ARGS] - } else { - const { auto, approvalMode } = getClaudePermissionSupport(harness.path) - if (!approvalMode) { - Log.error('Could not determine a supported Claude approval mode.') - process.exitCode = 1 - return - } - autoPermissionArgs = auto ? ['--permission-mode', 'auto'] : null - approvalPermissionArgs = ['--permission-mode', approvalMode] - } - - let permissionArgs = approvalPermissionArgs - if (autoPermissionArgs) { - const useAuto = await chooseOption( - `Use Auto permission mode for ${getHarnessDisplayName(harness.name)}?`, - { yes: 'Yes', no: 'No, ask for approval' }, - 0 - ) - if (useAuto !== 'yes' && useAuto !== 'no') { - Log.bootstrap(` ${dim('Upgrade cancelled.')}\n`) - process.exitCode = 1 + let stage: 'harness' | 'model' | 'effort' | 'permission' | 'worktree' = + 'harness' + let harness: UpgradeHarness | undefined + let model: { id: string; efforts: readonly string[] } | undefined + let effort: string | undefined + let autoPermissionArgs: string[] | null = null + let approvalPermissionArgs: string[] = [] + let permissionArgs: string[] = [] + let useAuto = true + let useWorktree = true + let codexModels: ReturnType | undefined + let codexAutoReview: boolean | undefined + let claudePermissionSupport: + | ReturnType + | undefined + + while (true) { + if (stage === 'harness') { + const choice = await chooseHarness(installed, harness?.name) + if (choice === 'copy') { + copyUpgradePrompt(resolvePrompt(prompt, null)) + return + } + if (!choice) { + break + } + harness = choice + stage = 'model' + } else if (stage === 'model') { + const models = + harness!.name === 'codex' + ? (codexModels ??= getCodexModels(harness!.path)) + : UPGRADE_MODELS.claude + if (models.length === 0 && harness!.name === 'codex') { + Log.warn('Could not verify Codex models; using the CLI defaults.') + model = undefined + effort = 'default' + stage = 'effort' + continue + } + if (models.length === 0) { + Log.error( + 'No supported models were found for the selected coding agent.' + ) + process.exitCode = 1 + return + } + const previousModelId = model?.id + const modelId = await chooseOption( + `Which ${getHarnessDisplayName(harness!.name)} model should run the upgrade?`, + Object.fromEntries(models.map(({ id, label }) => [id, label])), + Math.max( + 0, + models.findIndex(({ id }) => id === previousModelId) + ) + ) + if (modelId === null) { + break + } + if (modelId === undefined) { + stage = 'harness' + continue + } + model = models.find(({ id }) => id === modelId) + if (!model) { + throw new Error(`Unknown upgrade model: ${modelId}`) + } + stage = 'effort' + } else if (stage === 'effort') { + if (model) { + const efforts = ['default', ...model.efforts] + const previousEffortIndex = efforts.indexOf(effort ?? 'default') + const selectedEffort = await chooseOption( + 'Which reasoning effort should the upgrade use?', + Object.fromEntries( + efforts.map((value) => [ + value, + value === 'default' ? 'Model default' : value, + ]) + ), + Math.max(0, previousEffortIndex) + ) + if (selectedEffort === null) { + break + } + if (selectedEffort === undefined) { + stage = 'model' + continue + } + if (!efforts.includes(selectedEffort)) { + throw new Error(`Unknown upgrade effort: ${selectedEffort}`) + } + effort = selectedEffort + } + if (harness!.name === 'codex') { + codexAutoReview ??= supportsCodexAutoReview(harness!.path) + autoPermissionArgs = codexAutoReview ? ['--approve-for-me'] : null + approvalPermissionArgs = [...CODEX_APPROVAL_ARGS] + } else { + const { auto, approvalMode } = (claudePermissionSupport ??= + getClaudePermissionSupport(harness!.path)) + if (!approvalMode) { + Log.error('Could not determine a supported Claude approval mode.') + process.exitCode = 1 + return + } + autoPermissionArgs = auto ? ['--permission-mode', 'auto'] : null + approvalPermissionArgs = ['--permission-mode', approvalMode] + } + if (autoPermissionArgs) { + stage = 'permission' + } else { + Log.info( + dim('Auto permission mode is unavailable; using approval requests.') + ) + permissionArgs = approvalPermissionArgs + stage = 'worktree' + } + } else if (stage === 'permission') { + const permissionChoice = await chooseOption( + `Use Auto permission mode for ${getHarnessDisplayName(harness!.name)}?`, + { yes: 'Yes', no: 'No, ask for approval' }, + useAuto ? 0 : 1 + ) + if (permissionChoice === null) { + break + } + if (permissionChoice === undefined) { + stage = model ? 'effort' : 'harness' + continue + } + useAuto = permissionChoice === 'yes' + permissionArgs = useAuto ? autoPermissionArgs! : approvalPermissionArgs + stage = 'worktree' + } else { + const choice = await chooseWorktree() + if (choice === null) { + break + } + if (choice === undefined) { + stage = autoPermissionArgs ? 'permission' : model ? 'effort' : 'harness' + continue + } + useWorktree = choice + Log.bootstrap( + ` Continuing with ${cyan(bold(getHarnessDisplayName(harness!.name)))}...\n` + ) + try { + process.exitCode = await launchHarness( + harness!, + resolvePrompt(prompt, useWorktree), + directory, + model?.id ?? null, + effort!, + permissionArgs + ) + } catch { + Log.error(`Could not start ${getHarnessDisplayName(harness!.name)}.`) + process.exitCode = 1 + } return } - if (useAuto === 'yes') { - permissionArgs = autoPermissionArgs - } - } else { - Log.info( - dim('Auto permission mode is unavailable; using approval requests.') - ) - } - - let useWorktree: boolean - try { - useWorktree = await chooseWorktree() - } catch (error) { - if (error) { - throw error - } - process.exitCode = 1 - return } - Log.bootstrap( - ` Continuing with ${cyan(bold(getHarnessDisplayName(harness.name)))}...\n` - ) - try { - process.exitCode = await launchHarness( - harness, - resolvePrompt(prompt, useWorktree), - directory, - model?.id ?? null, - effort, - permissionArgs - ) - } catch { - Log.error(`Could not start ${getHarnessDisplayName(harness.name)}.`) - process.exitCode = 1 - } + Log.bootstrap(` ${dim('Upgrade cancelled.')}\n`) + process.exitCode = 1 } diff --git a/test/unit/agentic-upgrade-prompts.test.ts b/test/unit/agentic-upgrade-prompts.test.ts index c26fd1667458..1f728ee3bbf4 100644 --- a/test/unit/agentic-upgrade-prompts.test.ts +++ b/test/unit/agentic-upgrade-prompts.test.ts @@ -388,7 +388,7 @@ describe('agentic upgrade prompts', () => { jest.mocked(getAgentName).mockResolvedValue(null) jest.mocked(access).mockResolvedValue(undefined) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) - jest.mocked(cliSelect).mockResolvedValue({ id: 'cancel' } as never) + jest.mocked(cliSelect).mockRejectedValue(undefined) await handoffUpgrade('Prepared upgrade prompt.', '/workspace/app') @@ -423,10 +423,6 @@ describe('agentic upgrade prompts', () => { "copy", "Copy prompt for another coding agent", ], - [ - "cancel", - "Cancel", - ], ], }, "progress": [ @@ -442,7 +438,7 @@ describe('agentic upgrade prompts', () => { " Multiple coding agents detected. Which one would you like to use?", ], [ - " Use ↑/↓ to choose, then press Enter. + " Use ↑/↓ to choose, Enter to confirm, or Esc to cancel. ", ], [ @@ -465,7 +461,7 @@ describe('agentic upgrade prompts', () => { throw Object.assign(new Error('not found'), { code: 'ENOENT' }) }) jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) - jest.mocked(cliSelect).mockResolvedValue({ id: 'cancel' } as never) + jest.mocked(cliSelect).mockRejectedValue(undefined) await handoffUpgrade('Prepared upgrade prompt.', '/workspace/app') @@ -547,36 +543,24 @@ describe('agentic upgrade prompts', () => { 'gpt-5.6-terra': 'GPT-5.6-Terra', 'gpt-5.6-sol': 'GPT-5.6-Sol', 'gpt-6-astra': 'GPT-6-Astra', - cancel: 'Cancel', } : { 'claude-sonnet-5[1m]': 'Claude Sonnet 5 (1M)', opus: 'Claude Opus (latest)', fable: 'Claude Fable (latest)', - cancel: 'Cancel', } ) const effortMenu = jest.mocked(cliSelect).mock.calls[2][0] expect(Object.keys(effortMenu.values)).toEqual( agent === 'claude' - ? ['default', 'low', 'medium', 'high', 'max', 'cancel'] - : [ - 'default', - 'low', - 'medium', - 'high', - 'xhigh', - 'max', - 'ultra', - 'cancel', - ] + ? ['default', 'low', 'medium', 'high', 'max'] + : ['default', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] ) expect(effortMenu.defaultValue).toBe(0) const permissionMenu = jest.mocked(cliSelect).mock.calls[3][0] expect(permissionMenu.values).toEqual({ yes: 'Yes', no: 'No, ask for approval', - cancel: 'Cancel', }) expect(permissionMenu.defaultValue).toBe(0) expect(jest.mocked(cliSelect).mock.calls[4][0].values).toEqual({ @@ -664,7 +648,6 @@ describe('agentic upgrade prompts', () => { expect(jest.mocked(cliSelect).mock.calls[1][0].values).toEqual({ 'gpt-5.6-terra': 'GPT-5.6-Terra', 'gpt-5.6-sol': 'GPT-5.6-Sol', - cancel: 'Cancel', }) expect(crossSpawn.sync).toHaveBeenCalledWith( expectedHarnessPath('codex'), @@ -908,7 +891,7 @@ describe('agentic upgrade prompts', () => { ) }) - it('cancels the handoff when permission selection is cancelled', async () => { + it('cancels the handoff when Ctrl+C is pressed at permission selection', async () => { process.env.PATH = '/agents' overrideTTY(process.stdin) overrideTTY(process.stdout) @@ -920,7 +903,10 @@ describe('agentic upgrade prompts', () => { .mockResolvedValueOnce({ id: 'codex' } as never) .mockResolvedValueOnce({ id: 'gpt-5.6-terra' } as never) .mockResolvedValueOnce({ id: 'high' } as never) - .mockResolvedValueOnce({ id: 'cancel' } as never) + .mockImplementationOnce(() => { + process.stdin.emit('keypress', '\u0003', { name: 'c', ctrl: true }) + return Promise.reject(undefined) + }) await handoffUpgrade('Upgrade prompt', '/workspace/app') @@ -928,6 +914,197 @@ describe('agentic upgrade prompts', () => { expect(crossSpawn).not.toHaveBeenCalled() }) + it('goes back through worktree, permission, effort, and model before launching', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' }) + .mockResolvedValueOnce({ id: 'gpt-5.6-terra' }) + .mockResolvedValueOnce({ id: 'high' }) + .mockResolvedValueOnce({ id: 'yes' }) + .mockRejectedValueOnce(undefined) + .mockResolvedValueOnce({ id: 'no' }) + .mockRejectedValueOnce(undefined) + .mockRejectedValueOnce(undefined) + .mockRejectedValueOnce(undefined) + .mockResolvedValueOnce({ id: 'gpt-6-astra' }) + .mockResolvedValueOnce({ id: 'ultra' }) + .mockResolvedValueOnce({ id: 'yes' }) + .mockResolvedValueOnce({ id: 'no' }) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect( + crossSpawn.sync.mock.calls.filter(([, args]) => args[0] === 'debug') + ).toHaveLength(1) + expect( + crossSpawn.sync.mock.calls.filter(([, args]) => args[0] === '--help') + ).toHaveLength(1) + expect(jest.mocked(cliSelect).mock.calls[7][0].defaultValue).toBe(1) + expect(jest.mocked(cliSelect).mock.calls[9][0].defaultValue).toBe(0) + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + [ + '--model', + 'gpt-6-astra', + '-c', + 'model_reasoning_effort=ultra', + '--approve-for-me', + 'Upgrade prompt', + ], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + }) + + it('defaults to the selected model when the previous effort is unavailable', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' }) + .mockResolvedValueOnce({ id: 'gpt-5.6-terra' }) + .mockResolvedValueOnce({ id: 'ultra' }) + .mockRejectedValueOnce(undefined) + .mockRejectedValueOnce(undefined) + .mockRejectedValueOnce(undefined) + .mockResolvedValueOnce({ id: 'claude' }) + .mockResolvedValueOnce({ id: 'opus' }) + .mockResolvedValueOnce({ id: 'default' }) + .mockResolvedValueOnce({ id: 'yes' }) + .mockResolvedValueOnce({ id: 'no' }) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect(jest.mocked(cliSelect).mock.calls[8][0].defaultValue).toBe(0) + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('claude'), + ['--model', 'opus', '--permission-mode', 'auto', 'Upgrade prompt'], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + }) + + it('reuses Claude permission support after going back', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'claude' }) + .mockResolvedValueOnce({ id: 'opus' }) + .mockResolvedValueOnce({ id: 'high' }) + .mockRejectedValueOnce(undefined) + .mockResolvedValueOnce({ id: 'medium' }) + .mockResolvedValueOnce({ id: 'yes' }) + .mockResolvedValueOnce({ id: 'no' }) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect( + crossSpawn.sync.mock.calls.filter(([, args]) => args[0] === '--help') + ).toHaveLength(1) + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('claude'), + [ + '--model', + 'opus', + '--effort', + 'medium', + '--permission-mode', + 'auto', + 'Upgrade prompt', + ], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + }) + + it('returns from worktree to effort when Auto mode is unavailable', async () => { + process.env.PATH = '/agents' + overrideTTY(process.stdin) + overrideTTY(process.stdout) + jest.mocked(getAgentName).mockResolvedValue(null) + jest.mocked(access).mockResolvedValue(undefined) + jest.mocked(stat).mockResolvedValue({ isFile: () => true } as never) + crossSpawn.sync.mockImplementation((_path, args) => { + if (args[0] === 'debug') { + return { + status: 0, + stdout: JSON.stringify({ models: [{ slug: 'gpt-5.6-terra' }] }), + } + } + return { status: 0, stdout: ' --ask-for-approval ' } + }) + jest + .mocked(cliSelect) + .mockResolvedValueOnce({ id: 'codex' }) + .mockResolvedValueOnce({ id: 'gpt-5.6-terra' }) + .mockResolvedValueOnce({ id: 'high' }) + .mockRejectedValueOnce(undefined) + .mockResolvedValueOnce({ id: 'max' }) + .mockResolvedValueOnce({ id: 'no' }) + crossSpawn.mockImplementation(() => { + const child = new EventEmitter() + process.nextTick(() => child.emit('close', 0, null)) + return child + }) + + await handoffUpgrade('Upgrade prompt', '/workspace/app') + + expect( + crossSpawn.sync.mock.calls.filter(([, args]) => args[0] === '--help') + ).toHaveLength(1) + expect(jest.mocked(cliSelect).mock.calls[4][0].values).toEqual({ + default: 'Model default', + low: 'low', + medium: 'medium', + high: 'high', + xhigh: 'xhigh', + max: 'max', + ultra: 'ultra', + }) + expect(crossSpawn).toHaveBeenCalledWith( + expectedHarnessPath('codex'), + [ + '--model', + 'gpt-5.6-terra', + '-c', + 'model_reasoning_effort=max', + '--sandbox', + 'workspace-write', + '--ask-for-approval', + 'on-request', + 'Upgrade prompt', + ], + { cwd: '/workspace/app', stdio: 'inherit' } + ) + }) + it('uses the existing agent settings without prompting interactively', async () => { const prompt = jest.fn(() => 'Prepared upgrade prompt.')