scripts.spec.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { dirname, join } from 'node:path'
  4. import { PassThrough, Writable } from 'node:stream'
  5. import { fileURLToPath, pathToFileURL } from 'node:url'
  6. import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest'
  7. import {
  8. HeadlessPromptPort,
  9. LocalPluginBlueprint,
  10. NpmPackageManager,
  11. SdkProject,
  12. featureId,
  13. createBuiltinRegistry,
  14. type CommandRunner,
  15. type NestedMultiSelectValue,
  16. type ProjectCreationRequest,
  17. type PromptPort,
  18. } from '@deepseek-ai/dsh-helper'
  19. import type {
  20. ConfirmPromptRequest,
  21. MultiSelectPromptRequest,
  22. NestedMultiSelectRequest,
  23. PromptOutcome,
  24. SecretPromptRequest,
  25. SelectPromptRequest,
  26. TextPromptRequest,
  27. } from '../../helper/src/questions/prompt-port.ts'
  28. import { runSDK, startSDK } from '@deepseek-ai/dsh-scripts'
  29. import { parseDshSdkArgs, parseSdkBootArgs } from '../src/args.ts'
  30. import { PluginBuild, ProjectBuild, runProjectBuild } from '../src/build.ts'
  31. import { runDshSdkCommand, type DshSdkCommandContext } from '../src/command.ts'
  32. import { runConfigCommand } from '../src/config.ts'
  33. import { ConfigWorkflow, type ConfigPlan } from '../src/config/config-workflow.ts'
  34. import { runCreatePluginCommand } from '../src/create-plugin.ts'
  35. import { reportCommandTelemetry, type CommandTelemetryEvent } from '../src/telemetry.ts'
  36. import { initialize, resolve as resolveLocalPlugin } from '../src/local-plugin-loader-hooks.ts'
  37. const temporary: string[] = []
  38. afterEach(async () => {
  39. await Promise.all(temporary.splice(0).map(path => rm(path, { recursive: true, force: true })))
  40. })
  41. class QueuePort implements PromptPort {
  42. readonly #answers: unknown[]
  43. constructor(answers: unknown[]) { this.#answers = [...answers] }
  44. next<T>(): Promise<PromptOutcome<T>> {
  45. return Promise.resolve({ status: 'answered', value: this.#answers.shift() as T })
  46. }
  47. text(_request: TextPromptRequest): Promise<PromptOutcome<string>> { return this.next() }
  48. secret(_request: SecretPromptRequest): Promise<PromptOutcome<string>> { return this.next() }
  49. select<T>(_request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> { return this.next() }
  50. multiselect<T>(_request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> { return this.next() }
  51. confirm(_request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> { return this.next() }
  52. nestedMultiselect<TValue, TChoice>(
  53. _request: NestedMultiSelectRequest<TValue, TChoice>,
  54. ): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> { return this.next() }
  55. }
  56. function outputBuffer(): { stream: Writable; read: () => string } {
  57. let text = ''
  58. return {
  59. stream: new Writable({ write(chunk, _encoding, callback) { text += String(chunk); callback() } }),
  60. read: () => text,
  61. }
  62. }
  63. function commandContext(cwd: string): DshSdkCommandContext & { readStdout: () => string; readStderr: () => string } {
  64. let stdout = ''
  65. let stderr = ''
  66. const stdin = Object.assign(new PassThrough(), { isTTY: true }) as unknown as NodeJS.ReadStream
  67. const output = Object.assign(new Writable({
  68. write(chunk, _encoding, callback) { stdout += String(chunk); callback() },
  69. }), { isTTY: true }) as unknown as NodeJS.WriteStream
  70. const error = new Writable({
  71. write(chunk, _encoding, callback) { stderr += String(chunk); callback() },
  72. }) as unknown as NodeJS.WriteStream
  73. return {
  74. cwd, stdin, stdout: output, stderr: error,
  75. readStdout: () => stdout,
  76. readStderr: () => stderr,
  77. }
  78. }
  79. function creation(
  80. extra: ProjectCreationRequest['features'] = [],
  81. localPlugins: readonly LocalPluginBlueprint[] = [],
  82. app: 'acp' | 'tui' | 'embed' = 'embed',
  83. ): ProjectCreationRequest {
  84. return {
  85. name: 'config-agent',
  86. description: 'config test',
  87. runtime: { model: 'deepseek-v4-flash' },
  88. packageManager: new NpmPackageManager('10.0.0'),
  89. releaseVersion: '0.0.1',
  90. features: [
  91. { id: featureId('provider'), options: ['deepseek'], secrets: { apiKey: 'key' } },
  92. { id: featureId('bash'), options: ['local'] },
  93. { id: featureId('app'), options: [app] },
  94. { id: featureId('persistence'), options: ['jsonl'] },
  95. ...extra,
  96. ],
  97. localPlugins,
  98. }
  99. }
  100. async function committedProject(
  101. extra: ProjectCreationRequest['features'] = [],
  102. localPlugins: readonly LocalPluginBlueprint[] = [],
  103. app: 'acp' | 'tui' | 'embed' = 'embed',
  104. ): Promise<SdkProject> {
  105. const root = await mkdtemp(join(tmpdir(), 'dsh-config-workflow-'))
  106. temporary.push(root)
  107. const request = creation(extra, localPlugins, app)
  108. const project = SdkProject.create(root, request)
  109. const registry = createBuiltinRegistry(project.profile)
  110. const edit = project.edit(registry)
  111. for (const item of request.features) edit.installFeature(registry.get(item.id), item)
  112. for (const plugin of localPlugins) edit.addPlugin(plugin)
  113. return (await edit.commit()).project
  114. }
  115. describe('Commander launcher arguments', () => {
  116. it('parses real subcommands and forwards arbitrary build options', () => {
  117. expect(parseDshSdkArgs([])).toMatchObject({ help: true })
  118. expect(parseDshSdkArgs(['start', 'index.js'])).toMatchObject({ command: 'start', target: 'index.js' })
  119. expect(parseDshSdkArgs(['dev'])).toEqual({ command: 'dev', forwarded: [], help: false })
  120. expect(parseDshSdkArgs(['build', '--watch', '--minify'])).toMatchObject({
  121. command: 'build', forwarded: ['--watch', '--minify'],
  122. })
  123. expect(parseDshSdkArgs(['start', 'index.js', '--', '--resume', 'session-1'])).toMatchObject({
  124. command: 'start', target: 'index.js', forwarded: ['--resume', 'session-1'],
  125. })
  126. expect(parseDshSdkArgs(['config'])).toMatchObject({ command: 'config' })
  127. expect(parseDshSdkArgs(['start'])).toEqual({ command: 'start', forwarded: [], help: false })
  128. expect(parseDshSdkArgs(['dev', 'index.ts'])).toMatchObject({ command: 'dev', target: 'index.ts' })
  129. expect(parseDshSdkArgs(['-h'])).toMatchObject({ help: true })
  130. expect(parseDshSdkArgs(['--help'])).toMatchObject({ help: true })
  131. expect(() => parseDshSdkArgs(['unknown'])).toThrow()
  132. expect(() => parseDshSdkArgs(['config', 'extra'])).toThrow()
  133. expect(() => parseDshSdkArgs(['config', '--', 'extra'])).toThrow('does not accept forwarded')
  134. expect(parseSdkBootArgs([
  135. '--model=mock', '--resume=session-1', '--custom=value', '--verbose', '--no-cache', '--max-depth=-1',
  136. ])).toEqual({
  137. model: 'mock', resume: 'session-1', custom: 'value', verbose: true, cache: false, 'max-depth': '-1',
  138. })
  139. })
  140. it('dispatches every command and maps failures to exit codes', async () => {
  141. const root = await mkdtemp(join(tmpdir(), 'dsh-command-'))
  142. temporary.push(root)
  143. const context = commandContext(root)
  144. const calls: unknown[] = []
  145. context.run = async (target, options) => { calls.push(['run', target, options]); return undefined }
  146. context.build = async (args, cwd) => { calls.push(['build', args, cwd]) }
  147. context.config = async () => { calls.push(['config']); return {} }
  148. await expect(runDshSdkCommand(['start', 'index.js', '--', '--resume', 'session-1'], context)).resolves.toBe(0)
  149. await expect(runDshSdkCommand(['dev', 'index.ts'], context)).resolves.toBe(0)
  150. await expect(runDshSdkCommand(['build', '--watch'], context)).resolves.toBe(0)
  151. await expect(runDshSdkCommand(['config'], context)).resolves.toBe(0)
  152. expect(calls).toHaveLength(4)
  153. expect(calls[0]).toEqual(['run', 'index.js', { cwd: root, argv: ['--resume', 'session-1'] }])
  154. expect(calls[1]).toEqual(['run', 'index.ts', { cwd: root, dev: true, argv: [] }])
  155. context.config = async () => ({ installError: new Error('offline') })
  156. await expect(runDshSdkCommand(['config'], context)).resolves.toBe(1)
  157. context.config = async () => { throw 'broken' }
  158. await expect(runDshSdkCommand(['config'], context)).resolves.toBe(1)
  159. expect(context.readStderr()).toContain('broken')
  160. await expect(runDshSdkCommand(['unknown'], context)).resolves.toBe(1)
  161. await expect(runDshSdkCommand([], context)).resolves.toBe(0)
  162. expect(context.readStdout()).toContain('Usage: dsh-sdk')
  163. expect(context.readStdout()).toContain('create <source>')
  164. const defaults = commandContext(root)
  165. await writeFile(join(root, 'main.mjs'), 'export function main() { return "ok" }\n')
  166. await expect(runDshSdkCommand(['start', 'main.mjs'], defaults)).resolves.toBe(0)
  167. await expect(runDshSdkCommand(['build'], defaults)).resolves.toBe(0)
  168. defaults.port = new QueuePort([[]])
  169. await expect(runDshSdkCommand(['config'], defaults)).resolves.toBe(1)
  170. })
  171. })
  172. describe('build profiles and invocation', () => {
  173. it('discovers root and plugin targets and creates independent profiles', async () => {
  174. const root = await mkdtemp(join(tmpdir(), 'dsh-build-profile-'))
  175. temporary.push(root)
  176. await mkdir(join(root, 'plugins', 'one', 'src'), { recursive: true })
  177. await writeFile(join(root, 'index.ts'), 'export {}\n')
  178. await writeFile(join(root, 'plugins', 'one', 'package.json'), '{"name":"one"}\n')
  179. await writeFile(join(root, 'plugins', 'one', 'src', 'index.ts'), 'export {}\n')
  180. expect(ProjectBuild({ cwd: root, entry: ['index.ts'] })).toEqual([
  181. { cwd: root, entry: ['index.ts'] },
  182. { workspace: { include: ['plugins/*'] } },
  183. ])
  184. expect(PluginBuild({ entry: ['src/index.ts'], dts: true })).toEqual({ entry: ['src/index.ts'], dts: true })
  185. expect(() => ProjectBuild({ workspace: true })).toThrow('owns workspace discovery')
  186. expect(() => PluginBuild({ workspace: true })).toThrow('does not accept nested workspace')
  187. expect(ProjectBuild({ cwd: join(root, 'empty'), entry: ['index.ts'] })).toEqual([
  188. { cwd: join(root, 'empty'), entry: ['index.ts'] },
  189. ])
  190. expect(ProjectBuild({ entry: ['index.ts'] })[0]).toMatchObject({ entry: ['index.ts'] })
  191. })
  192. it('runs the project-installed tsdown and reports child failure', async () => {
  193. const root = await mkdtemp(join(tmpdir(), 'dsh-build-run-'))
  194. temporary.push(root)
  195. await writeFile(join(root, 'package.json'), '{"type":"module"}\n')
  196. await writeFile(join(root, 'index.ts'), 'export {}\n')
  197. await writeFile(join(root, 'tsdown.config.ts'), 'export default {}\n')
  198. await mkdir(join(root, 'node_modules'), { recursive: true })
  199. const manifest = fileURLToPath(import.meta.resolve('tsdown/package.json'))
  200. await symlink(dirname(manifest), join(root, 'node_modules', 'tsdown'))
  201. const calls: string[][] = []
  202. const runner: CommandRunner = {
  203. run: async (command, args) => {
  204. calls.push([command, ...args])
  205. return { exitCode: 0, signal: null }
  206. },
  207. }
  208. await runProjectBuild(['--watch'], root, runner)
  209. expect(calls[0]?.[0]).toBe(process.execPath)
  210. expect(calls[0]?.at(-1)).toBe('--watch')
  211. const failed: CommandRunner = { run: async () => ({ exitCode: 2, signal: null }) }
  212. await expect(runProjectBuild([], root, failed)).rejects.toThrow('exited with code 2')
  213. const killed: CommandRunner = { run: async () => ({ exitCode: null, signal: 'SIGTERM' }) }
  214. await expect(runProjectBuild([], root, killed)).rejects.toThrow('killed by SIGTERM')
  215. })
  216. it('recognizes every tsdown config source', async () => {
  217. const manifest = fileURLToPath(import.meta.resolve('tsdown/package.json'))
  218. for (const extension of ['cts', 'cjs', 'json']) {
  219. const root = await mkdtemp(join(tmpdir(), `dsh-build-${extension}-`))
  220. temporary.push(root)
  221. await writeFile(join(root, 'package.json'), '{"type":"module"}\n')
  222. await writeFile(join(root, `tsdown.config.${extension}`), '{}\n')
  223. await mkdir(join(root, 'node_modules'), { recursive: true })
  224. await symlink(dirname(manifest), join(root, 'node_modules', 'tsdown'))
  225. let called = false
  226. await runProjectBuild([], root, {
  227. run: async () => { called = true; return { exitCode: 0, signal: null } },
  228. })
  229. expect(called).toBe(true)
  230. }
  231. const root = await mkdtemp(join(tmpdir(), 'dsh-build-package-json-'))
  232. temporary.push(root)
  233. await writeFile(join(root, 'package.json'), '{"type":"module","tsdown":{}}\n')
  234. await mkdir(join(root, 'node_modules'), { recursive: true })
  235. await symlink(dirname(manifest), join(root, 'node_modules', 'tsdown'))
  236. let called = false
  237. await runProjectBuild([], root, {
  238. run: async () => { called = true; return { exitCode: 0, signal: null } },
  239. })
  240. expect(called).toBe(true)
  241. })
  242. it('reports missing and malformed project tsdown executables', async () => {
  243. const missing = await mkdtemp(join(tmpdir(), 'dsh-build-missing-'))
  244. temporary.push(missing)
  245. await writeFile(join(missing, 'package.json'), '{"type":"module"}')
  246. await writeFile(join(missing, 'tsdown.config.ts'), 'export default {}\n')
  247. await expect(runProjectBuild([], missing)).rejects.toThrow('requires tsdown')
  248. const malformed = await mkdtemp(join(tmpdir(), 'dsh-build-malformed-'))
  249. temporary.push(malformed)
  250. await writeFile(join(malformed, 'package.json'), '{"type":"module"}')
  251. await writeFile(join(malformed, 'tsdown.config.ts'), 'export default {}\n')
  252. await mkdir(join(malformed, 'node_modules', 'tsdown'), { recursive: true })
  253. await writeFile(join(malformed, 'node_modules', 'tsdown', 'package.json'), JSON.stringify({
  254. name: 'tsdown', version: '0.0.0', exports: { './package.json': './package.json' }, bin: {},
  255. }))
  256. await expect(runProjectBuild([], malformed)).rejects.toThrow('has no executable')
  257. await writeFile(join(malformed, 'node_modules', 'tsdown', 'package.json'), JSON.stringify({
  258. name: 'tsdown', version: '0.0.0', exports: { './package.json': './package.json' },
  259. }))
  260. await expect(runProjectBuild([], malformed)).rejects.toThrow('has no executable')
  261. const stringBin = await mkdtemp(join(tmpdir(), 'dsh-build-string-bin-'))
  262. temporary.push(stringBin)
  263. await writeFile(join(stringBin, 'package.json'), '{"type":"module"}')
  264. await writeFile(join(stringBin, 'tsdown.config.js'), 'export default {}\n')
  265. await mkdir(join(stringBin, 'node_modules', 'tsdown'), { recursive: true })
  266. await writeFile(join(stringBin, 'node_modules', 'tsdown', 'package.json'), JSON.stringify({
  267. name: 'tsdown', version: '0.0.0', exports: { './package.json': './package.json' }, bin: 'cli.js',
  268. }))
  269. await writeFile(join(stringBin, 'node_modules', 'tsdown', 'cli.js'), '')
  270. let command = ''
  271. await runProjectBuild([], stringBin, {
  272. run: async (_node, args) => { command = args[0] ?? ''; return { exitCode: 0, signal: null } },
  273. })
  274. expect(command).toContain('cli.js')
  275. })
  276. it('returns a no-op for a project with no build targets and hints on a missing start target', async () => {
  277. const root = await mkdtemp(join(tmpdir(), 'dsh-no-build-'))
  278. temporary.push(root)
  279. let called = false
  280. await runProjectBuild([], root, { run: async () => { called = true; return { exitCode: 0, signal: null } } })
  281. expect(called).toBe(false)
  282. const unreadableManifest = await mkdtemp(join(tmpdir(), 'dsh-build-unreadable-manifest-'))
  283. temporary.push(unreadableManifest)
  284. await mkdir(join(unreadableManifest, 'package.json'))
  285. await expect(runProjectBuild([], unreadableManifest)).rejects.toThrow()
  286. await expect(runSDK('index.js', { cwd: root })).rejects.toThrow('Run dsh-sdk build first')
  287. })
  288. it('invokes the target module main export and rejects passive modules', async () => {
  289. const root = await mkdtemp(join(tmpdir(), 'dsh-module-main-'))
  290. temporary.push(root)
  291. await writeFile(join(root, 'main.mjs'), 'export function main(context) { return context }\n')
  292. await writeFile(join(root, 'passive.mjs'), 'export const value = 1\n')
  293. await expect(runSDK('main.mjs', {
  294. cwd: root,
  295. argv: ['--model=mock', '--resume=session-1', 'custom'],
  296. })).resolves.toEqual({
  297. argv: ['--model=mock', '--resume=session-1', 'custom'],
  298. args: { model: 'mock', resume: 'session-1' }, cwd: root, mode: 'start',
  299. })
  300. await expect(runSDK('passive.mjs', { cwd: root })).rejects.toThrow('must export function main()')
  301. })
  302. it('boots empty Cordis configs and delegates targetless runs', async () => {
  303. expectTypeOf(runSDK).toBeCallableWith()
  304. const root = await mkdtemp(join(tmpdir(), 'dsh-start-sdk-'))
  305. temporary.push(root)
  306. await writeFile(join(root, 'cordis.yml'), '[]\n')
  307. const byUrl = await startSDK(pathToFileURL(join(root, 'cordis.yml')))
  308. await byUrl.fiber.dispose()
  309. const byRun = await runSDK(undefined, { cwd: root }) as import('cordis').Context
  310. await byRun.fiber.dispose()
  311. const dev = await startSDK('./cordis.yml', { cwd: root, dev: true })
  312. await dev.fiber.dispose()
  313. await expect(startSDK(new URL('https://example.invalid/cordis.yml'), { cwd: root })).rejects.toThrow()
  314. })
  315. it('validates local plugin metadata in dev mode', async () => {
  316. const malformed = await mkdtemp(join(tmpdir(), 'dsh-dev-malformed-'))
  317. temporary.push(malformed)
  318. await mkdir(join(malformed, 'plugins', 'bad'), { recursive: true })
  319. await expect(runSDK('missing.ts', { cwd: malformed, dev: true })).rejects.toThrow('cannot load local plugin metadata')
  320. const absent = await mkdtemp(join(tmpdir(), 'dsh-dev-absent-'))
  321. temporary.push(absent)
  322. await expect(runSDK('missing.ts', { cwd: absent, dev: true })).rejects.toThrow('cannot start missing target')
  323. const unnamed = await mkdtemp(join(tmpdir(), 'dsh-dev-unnamed-'))
  324. temporary.push(unnamed)
  325. await mkdir(join(unnamed, 'plugins', 'bad', 'src'), { recursive: true })
  326. await writeFile(join(unnamed, 'plugins', 'bad', 'package.json'), '{}')
  327. await writeFile(join(unnamed, 'plugins', 'bad', 'src/index.ts'), 'export {}\n')
  328. await expect(runSDK('missing.ts', { cwd: unnamed, dev: true })).rejects.toThrow('has no name')
  329. const duplicate = await mkdtemp(join(tmpdir(), 'dsh-dev-duplicate-'))
  330. temporary.push(duplicate)
  331. for (const name of ['one', 'two']) {
  332. await mkdir(join(duplicate, 'plugins', name, 'src'), { recursive: true })
  333. await writeFile(join(duplicate, 'plugins', name, 'package.json'), '{"name":"same"}')
  334. await writeFile(join(duplicate, 'plugins', name, 'src/index.ts'), 'export {}\n')
  335. }
  336. await expect(runSDK('missing.ts', { cwd: duplicate, dev: true })).rejects.toThrow('duplicate local plugin')
  337. const valid = await mkdtemp(join(tmpdir(), 'dsh-dev-valid-'))
  338. temporary.push(valid)
  339. await mkdir(join(valid, 'plugins', 'one', 'src'), { recursive: true })
  340. await writeFile(join(valid, 'plugins', 'README.md'), 'skip\n')
  341. await writeFile(join(valid, 'plugins', 'one', 'package.json'), '{"name":"local"}')
  342. await writeFile(join(valid, 'plugins', 'one', 'src/index.ts'), 'export {}\n')
  343. await writeFile(join(valid, 'main.ts'), 'export function main() { return "dev" }\n')
  344. await expect(runSDK('main.ts', { cwd: valid, dev: true })).resolves.toBe('dev')
  345. await expect(runSDK('missing.ts', { cwd: valid, dev: true })).rejects.toThrow('cannot start missing target')
  346. })
  347. it('maps only exact local package names through the loader hook', async () => {
  348. initialize({ mappings: { local: 'file:///tmp/local.ts' } })
  349. const next = async (specifier: string) => ({ url: specifier, format: 'module' as const })
  350. const context: import('node:module').ResolveHookContext = {
  351. conditions: [], importAttributes: {}, parentURL: undefined,
  352. }
  353. await expect(resolveLocalPlugin('local', context, next)).resolves.toMatchObject({ url: 'file:///tmp/local.ts' })
  354. await expect(resolveLocalPlugin('other', context, next)).resolves.toMatchObject({ url: 'other' })
  355. })
  356. })
  357. describe('ConfigWorkflow', () => {
  358. it('opens a project through the config command prompt seam', async () => {
  359. const project = await committedProject()
  360. const context = commandContext(project.root)
  361. context.port = new QueuePort([[]])
  362. context.install = async () => { throw new Error('install should not run') }
  363. await expect(runConfigCommand(context)).resolves.toEqual({})
  364. delete context.port
  365. delete context.install
  366. context.stdin.isTTY = false
  367. await expect(runConfigCommand(context)).rejects.toThrow('interactive TTY')
  368. context.stdin.isTTY = true
  369. context.stdout.isTTY = false
  370. await expect(runConfigCommand(context)).rejects.toThrow('interactive TTY')
  371. })
  372. it('accumulates a disable and commits only after Review & Apply', async () => {
  373. const project = await committedProject([{ id: featureId('todo'), options: ['default'] }])
  374. const registry = createBuiltinRegistry(project.profile)
  375. const output = outputBuffer()
  376. const workflow = new ConfigWorkflow(new QueuePort([
  377. [], true,
  378. ]), output.stream, async () => { throw new Error('install should not run') })
  379. const result = await workflow.run(project, registry)
  380. expect(result.commit?.project.cordis.entry('tool-todo')?.disabled).toBe(true)
  381. expect(output.read()).toContain('Disable feature: todo')
  382. })
  383. it('reconciles a headless plan without prompting and preserves custom plugins', async () => {
  384. const project = await committedProject([], [new LocalPluginBlueprint('plugin', 'plugin')])
  385. const registry = createBuiltinRegistry(project.profile)
  386. const output = outputBuffer()
  387. let installs = 0
  388. const plan: ConfigPlan = {
  389. features: [
  390. { id: featureId('bash'), options: ['local'] },
  391. { id: featureId('persistence'), options: ['jsonl'] },
  392. { id: featureId('todo'), options: ['default'] },
  393. { id: featureId('web'), options: ['exa'], secrets: { apiKey: 'exa-key' } },
  394. ],
  395. }
  396. const result = await new ConfigWorkflow(
  397. new HeadlessPromptPort(), output.stream, async () => { installs += 1 },
  398. ).run(project, registry, plan)
  399. expect(result.commit?.project.cordis.entry('tool-todo')).toBeDefined()
  400. // the unlisted custom local plugin keeps its enabled state (not nuked by the plan)
  401. expect(result.commit?.project.cordis.entry('plugin')?.disabled).toBeFalsy()
  402. expect(installs).toBe(1)
  403. })
  404. it('installs once after NPM dependency changes and keeps committed files on install failure', async () => {
  405. const project = await committedProject()
  406. const registry = createBuiltinRegistry(project.profile)
  407. const output = outputBuffer()
  408. let installs = 0
  409. const workflow = new ConfigWorkflow(new QueuePort([
  410. [{ value: 'feature:todo', choices: [] }], true,
  411. ]), output.stream, async () => {
  412. installs += 1
  413. throw new Error('offline')
  414. })
  415. const result = await workflow.run(project, registry)
  416. expect(installs).toBe(1)
  417. expect(result.installError?.message).toBe('offline')
  418. expect(result.commit?.project.cordis.entry('tool-todo')).toBeDefined()
  419. expect(output.read()).toContain('Changes were committed, but install failed')
  420. })
  421. it('cancels apply and enables a disabled feature without reinstalling', async () => {
  422. const project = await committedProject([{ id: featureId('todo'), options: ['default'] }])
  423. const registry = createBuiltinRegistry(project.profile)
  424. const cancelled = await new ConfigWorkflow(new QueuePort([[], false]), outputBuffer().stream).run(project, registry)
  425. expect(cancelled).toEqual({})
  426. const disable = project.edit(registry)
  427. disable.disableFeature(registry.get(featureId('todo')))
  428. const disabled = (await disable.commit()).project
  429. let installs = 0
  430. const enabled = await new ConfigWorkflow(new QueuePort([
  431. [{ value: 'feature:todo', choices: [] }], true,
  432. ]), outputBuffer().stream, async () => { installs += 1 }).run(disabled, createBuiltinRegistry(disabled.profile))
  433. expect(enabled.commit?.project.cordis.entry('tool-todo')?.disabled).toBeUndefined()
  434. expect(installs).toBe(0)
  435. })
  436. it('toggles custom Cordis config entries without changing NPM dependencies', async () => {
  437. const project = await committedProject([], [new LocalPluginBlueprint('sample', 'plugin')])
  438. await expect(new ConfigWorkflow(new QueuePort([
  439. [{ value: 'plugin:sample', choices: [] }],
  440. ]), outputBuffer().stream).run(project, createBuiltinRegistry(project.profile))).resolves.toEqual({})
  441. const output = outputBuffer()
  442. const disabled = await new ConfigWorkflow(new QueuePort([[], true]), output.stream).run(
  443. project, createBuiltinRegistry(project.profile),
  444. )
  445. expect(disabled.commit?.project.cordis.entry('sample')?.disabled).toBe(true)
  446. expect(output.read()).toContain('Disable custom plugin: sample')
  447. const next = disabled.commit?.project
  448. if (!next) throw new Error('custom toggle did not commit')
  449. const enabled = await new ConfigWorkflow(new QueuePort([
  450. [{ value: 'plugin:sample', choices: [] }], true,
  451. ]), outputBuffer().stream).run(next, createBuiltinRegistry(next.profile))
  452. expect(enabled.commit?.project.cordis.entry('sample')?.disabled).toBeUndefined()
  453. })
  454. it('shows inconsistent features as diagnostic-only rows', async () => {
  455. const complete = await committedProject()
  456. await writeFile(join(complete.root, 'cordis.yml'), `${await readFile(join(complete.root, 'cordis.yml'), 'utf8')}- id: web-search-exa
  457. name: '@deepseek-ai/dsh-web-search-exa'
  458. `)
  459. const project = await SdkProject.open(complete.root)
  460. const port = new QueuePort([[]])
  461. await expect(new ConfigWorkflow(port, outputBuffer().stream).run(project, createBuiltinRegistry(project.profile)))
  462. .resolves.toEqual({})
  463. })
  464. it('uses the default installer and normalizes non-Error install failures', async () => {
  465. const project = await committedProject()
  466. const install = vi.spyOn(NpmPackageManager.prototype, 'install').mockResolvedValue()
  467. await new ConfigWorkflow(new QueuePort([
  468. [{ value: 'feature:todo', choices: [] }], true,
  469. ])).run(project, createBuiltinRegistry(project.profile))
  470. expect(install).toHaveBeenCalledOnce()
  471. install.mockRestore()
  472. const next = await committedProject()
  473. const failed = await new ConfigWorkflow(new QueuePort([
  474. [{ value: 'feature:todo', choices: [] }], true,
  475. ]), outputBuffer().stream, async () => { throw 'offline-string' }).run(next, createBuiltinRegistry(next.profile))
  476. expect(failed.installError?.message).toBe('offline-string')
  477. })
  478. it('reconciles a child option selected in the feature tree', async () => {
  479. const project = await committedProject()
  480. const registry = createBuiltinRegistry(project.profile)
  481. let installs = 0
  482. const workflow = new ConfigWorkflow(new QueuePort([
  483. [{ value: 'feature:persistence', choices: ['sqlite'] }], true,
  484. ]), outputBuffer().stream, async () => { installs += 1 })
  485. const result = await workflow.run(project, registry)
  486. expect(result.commit?.project.cordis.entry('session-persistence')).toMatchObject({
  487. name: '@deepseek-ai/dsh-session-persistence-sqlite',
  488. config: { path: './.sessions/sessions.sqlite' },
  489. })
  490. expect(installs).toBe(1)
  491. })
  492. it('switches required provider and interface options', async () => {
  493. const project = await committedProject()
  494. const registry = createBuiltinRegistry(project.profile)
  495. const workflow = new ConfigWorkflow(new QueuePort([
  496. [
  497. { value: 'feature:provider', choices: ['custom'] },
  498. { value: 'feature:app', choices: ['tui'] },
  499. { value: 'feature:persistence', choices: ['jsonl'] },
  500. ],
  501. 'https://provider.example/v1',
  502. 'custom-key',
  503. true,
  504. ]), outputBuffer().stream, async () => {})
  505. const result = await workflow.run(project, registry)
  506. const provider = result.commit?.project.cordis.entry('llm-pi-ai')
  507. expect(provider?.config?.apiKey).toBeDefined()
  508. expect(provider?.config?.baseURL).toBe('https://provider.example/v1')
  509. expect(result.commit?.project.cordis.entry('tui')).toBeDefined()
  510. expect(result.commit?.project.cordis.entry('agent-loop')).toBeDefined()
  511. expect(result.commit?.project.cordis.entry('agent-core')).toBeUndefined()
  512. })
  513. it('disables ask-user when switching its app interface to ACP', async () => {
  514. const project = await committedProject([
  515. { id: featureId('ask-user'), options: ['default'] },
  516. ], [], 'tui')
  517. const registry = createBuiltinRegistry(project.profile)
  518. const output = outputBuffer()
  519. const workflow = new ConfigWorkflow(new QueuePort([
  520. [
  521. { value: 'feature:provider', choices: ['deepseek'] },
  522. { value: 'feature:app', choices: ['acp'] },
  523. { value: 'feature:persistence', choices: ['jsonl'] },
  524. { value: 'feature:ask-user', choices: ['default'] },
  525. ],
  526. true,
  527. ]), output.stream, async () => {})
  528. const result = await workflow.run(project, registry)
  529. expect(result.commit?.project.profile.runInterface).toBe('acp')
  530. expect(result.commit?.project.cordis.entry('tool-ask-user')?.disabled).toBe(true)
  531. expect(output.read()).toContain('Disable feature: ask-user')
  532. })
  533. })
  534. describe('dsh-sdk create', () => {
  535. const writeDependency = (name: string) => async (_m: unknown, spec: string, cwd: string): Promise<void> => {
  536. const path = join(cwd, 'package.json')
  537. const manifest = JSON.parse(await readFile(path, 'utf8')) as { dependencies?: Record<string, string> }
  538. manifest.dependencies = { ...manifest.dependencies, [name]: spec }
  539. await writeFile(path, JSON.stringify(manifest, null, 2))
  540. }
  541. it('adds a dependency and mounts it after confirmation', async () => {
  542. const project = await committedProject()
  543. const context = { ...commandContext(project.root), port: new QueuePort([true]), add: writeDependency('my-ext-plugin') }
  544. const result = await runCreatePluginCommand('github:o/r#sha', context)
  545. expect(result?.project.cordis.entry('my-ext-plugin')?.name).toBe('my-ext-plugin')
  546. expect(context.readStdout()).toContain('Mounted my-ext-plugin')
  547. })
  548. it('derives the cordis id from a scoped package name', async () => {
  549. const project = await committedProject()
  550. const context = { ...commandContext(project.root), port: new QueuePort([true]), add: writeDependency('@acme/cool-plugin') }
  551. const result = await runCreatePluginCommand('@acme/cool-plugin@1.0.0', context)
  552. expect(result?.project.cordis.entry('cool-plugin')?.name).toBe('@acme/cool-plugin')
  553. })
  554. it('returns undefined and adds nothing when declined', async () => {
  555. const project = await committedProject()
  556. let added = false
  557. const context = {
  558. ...commandContext(project.root),
  559. port: new QueuePort([false]),
  560. add: async () => { added = true },
  561. }
  562. await expect(runCreatePluginCommand('pkg@1.0.0', context)).resolves.toBeUndefined()
  563. expect(added).toBe(false)
  564. })
  565. it('rejects an empty source, a non-TTY session, and a no-op add', async () => {
  566. const project = await committedProject()
  567. await expect(runCreatePluginCommand(' ', { ...commandContext(project.root), port: new QueuePort([]) }))
  568. .rejects.toThrow('requires a plugin source')
  569. const noTty = commandContext(project.root)
  570. noTty.stdin.isTTY = false
  571. noTty.stdout.isTTY = false
  572. await expect(runCreatePluginCommand('pkg@1.0.0', noTty)).rejects.toThrow('interactive TTY')
  573. const noOutTty = commandContext(project.root)
  574. noOutTty.stdout.isTTY = false
  575. await expect(runCreatePluginCommand('pkg@1.0.0', noOutTty)).rejects.toThrow('interactive TTY')
  576. await expect(runCreatePluginCommand('pkg@1.0.0', {
  577. ...commandContext(project.root), port: new QueuePort([true]), add: async () => {},
  578. })).rejects.toThrow('added no new dependency')
  579. })
  580. it('dispatches create through the launcher', async () => {
  581. const project = await committedProject()
  582. const context = commandContext(project.root)
  583. context.createPlugin = async () => undefined
  584. await expect(runDshSdkCommand(['create', 'pkg@1.0.0'], context)).resolves.toBe(0)
  585. })
  586. })
  587. describe('command telemetry', () => {
  588. it('reports when consent allows and skips when denied or faulting', async () => {
  589. const dir = await mkdtemp(join(tmpdir(), 'dsh-telemetry-'))
  590. temporary.push(dir)
  591. const sent: unknown[] = []
  592. const reporter = { report: () => { sent.push(1) }, flush: async () => {} }
  593. await reportCommandTelemetry(
  594. { command: 'build', cwd: dir, durationMs: 5, success: true },
  595. { resolve: async () => ({ allowed: true, reason: 'absent' }), reporter },
  596. )
  597. expect(sent).toHaveLength(1)
  598. await reportCommandTelemetry(
  599. { command: 'build', cwd: dir, durationMs: 5, success: true },
  600. { resolve: async () => ({ allowed: false, reason: 'disabled' }), reporter },
  601. )
  602. expect(sent).toHaveLength(1)
  603. await expect(reportCommandTelemetry(
  604. { command: 'build', cwd: dir, durationMs: 5, success: true },
  605. { resolve: async () => { throw new Error('boom') }, reporter },
  606. )).resolves.toBeUndefined()
  607. expect(sent).toHaveLength(1)
  608. })
  609. it('emits a telemetry event carrying each command outcome', async () => {
  610. const project = await committedProject()
  611. const events: CommandTelemetryEvent[] = []
  612. const context = commandContext(project.root)
  613. context.telemetry = async (event) => { events.push(event) }
  614. context.build = async () => {}
  615. await expect(runDshSdkCommand(['build'], context)).resolves.toBe(0)
  616. expect(events).toHaveLength(1)
  617. expect(events[0]).toMatchObject({ command: 'build', cwd: project.root, success: true })
  618. await runDshSdkCommand([], context)
  619. expect(events).toHaveLength(1)
  620. context.build = async () => { throw new Error('boom') }
  621. await expect(runDshSdkCommand(['build'], context)).resolves.toBe(1)
  622. expect(events[1]).toMatchObject({ command: 'build', success: false })
  623. context.config = async () => ({ installError: new Error('offline') })
  624. await expect(runDshSdkCommand(['config'], context)).resolves.toBe(1)
  625. expect(events.at(-1)).toMatchObject({ command: 'config', success: false })
  626. })
  627. })