hmr-live.e2e.ts 6.5 KB

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