built-bin.e2e.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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 launching endpoint 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: 'launching endpoint 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, '.credentials.yaml'), `DEEPSEEK_API_KEY: ${apiKey}\n`, { mode: 0o600 })
  402. createEnvironmentProbeProfile(home, project)
  403. try {
  404. const result = await runBuiltBin(
  405. ['--profile', 'environment-probe'],
  406. {
  407. DSH_HOME: home,
  408. DSH_TELEMETRY_DISABLED: '1',
  409. DEEPSEEK_API_KEY: undefined,
  410. DEEPSEEK_BASE_URL: server.baseURL,
  411. },
  412. project,
  413. )
  414. expect(
  415. result.code,
  416. `${result.stderr}\nstdout:\n${result.stdout}\nmock requests: ${String(server.requests.length)}`,
  417. ).toBe(0)
  418. expect(result.stdout).toBe('launching endpoint reached the mock')
  419. expect(result.stdout).not.toContain(apiKey)
  420. expect(result.stderr).not.toContain(apiKey)
  421. expect(server.requests).toHaveLength(1)
  422. expect(server.requests[0]?.path).toBe('/chat/completions')
  423. expect(server.requests[0]?.headers.authorization).toBe(`Bearer ${apiKey}`)
  424. expect(JSON.stringify(server.requests[0]?.body)).not.toContain(apiKey)
  425. } finally {
  426. await server.close()
  427. rmSync(home, { recursive: true, force: true })
  428. rmSync(project, { recursive: true, force: true })
  429. }
  430. }, 30_000)
  431. it('reports a patch-overlay boot failure without hanging', async () => {
  432. // The HMR main watcher's initial scan once refreshed the include
  433. // mid-initial-apply, deadlocking the failing apply's rollback against the
  434. // refresh drain: dsh exited 13 with no diagnostic instead of settling
  435. // ([Agent Note](../../../.agents/notes/implemented/bug-fix/2026-08-03-hmr-initial-scan-boot-deadlock.md)).
  436. const home = mkdtempSync(join(tmpdir(), 'dsh-invalid-patch-'))
  437. try {
  438. const result = await runBuiltBin(['--profile', 'web', '--patch', invalidProvider], {
  439. DSH_HOME: home,
  440. DEEPSEEK_API_KEY: 'keyless-invalid-config',
  441. DSH_TELEMETRY_DISABLED: '1',
  442. })
  443. expect(result.code).toBe(1)
  444. expect(result.stdout).toBe('')
  445. expect(result.stderr).toContain('llm-pi-ai')
  446. } finally {
  447. rmSync(home, { recursive: true, force: true })
  448. }
  449. }, 30_000)
  450. it('lets a profile without a parser ignore app arguments and dispose on a startup-time signal', async () => {
  451. const fixture = createProfileLifecycleFixture()
  452. const child = startProfileLifecycle(fixture, ['--unclaimed'])
  453. try {
  454. await waitForFile(fixture.ready)
  455. requestProfileShutdown(child, fixture)
  456. const result = await child
  457. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  458. expect(result.signal).toBeUndefined()
  459. expect(existsSync(fixture.disposed)).toBe(true)
  460. } finally {
  461. child.kill('SIGKILL')
  462. rmSync(fixture.home, { recursive: true, force: true })
  463. }
  464. }, 30_000)
  465. it('fully settles a custom profile, hot-reloads its patch layer with removal reverting, and disposes on a signal', async () => {
  466. const fixture = createProfileLifecycleFixture()
  467. const child = startProfileLifecycle(fixture)
  468. const profilePatch = join(fixture.home, 'profiles', 'lifecycle', 'cordis.patch.yml')
  469. const configFile = join(fixture.home, 'config-echo')
  470. try {
  471. await waitForFile(fixture.settled)
  472. // The live profile layer: even without an hmr row in the composition,
  473. // the launcher mounts a config-only watcher, so an edited
  474. // cordis.patch.yml lands in the running tree (the reload disposes the
  475. // patched row's old fiber — observable as the disposed marker — and
  476. // mounts the new config, which echoes its generation and re-writes the
  477. // ready marker).
  478. rmSync(fixture.ready)
  479. writeFileSync(profilePatch, [
  480. '- id: profile-lifecycle-fixture',
  481. ' config:',
  482. ' generation: 2',
  483. '',
  484. ].join('\n'))
  485. await waitForFile(fixture.ready)
  486. expect(readFileSync(configFile, 'utf8')).toBe('2')
  487. // Removal reverts: the bundle's inserted row must return to its own
  488. // default config, not keep the removed override — the insert-aliasing
  489. // regression (a shared patch object mutated in place by a former
  490. // generation would make this impossible).
  491. rmSync(fixture.ready)
  492. writeFileSync(profilePatch, '[]\n')
  493. await waitForFile(fixture.ready)
  494. expect(readFileSync(configFile, 'utf8')).toBe('bundle-default')
  495. // The home-level user layer ($DSH_HOME/cordis.patch.yml) is live too
  496. // and outranks the per-profile layer.
  497. rmSync(fixture.ready)
  498. writeFileSync(join(fixture.home, 'cordis.patch.yml'), [
  499. '- id: profile-lifecycle-fixture',
  500. ' config:',
  501. ' generation: home',
  502. '',
  503. ].join('\n'))
  504. await waitForFile(fixture.ready)
  505. expect(readFileSync(configFile, 'utf8')).toBe('home')
  506. requestProfileShutdown(child, fixture)
  507. const result = await child
  508. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  509. expect(result.signal).toBeUndefined()
  510. expect(existsSync(fixture.disposed)).toBe(true)
  511. } finally {
  512. child.kill('SIGKILL')
  513. rmSync(fixture.home, { recursive: true, force: true })
  514. }
  515. }, 30_000)
  516. it('hands the app arguments to the profile, which applies them before its rows start', async () => {
  517. const fixture = createStartupFixture()
  518. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  519. try {
  520. await waitForFile(fixture.ready)
  521. // The consumer started once, already carrying the flag value: the
  522. // launcher never saw --generation, and the app provider resolved it first.
  523. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  524. requestProfileShutdown(child, fixture)
  525. expect((await child).exitCode).toBe(0)
  526. } finally {
  527. child.kill('SIGKILL')
  528. rmSync(fixture.home, { recursive: true, force: true })
  529. }
  530. }, 30_000)
  531. it('starts a consumer on its composed value when the invocation carries no app arguments', async () => {
  532. const fixture = createStartupFixture()
  533. const child = startStartupProfile(fixture, [])
  534. try {
  535. await waitForFile(fixture.ready)
  536. expect(readFileSync(fixture.echo, 'utf8')).toBe('bundle-default')
  537. requestProfileShutdown(child, fixture)
  538. expect((await child).exitCode).toBe(0)
  539. } finally {
  540. child.kill('SIGKILL')
  541. rmSync(fixture.home, { recursive: true, force: true })
  542. }
  543. }, 30_000)
  544. it('keeps the app arguments across a user patch reload', async () => {
  545. // A live edit recomposes every row while the provider service remains
  546. // active, so each config expression reads the same invocation value (a
  547. // served port does not move back to its composed fallback).
  548. const fixture = createStartupFixture()
  549. const profilePatch = join(fixture.home, 'profiles', 'startup', 'cordis.patch.yml')
  550. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  551. try {
  552. // Both rows: the waiting one carries the flag value, and the witness is
  553. // what a reload will re-mount. They start independently, so neither
  554. // marker implies the other.
  555. await waitForFile(fixture.ready)
  556. await waitForFile(fixture.witness)
  557. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  558. // An edit to an unrelated row: the witness re-mounts, which is how this
  559. // test knows the whole tree was recomposed.
  560. rmSync(fixture.witness)
  561. writeFileSync(profilePatch, [
  562. '- id: reload-witness',
  563. ' config:',
  564. ' generation: reloaded',
  565. '',
  566. ].join('\n'))
  567. await waitForFile(fixture.witness)
  568. expect(readFileSync(fixture.witness, 'utf8')).toBe('reloaded')
  569. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  570. requestProfileShutdown(child, fixture)
  571. expect((await child).exitCode).toBe(0)
  572. } finally {
  573. child.kill('SIGKILL')
  574. rmSync(fixture.home, { recursive: true, force: true })
  575. }
  576. }, 30_000)
  577. it("prints the app's own help, starts none of its rows, and exits", async () => {
  578. const fixture = createStartupFixture()
  579. try {
  580. const result = await startStartupProfile(fixture, ['--help'])
  581. expect(result.exitCode).toBe(0)
  582. expect(result.stdout).toContain('Usage: fixture')
  583. expect(result.stdout).toContain('--generation')
  584. expect(existsSync(fixture.ready)).toBe(false)
  585. } finally {
  586. rmSync(fixture.home, { recursive: true, force: true })
  587. }
  588. }, 30_000)
  589. it('anchors a relative add spec to the invoking directory, not the profile', async () => {
  590. // `dsh plugin --profile x add .` from a plugin checkout must install THAT
  591. // checkout — pnpm's cwd is the profile directory, so an un-anchored `.`
  592. // would self-link the profile.
  593. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-anchor-'))
  594. const checkout = mkdtempSync(join(tmpdir(), 'dsh-plugin-checkout-'))
  595. try {
  596. writeFileSync(join(checkout, 'package.json'), JSON.stringify({
  597. name: 'anchored-bundle',
  598. version: '1.0.0',
  599. dsh: { bundle: { patch: './cordis.patch.yml' } },
  600. }))
  601. writeFileSync(join(checkout, 'cordis.patch.yml'), '[]\n')
  602. const result = await execa(process.execPath, [dshBin, 'plugin', '--profile', 'anchor', 'add', '.'], {
  603. cwd: checkout,
  604. input: '',
  605. timeout: 60_000,
  606. killSignal: 'SIGKILL',
  607. reject: false,
  608. env: { DSH_HOME: home },
  609. })
  610. expect(result.exitCode).toBe(0)
  611. const manifest = JSON.parse(readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8')) as {
  612. dependencies: Record<string, string>
  613. dsh: { profile: { bundles: string[] } }
  614. }
  615. expect(Object.keys(manifest.dependencies)).toEqual(['anchored-bundle'])
  616. expect(manifest.dsh.profile.bundles).toContain('anchored-bundle')
  617. } finally {
  618. rmSync(home, { recursive: true, force: true })
  619. rmSync(checkout, { recursive: true, force: true })
  620. }
  621. }, 90_000)
  622. it('activates a dependency that gained dsh.bundle in a later update', async () => {
  623. // Reconcile runs against the INSTALLED state on every successful pnpm
  624. // run, so `update` (not only `add`) activates a package whose newer
  625. // version declares dsh.bundle. Simulated without a registry: hand-place
  626. // the installed package, flip its manifest, and run a benign pnpm verb.
  627. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-update-'))
  628. try {
  629. const profileDir = join(home, 'profiles', 'up')
  630. const installed = join(profileDir, 'node_modules', 'late-bundle')
  631. mkdirSync(installed, { recursive: true })
  632. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  633. name: 'dsh-profile-up',
  634. private: true,
  635. dependencies: { 'late-bundle': 'file:./late-bundle' },
  636. dsh: { profile: { bundles: ['@deepseek-ai/dsh-base'] } },
  637. }))
  638. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  639. // v1: no dsh manifest — a plain dependency.
  640. writeFileSync(join(installed, 'package.json'), JSON.stringify({ name: 'late-bundle', version: '1.0.0' }))
  641. const first = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  642. expect(first.code).toBe(0)
  643. let manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  644. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base'])
  645. // v2: the installed package now declares dsh.bundle (an update landed).
  646. writeFileSync(join(installed, 'package.json'), JSON.stringify({
  647. name: 'late-bundle', version: '2.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } },
  648. }))
  649. writeFileSync(join(installed, 'cordis.patch.yml'), '[]\n')
  650. const second = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  651. expect(second.code).toBe(0)
  652. manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  653. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', 'late-bundle'])
  654. } finally {
  655. rmSync(home, { recursive: true, force: true })
  656. }
  657. }, 30_000)
  658. describe('config dump', () => {
  659. let home: string
  660. beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'dsh-dump-bin-')) })
  661. afterEach(() => { rmSync(home, { recursive: true, force: true }) })
  662. it('prints the web profile bundle layers without a user layer', async () => {
  663. const { stdout, code, stderr } = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  664. expect(code).toBe(0)
  665. expect(stderr).toBe('')
  666. expect(stdout).toContain("name: '@deepseek-ai/dsh-agent-loop'")
  667. expect(stdout).toContain('agents: []')
  668. expect(stdout).toContain('# == @deepseek-ai/dsh-base')
  669. expect(stdout).toContain("name: '@deepseek-ai/dsh-host-webserver'")
  670. }, 30_000)
  671. it('prints the headless profile without Host or browser layers', async () => {
  672. const { stdout, code, stderr } = await runBuiltBin(
  673. ['--profile', 'headless', '--dump-default-config'],
  674. { DSH_HOME: home },
  675. )
  676. expect(code).toBe(0)
  677. expect(stderr).toBe('')
  678. expect(stdout).toContain("name: '@deepseek-ai/dsh-headless'")
  679. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-host-/)
  680. expect(stdout).not.toContain("name: '@deepseek-ai/dsh-web-app'")
  681. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-client-/)
  682. }, 30_000)
  683. it('composes the profile user layer and a --patch overlay in order', async () => {
  684. // Auto-init the web profile first, then write its user layer.
  685. const init = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  686. expect(init.code).toBe(0)
  687. const profilePatch = join(home, 'profiles', 'web', 'cordis.patch.yml')
  688. writeFileSync(profilePatch, [
  689. '- id: agent-loop',
  690. ' config:',
  691. ' agents:',
  692. ' - id: personal',
  693. ' provider: personal-provider',
  694. ' model: personal-model',
  695. '- id: absent-row',
  696. ' config:',
  697. ' x: 1',
  698. '',
  699. ].join('\n'))
  700. const overlay = join(home, 'overlay.cordis.yml')
  701. writeFileSync(overlay, [
  702. '- id: agent-loop',
  703. ' config:',
  704. ' agents:',
  705. ' - id: configured',
  706. ' provider: configured-provider',
  707. ' model: configured-model',
  708. '',
  709. ].join('\n'))
  710. const { stdout, code, stderr } = await runBuiltBin(
  711. ['--profile', 'web', '--patch', overlay, '--dump-config'],
  712. { DSH_HOME: home },
  713. )
  714. expect(code).toBe(0)
  715. expect(stdout).toContain('provider: configured-provider')
  716. expect(stdout).not.toContain('personal-provider')
  717. // Both layers patched the row; the comment lists them in application order.
  718. expect(stdout).toContain(`patched by ${profilePatch}, ${overlay}`)
  719. expect(stderr).toContain('patch: entry "absent-row" not found')
  720. }, 30_000)
  721. })
  722. })