built-bin.e2e.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { fileURLToPath, pathToFileURL } from 'node:url'
  5. import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server'
  6. import { execa } from 'execa'
  7. import { afterEach, beforeEach, describe, expect, it } from 'vitest'
  8. /** Published-entry acceptance for argument errors, profile lifecycle, and boot-free config dumps. */
  9. const repoRoot = fileURLToPath(new URL('../../../', import.meta.url))
  10. // The release version, including a prerelease such as 0.0.1-rc.1: `--version`
  11. // prints what this manifest carries, so no test may pin it to a literal.
  12. const cliVersion = (JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }).version
  13. const dshBin = join(repoRoot, 'apps/cli/lib/bin.js')
  14. const invalidProvider = fileURLToPath(new URL('./fixtures/invalid-provider.cordis.yml', import.meta.url))
  15. async function runBuiltBin(
  16. args: readonly string[] = [],
  17. env: Readonly<Record<string, string | undefined>> = {},
  18. cwd?: string,
  19. ): Promise<{ stdout: string; code: number; stderr: string }> {
  20. const childEnv = Object.fromEntries(
  21. Object.entries({ ...process.env, ...env })
  22. .filter((entry): entry is [string, string] => entry[1] !== undefined),
  23. )
  24. const result = await execa(process.execPath, [dshBin, ...args], {
  25. input: '',
  26. timeout: 25_000,
  27. killSignal: 'SIGKILL',
  28. reject: false,
  29. env: childEnv,
  30. extendEnv: false,
  31. ...cwd === undefined ? {} : { cwd },
  32. })
  33. if (result.timedOut) {
  34. throw new Error(`dsh built bin did not exit within 25s. stdout:\n${result.stdout}\nstderr:\n${result.stderr}`)
  35. }
  36. return { stdout: result.stdout, code: result.exitCode ?? -1, stderr: result.stderr }
  37. }
  38. async function waitForFile(file: string): Promise<void> {
  39. const deadline = Date.now() + 20_000
  40. while (!existsSync(file)) {
  41. if (Date.now() >= deadline) throw new Error(`dsh profile lifecycle marker did not appear: ${file}`)
  42. await new Promise(resolve => setTimeout(resolve, 20))
  43. }
  44. }
  45. interface ProfileLifecycleFixture {
  46. home: string
  47. ready: string
  48. settled: string
  49. disposed: string
  50. interrupt: string
  51. }
  52. /**
  53. * A minimal custom profile: one lifecycle-marker plugin bundle listed in
  54. * dsh.profile.bundles, no dsh-base — proving out-of-box composition machinery without
  55. * booting the entire product tree.
  56. */
  57. function createProfileLifecycleFixture(): ProfileLifecycleFixture {
  58. const home = mkdtempSync(join(tmpdir(), 'dsh-profile-lifecycle-'))
  59. const ready = join(home, 'ready')
  60. const settled = join(home, 'settled')
  61. const disposed = join(home, 'disposed')
  62. const interrupt = join(home, 'interrupt')
  63. const bundleDir = join(home, 'lifecycle-bundle')
  64. mkdirSync(bundleDir, { recursive: true })
  65. writeFileSync(join(bundleDir, 'plugin.mjs'), [
  66. "import { existsSync, writeFileSync } from 'node:fs'",
  67. "import { join } from 'node:path'",
  68. "export const name = 'profile-lifecycle-fixture'",
  69. 'export function apply(ctx, config = {}) {',
  70. ' let active = true',
  71. ' // Keep the event loop alive so process lifetime is signal-owned, like a real surface.',
  72. ' // Windows has no deliverable SIGTERM; the marker emits the same process event there.',
  73. ' let interrupted = false',
  74. ' const heartbeat = setInterval(() => {',
  75. ' if (interrupted || !existsSync(process.env.RAW_INTERRUPT_FILE)) return',
  76. ' interrupted = true',
  77. " process.emit('SIGTERM')",
  78. ' }, 20)',
  79. ' // Echo the mounted generation so the hot-reload e2e can assert both an',
  80. ' // applied override and its removal reverting to this bundle default.',
  81. " writeFileSync(join(process.env.DSH_HOME, 'config-echo'), String(config.generation ?? 'bundle-default'))",
  82. " writeFileSync(process.env.RAW_READY_FILE, 'ready')",
  83. ' void ctx.loader.await().then(() => {',
  84. " if (active) writeFileSync(process.env.RAW_SETTLED_FILE, 'settled')",
  85. ' })',
  86. ' ctx.effect(() => () => {',
  87. ' active = false',
  88. ' clearInterval(heartbeat)',
  89. " writeFileSync(process.env.RAW_DISPOSED_FILE, 'disposed')",
  90. ' })',
  91. '}',
  92. '',
  93. ].join('\n'))
  94. writeFileSync(join(bundleDir, 'cordis.patch.yml'), [
  95. '- insert:',
  96. ' - id: profile-lifecycle-fixture',
  97. ` name: ${pathToFileURL(join(bundleDir, 'plugin.mjs')).href}`,
  98. '',
  99. ].join('\n'))
  100. writeFileSync(join(bundleDir, 'package.json'), JSON.stringify({
  101. name: 'dsh-lifecycle-bundle',
  102. version: '0.0.0',
  103. type: 'module',
  104. dsh: { bundle: { patch: './cordis.patch.yml' } },
  105. }, undefined, 2))
  106. const profileDir = join(home, 'profiles', 'lifecycle')
  107. mkdirSync(join(profileDir, 'node_modules'), { recursive: true })
  108. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  109. name: 'dsh-profile-lifecycle',
  110. private: true,
  111. dependencies: {},
  112. dsh: { profile: { bundles: ['dsh-lifecycle-bundle'] } },
  113. }, undefined, 2))
  114. // Hand-place the "installed" bundle where profile resolution finds it.
  115. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  116. const linkTarget = join(profileDir, 'node_modules', 'dsh-lifecycle-bundle')
  117. mkdirSync(join(profileDir, 'node_modules'), { recursive: true })
  118. try {
  119. rmSync(linkTarget, { recursive: true, force: true })
  120. } catch { /* fresh dir */ }
  121. // Copy-free: a package.json redirecting via a relative main is enough for require.resolve.
  122. mkdirSync(linkTarget, { recursive: true })
  123. for (const file of ['package.json', 'cordis.patch.yml', 'plugin.mjs']) {
  124. writeFileSync(join(linkTarget, file), readFileSync(join(bundleDir, file)))
  125. }
  126. return { home, ready, settled, disposed, interrupt }
  127. }
  128. function startProfileLifecycle(fixture: ProfileLifecycleFixture, args: readonly string[] = []) {
  129. return execa(process.execPath, [dshBin, '--profile', 'lifecycle', ...args], {
  130. cwd: fixture.home,
  131. input: '',
  132. reject: false,
  133. env: {
  134. DSH_HOME: fixture.home,
  135. RAW_READY_FILE: fixture.ready,
  136. RAW_SETTLED_FILE: fixture.settled,
  137. RAW_DISPOSED_FILE: fixture.disposed,
  138. RAW_INTERRUPT_FILE: fixture.interrupt,
  139. },
  140. })
  141. }
  142. function requestProfileShutdown(
  143. child: Pick<ReturnType<typeof startProfileLifecycle>, 'kill'>,
  144. fixture: Pick<ProfileLifecycleFixture, 'interrupt'>,
  145. ): void {
  146. if (process.platform === 'win32') {
  147. writeFileSync(fixture.interrupt, 'interrupt')
  148. return
  149. }
  150. child.kill('SIGTERM')
  151. }
  152. function createEnvironmentProbeProfile(home: string, project: string): void {
  153. const pluginFile = join(project, 'environment-probe.mjs')
  154. writeFileSync(pluginFile, [
  155. "export const name = 'environment-probe'",
  156. "export const inject = ['llm']",
  157. 'export function apply(ctx) {',
  158. ' void ctx.loader.await().then(async () => {',
  159. " let text = ''",
  160. ' for await (const chunk of ctx.llm.stream({',
  161. " provider: 'deepseek-official',",
  162. " model: 'deepseek-v4-flash',",
  163. ' messages: [],',
  164. ' maxTokens: 32,',
  165. ' })) {',
  166. " if (chunk.type === 'text-delta') text += chunk.text",
  167. ' }',
  168. ' process.stdout.write(`${text}\\n`)',
  169. " if (process.platform === 'win32') process.emit('SIGTERM')",
  170. " else process.kill(process.pid, 'SIGTERM')",
  171. ' })',
  172. '}',
  173. '',
  174. ].join('\n'))
  175. const profileDir = join(home, 'profiles', 'environment-probe')
  176. mkdirSync(profileDir, { recursive: true })
  177. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  178. name: 'dsh-profile-environment-probe',
  179. private: true,
  180. dependencies: {},
  181. dsh: { profile: { bundles: ['@deepseek-ai/dsh-base'] } },
  182. }, undefined, 2))
  183. writeFileSync(join(profileDir, 'cordis.patch.yml'), [
  184. '- insert:',
  185. ' - id: environment-probe',
  186. ` name: ${pathToFileURL(pluginFile).href}`,
  187. '',
  188. ].join('\n'))
  189. }
  190. interface StartupFixture {
  191. home: string
  192. ready: string
  193. echo: string
  194. interrupt: string
  195. /** An always-running row's echo, used to observe that a user patch reload landed. */
  196. witness: string
  197. }
  198. /**
  199. * A custom profile whose ordinary provider plugin injects `cmdlineArgs`, plus
  200. * a row that reads its app-owned service through a `!!js` config expression.
  201. * Both plugin modules resolve
  202. * `@deepseek-ai/dsh-cmdline` and `commander` through the profile module
  203. * fallback, exactly as an installed out-of-tree bundle does.
  204. */
  205. function createStartupFixture(): StartupFixture {
  206. const home = mkdtempSync(join(tmpdir(), 'dsh-profile-startup-'))
  207. const profileDir = join(home, 'profiles', 'startup')
  208. // Written straight into the installed location: a row module resolves its
  209. // own imports from where it is installed, and only inside the profile does
  210. // Node's parent walk reach the installation fallback these plugins need.
  211. const bundleDir = join(profileDir, 'node_modules', 'dsh-startup-bundle')
  212. mkdirSync(bundleDir, { recursive: true })
  213. writeFileSync(join(bundleDir, 'startup.mjs'), [
  214. "import { Command } from 'commander'",
  215. "import { parseCmdline } from '@deepseek-ai/dsh-cmdline'",
  216. "export const name = 'fixture-startup'",
  217. "export const inject = ['cmdlineArgs']",
  218. 'export function apply(ctx) {',
  219. " const program = new Command().name('fixture').option('--generation <value>', 'echoed generation')",
  220. ' const values = parseCmdline(ctx, program, parsed => ({ generation: parsed.opts().generation }))',
  221. ' if (values !== undefined) ctx.provide(\'fixtureStartup\', values)',
  222. '}',
  223. '',
  224. ].join('\n'))
  225. writeFileSync(join(bundleDir, 'waiting.mjs'), [
  226. "import { existsSync, writeFileSync } from 'node:fs'",
  227. "import { join } from 'node:path'",
  228. "export const name = 'startup-fixture'",
  229. 'export function apply(ctx, config = {}) {',
  230. ' let interrupted = false',
  231. ' const heartbeat = setInterval(() => {',
  232. ' if (interrupted || !existsSync(process.env.RAW_INTERRUPT_FILE)) return',
  233. ' interrupted = true',
  234. " process.emit('SIGTERM')",
  235. ' }, 20)',
  236. " writeFileSync(join(process.env.DSH_HOME, 'config-echo'), String(config.generation ?? 'bundle-default'))",
  237. " writeFileSync(process.env.RAW_READY_FILE, 'ready')",
  238. ' ctx.effect(() => () => { clearInterval(heartbeat) })',
  239. '}',
  240. '',
  241. ].join('\n'))
  242. writeFileSync(join(bundleDir, 'witness.mjs'), [
  243. "import { writeFileSync } from 'node:fs'",
  244. "import { join } from 'node:path'",
  245. "export const name = 'reload-witness'",
  246. 'export function apply(ctx, config = {}) {',
  247. " writeFileSync(join(process.env.DSH_HOME, 'witness'), String(config.generation ?? 'bundle-default'))",
  248. '}',
  249. '',
  250. ].join('\n'))
  251. writeFileSync(join(bundleDir, 'cordis.patch.yml'), [
  252. '- insert:',
  253. ' - id: startup-fixture',
  254. ` name: ${pathToFileURL(join(bundleDir, 'waiting.mjs')).href}`,
  255. ' inject: [fixtureStartup]',
  256. ' config:',
  257. // Lazy interpolation runs only after the provider's service is injected.
  258. " generation: !!js ctx.fixtureStartup.generation ?? 'bundle-default'",
  259. ' - id: fixture-startup',
  260. ` name: ${pathToFileURL(join(bundleDir, 'startup.mjs')).href}`,
  261. ' - id: reload-witness',
  262. ` name: ${pathToFileURL(join(bundleDir, 'witness.mjs')).href}`,
  263. '',
  264. ].join('\n'))
  265. writeFileSync(join(bundleDir, 'package.json'), JSON.stringify({
  266. name: 'dsh-startup-bundle',
  267. version: '0.0.0',
  268. type: 'module',
  269. dsh: { bundle: { patch: './cordis.patch.yml' } },
  270. }, undefined, 2))
  271. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  272. name: 'dsh-profile-startup',
  273. private: true,
  274. dependencies: {},
  275. dsh: { profile: { bundles: ['dsh-startup-bundle'] } },
  276. }, undefined, 2))
  277. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  278. return {
  279. home,
  280. ready: join(home, 'ready'),
  281. echo: join(home, 'config-echo'),
  282. interrupt: join(home, 'interrupt'),
  283. witness: join(home, 'witness'),
  284. }
  285. }
  286. function startStartupProfile(fixture: StartupFixture, args: readonly string[]) {
  287. return execa(process.execPath, [dshBin, '--profile', 'startup', ...args], {
  288. cwd: fixture.home,
  289. input: '',
  290. reject: false,
  291. timeout: 25_000,
  292. killSignal: 'SIGKILL',
  293. env: {
  294. DSH_HOME: fixture.home,
  295. RAW_READY_FILE: fixture.ready,
  296. RAW_INTERRUPT_FILE: fixture.interrupt,
  297. },
  298. })
  299. }
  300. describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', () => {
  301. it('requires --profile and rejects removed commands', async () => {
  302. const bare = await runBuiltBin()
  303. expect(bare.code).toBe(1)
  304. expect(bare.stdout).toBe('')
  305. expect(bare.stderr).toContain('--profile <name> is required')
  306. const help = await runBuiltBin(['--help'])
  307. expect(help.code).toBe(0)
  308. expect(help.stdout).toContain('dsh --profile web')
  309. expect(help.stdout).toContain('dsh plugin --profile')
  310. expect(help.stdout).not.toMatch(/^\s+(?:tui|meta|upgrade)\b/mu)
  311. for (const removed of [['tui'], ['--config', 'x.yml'], ['-p', 'task'], ['run', 'task']]) {
  312. const result = await runBuiltBin(removed)
  313. expect(result.code).toBe(1)
  314. }
  315. }, 30_000)
  316. it('routes help and usage errors without activating startup-dependent rows', async () => {
  317. const home = mkdtempSync(join(tmpdir(), 'dsh-app-help-'))
  318. try {
  319. const web = await runBuiltBin(['--profile', 'web', '--help'], {
  320. DSH_HOME: home,
  321. DSH_TELEMETRY_DISABLED: '1',
  322. })
  323. expect(web.code).toBe(0)
  324. expect(web.stderr).toBe('')
  325. expect(web.stdout).toContain('Usage: dsh --profile web')
  326. expect(web.stdout).toContain('--port <port>')
  327. expect(web.stdout).not.toContain('dsh web: http://')
  328. const headlessHelp = await runBuiltBin(['--profile', 'headless', '--help'], {
  329. DSH_HOME: home,
  330. DSH_TELEMETRY_DISABLED: '1',
  331. })
  332. expect(headlessHelp.code).toBe(0)
  333. expect(headlessHelp.stderr).toBe('')
  334. expect(headlessHelp.stdout).toContain('Usage: dsh --profile headless')
  335. const missingTask = await runBuiltBin(['--profile', 'headless'], {
  336. DSH_HOME: home,
  337. DSH_TELEMETRY_DISABLED: '1',
  338. })
  339. expect(missingTask.code).toBe(1)
  340. expect(missingTask.stderr).toContain('a task is required')
  341. } finally {
  342. rmSync(home, { recursive: true, force: true })
  343. }
  344. }, 30_000)
  345. it('runs the headless profile through its app-owned task positional', async () => {
  346. const apiKey = 'built-dsh-headless-key'
  347. const server = await startMockLlmServer({
  348. sequence: ['success'],
  349. apiKey,
  350. successText: 'published headless profile reached the mock',
  351. })
  352. const home = mkdtempSync(join(tmpdir(), 'dsh-built-headless-'))
  353. try {
  354. const result = await runBuiltBin(['--profile', 'headless', 'answer', 'from', 'the', 'published', 'entry'], {
  355. DSH_HOME: home,
  356. DSH_TELEMETRY_DISABLED: '1',
  357. DEEPSEEK_API_KEY: apiKey,
  358. DEEPSEEK_BASE_URL: server.baseURL,
  359. })
  360. expect(result.code, result.stderr).toBe(0)
  361. expect(result.stdout).toBe('published headless profile reached the mock')
  362. expect(result.stderr).toBe('')
  363. expect(server.requests.length).toBeGreaterThan(0)
  364. expect(server.requests.every(request => request.path === '/chat/completions')).toBe(true)
  365. expect(JSON.stringify(server.requests.map(request => request.body))).toContain('answer from the published entry')
  366. } finally {
  367. await server.close()
  368. rmSync(home, { recursive: true, force: true })
  369. }
  370. }, 30_000)
  371. it('does not load a project environment for --version', async () => {
  372. const project = mkdtempSync(join(tmpdir(), 'dsh-version-project-'))
  373. writeFileSync(join(project, '.env'), 'PATH=/project-only-path\n')
  374. try {
  375. const result = await runBuiltBin(['--version'], {}, project)
  376. expect(result).toEqual({ code: 0, stdout: cliVersion, stderr: '' })
  377. } finally {
  378. rmSync(project, { recursive: true, force: true })
  379. }
  380. })
  381. it('fails loud on a nonexistent profile with the plugin-command hint', async () => {
  382. const home = mkdtempSync(join(tmpdir(), 'dsh-missing-profile-'))
  383. try {
  384. const result = await runBuiltBin(['--profile', 'nope'], { DSH_HOME: home })
  385. expect(result.code).toBe(1)
  386. expect(result.stderr).toContain('profile "nope" does not exist')
  387. expect(result.stderr).toContain('dsh plugin --profile nope add')
  388. } finally {
  389. rmSync(home, { recursive: true, force: true })
  390. }
  391. }, 30_000)
  392. it('uses the Harness-home environment and managed credential through the published entry', async () => {
  393. const apiKey = 'built-home-layer-key'
  394. const server = await startMockLlmServer({
  395. sequence: ['success'],
  396. apiKey,
  397. successText: 'home environment reached the mock',
  398. })
  399. const home = mkdtempSync(join(tmpdir(), 'dsh-home-environment-'))
  400. const project = mkdtempSync(join(tmpdir(), 'dsh-home-project-'))
  401. writeFileSync(join(home, '.env'), `DEEPSEEK_BASE_URL=${server.baseURL}\n`)
  402. writeFileSync(join(home, '.credentials.yaml'), `DEEPSEEK_API_KEY: ${apiKey}\n`, { mode: 0o600 })
  403. createEnvironmentProbeProfile(home, project)
  404. try {
  405. const result = await runBuiltBin(
  406. ['--profile', 'environment-probe'],
  407. {
  408. DSH_HOME: home,
  409. DSH_TELEMETRY_DISABLED: '1',
  410. DEEPSEEK_API_KEY: undefined,
  411. DEEPSEEK_BASE_URL: undefined,
  412. },
  413. project,
  414. )
  415. expect(
  416. result.code,
  417. `${result.stderr}\nstdout:\n${result.stdout}\nmock requests: ${String(server.requests.length)}`,
  418. ).toBe(0)
  419. expect(result.stdout).toBe('home environment reached the mock')
  420. expect(result.stdout).not.toContain(apiKey)
  421. expect(result.stderr).not.toContain(apiKey)
  422. expect(server.requests).toHaveLength(1)
  423. expect(server.requests[0]?.path).toBe('/chat/completions')
  424. expect(server.requests[0]?.headers.authorization).toBe(`Bearer ${apiKey}`)
  425. expect(JSON.stringify(server.requests[0]?.body)).not.toContain(apiKey)
  426. } finally {
  427. await server.close()
  428. rmSync(home, { recursive: true, force: true })
  429. rmSync(project, { recursive: true, force: true })
  430. }
  431. }, 30_000)
  432. it('reports a patch-overlay boot failure without hanging', async () => {
  433. // The HMR main watcher's initial scan once refreshed the include
  434. // mid-initial-apply, deadlocking the failing apply's rollback against the
  435. // refresh drain: dsh exited 13 with no diagnostic instead of settling
  436. // ([Agent Note](../../../.agents/notes/implemented/bug-fix/2026-08-03-hmr-initial-scan-boot-deadlock.md)).
  437. const home = mkdtempSync(join(tmpdir(), 'dsh-invalid-patch-'))
  438. try {
  439. const result = await runBuiltBin(['--profile', 'web', '--patch', invalidProvider], {
  440. DSH_HOME: home,
  441. DEEPSEEK_API_KEY: 'keyless-invalid-config',
  442. DSH_TELEMETRY_DISABLED: '1',
  443. })
  444. expect(result.code).toBe(1)
  445. expect(result.stdout).toBe('')
  446. expect(result.stderr).toContain('llm-pi-ai')
  447. } finally {
  448. rmSync(home, { recursive: true, force: true })
  449. }
  450. }, 30_000)
  451. it('lets a profile without a parser ignore app arguments and dispose on a startup-time signal', async () => {
  452. const fixture = createProfileLifecycleFixture()
  453. const child = startProfileLifecycle(fixture, ['--unclaimed'])
  454. try {
  455. await waitForFile(fixture.ready)
  456. requestProfileShutdown(child, fixture)
  457. const result = await child
  458. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  459. expect(result.signal).toBeUndefined()
  460. expect(existsSync(fixture.disposed)).toBe(true)
  461. } finally {
  462. child.kill('SIGKILL')
  463. rmSync(fixture.home, { recursive: true, force: true })
  464. }
  465. }, 30_000)
  466. it('fully settles a custom profile, hot-reloads its patch layer with removal reverting, and disposes on a signal', async () => {
  467. const fixture = createProfileLifecycleFixture()
  468. const child = startProfileLifecycle(fixture)
  469. const profilePatch = join(fixture.home, 'profiles', 'lifecycle', 'cordis.patch.yml')
  470. const configFile = join(fixture.home, 'config-echo')
  471. try {
  472. await waitForFile(fixture.settled)
  473. // The live profile layer: even without an hmr row in the composition,
  474. // the launcher mounts a config-only watcher, so an edited
  475. // cordis.patch.yml lands in the running tree (the reload disposes the
  476. // patched row's old fiber — observable as the disposed marker — and
  477. // mounts the new config, which echoes its generation and re-writes the
  478. // ready marker).
  479. rmSync(fixture.ready)
  480. writeFileSync(profilePatch, [
  481. '- id: profile-lifecycle-fixture',
  482. ' config:',
  483. ' generation: 2',
  484. '',
  485. ].join('\n'))
  486. await waitForFile(fixture.ready)
  487. expect(readFileSync(configFile, 'utf8')).toBe('2')
  488. // Removal reverts: the bundle's inserted row must return to its own
  489. // default config, not keep the removed override — the insert-aliasing
  490. // regression (a shared patch object mutated in place by a former
  491. // generation would make this impossible).
  492. rmSync(fixture.ready)
  493. writeFileSync(profilePatch, '[]\n')
  494. await waitForFile(fixture.ready)
  495. expect(readFileSync(configFile, 'utf8')).toBe('bundle-default')
  496. // The home-level user layer ($DSH_HOME/cordis.patch.yml) is live too
  497. // and outranks the per-profile layer.
  498. rmSync(fixture.ready)
  499. writeFileSync(join(fixture.home, 'cordis.patch.yml'), [
  500. '- id: profile-lifecycle-fixture',
  501. ' config:',
  502. ' generation: home',
  503. '',
  504. ].join('\n'))
  505. await waitForFile(fixture.ready)
  506. expect(readFileSync(configFile, 'utf8')).toBe('home')
  507. requestProfileShutdown(child, fixture)
  508. const result = await child
  509. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  510. expect(result.signal).toBeUndefined()
  511. expect(existsSync(fixture.disposed)).toBe(true)
  512. } finally {
  513. child.kill('SIGKILL')
  514. rmSync(fixture.home, { recursive: true, force: true })
  515. }
  516. }, 30_000)
  517. it('hands the app arguments to the profile, which applies them before its rows start', async () => {
  518. const fixture = createStartupFixture()
  519. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  520. try {
  521. await waitForFile(fixture.ready)
  522. // The consumer started once, already carrying the flag value: the
  523. // launcher never saw --generation, and the app provider resolved it first.
  524. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  525. requestProfileShutdown(child, fixture)
  526. expect((await child).exitCode).toBe(0)
  527. } finally {
  528. child.kill('SIGKILL')
  529. rmSync(fixture.home, { recursive: true, force: true })
  530. }
  531. }, 30_000)
  532. it('starts a consumer on its composed value when the invocation carries no app arguments', async () => {
  533. const fixture = createStartupFixture()
  534. const child = startStartupProfile(fixture, [])
  535. try {
  536. await waitForFile(fixture.ready)
  537. expect(readFileSync(fixture.echo, 'utf8')).toBe('bundle-default')
  538. requestProfileShutdown(child, fixture)
  539. expect((await child).exitCode).toBe(0)
  540. } finally {
  541. child.kill('SIGKILL')
  542. rmSync(fixture.home, { recursive: true, force: true })
  543. }
  544. }, 30_000)
  545. it('keeps the app arguments across a user patch reload', async () => {
  546. // A live edit recomposes every row while the provider service remains
  547. // active, so each config expression reads the same invocation value (a
  548. // served port does not move back to its composed fallback).
  549. const fixture = createStartupFixture()
  550. const profilePatch = join(fixture.home, 'profiles', 'startup', 'cordis.patch.yml')
  551. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  552. try {
  553. // Both rows: the waiting one carries the flag value, and the witness is
  554. // what a reload will re-mount. They start independently, so neither
  555. // marker implies the other.
  556. await waitForFile(fixture.ready)
  557. await waitForFile(fixture.witness)
  558. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  559. // An edit to an unrelated row: the witness re-mounts, which is how this
  560. // test knows the whole tree was recomposed.
  561. rmSync(fixture.witness)
  562. writeFileSync(profilePatch, [
  563. '- id: reload-witness',
  564. ' config:',
  565. ' generation: reloaded',
  566. '',
  567. ].join('\n'))
  568. await waitForFile(fixture.witness)
  569. expect(readFileSync(fixture.witness, 'utf8')).toBe('reloaded')
  570. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  571. requestProfileShutdown(child, fixture)
  572. expect((await child).exitCode).toBe(0)
  573. } finally {
  574. child.kill('SIGKILL')
  575. rmSync(fixture.home, { recursive: true, force: true })
  576. }
  577. }, 30_000)
  578. it("prints the app's own help, starts none of its rows, and exits", async () => {
  579. const fixture = createStartupFixture()
  580. try {
  581. const result = await startStartupProfile(fixture, ['--help'])
  582. expect(result.exitCode).toBe(0)
  583. expect(result.stdout).toContain('Usage: fixture')
  584. expect(result.stdout).toContain('--generation')
  585. expect(existsSync(fixture.ready)).toBe(false)
  586. } finally {
  587. rmSync(fixture.home, { recursive: true, force: true })
  588. }
  589. }, 30_000)
  590. it('anchors a relative add spec to the invoking directory, not the profile', async () => {
  591. // `dsh plugin --profile x add .` from a plugin checkout must install THAT
  592. // checkout — pnpm's cwd is the profile directory, so an un-anchored `.`
  593. // would self-link the profile.
  594. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-anchor-'))
  595. const checkout = mkdtempSync(join(tmpdir(), 'dsh-plugin-checkout-'))
  596. try {
  597. writeFileSync(join(checkout, 'package.json'), JSON.stringify({
  598. name: 'anchored-bundle',
  599. version: '1.0.0',
  600. dsh: { bundle: { patch: './cordis.patch.yml' } },
  601. }))
  602. writeFileSync(join(checkout, 'cordis.patch.yml'), '[]\n')
  603. const result = await execa(process.execPath, [dshBin, 'plugin', '--profile', 'anchor', 'add', '.'], {
  604. cwd: checkout,
  605. input: '',
  606. timeout: 60_000,
  607. killSignal: 'SIGKILL',
  608. reject: false,
  609. env: { DSH_HOME: home },
  610. })
  611. expect(result.exitCode).toBe(0)
  612. const manifest = JSON.parse(readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8')) as {
  613. dependencies: Record<string, string>
  614. dsh: { profile: { bundles: string[] } }
  615. }
  616. expect(Object.keys(manifest.dependencies)).toEqual(['anchored-bundle'])
  617. expect(manifest.dsh.profile.bundles).toContain('anchored-bundle')
  618. } finally {
  619. rmSync(home, { recursive: true, force: true })
  620. rmSync(checkout, { recursive: true, force: true })
  621. }
  622. }, 90_000)
  623. it('activates a dependency that gained dsh.bundle in a later update', async () => {
  624. // Reconcile runs against the INSTALLED state on every successful pnpm
  625. // run, so `update` (not only `add`) activates a package whose newer
  626. // version declares dsh.bundle. Simulated without a registry: hand-place
  627. // the installed package, flip its manifest, and run a benign pnpm verb.
  628. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-update-'))
  629. try {
  630. const profileDir = join(home, 'profiles', 'up')
  631. const installed = join(profileDir, 'node_modules', 'late-bundle')
  632. mkdirSync(installed, { recursive: true })
  633. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  634. name: 'dsh-profile-up',
  635. private: true,
  636. dependencies: { 'late-bundle': 'file:./late-bundle' },
  637. dsh: { profile: { bundles: ['@deepseek-ai/dsh-base'] } },
  638. }))
  639. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  640. // v1: no dsh manifest — a plain dependency.
  641. writeFileSync(join(installed, 'package.json'), JSON.stringify({ name: 'late-bundle', version: '1.0.0' }))
  642. const first = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  643. expect(first.code).toBe(0)
  644. let manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  645. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base'])
  646. // v2: the installed package now declares dsh.bundle (an update landed).
  647. writeFileSync(join(installed, 'package.json'), JSON.stringify({
  648. name: 'late-bundle', version: '2.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } },
  649. }))
  650. writeFileSync(join(installed, 'cordis.patch.yml'), '[]\n')
  651. const second = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  652. expect(second.code).toBe(0)
  653. manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  654. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', 'late-bundle'])
  655. } finally {
  656. rmSync(home, { recursive: true, force: true })
  657. }
  658. }, 30_000)
  659. describe('config dump', () => {
  660. let home: string
  661. beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'dsh-dump-bin-')) })
  662. afterEach(() => { rmSync(home, { recursive: true, force: true }) })
  663. it('prints the web profile bundle layers without a user layer', async () => {
  664. const { stdout, code, stderr } = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  665. expect(code).toBe(0)
  666. expect(stderr).toBe('')
  667. expect(stdout).toContain("name: '@deepseek-ai/dsh-agent-loop'")
  668. expect(stdout).toContain('agents: []')
  669. expect(stdout).toContain('# == @deepseek-ai/dsh-base')
  670. expect(stdout).toContain("name: '@deepseek-ai/dsh-host-webserver'")
  671. }, 30_000)
  672. it('prints the headless profile without Host or browser layers', async () => {
  673. const { stdout, code, stderr } = await runBuiltBin(
  674. ['--profile', 'headless', '--dump-default-config'],
  675. { DSH_HOME: home },
  676. )
  677. expect(code).toBe(0)
  678. expect(stderr).toBe('')
  679. expect(stdout).toContain("name: '@deepseek-ai/dsh-headless'")
  680. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-host-/)
  681. expect(stdout).not.toContain("name: '@deepseek-ai/dsh-web-app'")
  682. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-client-/)
  683. }, 30_000)
  684. it('composes the profile user layer and a --patch overlay in order', async () => {
  685. // Auto-init the web profile first, then write its user layer.
  686. const init = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  687. expect(init.code).toBe(0)
  688. const profilePatch = join(home, 'profiles', 'web', 'cordis.patch.yml')
  689. writeFileSync(profilePatch, [
  690. '- id: agent-loop',
  691. ' config:',
  692. ' agents:',
  693. ' - id: personal',
  694. ' provider: personal-provider',
  695. ' model: personal-model',
  696. '- id: absent-row',
  697. ' config:',
  698. ' x: 1',
  699. '',
  700. ].join('\n'))
  701. const overlay = join(home, 'overlay.cordis.yml')
  702. writeFileSync(overlay, [
  703. '- id: agent-loop',
  704. ' config:',
  705. ' agents:',
  706. ' - id: configured',
  707. ' provider: configured-provider',
  708. ' model: configured-model',
  709. '',
  710. ].join('\n'))
  711. const { stdout, code, stderr } = await runBuiltBin(
  712. ['--profile', 'web', '--patch', overlay, '--dump-config'],
  713. { DSH_HOME: home },
  714. )
  715. expect(code).toBe(0)
  716. expect(stdout).toContain('provider: configured-provider')
  717. expect(stdout).not.toContain('personal-provider')
  718. // Both layers patched the row; the comment lists them in application order.
  719. expect(stdout).toContain(`patched by ${profilePatch}, ${overlay}`)
  720. expect(stderr).toContain('patch: entry "absent-row" not found')
  721. }, 30_000)
  722. })
  723. })