hmr-live.e2e.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. /** Published dsh web + pnpm dev:web → browser HMR, with no page reload. */
  2. import { existsSync, globSync, statSync } from 'node:fs'
  3. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { chromium } from 'playwright'
  7. import { expect, it } from 'vitest'
  8. import { Context } from '@deepseek-ai/cordis'
  9. import type { Fiber } from '@deepseek-ai/cordis'
  10. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  11. import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
  12. import { readClientBuildRecord } from '../../../scripts/client-build-environment.ts'
  13. import { REPO_ROOT } from './support.ts'
  14. const CLIENT_ARTIFACT_PATTERNS = [
  15. 'apps/web/dist/**/*',
  16. 'packages/*/*/lib/client.js',
  17. 'packages/*/*/lib/client.js.map',
  18. ]
  19. /** Return every artifact that `pnpm run dev:web` can rewrite. */
  20. function clientArtifactPaths(): string[] {
  21. return globSync(CLIENT_ARTIFACT_PATTERNS, { cwd: REPO_ROOT })
  22. .map(path => join(REPO_ROOT, path))
  23. .filter(path => statSync(path).isFile())
  24. .sort()
  25. }
  26. function spawnSpec(argv: readonly string[], cwd: string, env?: Record<string, string>): SubprocessSpawnSpec {
  27. return {
  28. argv,
  29. cwd,
  30. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' },
  31. graceMs: 5_000,
  32. ...env === undefined ? {} : { env },
  33. }
  34. }
  35. function waitForOutput(child: SubprocessHandle, pattern: RegExp, label: string): Promise<string> {
  36. return new Promise((resolveReady, reject) => {
  37. let output = ''
  38. let settled = false
  39. const cleanup = (): void => {
  40. clearTimeout(timer)
  41. child.stdout?.off('data', onData)
  42. child.stderr?.off('data', onData)
  43. }
  44. const resolveOnce = (value: string): void => {
  45. if (settled) return
  46. settled = true
  47. cleanup()
  48. resolveReady(value)
  49. }
  50. const rejectOnce = (error: Error): void => {
  51. if (settled) return
  52. settled = true
  53. cleanup()
  54. reject(error)
  55. }
  56. const onData = (chunk: Buffer): void => {
  57. output += chunk.toString()
  58. const match = pattern.exec(output)
  59. if (match === null) return
  60. resolveOnce(match[1] ?? match[0])
  61. }
  62. const timer = setTimeout(() => { rejectOnce(new Error(`${label} not ready:\n${output}`)) }, 60_000)
  63. child.stdout?.on('data', onData)
  64. child.stderr?.on('data', onData)
  65. void child.done.then((outcome) => {
  66. rejectOnce(new Error(`${label} exited before ready (${JSON.stringify(outcome)}):\n${output}`))
  67. }, (error: unknown) => {
  68. rejectOnce(new Error(`${label} failed before ready:\n${output}`, { cause: error }))
  69. })
  70. })
  71. }
  72. async function stopTree(child: SubprocessHandle): Promise<void> {
  73. child.terminate()
  74. const stopped = await child.waitForExit(AbortSignal.timeout(15_000))
  75. if (!stopped) throw new Error('managed process range did not stop after termination escalation')
  76. await child.done
  77. }
  78. it('hot-reloads a real client-plugin source edit without refreshing the page', async () => {
  79. const world = await mkdtemp(join(tmpdir(), 'dsh-web-hmr-world-'))
  80. const sourcePath = join(REPO_ROOT, 'packages/client/ui-conversation/src/client/locales.ts')
  81. const binPath = join(REPO_ROOT, 'apps/cli/lib/bin.js')
  82. if (!existsSync(binPath)) throw new Error('HMR browser test needs the built dsh bin; run pnpm run build first')
  83. const clientBuildEnvironment = readClientBuildRecord(REPO_ROOT).environment
  84. const originalClientArtifacts = await Promise.all(clientArtifactPaths()
  85. .map(async path => [path, await readFile(path)] as const))
  86. const originalClientArtifactPaths = new Set(originalClientArtifacts.map(([path]) => path))
  87. const originalSource = await readFile(sourcePath)
  88. const oldText = 'Into the Unknown'
  89. const sourceNeedle = "'hero.headline': 'Into the Unknown'"
  90. const newText = `HMR UPDATED ${'x'.repeat(80)}`
  91. const updatedSource = originalSource.toString().replace(sourceNeedle, `'hero.headline': '${newText}'`)
  92. if (updatedSource === originalSource.toString()) throw new Error(`HMR source lacks ${JSON.stringify(sourceNeedle)}`)
  93. const subprocessCtx = new Context()
  94. let subprocessFiber: Fiber | undefined
  95. let watcher: SubprocessHandle | undefined
  96. let host: SubprocessHandle | undefined
  97. let browser: Awaited<ReturnType<typeof chromium.launch>> | undefined
  98. const failures: unknown[] = []
  99. try {
  100. subprocessFiber = await subprocessCtx.plugin(LocalSubprocessRuntime)
  101. watcher = subprocessCtx.subprocess.spawn(spawnSpec(
  102. ['pnpm', 'run', 'dev:web'],
  103. REPO_ROOT,
  104. { ...clientBuildEnvironment },
  105. ))
  106. await waitForOutput(watcher, /dev-web: watching/, 'pnpm run dev:web')
  107. host = subprocessCtx.subprocess.spawn(spawnSpec(
  108. [process.execPath, binPath, 'web', '--no-open', '--port', '0'],
  109. world,
  110. {
  111. DEEPSEEK_API_KEY: 'keyless-hmr-no-call',
  112. DSH_HOME: join(world, '.dsh'),
  113. },
  114. ))
  115. const baseUrl = await waitForOutput(host, /dsh web: (http:\/\/[^\s]+)/, 'built dsh web')
  116. browser = await chromium.launch()
  117. const page = await browser.newPage()
  118. const pageErrors: string[] = []
  119. page.on('pageerror', error => pageErrors.push(String(error)))
  120. await page.goto(baseUrl, { waitUntil: 'load' })
  121. await page.getByText(oldText, { exact: true }).waitFor({ timeout: 15_000 })
  122. const pageIdentity = await page.evaluate(() => {
  123. // In-page code: an import would not survive serialization, and the page
  124. // entropy source available in every context is getRandomValues.
  125. const identity = Array.from(crypto.getRandomValues(new Uint8Array(8)), byte => byte.toString(16).padStart(2, '0')).join('')
  126. Object.defineProperty(window, '__dshHmrPageIdentity', { value: identity })
  127. return identity
  128. })
  129. await writeFile(sourcePath, updatedSource)
  130. await page.getByText(newText, { exact: true }).waitFor({ timeout: 30_000 })
  131. expect(await page.evaluate(() => (window as Window & { __dshHmrPageIdentity?: string }).__dshHmrPageIdentity))
  132. .toBe(pageIdentity)
  133. expect(pageErrors).toEqual([])
  134. } catch (error) {
  135. failures.push(error)
  136. } finally {
  137. await writeFile(sourcePath, originalSource).catch((error: unknown) => failures.push(error))
  138. if (watcher !== undefined) await stopTree(watcher).catch((error: unknown) => failures.push(error))
  139. if (host !== undefined) await stopTree(host).catch((error: unknown) => failures.push(error))
  140. await browser?.close().catch((error: unknown) => failures.push(error))
  141. await subprocessFiber?.dispose().catch((error: unknown) => failures.push(error))
  142. await Promise.all(clientArtifactPaths()
  143. .filter(path => !originalClientArtifactPaths.has(path))
  144. .map(async (path) => { await rm(path, { force: true }) }))
  145. .catch((error: unknown) => failures.push(error))
  146. await Promise.all(originalClientArtifacts.map(async ([path, content]) => {
  147. await writeFile(path, content)
  148. })).catch((error: unknown) => failures.push(error))
  149. try {
  150. readClientBuildRecord(REPO_ROOT)
  151. } catch (error) {
  152. failures.push(error)
  153. }
  154. await rm(world, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  155. }
  156. if (failures.length > 0) throw new AggregateError(failures, 'HMR browser test or cleanup failed')
  157. }, 120_000)