Unverified Commit 50e90fb7 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Enable agent upgrade reminders by default (#99311)

### Why?

Enable agent upgrade reminders by default and give the experimental
Future Defaults policy a clear name.

### How?

Rename `experimental.agenticAutoUpgrade` to `experimental.agentUpgrade`
across config, runtime, docs, tests, and evals. Default it to `true`,
which normalizes to the `security` policy while preserving explicit
policies and `false`. Rename the `future` policy value to
`experimental-future`, reuse the development advisory assessment, and
preserve CI agent reminders.

<!-- NEXT_JS_LLM -->

Closes NAR-940
parent 3854a984
......@@ -18,7 +18,7 @@ Stable, RC, beta, and numbered preview installations use the stable `latest`
dist-tag when it is newer than the installed version.
Security upgrades and advisory checks are supported only for stable installations.
Canary installations support `latest` and `future` without advisory assessment.
Canary installations support `latest` and `experimental-future` without advisory assessment.
## 1. Make a checklist
......@@ -43,7 +43,7 @@ Canary installations support `latest` and `future` without advisory assessment.
- [ ] Complete the codemod's manual steps, resolve its review markers, and
complete every applicable migration item. Keep only changes required by
the final target.
- [ ] Set `experimental.agenticAutoUpgrade` to the policy specified in the
- [ ] Set `experimental.agentUpgrade` to the policy specified in the
prompt, preserving unrelated configuration. If the target Next.js version
does not support this option, skip the setting and report why.
......
......@@ -10,7 +10,7 @@ installed and target Next.js versions differ, complete the version guide first.
## Adopt and verify
- [ ] Set `experimental.agenticAutoUpgrade` to the policy specified in the
- [ ] Set `experimental.agentUpgrade` to the policy specified in the
prompt, preserving unrelated configuration. If the installed Next.js
version does not support this option, skip the setting and report why.
- [ ] Read and follow each adoption document in the prompt, in order. If none
......
......@@ -26,7 +26,7 @@ test('leaves the Future policy and installed version unchanged', () => {
const config = readFileSync('next.config.js', 'utf8')
expect(manifest.dependencies.next).toBe('16.3.5')
expect(config).toMatch(/agenticAutoUpgrade\s*:\s*['"]future['"]/)
expect(config).toMatch(/agentUpgrade\s*:\s*['"]experimental-future['"]/)
})
test('mentions the Next.js Future Defaults notification', async () => {
......
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
agenticAutoUpgrade: 'future',
agentUpgrade: 'experimental-future',
},
}
......
Run `next upgrade --ai future` for this app and complete the upgrade.
Run `next upgrade --ai experimental-future` for this app and complete the upgrade.
Run `next upgrade --ai future` for this app and complete the upgrade.
Run `next upgrade --ai experimental-future` for this app and complete the upgrade.
......@@ -25,7 +25,7 @@ test('leaves the latest policy and installed version unchanged', () => {
const config = readFileSync('next.config.ts', 'utf8')
expect(manifest.dependencies.next).toBe('15.5.9')
expect(config).toMatch(/agenticAutoUpgrade\s*:\s*['"]latest['"]/)
expect(config).toMatch(/agentUpgrade\s*:\s*['"]latest['"]/)
})
test('mentions the latest Next.js notification', async () => {
......
......@@ -3,7 +3,7 @@ const nextConfig = {
// supplies the agent rules after preparing this fixture.
agentRules: false,
experimental: {
agenticAutoUpgrade: 'latest' as const,
agentUpgrade: 'latest' as const,
},
}
......
......@@ -30,7 +30,7 @@ test('leaves the security policy and installed version unchanged', () => {
const config = readFileSync('next.config.ts', 'utf8')
expect(manifest.dependencies.next).toBe('15.5.23')
expect(config).toMatch(/agenticAutoUpgrade\s*:\s*['"]security['"]/)
expect(config).toMatch(/agentUpgrade\s*:\s*['"]security['"]/)
})
test('mentions the Next.js security notification', async () => {
......
......@@ -3,7 +3,7 @@ const nextConfig = {
// supplies the agent rules after preparing this fixture.
agentRules: false,
experimental: {
agenticAutoUpgrade: 'security' as const,
agentUpgrade: 'security' as const,
},
}
......
......@@ -587,7 +587,7 @@ program
.addOption(
new Option(
'--ai, --experimental-ai [type]',
'Upgrade with AI to security, latest, or future. Defaults to security.'
'Upgrade with AI to security, latest, or experimental-future. Defaults to security.'
).conflicts('revision')
)
.action(async (directory, options) => {
......
......@@ -1165,10 +1165,11 @@ export default async function build(
// Reuse the loaded config; ordinary builds do not load upgrade tooling.
if (
config.experimental.agenticAutoUpgrade === 'security' ||
config.experimental.agenticAutoUpgrade === 'latest' ||
config.experimental.agenticAutoUpgrade === 'future' ||
process.env.__NEXT_AGENTIC_AUTO_UPGRADE
config.experimental.agentUpgrade === true ||
config.experimental.agentUpgrade === 'security' ||
config.experimental.agentUpgrade === 'latest' ||
config.experimental.agentUpgrade === 'experimental-future' ||
process.env.__NEXT_AGENT_UPGRADE
) {
const { nudgeUpgrade, getUpgradeContext } =
require('../lib/upgrade/nudge') as typeof import('../lib/upgrade/nudge')
......@@ -1184,11 +1185,8 @@ export default async function build(
).catch((error) => {
Log.warn(`Could not offer the upgrade: ${String(error)}`)
})
if (
action === 'update' &&
upgradeContext.experimental.agenticAutoUpgrade
) {
return upgradeContext.experimental.agenticAutoUpgrade
if (action === 'update' && upgradeContext.experimental.agentUpgrade) {
return upgradeContext.experimental.agentUpgrade
}
if (action === 'interrupt') {
return 'interrupt' as const
......
......@@ -254,7 +254,12 @@ const nextDev = async (
'../lib/upgrade/nudge.js'
)
const humanUpgrade = await shouldPromptForUpgrade()
async function offerUpgrade(worker: ChildProcess, context: UpgradeContext) {
const allowedUpgradeRetries = new Set<string>()
async function offerUpgrade(
worker: ChildProcess,
context: UpgradeContext,
initialAssessment: Parameters<typeof nudgeUpgrade>[4]
) {
process.on('SIGHUP', onHangup)
upgradeOffered = true
upgradeInProgress = true
......@@ -262,7 +267,13 @@ const nextDev = async (
upgradeController = controller
let action
try {
action = await nudgeUpgrade(dir, context, 'dev', controller.signal)
action = await nudgeUpgrade(
dir,
context,
'dev',
controller.signal,
initialAssessment
)
} catch (error) {
Log.warn(`Could not offer the upgrade: ${String(error)}`)
} finally {
......@@ -277,7 +288,7 @@ const nextDev = async (
onInterrupt()
return
}
if (action === 'update' && context.experimental.agenticAutoUpgrade) {
if (action === 'update' && context.experimental.agentUpgrade) {
await handleSessionStop('SIGTERM', false)
if (interruption) {
process.exit(128 + os.constants.signals[interruption])
......@@ -285,9 +296,7 @@ const nextDev = async (
process.off('SIGINT', onInterrupt)
process.off('SIGTERM', onTerminate)
process.off('SIGHUP', onHangup)
process.exit(
await runUpgrade(dir, context.experimental.agenticAutoUpgrade)
)
process.exit(await runUpgrade(dir, context.experimental.agentUpgrade))
}
upgradeInProgress = false
process.off('SIGHUP', onHangup)
......@@ -486,6 +495,9 @@ const nextDev = async (
NEXT_PRIVATE_WORKER: '1',
NEXT_PRIVATE_UPGRADE_PROMPT:
humanUpgrade && !upgradeOffered ? '1' : undefined,
NEXT_PRIVATE_ALLOWED_UPGRADE_RETRIES: Array.from(
allowedUpgradeRetries
).join(','),
NEXT_PRIVATE_TRACE_ID: traceId,
NEXT_PRIVATE_ENABLED_FEATURES: JSON.stringify(enabledFeatures),
NEXT_PRIVATE_DEV_SPAN_ATTRS: JSON.stringify(devSpanAttrs),
......@@ -514,9 +526,19 @@ const nextDev = async (
child.on('message', (msg: any) => {
if (msg && typeof msg === 'object') {
if (msg.nextUpgradeContext) {
distDir = msg.nextUpgradeContext.distDir
void offerUpgrade(child!, msg.nextUpgradeContext).catch(
if (
typeof msg.nextUpgradeRetryAllowed === 'string' &&
/^[a-f0-9]{64}$/.test(msg.nextUpgradeRetryAllowed)
) {
allowedUpgradeRetries.add(msg.nextUpgradeRetryAllowed)
} else if (msg.nextUpgradeContext) {
const context = msg.nextUpgradeContext as UpgradeContext
distDir = context.distDir
const initialAssessment =
msg.nextUpgradeAssessment !== undefined
? Promise.resolve(msg.nextUpgradeAssessment)
: null
void offerUpgrade(child!, context, initialAssessment).catch(
async (error) => {
console.error(error)
await handleSessionStop('SIGTERM', false)
......
......@@ -137,11 +137,16 @@ async function resolveAIUpgradeType(
PHASE_PRODUCTION_BUILD,
interopDefault(rawConfig)
)
const policy = config.experimental?.agenticAutoUpgrade
return policy === 'security' || policy === 'latest' || policy === 'future'
? policy
: 'security'
const policy = config.experimental?.agentUpgrade
if (
policy === 'security' ||
policy === 'latest' ||
policy === 'experimental-future'
) {
return policy
}
return 'security'
}
async function resolveCanaryVersion(): Promise<string> {
......@@ -234,10 +239,10 @@ export async function spawnNextUpgrade(
if (
upgradeType !== 'security' &&
upgradeType !== 'latest' &&
upgradeType !== 'future'
upgradeType !== 'experimental-future'
) {
throw new Error(
`Unsupported AI upgrade type ${JSON.stringify(upgradeType)}. Expected "security", "latest", or "future".`
`Unsupported AI upgrade type ${JSON.stringify(upgradeType)}. Expected "security", "latest", or "experimental-future".`
)
}
......@@ -346,7 +351,7 @@ export async function spawnNextUpgrade(
}
}
if (upgradeType === 'future' && needsVersionUpdate) {
if (upgradeType === 'experimental-future' && needsVersionUpdate) {
await cp(
join(
bundledDocs,
......@@ -440,7 +445,7 @@ export async function spawnNextUpgrade(
)
.join('\n')
const futureDefaultsPrompt =
upgradeType === 'future'
upgradeType === 'experimental-future'
? `${needsVersionUpdate ? `After completing and verifying the version update, read and follow ${JSON.stringify(futureGuidePath)}.\n` : ''}${futureDefaultsList ? `Adopt these Future Defaults in order:\n${futureDefaultsList}\nComplete each adoption. Temporary opt-outs and TODO markers are intermediate work only; do not stop until they are removed and the adoption is fully verified.` : 'No Future Defaults are pending adoption.'}`
: ''
......@@ -456,7 +461,7 @@ ${taskSummary}
${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.
Set \`experimental.agentUpgrade\` 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.
${futureDefaultsPrompt ? `${futureDefaultsPrompt.trimStart()}\n\n` : ''}References:
${references}`
......
......@@ -19,17 +19,25 @@ type NudgeOptions = {
command: 'dev' | 'build'
}
export type NudgeKind = 'security' | 'latest' | 'future'
export type NudgeKind = 'security' | 'latest' | 'experimental-future'
function getRequestedUpgrade() {
const policy = process.env.__NEXT_AGENTIC_AUTO_UPGRADE
return policy === 'security' || policy === 'latest' || policy === 'future'
const policy = process.env.__NEXT_AGENT_UPGRADE
return policy === 'security' ||
policy === 'latest' ||
policy === 'experimental-future'
? policy
: null
}
const RETRY_TTL = 5 * 60 * 1000
const allowedRetries = new Set<string>()
const allowedRetries = new Set(
process.env.NEXT_PRIVATE_WORKER === '1'
? (process.env.NEXT_PRIVATE_ALLOWED_UPGRADE_RETRIES ?? '')
.split(',')
.filter((identity) => /^[a-f0-9]{64}$/.test(identity))
: []
)
function hasCode(error: unknown, code: string): boolean {
return (
......@@ -103,6 +111,18 @@ async function allowNudgeRetry(
issuedAt <= now &&
now - issuedAt < RETRY_TTL
) {
if (command === 'dev' && process.env.NEXT_PRIVATE_WORKER === '1') {
await new Promise<void>((complete, reject) => {
const message = { nextUpgradeRetryAllowed: identity }
process.send!(message, (error: Error | null) => {
if (error) {
reject(error)
} else {
complete()
}
})
})
}
allowedRetries.add(identity)
return true
}
......@@ -115,7 +135,7 @@ export type UpgradeContext = Pick<
NextConfigComplete,
'distDir' | 'cacheComponents'
> & {
experimental: Pick<NextConfigComplete['experimental'], 'agenticAutoUpgrade'>
experimental: { agentUpgrade: NudgeKind | false }
}
type UpgradeReminder = {
......@@ -128,7 +148,7 @@ type UpgradeReminder = {
targetVersion: string
}
| { kind: 'latest'; latestVersion: string | null; names: string[] }
| { kind: 'future'; targetVersion: string; names: string[] }
| { kind: 'experimental-future'; targetVersion: string; names: string[] }
)
export function getUpgradeContext(config: NextConfigComplete): UpgradeContext {
......@@ -136,8 +156,11 @@ export function getUpgradeContext(config: NextConfigComplete): UpgradeContext {
distDir: config.distDir,
cacheComponents: config.cacheComponents,
experimental: {
agenticAutoUpgrade:
getRequestedUpgrade() ?? config.experimental.agenticAutoUpgrade,
agentUpgrade:
getRequestedUpgrade() ??
(config.experimental.agentUpgrade === true
? 'security'
: (config.experimental.agentUpgrade ?? false)),
},
}
}
......@@ -149,8 +172,12 @@ export async function assessUpgrade(
stopBefore: NudgeKind | null = null,
forceVersionReminder: boolean = false
): Promise<UpgradeReminder | null> {
const policy = config.experimental.agenticAutoUpgrade
if (policy !== 'security' && policy !== 'latest' && policy !== 'future') {
const policy = config.experimental.agentUpgrade
if (
policy !== 'security' &&
policy !== 'latest' &&
policy !== 'experimental-future'
) {
return null
}
if (stopBefore === 'security') {
......@@ -216,7 +243,7 @@ export async function assessUpgrade(
installedVersion,
latestVersion: upgrade.targetVersion,
names:
policy === 'future'
policy === 'experimental-future'
? getPendingFutureDefaults(
directory,
config,
......@@ -226,7 +253,10 @@ export async function assessUpgrade(
}
}
if (policy !== 'future' || stopBefore === 'future') {
if (
policy !== 'experimental-future' ||
stopBefore === 'experimental-future'
) {
return null
}
const pending = getPendingFutureDefaults(directory, config, installedVersion)
......@@ -234,7 +264,7 @@ export async function assessUpgrade(
return null
}
return {
kind: 'future',
kind: 'experimental-future',
policy,
installedVersion,
targetVersion: upgrade.targetVersion,
......@@ -261,20 +291,17 @@ async function nudgeUpgradeForAgent(
recommendation = 'We recommend you upgrade Next.js.'
reference = `https://registry.npmjs.org/next/${semver.prerelease(reminder.installedVersion)?.[0] === 'canary' ? 'canary' : 'latest'}`
break
case 'future':
case 'experimental-future':
summary = `Installed Next.js ${reminder.installedVersion} includes Future Defaults available for this app:\n\n${reminder.names.map((name) => `- ${name}`).join('\n')}`
recommendation = 'We recommend you adopt these Future Defaults.'
break
}
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}'\`.`
const message = `${summary}
**${recommendation}**
This command stopped so the reminder you configured is not missed. Retry the same command to continue the original task.
This command stopped to show the upgrade recommendation. Retry the same command to continue the original task.
When you report back to the user, include this upgrade recommendation even if the retry succeeds.
......@@ -284,7 +311,7 @@ At the end of the task, ask the user once: "Would you like me to run the '${remi
${command}
\`\`\`
${reference ? `Reference: ${reference}\n\n` : ''}${note}`
${reference ? `Reference: ${reference}` : ''}`
let retryAllowed = false
try {
retryAllowed = await allowNudgeRetry(
......@@ -299,7 +326,7 @@ ${reference ? `Reference: ${reference}\n\n` : ''}${note}`
}
if (retryAllowed) {
Log.warn(
`${summary} This command is continuing after the reminder you configured.${reference ? `\nReference: ${reference}` : ''}`
`${summary} This command is continuing after the upgrade reminder.${reference ? `\nReference: ${reference}` : ''}`
)
return
}
......@@ -359,7 +386,7 @@ async function getUpgradeDismissal(
): Promise<NudgeKind | null> {
try {
const { key, preferences } = await getUpgradePreferences(directory)
for (const kind of ['security', 'latest', 'future'] as const) {
for (const kind of ['security', 'latest', 'experimental-future'] as const) {
if (preferences.get(`${key}.${kind}`) === `${version}:${policy}`) {
return kind
}
......@@ -382,7 +409,7 @@ async function nudgeUpgradeForHuman(
if (reminder.kind === 'security') {
message = `⚠ Installed Next.js version ${reminder.installedVersion} is affected by a known security vulnerability.`
message += `\n\nNext.js security version upgrade available: ${reminder.installedVersion} -> ${reminder.targetVersion}`
} else if (reminder.policy === 'future') {
} else if (reminder.policy === 'experimental-future') {
const targetVersion =
reminder.kind === 'latest'
? reminder.latestVersion
......@@ -423,8 +450,8 @@ async function nudgeUpgradeForHuman(
export async function runUpgrade(directory: string, policy: NudgeKind) {
// The agent's dev/build commands must not trigger this explicit request again.
delete process.env.__NEXT_AGENTIC_AUTO_UPGRADE
updateInitialEnv({ __NEXT_AGENTIC_AUTO_UPGRADE: undefined })
delete process.env.__NEXT_AGENT_UPGRADE
updateInitialEnv({ __NEXT_AGENT_UPGRADE: undefined })
const { spawnNextUpgrade } = await import('../../cli/next-upgrade.js')
await spawnNextUpgrade(directory, {
revision: 'latest',
......@@ -442,11 +469,16 @@ export async function nudgeUpgrade(
directory: string,
config: UpgradeContext,
command: 'dev' | 'build',
signal: AbortSignal | null = null
signal: AbortSignal | null = null,
initialAssessment: Promise<UpgradeReminder | null> | null = null
): Promise<UpgradeAction | void> {
const requested = getRequestedUpgrade()
const policy = requested ?? config.experimental.agenticAutoUpgrade
if (policy !== 'security' && policy !== 'latest' && policy !== 'future') {
const policy = requested ?? config.experimental.agentUpgrade
if (
policy !== 'security' &&
policy !== 'latest' &&
policy !== 'experimental-future'
) {
return
}
if (requested && isCI) {
......@@ -473,13 +505,15 @@ export async function nudgeUpgrade(
return
}
}
const reminder = await assessUpgrade(
directory,
{ ...config, experimental: { agenticAutoUpgrade: policy } },
installedVersion,
stopBefore,
requested !== null
)
const reminder = await (stopBefore === null && initialAssessment
? initialAssessment
: assessUpgrade(
directory,
{ ...config, experimental: { agentUpgrade: policy } },
installedVersion,
stopBefore,
requested !== null
))
if (!reminder || signal?.aborted) {
return
}
......
......@@ -27,10 +27,10 @@ export async function prepareUpgrade(
if (
targetRequest !== 'security' &&
targetRequest !== 'latest' &&
targetRequest !== 'future'
targetRequest !== 'experimental-future'
) {
throw new Error(
`Unsupported AI upgrade type ${JSON.stringify(targetRequest)}. Expected "security", "latest", or "future".`
`Unsupported AI upgrade type ${JSON.stringify(targetRequest)}. Expected "security", "latest", or "experimental-future".`
)
}
......@@ -54,7 +54,7 @@ export async function prepareUpgrade(
if (upgrade.status === 'blocked' || upgrade.status === 'unknown') {
throw new Error(upgrade.reason)
}
if (upgrade.status !== 'ready' || targetRequest !== 'future') {
if (upgrade.status !== 'ready' || targetRequest !== 'experimental-future') {
return upgrade
}
......@@ -95,7 +95,7 @@ export type UpgradeAssessment = {
// target, so expire cached results and refresh metadata before execution.
export async function getUpgradeAssessment(
installedVersion: string,
policy: 'security' | 'latest' | 'future',
policy: 'security' | 'latest' | 'experimental-future',
onlyIfAffected: boolean = false
): Promise<UpgradeAssessment> {
if (!semver.valid(installedVersion)) {
......@@ -117,7 +117,7 @@ export async function getUpgradeAssessment(
},
}
}
if (channel && channel !== 'canary' && policy === 'future') {
if (channel && channel !== 'canary' && policy === 'experimental-future') {
return {
affected: null,
reference: null,
......@@ -205,7 +205,8 @@ export async function getUpgradeAssessment(
)
}
targetVersion =
policy === 'future' && semver.gt(installedVersion, release.version)
policy === 'experimental-future' &&
semver.gt(installedVersion, release.version)
? installedVersion
: release.version
references = [release.reference]
......
......@@ -197,8 +197,8 @@ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({
})
export const experimentalSchema = {
agenticAutoUpgrade: z
.union([z.enum(['security', 'latest', 'future']), z.literal(false)])
agentUpgrade: z
.union([z.enum(['security', 'latest', 'experimental-future']), z.boolean()])
.optional(),
agentFeedback: z.boolean().optional(),
turbopackAdditionalRoots: z
......
......@@ -499,8 +499,8 @@ export interface DeprecatedConfig {
}
export interface ExperimentalConfig {
/** Nudge coding agents about security upgrades, stable releases, or Future Defaults. */
agenticAutoUpgrade?: 'security' | 'latest' | 'future' | false
/** Nudge coding agents about security upgrades, stable releases, or Future Defaults. `true` uses the security policy. */
agentUpgrade?: 'security' | 'latest' | 'experimental-future' | boolean
/**
* Adds managed instructions to AGENTS.md that let AI coding agents prepare
* anonymized Next.js feedback for user review.
......@@ -2363,6 +2363,7 @@ export const defaultConfig = Object.freeze({
adapterPath: process.env.NEXT_ADAPTER_PATH || undefined,
deprecated: {} as DeprecatedConfig,
experimental: {
agentUpgrade: true,
agentFeedback: false,
coldCacheBadge: false,
collapseAdapterRoutes: true,
......
......@@ -222,18 +222,19 @@ export async function initialize(opts: {
// Check only development; production startup does not query advisories.
if (
developmentConfig.experimental.agenticAutoUpgrade === 'security' ||
developmentConfig.experimental.agenticAutoUpgrade === 'latest' ||
developmentConfig.experimental.agenticAutoUpgrade === 'future' ||
process.env.__NEXT_AGENTIC_AUTO_UPGRADE ||
developmentConfig.experimental.agentUpgrade === true ||
developmentConfig.experimental.agentUpgrade === 'security' ||
developmentConfig.experimental.agentUpgrade === 'latest' ||
developmentConfig.experimental.agentUpgrade === 'experimental-future' ||
process.env.__NEXT_AGENT_UPGRADE ||
process.env.__NEXT_AGENT_UPGRADE_FORCE_DEVTOOLS_FOR_TESTING === '1'
) {
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 policy = upgradeContext.experimental.agentUpgrade
const forced = process.env.__NEXT_AGENT_UPGRADE === policy
const forceDevToolsForTesting =
process.env.__NEXT_AGENT_UPGRADE_FORCE_DEVTOOLS_FOR_TESTING === '1'
const assessment: ReturnType<typeof assessUpgrade> =
......@@ -254,6 +255,8 @@ export async function initialize(opts: {
}
)
if (process.env.NEXT_PRIVATE_UPGRADE_PROMPT === '1' && process.send) {
// The parent retries if the worker assessment rejects.
const [promptAssessment] = await Promise.allSettled([assessment])
// TODO: Do not block dev startup while prompting for an upgrade.
// Preserve all logs for display after the prompt and stop dev before Update.
// The existing dev worker pauses here while its parent owns the menu.
......@@ -269,10 +272,20 @@ export async function initialize(opts: {
process.on('message', resume)
process.send!({
nextUpgradeContext: upgradeContext,
...(promptAssessment.status === 'fulfilled'
? { nextUpgradeAssessment: promptAssessment.value }
: {}),
})
})
} else {
void nudgeUpgrade(opts.dir, developmentConfig, 'dev').catch((error) => {
// CI skips the DevTools assessment, but agents still need the nudge.
void nudgeUpgrade(
opts.dir,
upgradeContext,
'dev',
null,
isCI || forceDevToolsForTesting ? null : assessment
).catch((error) => {
const { printAndExit } =
require('./utils') as typeof import('./utils')
const exitCode =
......
......@@ -195,7 +195,7 @@ describe('agentic upgrade prompts', () => {
jest.mocked(writeFile).mockResolvedValue(undefined)
jest.mocked(getAgentName).mockResolvedValue('codex')
jest.mocked(loadConfig).mockResolvedValue({
default: { experimental: { agenticAutoUpgrade: false } },
default: { experimental: { agentUpgrade: false } },
} as never)
jest
.mocked(normalizeConfig)
......@@ -303,7 +303,7 @@ describe('agentic upgrade prompts', () => {
}
)
it.each([true, 'security', 'latest', 'future'])(
it.each([true, 'security', 'latest', 'experimental-future'])(
'delegates %s to the exact canary and preserves its failure status',
async (ai) => {
delete process.env.__NEXT_UPGRADE_EXPECTED_CLI_VERSION
......@@ -1220,7 +1220,7 @@ describe('agentic upgrade prompts', () => {
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.
Set \`experimental.agentUpgrade\` 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.
References:
- https://api.github.com/advisories?affects=next
......@@ -1259,11 +1259,11 @@ describe('agentic upgrade prompts', () => {
expect(prepareUpgrade).toHaveBeenCalledWith('/workspace/app', 'security')
})
it.each(['security', 'latest', 'future'] as const)(
it.each(['security', 'latest', 'experimental-future'] as const)(
'uses the configured %s policy for a bare AI upgrade',
async (policy) => {
jest.mocked(loadConfig).mockResolvedValue({
default: { experimental: { agenticAutoUpgrade: policy } },
default: { experimental: { agentUpgrade: policy } },
} as never)
await spawnNextUpgrade('/workspace/app', {
......@@ -1275,7 +1275,7 @@ describe('agentic upgrade prompts', () => {
expect(prepareUpgrade).toHaveBeenCalledWith('/workspace/app', policy)
expect(Log.bootstrap).toHaveBeenCalledWith(
expect.stringContaining(
`Set \`experimental.agenticAutoUpgrade\` to "${policy}"`
`Set \`experimental.agentUpgrade\` to "${policy}"`
)
)
}
......@@ -1317,7 +1317,7 @@ describe('agentic upgrade prompts', () => {
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.
Set \`experimental.agentUpgrade\` 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.
References:
- https://registry.npmjs.org/next/latest",
......@@ -1392,7 +1392,7 @@ describe('agentic upgrade prompts', () => {
await spawnNextUpgrade('/workspace/app', {
revision: 'latest',
verbose: false,
ai: 'future',
ai: 'experimental-future',
})
const prompt = normalizedBootstrapCalls().flat().join('\n')
......@@ -1405,7 +1405,7 @@ describe('agentic upgrade prompts', () => {
)
})
it.each(['latest', 'future'] as const)(
it.each(['latest', 'experimental-future'] as const)(
'hands off the exact canary target for %s upgrades',
async (policy) => {
jest.mocked(prepareUpgrade).mockResolvedValue({
......@@ -1501,7 +1501,7 @@ describe('agentic upgrade prompts', () => {
await spawnNextUpgrade('/workspace/app', {
revision: 'latest',
verbose: false,
ai: 'future',
ai: 'experimental-future',
})
expect(crossSpawn).toHaveBeenCalledTimes(1)
......@@ -1526,7 +1526,7 @@ describe('agentic upgrade prompts', () => {
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.
Set \`experimental.agentUpgrade\` to "experimental-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.
After completing and verifying the version update, read and follow "/tmp/next-upgrade-test/docs/01-app/02-guides/upgrading/agentic-upgrade/future-defaults.md".
Adopt these Future Defaults in order:
......@@ -1592,7 +1592,7 @@ describe('agentic upgrade prompts', () => {
await spawnNextUpgrade('/workspace/app', {
revision: 'latest',
verbose: false,
ai: 'future',
ai: 'experimental-future',
})
expect(
......@@ -1625,7 +1625,7 @@ describe('agentic upgrade prompts', () => {
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.
Set \`experimental.agentUpgrade\` to "experimental-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.
Adopt these Future Defaults in order:
- Cache Components
......
......@@ -182,7 +182,7 @@ describe('prepare latest upgrade', () => {
it('does not request canary target metadata after a release dismissal', async () => {
global.fetch = jest.fn()
await expect(
getUpgradeAssessment('16.4.0-canary.1', 'future', true)
getUpgradeAssessment('16.4.0-canary.1', 'experimental-future', true)
).resolves.toMatchObject({ affected: null, upgrade: { status: 'blocked' } })
expect(global.fetch).toHaveBeenCalledTimes(0)
})
......@@ -190,7 +190,7 @@ describe('prepare latest upgrade', () => {
it('checks advisories without target metadata after a release dismissal', async () => {
mockLatestVersion('17.0.0')
await expect(
getUpgradeAssessment('16.4.0', 'future', true)
getUpgradeAssessment('16.4.0', 'experimental-future', true)
).resolves.toMatchObject({
affected: false,
upgrade: { status: 'unaffected' },
......@@ -202,7 +202,7 @@ describe('prepare latest upgrade', () => {
describe('shared stable eligibility', () => {
const installed = '17.2.0'
it.each(['security', 'latest', 'future'] as const)(
it.each(['security', 'latest', 'experimental-future'] as const)(
'uses the same safe target in the %s nudge and command',
async (policy) => {
const directory = await createApp(installed)
......@@ -223,7 +223,7 @@ describe('prepare latest upgrade', () => {
}
)
it.each(['security', 'latest', 'future'] as const)(
it.each(['security', 'latest', 'experimental-future'] as const)(
'retains the advisory when the %s target metadata cannot be fetched',
async (policy) => {
const directory = await createApp(installed)
......@@ -249,7 +249,7 @@ describe('prepare latest upgrade', () => {
}
)
it.each(['latest', 'future'] as const)(
it.each(['latest', 'experimental-future'] as const)(
'checks the %s target even when the installed version is unaffected',
async (policy) => {
const directory = await createApp(installed)
......@@ -271,7 +271,7 @@ describe('prepare latest upgrade', () => {
}
)
it.each(['security', 'latest', 'future'] as const)(
it.each(['security', 'latest', 'experimental-future'] as const)(
'retains npm advisory warnings without release metadata for %s',
async (policy) => {
const directory = await createApp(installed)
......@@ -332,7 +332,7 @@ describe('prepare latest upgrade', () => {
).resolves.toMatchObject({
upgrade: { status: 'ready', targetVersion: '18.0.0' },
})
for (const policy of ['latest', 'future'] as const) {
for (const policy of ['latest', 'experimental-future'] as const) {
await expect(
getUpgradeAssessment('17.2.0', policy)
).resolves.toMatchObject({ upgrade: { status: 'blocked' } })
......@@ -444,10 +444,14 @@ describe('prepare latest upgrade', () => {
async (version) => {
const directory = await createApp(version)
global.fetch = jest.fn()
await expect(prepareUpgrade(directory, 'future')).rejects.toThrow(
await expect(
prepareUpgrade(directory, 'experimental-future')
).rejects.toThrow(
`Future Defaults upgrades are not supported for Next.js ${version}.`
)
await expect(getUpgradeAssessment(version, 'future')).resolves.toEqual(
await expect(
getUpgradeAssessment(version, 'experimental-future')
).resolves.toEqual(
expect.objectContaining({
affected: null,
upgrade: expect.objectContaining({
......@@ -588,7 +592,7 @@ describe('prepare latest upgrade', () => {
)
})
describe.each(['latest', 'future'] as const)(
describe.each(['latest', 'experimental-future'] as const)(
'%s canary upgrades',
(policy) => {
it.each([
......@@ -642,7 +646,7 @@ describe('prepare latest upgrade', () => {
}
)
it.each(['latest', 'future'] as const)(
it.each(['latest', 'experimental-future'] as const)(
'runs canary %s without advisory assessment even when providers are unavailable',
async (policy) => {
const directory = await createApp('17.2.0-canary.4')
......@@ -677,7 +681,9 @@ describe('prepare latest upgrade', () => {
async (target) => {
const directory = await createApp('17.2.0-canary.4')
mockSecurityMetadata({ target, ranges: [] })
await expect(prepareUpgrade(directory, 'future')).resolves.toEqual(
await expect(
prepareUpgrade(directory, 'experimental-future')
).resolves.toEqual(
expect.objectContaining({
status: 'ready',
targetVersion: '17.2.0-canary.4',
......@@ -692,9 +698,9 @@ describe('prepare latest upgrade', () => {
it('keeps the stable Future availability boundary for a same-base canary', async () => {
const directory = await createApp('16.3.0-canary.1')
mockSecurityMetadata({ target: '16.3.0-canary.1', ranges: [] })
await expect(prepareUpgrade(directory, 'future')).resolves.toEqual(
expect.objectContaining({ status: 'unaffected' })
)
await expect(
prepareUpgrade(directory, 'experimental-future')
).resolves.toEqual(expect.objectContaining({ status: 'unaffected' }))
})
it('assesses a retained Future version missing from registry metadata', async () => {
......@@ -704,12 +710,12 @@ describe('prepare latest upgrade', () => {
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.'
)
await expect(
prepareUpgrade(directory, 'experimental-future')
).rejects.toThrow('17.2.9 is affected by an active advisory.')
})
it.each(['latest', 'future'] as const)(
it.each(['latest', 'experimental-future'] as const)(
'fails a %s assessment when the advisory endpoint is unavailable',
async (policy) => {
const directory = await createApp('17.2.0')
......@@ -856,7 +862,9 @@ describe('prepare latest upgrade', () => {
const directory = await createApp('16.2.0')
mockFutureMetadata('<16.3.0')
await expect(prepareUpgrade(directory, 'future')).resolves.toEqual(
await expect(
prepareUpgrade(directory, 'experimental-future')
).resolves.toEqual(
expect.objectContaining({
status: 'ready',
installedVersion: '16.2.0',
......@@ -869,9 +877,9 @@ describe('prepare latest upgrade', () => {
const directory = await createApp('16.2.0')
mockFutureMetadata('<=16.4.0')
await expect(prepareUpgrade(directory, 'future')).rejects.toThrow(
'Next.js 16.4.0 is affected by an active advisory.'
)
await expect(
prepareUpgrade(directory, 'experimental-future')
).rejects.toThrow('Next.js 16.4.0 is affected by an active advisory.')
})
it('uses the adapter to detect an adopted Future Default', async () => {
......@@ -881,7 +889,9 @@ describe('prepare latest upgrade', () => {
} as never)
mockFutureMetadata('<16.3.0')
await expect(prepareUpgrade(directory, 'future')).resolves.toEqual({
await expect(
prepareUpgrade(directory, 'experimental-future')
).resolves.toEqual({
status: 'unaffected',
reason:
'Next.js 16.4.0 is current and no applicable Future Defaults are pending.',
......@@ -892,7 +902,9 @@ describe('prepare latest upgrade', () => {
await rm(join(directory, 'app'), { recursive: true })
await mkdir(join(directory, 'pages'))
mockFutureMetadata('<16.3.0')
await expect(prepareUpgrade(directory, 'future')).resolves.toMatchObject({
await expect(
prepareUpgrade(directory, 'experimental-future')
).resolves.toMatchObject({
status: 'ready',
targetVersion: '16.4.0',
futureDefaults: [],
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment