Unverified Commit b145ad6f authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Fix initial Turbopack HMR update handling (#98385)

### What?

Prevent a real client HMR update from being discarded when it arrives as
the first subscription emission.

### Why?

Capturing the chunk baseline and installing the update subscription are
separate asynchronous operations. A change between them turns the first
emission into a real update, but the client handler previously assumed
that emission was always initialization-only and dropped it after the
server had advanced its version state.

### How?

Inspect the first subscription result and preserve the existing
issues-only initialization behavior while forwarding partial or restart
updates through the normal issue and browser-update paths. This is the
narrower option because it does not change handling of the usual initial
issues payload.

### Verification

- `pnpm --filter=next build`
- `HEADLESS=true pnpm test-dev-turbo
test/development/app-dir/hmr-dynamic-component/hmr-dynamic-component.test.ts`
(including a locally controlled baseline-to-subscription race)
- Prettier and ESLint on the changed source

<!-- NEXT_JS_LLM -->

<!-- fleet 3820fb8a-c662-4c74-8316-e2d7cd42bfbd -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent fc977d6d
......@@ -1063,10 +1063,14 @@ export async function createHotReloaderTurbopack(
const subscription = project!.clientHmrEvents(id)
state.subscriptions.set(id, subscription)
// The subscription will always emit once, which is the initial
// computation. This is not a change, so swallow it.
// Baseline capture and subscription setup are not atomic, so the first
// emission can be a real update. Ignore only the usual issues-only result.
try {
await subscription.next()
const initial = await subscription.next()
if (!initial.done && initial.value.type !== 'issues') {
processIssues(state.clientIssues, key, initial.value, false, true)
sendTurbopackMessage(initial.value as TurbopackUpdate)
}
for await (const data of subscription) {
processIssues(state.clientIssues, key, data, false, true)
......
import { mkdirSync, writeFileSync } from 'fs'
import { join } from 'path'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type * as Playwright from 'playwright'
describe('hmr-dynamic-component', () => {
const { next } = nextTestSetup({
const { next, isTurbopack, isNextDev } = nextTestSetup({
files: __dirname,
patchFileDelay: 500,
})
......@@ -138,4 +140,111 @@ describe('hmr-dynamic-component', () => {
await next.patchFile(cssPath, originalCss)
}
})
if (isTurbopack && isNextDev) {
it('should not lose an edit while establishing the client HMR subscription', async () => {
const componentPath = join('app', 'components', 'dynamic.tsx')
const absoluteComponentPath = join(next.testDir, componentPath)
const originalContent = await next.readFile(componentPath)
const graphDirectory = join(
next.testDir,
'app',
'components',
'hmr-subscription-race'
)
const moduleCount = 800
mkdirSync(graphDirectory, { recursive: true })
for (let index = 0; index < moduleCount; index++) {
writeFileSync(
join(graphDirectory, `module-${index}.ts`),
`export default ${index}\n`
)
}
const createComponent = (label: string) => `
'use client'
import styles from './dynamic.module.css'
${Array.from(
{ length: moduleCount },
(_, index) =>
`import value${index} from './hmr-subscription-race/module-${index}'`
).join('\n')}
const values = [${Array.from(
{ length: moduleCount },
(_, index) => `value${index}`
).join(', ')}]
export default function Dynamic() {
return (
<div id="dynamic-component" className={styles.dynamic}>
HMR subscription ${label} {values.length}
</div>
)
}
`
try {
await next.patchFile(componentPath, createComponent('before'))
const subscriptionPaths = new Set<string>()
let editTriggered = false
let pageLoads = 0
const browser = await next.browser('/', {
beforePageLoad(page: Playwright.Page) {
page.on('load', () => {
pageLoads++
})
page.on('websocket', (ws) => {
if (!ws.url().includes('/_next/hmr')) {
return
}
ws.on('framesent', (frame) => {
const payload =
typeof frame.payload === 'string'
? frame.payload
: frame.payload.toString('utf8')
try {
const message = JSON.parse(payload)
if (
message?.type === 'turbopack-subscribe' &&
typeof message?.path === 'string' &&
message.path.endsWith('.js')
) {
subscriptionPaths.add(message.path)
if (subscriptionPaths.size === 2 && !editTriggered) {
editTriggered = true
writeFileSync(
absoluteComponentPath,
createComponent('after')
)
}
}
} catch {
// Non-JSON frames are unrelated to Turbopack subscriptions.
}
})
})
},
})
await retry(async () => {
expect(editTriggered).toBe(true)
const div = await browser.elementByCss('#dynamic-component')
expect(await div.text()).toContain(
`HMR subscription after ${moduleCount}`
)
}, 10000)
// The edit must arrive through HMR, not a recovery reload.
expect(pageLoads).toBe(1)
} finally {
await next.patchFile(componentPath, originalContent)
}
})
} else {
it.skip('subscription race is Turbopack development-mode only', () => {})
}
})
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