service-sync.test.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { enterLocal } from './test-support/onboarding.mjs'
  2. import { test } from 'node:test'
  3. import assert from 'node:assert/strict'
  4. import { mkdtemp, readFile, writeFile, rm, cp, realpath } from 'node:fs/promises'
  5. import { tmpdir } from 'node:os'
  6. import { dirname, join, resolve } from 'node:path'
  7. import { createServer } from 'node:net'
  8. import { spawn } from 'node:child_process'
  9. import { createHash } from 'node:crypto'
  10. import { _electron as electron } from '@playwright/test'
  11. import { LaunchAgentService, localRequest, synchronizeDesktop } from '../bin/lib/service-update.mjs'
  12. import { sealRuntime, syncDecision, verifyRuntimePackage } from '../bin/lib/runtime-release.mjs'
  13. const root = resolve(import.meta.dirname, '..')
  14. const payloadRoot = process.env.DESKTOP_TEST_EXECUTABLE
  15. ? resolve(dirname(process.env.DESKTOP_TEST_EXECUTABLE), '../Resources/runtime/web-service')
  16. : join(root, '.desktop-build', 'web-service')
  17. async function freePort() {
  18. const server = createServer(); await new Promise(done => server.listen(0, '127.0.0.1', done))
  19. const port = server.address().port; await new Promise(done => server.close(done)); return port
  20. }
  21. async function until(read, accept, timeout = 60000) {
  22. const deadline = Date.now() + timeout
  23. while (Date.now() < deadline) {
  24. try { const value = await read(); if (accept(value)) return value } catch {}
  25. await new Promise(done => setTimeout(done, 200))
  26. }
  27. throw new Error('等待同步服务状态超时')
  28. }
  29. async function nativeQuit(app, menu = false) {
  30. let exited=false;app.process().once('exit',()=>{exited=true})
  31. let output='';app.process().stdout.on('data',bytes=>{output+=bytes})
  32. await app.evaluate(({app,BrowserWindow})=>{
  33. const navigations=[]
  34. BrowserWindow.getAllWindows()[0].webContents.on('did-start-navigation',(_event,url)=>navigations.push(url))
  35. app.once('will-quit',()=>console.log('QUIT_TEST_NAVIGATIONS='+JSON.stringify(navigations)))
  36. })
  37. await app.evaluate(({app,Menu},menu)=>{if(menu)Menu.getApplicationMenu().getMenuItemById('desktop-quit').click();else app.quit()},menu)
  38. await until(()=>exited,Boolean,10000)
  39. const proof=output.match(/QUIT_TEST_NAVIGATIONS=(\[[^\n]*\])/)
  40. assert.ok(proof,'native will-quit must complete')
  41. assert.equal(JSON.parse(proof[1]).some(url=>url.includes('boot.html')),false,'native quit must not navigate to a stopped boot page')
  42. await app.close().catch(()=>{})
  43. }
  44. test('App first launch installs an independent Web; Web remains up after quit and a newer Web is retained', { timeout: 150000 }, async () => {
  45. const home = await realpath(await mkdtemp(join(tmpdir(), 'yaoyao-sync-native-')))
  46. const port = await freePort(), upstreamPort = await freePort()
  47. const releaseRoot = join(home, 'updates', 'fixture-releases')
  48. const label = `cn.samien.yaoyao.sync-test.${createHash('sha256').update(home).digest('hex').slice(0, 16)}`
  49. const driver = new LaunchAgentService({ home, port, releaseRoot, label, plistPath: join(home, 'updates', 'fixture-service.plist') })
  50. const upstream = spawn(process.execPath, [join(root, 'tests/fixtures/fake-hermes.mjs')], {
  51. cwd: root, env: { ...process.env, FAKE_HERMES_PORT: String(upstreamPort), FAKE_HERMES_LOCAL_AUTH: '1' }, stdio: 'ignore',
  52. })
  53. let app
  54. const launch = () => electron.launch({
  55. ...(process.env.DESKTOP_TEST_EXECUTABLE ? { executablePath: process.env.DESKTOP_TEST_EXECUTABLE } : {}),
  56. args: process.env.DESKTOP_TEST_EXECUTABLE ? [] : [root], cwd: root,
  57. env: { ...process.env, HERMES_YAOYAO_DESKTOP_TEST_HOME: home, HERMES_YAOYAO_DESKTOP_PORT: String(port),
  58. HERMES_YAOYAO_DESKTOP_TEST_SYNC: '1', HERMES_YAOYAO_UPSTREAM: `http://127.0.0.1:${upstreamPort}` }, timeout: 30000,
  59. })
  60. try {
  61. await until(() => localRequest(`http://127.0.0.1:${upstreamPort}/api/status`), value => value.status === 200)
  62. const original = verifyRuntimePackage(payloadRoot)
  63. const previousRuntime = process.env.DESKTOP_TEST_PREVIOUS_RUNTIME
  64. if (previousRuntime) {
  65. // Install an actual historical release into this fixture's isolated home.
  66. // This catches same-version packages whose published Git history differs.
  67. const previous = verifyRuntimePackage(previousRuntime)
  68. assert.equal(syncDecision(original, previous), 'upgrade', 'the packaged App must unambiguously upgrade the historical release')
  69. await synchronizeDesktop({ home, runtimeRoot: previousRuntime, releaseRoot, driver })
  70. const saved = driver.snapshot().plist
  71. saved.EnvironmentVariables.YAOYAO_TEST_PRESERVE = 'historical-release-settings'
  72. driver.writePlist(saved)
  73. console.log(`Historical upgrade fixture: ${previous.version} ${previous.commit} -> ${original.version} ${original.commit}`)
  74. }
  75. app = await launch()
  76. const page = await app.firstWindow()
  77. await enterLocal(page, { username: 'sync-fixture', password: 'sync-fixture-password' })
  78. await page.waitForURL(`http://127.0.0.1:${port}/**`, { timeout: 90000 })
  79. const record = JSON.parse(await readFile(join(home, 'service-instance.json'), 'utf8'))
  80. assert.equal(record.desktopOwned, false)
  81. const identity = await localRequest(`http://127.0.0.1:${port}/desktop/service`, record.token)
  82. assert.equal(identity.body.build.artifactDigest, original.artifactDigest)
  83. assert.equal(identity.body.quiesced, false)
  84. if (previousRuntime) {
  85. const marker = JSON.parse(await readFile(join(home, 'updates', 'desktop-sync.json'), 'utf8'))
  86. assert.equal(marker.action, 'upgrade')
  87. assert.equal(driver.snapshot().plist.EnvironmentVariables.YAOYAO_TEST_PRESERVE, 'historical-release-settings')
  88. }
  89. // Credential setup can overlap the SPA's first route navigation; retry only this read.
  90. const support = await until(() => page.evaluate(async () =>
  91. (await fetch('/api/app/system/update/status')).json()), value => value.installationMode === 'release')
  92. assert.equal(support.installationMode, 'release'); assert.equal(support.supported, true)
  93. await nativeQuit(app); app = undefined
  94. assert.equal((await localRequest(`http://127.0.0.1:${port}/healthz`)).body.ok, true)
  95. assert.equal(driver.pid(), record.pid, 'quitting the App must leave the independent Web running')
  96. const saved = driver.snapshot().plist
  97. saved.EnvironmentVariables.YAOYAO_TEST_PRESERVE = 'keep-existing-settings'
  98. driver.writePlist(saved)
  99. // Install a later release through the same transaction engine used by Web's updater.
  100. const newer = join(home, 'updates', 'newer-package')
  101. const [major, minor, patch] = original.version.split('-')[0].split('.').map(Number)
  102. const newerVersion = `${major}.${minor}.${patch + 1}`
  103. await cp(payloadRoot, newer, { recursive: true })
  104. await writeFile(join(newer, 'release.json'), JSON.stringify({ schemaVersion: 1, releaseVersion: newerVersion, webVersion: newerVersion, gitTag: `v${newerVersion}` }))
  105. const build = JSON.parse(await readFile(join(newer, 'build-info.json'), 'utf8'))
  106. await writeFile(join(newer, 'build-info.json'), JSON.stringify({ ...build, commit: 'c'.repeat(40), ancestors: [build.commit, ...build.ancestors], dirty: false }))
  107. sealRuntime(newer)
  108. await synchronizeDesktop({ home, runtimeRoot: newer, releaseRoot, driver })
  109. const updated = JSON.parse(await readFile(join(home, 'service-instance.json'), 'utf8'))
  110. assert.equal(updated.version, newerVersion); assert.notEqual(updated.pid, record.pid)
  111. assert.equal(driver.snapshot().plist.EnvironmentVariables.YAOYAO_TEST_PRESERVE, 'keep-existing-settings')
  112. app = await launch()
  113. const reopened = await app.firstWindow(); await reopened.waitForURL(`http://127.0.0.1:${port}/**`, { timeout: 90000 })
  114. assert.equal(driver.pid(), updated.pid, 'older App must retain the newer Web without restarting it')
  115. const marker = JSON.parse(await readFile(join(home, 'updates', 'desktop-sync.json'), 'utf8'))
  116. assert.equal(marker.action, 'newer')
  117. assert.equal(marker.artifactDigest, original.artifactDigest)
  118. // Keep an authenticated event stream open. Stop-and-quit must close it,
  119. // unload launchd (not just kill its PID), and exit with one menu action.
  120. await reopened.evaluate(async()=>{
  121. const capabilities=await (await fetch('/api/realtime/capabilities')).json()
  122. const created=await fetch('/api/realtime/channels',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':capabilities.csrfToken},body:JSON.stringify({channel:'chat',chatProtocol:'ordinary-chat-transcript-v2'})})
  123. if(!created.ok)throw new Error('fixture realtime channel unavailable')
  124. const channel=await created.json()
  125. const response=await fetch(`/api/realtime/channels/${channel.id}/events`)
  126. if(!response.ok)throw new Error('fixture event stream unavailable')
  127. if(!response.headers.get('content-type')?.includes('text/event-stream'))throw new Error('expected a real SSE stream')
  128. window.stopTestStream=response.body.getReader()
  129. void window.stopTestStream.read()
  130. })
  131. let exited=false;app.process().once('exit',()=>{exited=true})
  132. await app.evaluate(({Menu})=>Menu.getApplicationMenu().getMenuItemById('desktop-stop-and-quit').click())
  133. await until(()=>exited,Boolean,30000);app=undefined
  134. assert.equal(driver.pid(),undefined)
  135. assert.equal(driver.listeners().size,0)
  136. await new Promise(done=>setTimeout(done,1000))
  137. assert.equal(driver.pid(),undefined,'launchd must not relaunch a deliberately stopped service')
  138. app = await launch()
  139. const restarted = await app.firstWindow(); await restarted.waitForURL(`http://127.0.0.1:${port}/**`, { timeout: 90000 })
  140. const resumed = JSON.parse(await readFile(join(home, 'service-instance.json'), 'utf8'))
  141. assert.equal(resumed.version, newerVersion); assert.equal(resumed.desktopOwned, false)
  142. assert.notEqual(resumed.pid, updated.pid)
  143. await nativeQuit(app,true); app = undefined
  144. } catch (error) {
  145. // Only this fixture's server log, which contains startup diagnostics.
  146. const log = await readFile(join(home, 'service.log'), 'utf8').catch(() => '')
  147. if (log) process.stderr.write(log.slice(-3000))
  148. throw error
  149. } finally {
  150. await app?.close().catch(() => {})
  151. await driver.stop()
  152. upstream.kill('SIGTERM')
  153. await rm(home, { recursive: true, force: true })
  154. }
  155. })