host-process.spec.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { afterEach, describe, expect, it, vi } from 'vitest'
  5. import { DesktopHostProcess } from '../src/host-process.ts'
  6. const roots: string[] = []
  7. const hosts: DesktopHostProcess[] = []
  8. const HTTP_HOST = `
  9. import { createServer } from 'node:http'
  10. import { writeFileSync } from 'node:fs'
  11. import { join } from 'node:path'
  12. const server = createServer((request, response) => {
  13. if (request.url === '/fatal') {
  14. process.send({ type: 'fatal', message: 'plugin unavailable' })
  15. response.end('reported')
  16. return
  17. }
  18. if (request.url === '/crash') {
  19. response.end('exiting', () => {
  20. process.stderr.write('plugin crashed', () => process.exit(7))
  21. })
  22. return
  23. }
  24. response.setHeader('content-type', 'application/json')
  25. response.end(JSON.stringify({runtime: process.argv[2], profile: process.argv[3], cwd: process.cwd(), nodePath: process.env.NODE_PATH, registry: process.env.NPM_CONFIG_REGISTRY, nodeOptions: process.env.NODE_OPTIONS, runAsNode: process.env.ELECTRON_RUN_AS_NODE, internals: process.execArgv.includes('--expose-internals')}))
  26. })
  27. server.listen(0, '127.0.0.1', () => {
  28. process.send({ type: 'ready', url: 'http://127.0.0.1:' + server.address().port + '/?token=fixture' })
  29. })
  30. process.on('message', message => {
  31. if (message.type !== 'shutdown') return
  32. server.close(() => {
  33. writeFileSync(join(process.argv[3], 'stopped'), '')
  34. process.disconnect()
  35. })
  36. server.closeAllConnections()
  37. })
  38. `
  39. function projectWithHost(source = HTTP_HOST): string {
  40. const project = mkdtempSync(join(tmpdir(), 'dsh-desktop-host-test-'))
  41. roots.push(project)
  42. const packageRoot = join(project, 'node_modules', '@deepseek-ai', 'dsh-desktop-host')
  43. mkdirSync(join(packageRoot, 'lib'), { recursive: true })
  44. writeFileSync(join(packageRoot, 'package.json'), '{"name":"@deepseek-ai/dsh-desktop-host","type":"module"}\n')
  45. writeFileSync(join(packageRoot, 'lib', 'index.js'), source)
  46. return project
  47. }
  48. function hostProcess(
  49. runtime: string, profile = runtime, onFailure?: (error: Error) => void, environment = process.env,
  50. ): DesktopHostProcess {
  51. const host = new DesktopHostProcess(process.execPath, runtime, profile, undefined, environment, onFailure)
  52. hosts.push(host)
  53. return host
  54. }
  55. afterEach(async () => {
  56. await Promise.all(hosts.splice(0).map(host => host.stop()))
  57. for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
  58. })
  59. describe('desktop host process', () => {
  60. it('returns the Web authentication URL and waits for graceful shutdown', async () => {
  61. const runtime = projectWithHost()
  62. const failure = vi.fn()
  63. const host = hostProcess(runtime, runtime, failure)
  64. const ready = await host.start()
  65. expect(new URL(ready.url).searchParams.get('token')).toBe('fixture')
  66. expect(await host.start()).toEqual(ready)
  67. expect((await fetch(ready.url)).status).toBe(200)
  68. await host.stop()
  69. expect(existsSync(join(runtime, 'stopped'))).toBe(true)
  70. await expect(fetch(ready.url)).rejects.toThrow()
  71. expect(failure).not.toHaveBeenCalled()
  72. })
  73. it('passes external dependencies and runtime profile resolution to the Host', async () => {
  74. const runtime = projectWithHost(HTTP_HOST.replace('runtime: process.argv[2]',
  75. 'primaryRuntime: process.argv[4], profileResolution: process.argv[5], runtime: process.argv[2]'))
  76. const primaryRuntime = join(runtime, 'external-primary-runtime')
  77. const host = new DesktopHostProcess(process.execPath, runtime, runtime, undefined, process.env,
  78. undefined, primaryRuntime, 'runtime')
  79. hosts.push(host)
  80. const { url } = await host.start()
  81. expect(await (await fetch(url)).json()).toMatchObject({ primaryRuntime, profileResolution: 'runtime' })
  82. })
  83. it('reports a fatal event after readiness once', async () => {
  84. const runtime = projectWithHost()
  85. const failure = vi.fn()
  86. const host = hostProcess(runtime, runtime, failure)
  87. const { url } = await host.start()
  88. await fetch(new URL('/fatal', url))
  89. await expect.poll(() => failure.mock.calls.length).toBe(1)
  90. await host.stop()
  91. expect(failure).toHaveBeenCalledTimes(1)
  92. expect(failure).toHaveBeenCalledWith(new Error('plugin unavailable'))
  93. })
  94. it('reports a child crash after readiness with its stderr diagnostic', async () => {
  95. const runtime = projectWithHost()
  96. const failure = vi.fn()
  97. const host = hostProcess(runtime, runtime, failure)
  98. const { url } = await host.start()
  99. await fetch(new URL('/crash', url))
  100. await expect.poll(() => failure.mock.calls.length).toBe(1)
  101. expect(failure).toHaveBeenCalledWith(new Error('dsh desktop host exited with 7: plugin crashed'))
  102. })
  103. it('retains only recent diagnostics from a noisy child', async () => {
  104. const runtime = projectWithHost('process.stderr.write(\'discarded-prefix\' + \'x\'.repeat(70_000) + \'recent-failure\', () => { process.exitCode = 7; process.disconnect() })')
  105. const failure = await hostProcess(runtime).start().catch((error: unknown) => error)
  106. expect(failure).toBeInstanceOf(Error)
  107. const message = (failure as Error).message
  108. expect(message).not.toContain('discarded-prefix')
  109. expect(message.endsWith('recent-failure')).toBe(true)
  110. expect(message.length).toBeLessThan(66_000)
  111. })
  112. it('settles teardown when the executable cannot be spawned', async () => {
  113. const runtime = projectWithHost()
  114. const host = new DesktopHostProcess(join(runtime, 'missing-node'), runtime, runtime)
  115. hosts.push(host)
  116. await expect(host.start()).rejects.toThrow()
  117. await host.stop()
  118. })
  119. it('loads the resource entry with a separate profile and inherits runtime and package-manager configuration', async () => {
  120. const runtime = projectWithHost()
  121. const profile = mkdtempSync(join(tmpdir(), 'desktop-external-profile-'))
  122. roots.push(profile)
  123. const host = hostProcess(runtime, profile, undefined, {
  124. ...process.env, NODE_OPTIONS: '--no-warnings', NODE_PATH: '/custom', NPM_CONFIG_REGISTRY: 'https://registry.example.test/',
  125. })
  126. const { url } = await host.start()
  127. const response = await fetch(url)
  128. expect(await response.json()).toEqual({ runtime, profile, cwd: realpathSync(profile), nodePath: '/custom', registry: 'https://registry.example.test/', nodeOptions: '--no-warnings', runAsNode: '1', internals: true })
  129. })
  130. it.each([
  131. ["process.send({ type: 'fatal', message: 'startup failed' }); process.disconnect()", 'startup failed'],
  132. ["process.send({ type: 'ready', url: 4 })", 'invalid IPC event'],
  133. ['process.exit(0)', 'host stopped'],
  134. ])('rejects startup when the child fails before readiness: %s', async (source, message) => {
  135. const host = hostProcess(projectWithHost(source))
  136. await expect(host.start()).rejects.toThrow(message)
  137. })
  138. })