loader-composition.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /**
  2. * REAL-composition coverage: a test-only cordis.yml booted through the
  3. * vendored Loader mounts the webserver row plus the adaptive chooser, and the
  4. * assertions observe the durable outcome — which backend and surface entries
  5. * the chooser mounted into the Loader store, the capability the seam then
  6. * serves, and that disposing the chooser removes both mounted entries again
  7. * (HMR safety), joining the backend's own teardown before the disposer settles.
  8. */
  9. import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs'
  10. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  11. import { tmpdir } from 'node:os'
  12. import { join } from 'node:path'
  13. import { pathToFileURL } from 'node:url'
  14. import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
  15. import { Context } from '@deepseek-ai/cordis'
  16. import Loader from '@deepseek-ai/cordis-plugin-loader'
  17. import Include from '@deepseek-ai/cordis-plugin-include'
  18. import HttpServer from '@deepseek-ai/dsh-host-webserver'
  19. import type { DirectoryPicker } from '@deepseek-ai/dsh-host-directory-picker'
  20. import BrowseDirectoryPicker from '@deepseek-ai/dsh-host-directory-picker-browse'
  21. import NativeDirectoryPicker from '@deepseek-ai/dsh-host-directory-picker-native'
  22. import {
  23. createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY, type LaunchEnvironmentSnapshot,
  24. } from '@deepseek-ai/dsh-launch-environment'
  25. import * as DirectoryPickerAuto from '../src/index.ts'
  26. const renameControl = vi.hoisted(() => ({
  27. attempts: 0,
  28. failureCode: 'EPERM',
  29. injectedFailures: 0,
  30. remainingFailures: 0,
  31. }))
  32. vi.mock('node:fs/promises', async (importOriginal) => {
  33. const actual = await importOriginal<typeof import('node:fs/promises')>()
  34. return {
  35. ...actual,
  36. async rename(oldPath: string, newPath: string): Promise<void> {
  37. renameControl.attempts++
  38. if (renameControl.remainingFailures > 0) {
  39. renameControl.remainingFailures--
  40. renameControl.injectedFailures++
  41. throw Object.assign(new Error(`injected rename failure for ${newPath}`), { code: renameControl.failureCode })
  42. }
  43. await actual.rename(oldPath, newPath)
  44. },
  45. }
  46. })
  47. const AUTO = '@deepseek-ai/dsh-host-directory-picker-auto'
  48. const NATIVE = '@deepseek-ai/dsh-host-directory-picker-native'
  49. const BROWSE = '@deepseek-ai/dsh-host-directory-picker-browse'
  50. const NATIVE_SURFACE = '@deepseek-ai/dsh-client-ui-directory-picker-native'
  51. const BROWSE_SURFACE = '@deepseek-ai/dsh-client-ui-directory-picker-browse'
  52. /**
  53. * Loader-visible stand-in for a client surface package: the surfaces belong to
  54. * the Client program and publish browser entry points only, so a Host-face spec
  55. * can neither name them in a static import nor resolve them from source. What
  56. * the chooser owns is the mounting decision, which every case observes through
  57. * the Loader store; the surface's own browser contributions belong to the
  58. * assembled web coverage.
  59. *
  60. * @param name Surface package specifier the chooser mounts.
  61. * @returns A function-plugin module the Loader can mount under that specifier.
  62. */
  63. function surfaceModule(name: string): unknown {
  64. return { name, apply: () => undefined }
  65. }
  66. let root: string | undefined
  67. let fakeBin: string | undefined
  68. let context: Context | undefined
  69. afterEach(async () => {
  70. vi.unstubAllEnvs()
  71. await context?.fiber.dispose()
  72. context = undefined
  73. for (const dir of [root, fakeBin]) {
  74. // maxRetries absorbs teardown stragglers (e.g. an unawaited fiber's late
  75. // file handle) that can otherwise race the recursive scan into ENOTEMPTY.
  76. if (dir !== undefined) await rm(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })
  77. }
  78. root = undefined
  79. fakeBin = undefined
  80. renameControl.attempts = 0
  81. renameControl.failureCode = 'EPERM'
  82. renameControl.injectedFailures = 0
  83. renameControl.remainingFailures = 0
  84. })
  85. /** Write a two-row cordis.yml (webserver + chooser), then boot it through the real Loader. */
  86. async function loadComposition(
  87. bindHost: '127.0.0.1' | '0.0.0.0',
  88. options: { failSurface?: boolean; launchEnvironment?: LaunchEnvironmentSnapshot } = {},
  89. ): Promise<{ ctx: Context; configPath: string }> {
  90. root = await mkdtemp(join(tmpdir(), 'dsh-directory-picker-auto-'))
  91. const configPath = join(root, 'cordis.yml')
  92. await writeFile(configPath, [
  93. "- name: '@deepseek-ai/dsh-host-webserver'",
  94. ' config:',
  95. ` host: '${bindHost}'`,
  96. ' port: 0',
  97. `- name: '${AUTO}'`,
  98. '',
  99. ].join('\n'))
  100. context = new Context()
  101. if (options.launchEnvironment !== undefined) context.provide(DSH_LAUNCH_ENVIRONMENT_KEY, options.launchEnvironment)
  102. context.baseUrl = pathToFileURL(root).href + '/'
  103. await context.plugin(Loader)
  104. context.loader.builtins.include = Include
  105. const modules = new Map<string, unknown>([
  106. ['@deepseek-ai/dsh-host-webserver', HttpServer],
  107. [AUTO, DirectoryPickerAuto],
  108. [NATIVE, NativeDirectoryPicker],
  109. [BROWSE, BrowseDirectoryPicker],
  110. [NATIVE_SURFACE, surfaceModule(NATIVE_SURFACE)],
  111. [BROWSE_SURFACE, surfaceModule(BROWSE_SURFACE)],
  112. ])
  113. context.loader.internal = {
  114. version: 'v2',
  115. async import(specifier: string) {
  116. if (options.failSurface === true && (specifier === NATIVE_SURFACE || specifier === BROWSE_SURFACE)) {
  117. throw new Error(`surface import failed: ${specifier}`)
  118. }
  119. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  120. return modules.get(specifier)
  121. },
  122. } as unknown as NonNullable<typeof context.loader.internal>
  123. await context.loader.create({
  124. name: 'cordis:include',
  125. config: { path: pathToFileURL(configPath).href },
  126. })
  127. await context.loader.await()
  128. return { ctx: context, configPath }
  129. }
  130. /** Entry names currently present in the loader store (root tree plus subtrees). */
  131. function entryNames(ctx: Context): string[] {
  132. return [...ctx.loader.entries()].map(entry => entry.options.name)
  133. }
  134. /** The Include tree that backs the booted `cordis.yml` file. */
  135. function includeTree(ctx: Context): Include {
  136. const include = [...ctx.loader.entries()]
  137. .find(entry => entry.options.name === 'cordis:include')?.subtree as Include | undefined
  138. if (include === undefined) throw new Error('expected the root Include tree')
  139. return include
  140. }
  141. /**
  142. * Force every signal of an attended host on any platform: no SSH launch, a
  143. * display, and a PATH holding one executable chooser binary so the real
  144. * probe resolves identically on hosts with and without zenity/kdialog.
  145. */
  146. function stubAttendedHost(): void {
  147. fakeBin = mkdtempSync(join(tmpdir(), 'dsh-picker-bin-'))
  148. const zenity = join(fakeBin, 'zenity')
  149. writeFileSync(zenity, '#!/bin/sh\n')
  150. chmodSync(zenity, 0o755)
  151. vi.stubEnv('PATH', fakeBin)
  152. vi.stubEnv('SSH_CONNECTION', '')
  153. vi.stubEnv('SSH_TTY', '')
  154. vi.stubEnv('DISPLAY', ':0')
  155. }
  156. describe('real Loader composition', () => {
  157. it.each(['project-env', 'user-env'] as const)('keeps the native backend with materialized SSH markers from %s', async (source) => {
  158. stubAttendedHost()
  159. vi.stubEnv('SSH_CONNECTION', 'stale-connection')
  160. vi.stubEnv('SSH_TTY', '/dev/pts/stale')
  161. const launchEnvironment = createLaunchEnvironmentSnapshot([
  162. { source, values: { SSH_CONNECTION: 'stale-connection', SSH_TTY: '/dev/pts/stale' } },
  163. ])
  164. const { ctx } = await loadComposition('127.0.0.1', { launchEnvironment })
  165. expect(ctx.get('directoryPicker')?.capability().kind).toBe('native')
  166. expect(entryNames(ctx)).toContain(NATIVE_SURFACE)
  167. expect(entryNames(ctx)).not.toContain(BROWSE_SURFACE)
  168. })
  169. // The 60s budget covers this file's static imports (webserver plus both
  170. // backend node halves through tsx), which dominate on cold caches; the
  171. // Loader itself resolves nothing here — `loader.internal` is a module map.
  172. it('mounts the native backend for an attended loopback host and unmounts it on disposal', { timeout: 60_000 }, async () => {
  173. stubAttendedHost()
  174. const { ctx, configPath } = await loadComposition('127.0.0.1')
  175. const unloaded = [...ctx.loader.entries()]
  176. .filter(entry => entry.fiber === undefined && !entry.disabled)
  177. .map(entry => entry.options.name)
  178. expect(unloaded).toEqual([])
  179. expect(entryNames(ctx)).toContain(NATIVE)
  180. expect(entryNames(ctx)).toContain(NATIVE_SURFACE)
  181. expect(entryNames(ctx)).not.toContain(BROWSE)
  182. expect(entryNames(ctx)).not.toContain(BROWSE_SURFACE)
  183. const picker = ctx.get('directoryPicker') as DirectoryPicker
  184. expect(picker.capability().kind).toBe('native')
  185. // The mounted row lives in the Loader's in-memory root tree only — the
  186. // booted config file must never gain the resolved backend row.
  187. expect(await readFile(configPath, 'utf8')).not.toContain(NATIVE)
  188. // HMR safety: disposing the chooser's fiber removes the entry it created,
  189. // and the disposer joins the backend's teardown — the service is gone the
  190. // moment dispose() settles, with no further loader await.
  191. const autoEntry = [...ctx.loader.entries()].find(entry => entry.options.name === AUTO)!
  192. const backendEntry = [...ctx.loader.entries()].find(entry => entry.options.name === NATIVE)!
  193. const cleanupStarted = Promise.withResolvers<undefined>()
  194. const releaseCleanup = Promise.withResolvers<undefined>()
  195. onTestFinished(() => { releaseCleanup.resolve(undefined) })
  196. backendEntry.fiber!.ctx.effect(() => async () => {
  197. cleanupStarted.resolve(undefined)
  198. await releaseCleanup.promise
  199. })
  200. let disposed = false
  201. const disposal = autoEntry.fiber!.dispose().then(() => { disposed = true })
  202. await cleanupStarted.promise
  203. await Promise.resolve()
  204. expect(disposed).toBe(false)
  205. releaseCleanup.resolve(undefined)
  206. await disposal
  207. expect(entryNames(ctx)).not.toContain(NATIVE)
  208. expect(entryNames(ctx)).not.toContain(NATIVE_SURFACE)
  209. expect(ctx.get('directoryPicker')).toBeUndefined()
  210. // Self-disposing an include-tree entry persists `disabled: true` (loader
  211. // behavior, not the chooser's); await that debounced write so it cannot
  212. // race the temp-dir removal, and pin that the persisted row is the
  213. // chooser itself — the resolved backend still never reaches the file.
  214. // stop() drains the Include write queue, so this assertion does not depend
  215. // on the debounce timer racing Windows coverage load.
  216. await includeTree(ctx).stop()
  217. expect(await readFile(configPath, 'utf8')).toContain('disabled: true')
  218. expect(await readFile(configPath, 'utf8')).not.toContain(NATIVE)
  219. })
  220. it('mounts the browse backend under an SSH launch', { timeout: 60_000 }, async () => {
  221. stubAttendedHost()
  222. vi.stubEnv('SSH_CONNECTION', '10.0.0.2 55 10.0.0.9 22')
  223. const { ctx } = await loadComposition('127.0.0.1')
  224. expect(entryNames(ctx)).toContain(BROWSE)
  225. expect(entryNames(ctx)).toContain(BROWSE_SURFACE)
  226. expect(entryNames(ctx)).not.toContain(NATIVE)
  227. expect(entryNames(ctx)).not.toContain(NATIVE_SURFACE)
  228. const picker = ctx.get('directoryPicker') as DirectoryPicker
  229. expect(picker.capability().kind).toBe('browse')
  230. })
  231. it('mounts the browse backend for an all-interfaces bind even on an attended host', { timeout: 60_000 }, async () => {
  232. stubAttendedHost()
  233. const { ctx } = await loadComposition('0.0.0.0')
  234. expect(entryNames(ctx)).toContain(BROWSE)
  235. expect(entryNames(ctx)).toContain(BROWSE_SURFACE)
  236. expect(entryNames(ctx)).not.toContain(NATIVE)
  237. expect(entryNames(ctx)).not.toContain(NATIVE_SURFACE)
  238. })
  239. it('unmounts the backend when the surface entry fails to load', { timeout: 60_000 }, async () => {
  240. stubAttendedHost()
  241. const { ctx } = await loadComposition('127.0.0.1', { failSurface: true })
  242. const chooser = [...ctx.loader.entries()].find(entry => entry.options.name === AUTO)!
  243. await expect(chooser.fiber!.await()).rejects.toThrow(/directory-picker-auto: failed to load/)
  244. // Setup owns both entries until it returns its disposer, so a failed surface
  245. // must take the mounted backend with it: otherwise a retry collides with the
  246. // directoryPicker registration this backend already made.
  247. expect(entryNames(context!)).not.toContain(NATIVE)
  248. expect(context!.get('directoryPicker')).toBeUndefined()
  249. })
  250. it('tolerates the mounted entry being removed by the tree before the chooser unloads', { timeout: 60_000 }, async () => {
  251. stubAttendedHost()
  252. const { ctx, configPath } = await loadComposition('127.0.0.1')
  253. const backendEntry = [...ctx.loader.entries()].find(entry => entry.options.name === NATIVE)!
  254. ctx.loader.remove(backendEntry.id)
  255. const autoEntry = [...ctx.loader.entries()].find(entry => entry.options.name === AUTO)!
  256. renameControl.remainingFailures = 1
  257. await expect(autoEntry.fiber!.dispose()).resolves.not.toThrow()
  258. expect(entryNames(ctx)).not.toContain(NATIVE)
  259. expect(entryNames(ctx)).not.toContain(NATIVE_SURFACE)
  260. // Same self-dispose persistence as above: drain the Include write queue
  261. // deterministically before asserting the persisted row.
  262. await includeTree(ctx).stop()
  263. expect(await readFile(configPath, 'utf8')).toContain('disabled: true')
  264. expect(renameControl.injectedFailures).toBe(1)
  265. expect(renameControl.remainingFailures).toBe(0)
  266. expect(renameControl.attempts).toBeGreaterThanOrEqual(2)
  267. })
  268. it('reports a terminal debounced-write failure again to the teardown owner', { timeout: 60_000 }, async () => {
  269. stubAttendedHost()
  270. const { ctx } = await loadComposition('127.0.0.1')
  271. const autoEntry = [...ctx.loader.entries()].find(entry => entry.options.name === AUTO)!
  272. const include = includeTree(ctx)
  273. renameControl.failureCode = 'EIO'
  274. renameControl.remainingFailures = 1
  275. await autoEntry.fiber!.dispose()
  276. await expect.poll(() => renameControl.injectedFailures).toBe(1)
  277. await expect(include.stop()).rejects.toMatchObject({ code: 'EIO' })
  278. await expect(ctx.fiber.dispose()).resolves.not.toThrow()
  279. context = undefined
  280. })
  281. })