plugin-manager.spec.ts 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. /**
  2. * The plugin manager over a real profile: a temporary harness home with one
  3. * profile, packages staged the way pnpm leaves them, the host tree booted
  4. * through `boot()` with the profile runtime the launcher provides, and a
  5. * fake pnpm that edits the profile the way the real one does. The manager
  6. * is built the way the Web host's adapter builds it, reading the runtime,
  7. * the roster, and the agent registry off the context per call.
  8. */
  9. import { EventEmitter } from 'node:events'
  10. import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  11. import { mkdtemp } from 'node:fs/promises'
  12. import { tmpdir } from 'node:os'
  13. import { join } from 'node:path'
  14. import { PassThrough } from 'node:stream'
  15. import type { ChildProcess } from 'node:child_process'
  16. import { afterEach, describe, expect, it } from 'vitest'
  17. import { Context, type Plugin } from '@deepseek-ai/cordis'
  18. import Loader from '@deepseek-ai/cordis-plugin-loader'
  19. import {
  20. boot, composeProfileStack, loadOptionalPatches, loadProfile, ProfileRuntime, readProbeCache, rootIncludeEntry,
  21. type ComposedStack, type Profile, type probePackage,
  22. } from '@deepseek-ai/dsh-app-boot'
  23. import {
  24. PluginManager, type PluginInstallLogChunk, type PluginToolingConfig, type SpawnLike,
  25. } from '@deepseek-ai/dsh-plugin-manager'
  26. import type {} from '@deepseek-ai/dsh-agent'
  27. import type {} from '@deepseek-ai/dsh-agent-presets'
  28. const NAME = 'dsh-test'
  29. /** A complete tooling config: the host's schema fills these defaults at load, the type does not. */
  30. function managerConfig(overrides: Partial<PluginToolingConfig> = {}): PluginToolingConfig {
  31. return { pnpmCommand: 'pnpm', installTimeoutMs: 1_000, probeTimeoutMs: 20_000, installLogTailBytes: 16_384, ...overrides }
  32. }
  33. /** Test seams: the child spawner and the package probe. */
  34. interface Internals {
  35. spawn?: SpawnLike
  36. probe?: typeof probePackage
  37. }
  38. const contexts: Context[] = []
  39. afterEach(async () => {
  40. await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose()))
  41. })
  42. /** Builtins the staged bundles name; registered on every boot. */
  43. const good: Plugin.Function = () => {}
  44. const throws: Plugin.Function = () => { throw new Error('boom at apply') }
  45. let flakyCalls = 0
  46. const flaky: Plugin.Function = () => {
  47. flakyCalls += 1
  48. if (flakyCalls === 1) throw new Error('flaky first start')
  49. }
  50. const provider: Plugin.Function = (ctx) => { ctx.effect(() => ctx.reflect.provide('fixtureSvc', { ready: true })) }
  51. const lonelyProvider: Plugin.Function = (ctx) => { ctx.effect(() => ctx.reflect.provide('lonelySvc', { ready: true })) }
  52. const consumer: Plugin.Object = { inject: ['fixtureSvc'], apply() {} }
  53. const prepare = (ctx: Context): void => {
  54. ctx.loader.builtins.good = good
  55. ctx.loader.builtins.throws = throws
  56. ctx.loader.builtins.flaky = flaky
  57. ctx.loader.builtins.provider = provider
  58. ctx.loader.builtins['lonely-provider'] = lonelyProvider
  59. ctx.loader.builtins.consumer = consumer
  60. }
  61. interface StagedHome {
  62. home: string
  63. profileDir: string
  64. anchor: string
  65. }
  66. /** A harness home with one empty live profile and an install anchor that carries nothing. */
  67. async function stageHome(patchReload: 'live' | 'startup' = 'live'): Promise<StagedHome> {
  68. const home = await mkdtemp(join(tmpdir(), 'dsh-plugin-manager-'))
  69. const profileDir = join(home, 'profiles', 'web')
  70. mkdirSync(profileDir, { recursive: true })
  71. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  72. name: 'dsh-profile-web', private: true, dependencies: {}, dsh: { profile: { bundles: [], patchReload } },
  73. }, null, 2))
  74. writeFileSync(join(profileDir, 'cordis.yml'), '[]\n')
  75. const anchorDir = join(home, 'anchor')
  76. mkdirSync(anchorDir, { recursive: true })
  77. const anchor = join(anchorDir, 'package.json')
  78. writeFileSync(anchor, JSON.stringify({ name: 'dsh-anchor', version: '0.0.0', dependencies: {} }))
  79. return { home, profileDir, anchor }
  80. }
  81. interface StagedPackage {
  82. /** The bundle patch text; omitted stages a bundle-less package. */
  83. patch?: string
  84. /** `index.js` text, exported as the package main. */
  85. main?: string
  86. version?: string
  87. /** Any string: a staged manifest may declare a stage the profile refuses. */
  88. stage?: string
  89. plugins?: { name: string; title?: string; config?: unknown }[]
  90. files?: Record<string, string>
  91. }
  92. /** Stage one package under the profile's node_modules, the way pnpm leaves it. */
  93. function stagePackage(profileDir: string, name: string, staged: StagedPackage): void {
  94. const dir = join(profileDir, 'node_modules', name)
  95. mkdirSync(dir, { recursive: true })
  96. writeFileSync(join(dir, 'package.json'), JSON.stringify({
  97. name,
  98. version: staged.version ?? '1.0.0',
  99. description: `staged ${name}`,
  100. type: 'module',
  101. ...staged.main === undefined ? {} : { main: 'index.js' },
  102. dsh: {
  103. title: `Title of ${name}`,
  104. ...staged.patch === undefined ? {} : { bundle: { patch: './cordis.patch.yml', ...staged.stage === undefined ? {} : { stage: staged.stage } } },
  105. ...staged.plugins === undefined ? {} : { plugins: staged.plugins },
  106. },
  107. }, null, 2))
  108. if (staged.patch !== undefined) writeFileSync(join(dir, 'cordis.patch.yml'), staged.patch)
  109. if (staged.main !== undefined) writeFileSync(join(dir, 'index.js'), staged.main)
  110. for (const [file, text] of Object.entries(staged.files ?? {})) {
  111. mkdirSync(join(dir, file, '..'), { recursive: true })
  112. writeFileSync(join(dir, file), text)
  113. }
  114. }
  115. /** Add a dependency to the profile manifest, as `pnpm add` does. */
  116. function addDependency(profileDir: string, name: string, spec = '1.0.0'): void {
  117. const path = join(profileDir, 'package.json')
  118. const manifest = JSON.parse(readFileSync(path, 'utf8')) as { dependencies: Record<string, string> }
  119. manifest.dependencies[name] = spec
  120. writeFileSync(path, JSON.stringify(manifest, null, 2))
  121. }
  122. function manifestOf(profileDir: string): { dependencies: Record<string, string>; dsh: { profile: { bundles: string[] } } } {
  123. return JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as ReturnType<typeof manifestOf>
  124. }
  125. /** What the fake pnpm does for one invocation. */
  126. type PnpmBehavior = (args: readonly string[]) => { code: number | null; stdout?: string; stderr?: string; hang?: boolean; error?: unknown }
  127. /** A fake `spawn` that runs `behavior` on the next tick and reports through a child-like emitter. */
  128. function fakePnpm(profileDir: string, behavior: PnpmBehavior, calls: string[][] = []): SpawnLike {
  129. return (command, args, options) => {
  130. calls.push([command, ...args])
  131. expect(options.cwd).toBe(profileDir)
  132. const child = new EventEmitter() as EventEmitter & { stdout: PassThrough; stderr: PassThrough; kill: (signal?: string) => boolean }
  133. child.stdout = new PassThrough()
  134. child.stderr = new PassThrough()
  135. let killed = false
  136. child.kill = () => { killed = true; return true }
  137. setTimeout(() => {
  138. const outcome = behavior(args)
  139. if (outcome.error !== undefined) {
  140. child.emit('error', outcome.error)
  141. return
  142. }
  143. if (outcome.stdout !== undefined) child.stdout.write(outcome.stdout)
  144. if (outcome.stderr !== undefined) child.stderr.write(outcome.stderr)
  145. if (outcome.hang === true) {
  146. // Report the kill the timeout sends, as a real child would.
  147. const poll = setInterval(() => {
  148. if (!killed) return
  149. clearInterval(poll)
  150. child.emit('close', null)
  151. }, 10)
  152. return
  153. }
  154. setTimeout(() => { child.emit('close', outcome.code) }, 5)
  155. }, 5)
  156. return child as unknown as ChildProcess
  157. }
  158. }
  159. /** The pnpm every install test shares: `add <name>` stages nothing (the test did) and records the dependency. */
  160. function recordingPnpm(profileDir: string, calls: string[][] = []): SpawnLike {
  161. return fakePnpm(profileDir, (args) => {
  162. const [verb, target] = args
  163. if (verb === 'add' && target !== undefined) {
  164. addDependency(profileDir, target)
  165. return { code: 0, stdout: `+ ${target} 1.0.0\n` }
  166. }
  167. if (verb === 'remove' && target !== undefined) {
  168. const path = join(profileDir, 'package.json')
  169. const manifest = JSON.parse(readFileSync(path, 'utf8')) as { dependencies: Record<string, string> }
  170. const { [target]: _removed, ...remaining } = manifest.dependencies
  171. writeFileSync(path, JSON.stringify({ ...manifest, dependencies: remaining }, null, 2))
  172. rmSync(join(profileDir, 'node_modules', target), { recursive: true, force: true })
  173. return { code: 0, stdout: `- ${target}\n` }
  174. }
  175. return { code: 1, stderr: 'unexpected pnpm invocation\n' }
  176. }, calls)
  177. }
  178. interface Booted {
  179. ctx: Context
  180. manager: PluginManager
  181. runtime: ProfileRuntime
  182. changes: { reason: string; packageName?: string }[]
  183. log: PluginInstallLogChunk[]
  184. }
  185. /** Boot the profile the way the launcher does, then build the manager over it. */
  186. async function bootProfile(staged: StagedHome, internals: Internals = {}, config: Partial<PluginToolingConfig> = {}): Promise<Booted> {
  187. const load = (): Profile => loadProfile(NAME, 'web', staged.anchor, staged.home)
  188. const composeFor = (profile: Profile): ComposedStack => {
  189. const stack = composeProfileStack(NAME, profile.layers, [
  190. { label: profile.patchPath, patches: loadOptionalPatches(NAME, profile.patchPath) ?? [] },
  191. ])
  192. return { ...stack, patches: structuredClone(stack.patches) }
  193. }
  194. const profile = load()
  195. const ctx = await boot(NAME, join(staged.profileDir, 'cordis.yml'), composeFor(profile).patches, prepare)
  196. contexts.push(ctx)
  197. await ctx.plugin(ProfileRuntime, {
  198. profile,
  199. stack: composeFor(profile),
  200. installAnchor: staged.anchor,
  201. loadProfile: load,
  202. compose: composeFor,
  203. rootEntry: () => rootIncludeEntry(ctx),
  204. })
  205. const changes: Booted['changes'] = []
  206. const log: PluginInstallLogChunk[] = []
  207. ctx.on('plugins/changed', (change) => { changes.push(change) })
  208. ctx.on('plugins/install-log', (chunk) => { log.push(chunk) })
  209. const manager = managerOver(ctx, internals, config)
  210. return { ctx, manager, runtime: ctx.profileRuntime, changes, log }
  211. }
  212. /** The manager as the Web host's adapter builds it: runtime, roster, and agent count read off the context per call. */
  213. function managerOver(ctx: Context, internals: Internals = {}, config: Partial<PluginToolingConfig> = {}): PluginManager {
  214. return new PluginManager(ctx, {
  215. config: managerConfig(config),
  216. runtime: () => ctx.get('profileRuntime'),
  217. presets: () => ctx.get('agentPresets'),
  218. runningAgents: () => (ctx.get('agents')?.list() ?? []).filter(agent => agent.status === 'running').length,
  219. ...internals,
  220. })
  221. }
  222. const entryIds = (ctx: Context): string[] => [...ctx.loader.entries()].map(entry => entry.id)
  223. const BUNDLE_ONE_ROW = '- insert:\n - id: hello\n name: cordis:good\n'
  224. describe('PluginManager', () => {
  225. it('reports plugins/unavailable without a profile runtime', async () => {
  226. const ctx = new Context()
  227. contexts.push(ctx)
  228. await ctx.plugin(Loader)
  229. await expect(managerOver(ctx).list()).rejects.toMatchObject({ code: 'plugins/unavailable', details: { reason: 'no profile runtime' } })
  230. })
  231. describe('list', () => {
  232. it('folds installed, enabled, and probed facts into one view per package', async () => {
  233. const staged = await stageHome()
  234. stagePackage(staged.profileDir, 'ext-bundle', { patch: BUNDLE_ONE_ROW, plugins: [{ name: './extra.js', title: 'Extra' }], files: { 'extra.js': 'export const name = "extra"\nexport function apply() {}\n' } })
  235. stagePackage(staged.profileDir, 'ext-lib', { main: 'export const x = 1\n' })
  236. stagePackage(staged.profileDir, 'ext-plugin', { main: 'export const name = "p"\nexport function apply() {}\n' })
  237. addDependency(staged.profileDir, 'ext-bundle')
  238. addDependency(staged.profileDir, 'ext-lib')
  239. addDependency(staged.profileDir, 'ext-plugin')
  240. const { manager } = await bootProfile(staged)
  241. const views = await manager.list()
  242. expect(views.map(view => [view.name, view.kind, view.status, view.installed, view.enabled, view.trust])).toEqual([
  243. ['ext-bundle', 'bundle', 'disabled', true, false, 'external'],
  244. ['ext-lib', 'library', 'plain', true, false, 'external'],
  245. ['ext-plugin', 'plugin', 'plain', true, false, 'external'],
  246. ])
  247. const bundle = views[0]
  248. expect(bundle).toMatchObject({ version: '1.0.0', title: 'Title of ext-bundle', description: 'staged ext-bundle', stage: 'runtime', liveReload: true })
  249. // Rows come from the probe while the bundle is not composed, under the ids the patch declares.
  250. expect(bundle?.rows).toEqual([{ entryId: 'hello', rowId: 'hello', moduleName: 'cordis:good', enabled: true, phase: null }])
  251. expect(bundle?.addable).toEqual([{ moduleName: 'ext-bundle/extra.js', declaredName: './extra.js', title: 'Extra', ok: true }])
  252. expect(bundle?.probedAt).toEqual(expect.any(String) as string)
  253. expect(readProbeCache(staged.profileDir, 'ext-bundle', '1.0.0')?.kind).toBe('bundle')
  254. })
  255. it('reads a composed bundle\'s rows from the live tree with their failures', async () => {
  256. const staged = await stageHome()
  257. stagePackage(staged.profileDir, 'ext-mixed', { patch: '- insert:\n - id: ok\n name: cordis:good\n - id: bad\n name: cordis:throws\n' })
  258. addDependency(staged.profileDir, 'ext-mixed')
  259. const manifest = manifestOf(staged.profileDir)
  260. manifest.dsh.profile.bundles.push('ext-mixed')
  261. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  262. const { manager } = await bootProfile(staged)
  263. const [view] = await manager.list()
  264. expect(view).toMatchObject({ name: 'ext-mixed', status: 'partial', enabled: true })
  265. expect(view?.reason).toContain('boom at apply')
  266. expect(view?.rows.map(row => [row.entryId, row.phase, row.failure?.stage])).toEqual([
  267. ['include:ok', 'active', undefined],
  268. ['include:bad', 'failed', 'apply'],
  269. ])
  270. })
  271. it('lists a bundle left out by an id conflict as failed, with the conflict as its row', async () => {
  272. const staged = await stageHome()
  273. stagePackage(staged.profileDir, 'ext-one', { patch: BUNDLE_ONE_ROW })
  274. addDependency(staged.profileDir, 'ext-one')
  275. stagePackage(staged.profileDir, 'ext-two', { patch: BUNDLE_ONE_ROW })
  276. addDependency(staged.profileDir, 'ext-two')
  277. const manifest = manifestOf(staged.profileDir)
  278. manifest.dsh.profile.bundles.push('ext-one', 'ext-two')
  279. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  280. const { ctx, manager } = await bootProfile(staged)
  281. const views = await manager.list()
  282. expect(entryIds(ctx)).toContain('include:hello')
  283. expect(views.find(view => view.name === 'ext-one')).toMatchObject({ status: 'running' })
  284. const two = views.find(view => view.name === 'ext-two')
  285. expect(two).toMatchObject({ status: 'failed', enabled: true })
  286. expect(two?.reason).toContain('already declared by ext-one')
  287. expect(two?.rows).toEqual([{
  288. entryId: 'conflict:ext-two:hello', rowId: 'hello', moduleName: 'cordis:good', enabled: true, phase: 'failed',
  289. failure: { stage: 'conflict', message: 'row "hello" is already declared by ext-one' },
  290. }])
  291. })
  292. it('reports a package the probe refuses as not enableable, and a stale layer as restart-required', async () => {
  293. const staged = await stageHome('startup')
  294. stagePackage(staged.profileDir, 'ext-broken', { patch: BUNDLE_ONE_ROW, main: 'throw new Error("no import for you")\n' })
  295. addDependency(staged.profileDir, 'ext-broken')
  296. stagePackage(staged.profileDir, 'ext-later', { patch: BUNDLE_ONE_ROW })
  297. addDependency(staged.profileDir, 'ext-later')
  298. const { manager } = await bootProfile(staged)
  299. // Enabled after boot on a startup-reload profile: the manifest says yes, the tree says no.
  300. const manifest = manifestOf(staged.profileDir)
  301. manifest.dsh.profile.bundles.push('ext-later')
  302. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  303. const views = await manager.list()
  304. expect(views.find(view => view.name === 'ext-broken')).toMatchObject({ status: 'not-enableable', reason: expect.stringContaining('no import for you') as string })
  305. expect(views.find(view => view.name === 'ext-later')).toMatchObject({ status: 'restart-required', liveReload: false })
  306. })
  307. it('reports a package whose probe cannot run with the probe\'s failure', async () => {
  308. const staged = await stageHome()
  309. stagePackage(staged.profileDir, 'ext-odd', { patch: BUNDLE_ONE_ROW })
  310. addDependency(staged.profileDir, 'ext-odd')
  311. stagePackage(staged.profileDir, 'ext-refused', { patch: BUNDLE_ONE_ROW })
  312. addDependency(staged.profileDir, 'ext-refused')
  313. const { manager } = await bootProfile(staged, {
  314. probe: ({ packageName }) => packageName === 'ext-odd'
  315. ? Promise.reject(new Error('probe exploded'))
  316. : Promise.resolve({ packageName, kind: 'bundle', ok: false, reason: 'foreign cordis', cordisSameCopy: false, rows: [], overrides: [], addable: [], checkedAt: 'now' }),
  317. })
  318. const views = await manager.list()
  319. expect(views.find(view => view.name === 'ext-odd')).toMatchObject({ status: 'not-enableable', reason: 'probe exploded', cordisSameCopy: null, rows: [] })
  320. expect(views.find(view => view.name === 'ext-refused')).toMatchObject({ status: 'not-enableable', reason: 'foreign cordis', cordisSameCopy: false })
  321. await expect(manager.enable('ext-odd')).rejects.toMatchObject({ code: 'plugins/not-enableable', details: { reason: 'cannot be probed: probe exploded' } })
  322. await expect(manager.enable('ext-refused')).rejects.toMatchObject({ code: 'plugins/not-enableable', details: { reason: 'foreign cordis' } })
  323. })
  324. it('reads a hand-written manifest: no dependencies, a template bundle, a ghost, and a builtin layer added after boot', async () => {
  325. const staged = await stageHome('startup')
  326. stagePackage(staged.profileDir, 'tpl', { patch: BUNDLE_ONE_ROW })
  327. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-web', dsh: { profile: { bundles: ['tpl'], patchReload: 'startup' } } }))
  328. const { manager } = await bootProfile(staged)
  329. expect((await manager.list()).map(view => [view.name, view.trust, view.status, view.installed, view.rows.length])).toEqual([['tpl', 'builtin', 'running', false, 1]])
  330. // A manifest with no dsh section at all knows no bundles.
  331. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-web' }))
  332. expect(await manager.list()).toEqual([])
  333. // Bundles the manifest names after boot: one staged, one that resolves to nothing.
  334. stagePackage(staged.profileDir, 'tpl-later', { patch: BUNDLE_ONE_ROW })
  335. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-web', dsh: { profile: { bundles: ['tpl', 'tpl-later', 'ghost'], patchReload: 'startup' } } }))
  336. const views = await manager.list()
  337. expect(views.map(view => [view.name, view.trust, view.kind, view.status])).toEqual([
  338. ['tpl', 'builtin', 'bundle', 'running'],
  339. ['tpl-later', 'builtin', 'bundle', 'restart-required'],
  340. ['ghost', 'builtin', 'library', 'plain'],
  341. ])
  342. await expect(manager.uninstall('ghost')).rejects.toMatchObject({ code: 'plugins/not-installed' })
  343. // Retrying takes the bundle out first, which a template bundle refuses.
  344. await expect(manager.retry('ghost')).rejects.toMatchObject({ code: 'plugins/bad-request' })
  345. })
  346. it('folds disabled, user-disabled, and waiting rows', async () => {
  347. const staged = await stageHome()
  348. stagePackage(staged.profileDir, 'ext-off', { patch: '- insert:\n - id: a\n name: cordis:good\n disabled: true\n - id: b\n name: cordis:good\n' })
  349. addDependency(staged.profileDir, 'ext-off')
  350. stagePackage(staged.profileDir, 'ext-waiting', { patch: '- insert:\n - id: w\n name: cordis:consumer\n' })
  351. addDependency(staged.profileDir, 'ext-waiting')
  352. const { manager } = await bootProfile(staged)
  353. await manager.enable('ext-off')
  354. await manager.enable('ext-waiting')
  355. await manager.setRowDisabled({ kind: 'global' }, 'b', true)
  356. const views = await manager.list()
  357. const off = views.find(view => view.name === 'ext-off')
  358. expect(off).toMatchObject({ status: 'running' })
  359. expect(off?.rows.map(row => [row.rowId, row.enabled, row.disabledBy, row.phase])).toEqual([
  360. ['a', false, 'composition', null],
  361. ['b', false, 'user', null],
  362. ])
  363. await manager.setRowDisabled({ kind: 'global' }, 'b', true)
  364. const waiting = views.find(view => view.name === 'ext-waiting')
  365. expect(waiting).toMatchObject({ status: 'failed', reason: expect.stringContaining('fixtureSvc') as string })
  366. expect(waiting?.rows).toEqual([expect.objectContaining({ entryId: 'include:w', phase: 'pending', failure: expect.objectContaining({ stage: 'inject-pending' }) as object })])
  367. // Another bundle's recorded failure is not this one's row.
  368. expect(off?.rows.some(row => row.failure !== undefined)).toBe(false)
  369. })
  370. it('reads anonymous and gated probe rows', async () => {
  371. const staged = await stageHome()
  372. stagePackage(staged.profileDir, 'ext-anon', { patch: '- insert:\n - name: cordis:good\n - id: gated\n name: cordis:good\n disabled: true\n' })
  373. addDependency(staged.profileDir, 'ext-anon')
  374. stagePackage(staged.profileDir, 'fp-bundle', { patch: BUNDLE_ONE_ROW })
  375. addDependency(staged.profileDir, 'fp-bundle')
  376. const manifest = JSON.parse(readFileSync(join(staged.profileDir, 'package.json'), 'utf8')) as { dsh: { profile: Record<string, unknown> } }
  377. manifest.dsh.profile.firstParty = ['fp-bundle']
  378. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest))
  379. const { manager } = await bootProfile(staged)
  380. const views = await manager.list()
  381. expect(views.find(view => view.name === 'ext-anon')?.rows).toEqual([
  382. { entryId: 'cordis:good', rowId: 'cordis:good', moduleName: 'cordis:good', enabled: true, phase: null },
  383. { entryId: 'gated', rowId: 'gated', moduleName: 'cordis:good', enabled: false, disabledBy: 'composition', phase: null },
  384. ])
  385. await manager.enable('fp-bundle')
  386. const firstParty = (await manager.list()).find(view => view.name === 'fp-bundle')
  387. expect(firstParty).toMatchObject({ trust: 'builtin', status: 'running' })
  388. expect(firstParty?.rows.map(row => row.entryId)).toEqual(['include:hello'])
  389. await manager.disable('fp-bundle')
  390. expect((await manager.list()).find(view => view.name === 'fp-bundle')?.rows.map(row => row.entryId)).toEqual(['hello'])
  391. })
  392. })
  393. describe('install', () => {
  394. it('removes a package that is neither a bundle nor a plugin module and says why', async () => {
  395. const staged = await stageHome()
  396. stagePackage(staged.profileDir, 'ext-lib', { main: 'export const answer = 42\n' })
  397. const calls: string[][] = []
  398. const { manager } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir, calls) })
  399. const result = await manager.add('ext-lib')
  400. expect(result).toMatchObject({
  401. installed: [], plain: [], installedOnly: [],
  402. removed: [{ name: 'ext-lib', reason: 'declares neither a dsh bundle nor a plugin module' }],
  403. })
  404. expect(calls).toEqual([['pnpm', 'add', 'ext-lib'], ['pnpm', 'remove', 'ext-lib']])
  405. expect(manifestOf(staged.profileDir).dependencies).not.toHaveProperty('ext-lib')
  406. expect(existsSync(join(staged.profileDir, '.dsh-plugins', 'ext-lib.json'))).toBe(false)
  407. expect((await manager.list()).some(view => view.name === 'ext-lib')).toBe(false)
  408. })
  409. it('removes an installed bundle whose row id another layer already owns', async () => {
  410. const staged = await stageHome()
  411. stagePackage(staged.profileDir, 'ext-one', { patch: BUNDLE_ONE_ROW })
  412. addDependency(staged.profileDir, 'ext-one')
  413. const manifest = manifestOf(staged.profileDir)
  414. manifest.dsh.profile.bundles.push('ext-one')
  415. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  416. stagePackage(staged.profileDir, 'ext-two', { patch: BUNDLE_ONE_ROW })
  417. const calls: string[][] = []
  418. const { manager } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir, calls) })
  419. const result = await manager.add('ext-two', { enable: true })
  420. expect(result).toMatchObject({
  421. installed: [], enabled: [], installedOnly: [],
  422. removed: [{ name: 'ext-two', reason: 'row "hello" is already declared by ext-one' }],
  423. })
  424. expect(calls).toEqual([['pnpm', 'add', 'ext-two'], ['pnpm', 'remove', 'ext-two']])
  425. expect(manifestOf(staged.profileDir)).toMatchObject({ dsh: { profile: { bundles: expect.not.arrayContaining(['ext-two']) as string[] } } })
  426. expect(manifestOf(staged.profileDir).dependencies).not.toHaveProperty('ext-two')
  427. })
  428. it('removes an installed bundle the profile cannot resolve and says why', async () => {
  429. const staged = await stageHome()
  430. // The probe reads the manifest without judging the stage; resolving the
  431. // layer is what refuses it, and that refusal is the removal's reason.
  432. stagePackage(staged.profileDir, 'ext-odd', { patch: BUNDLE_ONE_ROW, stage: 'weird' })
  433. const calls: string[][] = []
  434. const { manager } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir, calls) })
  435. const result = await manager.add('ext-odd')
  436. expect(result).toMatchObject({
  437. installed: [], installedOnly: [],
  438. removed: [{ name: 'ext-odd', reason: expect.stringContaining('declares stage "weird"') as string }],
  439. })
  440. expect(calls).toEqual([['pnpm', 'add', 'ext-odd'], ['pnpm', 'remove', 'ext-odd']])
  441. expect(manifestOf(staged.profileDir).dependencies).not.toHaveProperty('ext-odd')
  442. })
  443. it('keeps a package whose probe refused it, for the view to explain', async () => {
  444. const staged = await stageHome()
  445. stagePackage(staged.profileDir, 'ext-broken', { patch: BUNDLE_ONE_ROW, main: 'throw new Error("no import for you")\n' })
  446. const { manager } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir) })
  447. const result = await manager.add('ext-broken')
  448. expect(result).toMatchObject({ installed: ['ext-broken'], removed: [] })
  449. expect((await manager.list()).find(view => view.name === 'ext-broken')).toMatchObject({ status: 'not-enableable' })
  450. })
  451. it('restores the manifest when pnpm fails after writing it', async () => {
  452. const staged = await stageHome()
  453. const manifestPath = join(staged.profileDir, 'package.json')
  454. const before = readFileSync(manifestPath, 'utf8')
  455. const { manager } = await bootProfile(staged, { spawn: fakePnpm(staged.profileDir, (args) => {
  456. addDependency(staged.profileDir, args[1] ?? 'ext-ghost')
  457. return { code: 1, stderr: 'ERR_PNPM_FETCH_404\n' }
  458. }) })
  459. await expect(manager.add('ext-ghost')).rejects.toMatchObject({ code: 'plugins/install-failed' })
  460. expect(readFileSync(manifestPath, 'utf8')).toBe(before)
  461. })
  462. it('refuses a second mutation while one is still running', async () => {
  463. const staged = await stageHome()
  464. stagePackage(staged.profileDir, 'ext-slow', { patch: BUNDLE_ONE_ROW })
  465. let release = (): void => {}
  466. const gate = new Promise<void>((resolve) => { release = resolve })
  467. const spawn: SpawnLike = (_command, args) => {
  468. const child = new EventEmitter() as EventEmitter & { stdout: PassThrough; stderr: PassThrough; kill: () => boolean }
  469. child.stdout = new PassThrough()
  470. child.stderr = new PassThrough()
  471. child.kill = () => true
  472. void gate.then(() => {
  473. addDependency(staged.profileDir, args[1] ?? 'ext-slow')
  474. child.emit('close', 0)
  475. })
  476. return child as unknown as ChildProcess
  477. }
  478. const { manager } = await bootProfile(staged, { spawn })
  479. const first = manager.add('ext-slow')
  480. await expect(manager.enable('ext-slow')).rejects.toMatchObject({
  481. code: 'plugins/busy', details: { operation: 'enable', active: { operation: 'add', subject: 'ext-slow' } },
  482. })
  483. release()
  484. await expect(first).resolves.toMatchObject({ installed: ['ext-slow'] })
  485. // The lock is released with the run: the refused call now goes through.
  486. await expect(manager.enable('ext-slow')).resolves.toMatchObject({ changed: true })
  487. })
  488. it('refuses to change node_modules while a session is running', async () => {
  489. const staged = await stageHome()
  490. stagePackage(staged.profileDir, 'ext-bundle', { patch: BUNDLE_ONE_ROW })
  491. addDependency(staged.profileDir, 'ext-bundle')
  492. const calls: string[][] = []
  493. const { ctx, manager } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir, calls) })
  494. ctx.provide('agents', { list: () => [{ status: 'running' }, { status: 'idle' }] } as never)
  495. await expect(manager.add('ext-new')).rejects.toMatchObject({ code: 'plugins/agents-running', details: { operation: 'add', running: 1 } })
  496. await expect(manager.uninstall('ext-bundle')).rejects.toMatchObject({ code: 'plugins/agents-running', details: { operation: 'uninstall' } })
  497. expect(calls).toEqual([])
  498. // Enabling recomposes the tree without touching node_modules.
  499. await expect(manager.enable('ext-bundle')).resolves.toMatchObject({ changed: true })
  500. })
  501. it('runs pnpm add, records the dependency, probes the package, and leaves it disabled', async () => {
  502. const staged = await stageHome()
  503. stagePackage(staged.profileDir, 'ext-new', { patch: BUNDLE_ONE_ROW })
  504. const calls: string[][] = []
  505. const { manager, changes, log } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir, calls) })
  506. const result = await manager.add('github:acme/ext-new')
  507. expect(calls).toEqual([['pnpm', 'add', 'github:acme/ext-new']])
  508. // The fake pnpm records the spec itself as the dependency name, which
  509. // resolves to nothing: a plain dependency whose probe cannot run.
  510. expect(result).toEqual({ installed: ['github:acme/ext-new'], removed: [], enabled: [], installedOnly: [], plain: ['github:acme/ext-new'], jobId: expect.any(String) as string })
  511. expect(log.map(chunk => [chunk.argv, chunk.cwd, chunk.stream, chunk.text, chunk.exitCode])).toEqual([
  512. [['pnpm', 'add', 'github:acme/ext-new'], staged.profileDir, 'stdout', '+ github:acme/ext-new 1.0.0\n', undefined],
  513. [['pnpm', 'add', 'github:acme/ext-new'], staged.profileDir, 'stdout', '', 0],
  514. ])
  515. expect(changes).toEqual([{ reason: 'install' }])
  516. })
  517. it('has pnpm colour its output and streams the escapes as they come', async () => {
  518. const staged = await stageHome()
  519. stagePackage(staged.profileDir, 'ext-new', { patch: BUNDLE_ONE_ROW })
  520. const colours: (string | undefined)[] = []
  521. const pnpm = fakePnpm(staged.profileDir, (args) => {
  522. addDependency(staged.profileDir, args[1] as string)
  523. return { code: 0, stdout: '\u001b[32m+\u001b[39m ext-new \u001b[90m1.0.0\u001b[39m\n' }
  524. })
  525. const { manager, log } = await bootProfile(staged, {
  526. spawn: (command, args, options) => {
  527. colours.push(options.env?.FORCE_COLOR)
  528. return pnpm(command, args, options)
  529. },
  530. })
  531. await manager.add('ext-new')
  532. expect(colours).toEqual(['1'])
  533. expect(log[0]?.text).toBe('\u001b[32m+\u001b[39m ext-new \u001b[90m1.0.0\u001b[39m\n')
  534. })
  535. it('reconciles by the installed name, and enables the new bundle when asked', async () => {
  536. const staged = await stageHome()
  537. stagePackage(staged.profileDir, 'ext-new', { patch: BUNDLE_ONE_ROW })
  538. const { ctx, manager, changes } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir) })
  539. const result = await manager.add('ext-new', { enable: true })
  540. expect(result).toMatchObject({ installed: ['ext-new'], enabled: ['ext-new'], installedOnly: [], plain: [] })
  541. expect(manifestOf(staged.profileDir).dsh.profile.bundles).toEqual(['ext-new'])
  542. expect(entryIds(ctx)).toEqual(expect.arrayContaining(['include:bundle/ext-new', 'include:hello']))
  543. expect(readProbeCache(staged.profileDir, 'ext-new')).toBeDefined()
  544. expect(changes.map(change => change.reason)).toEqual(['enable', 'install'])
  545. expect((await manager.list()).find(view => view.name === 'ext-new')?.status).toBe('running')
  546. })
  547. it('reports a plugin module as plain and uninstalls it', async () => {
  548. const staged = await stageHome()
  549. stagePackage(staged.profileDir, 'ext-lib', { main: 'export function apply() {}\n' })
  550. const { manager } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir) })
  551. expect(await manager.add('ext-lib')).toMatchObject({ installed: ['ext-lib'], plain: ['ext-lib'], installedOnly: [], removed: [] })
  552. expect((await manager.list()).find(view => view.name === 'ext-lib')?.status).toBe('plain')
  553. await manager.uninstall('ext-lib')
  554. expect((await manager.list()).some(view => view.name === 'ext-lib')).toBe(false)
  555. })
  556. it('installs into a manifest that declares no dependencies yet', async () => {
  557. const staged = await stageHome()
  558. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-web', dsh: { profile: { bundles: [], patchReload: 'live' } } }))
  559. stagePackage(staged.profileDir, 'ext-new', { patch: BUNDLE_ONE_ROW })
  560. const { manager } = await bootProfile(staged, { spawn: fakePnpm(staged.profileDir, () => {
  561. const path = join(staged.profileDir, 'package.json')
  562. const manifest = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
  563. writeFileSync(path, JSON.stringify({ ...manifest, dependencies: { 'ext-new': '1.0.0' } }))
  564. return { code: 0 }
  565. }) })
  566. expect(await manager.add('ext-new')).toMatchObject({ installed: ['ext-new'], installedOnly: ['ext-new'] })
  567. })
  568. it('fails loud on a non-zero exit, a spawn error, a timeout, and an empty spec', async () => {
  569. const staged = await stageHome()
  570. const exits = await bootProfile(staged, { spawn: fakePnpm(staged.profileDir, () => ({ code: 1, stderr: 'ERR_PNPM_NO_MATCHING_VERSION\n' })) })
  571. await expect(exits.manager.add('nope')).rejects.toMatchObject({
  572. code: 'plugins/install-failed', details: { spec: 'nope', exitCode: 1, log: 'ERR_PNPM_NO_MATCHING_VERSION\n' },
  573. })
  574. expect(exits.log.at(-1)).toMatchObject({ exitCode: 1 })
  575. await expect(exits.manager.add(' ')).rejects.toMatchObject({ code: 'plugins/bad-request' })
  576. const erroringHome = await stageHome()
  577. const erroring = await bootProfile(erroringHome, { spawn: fakePnpm(erroringHome.profileDir, () => ({ code: null, error: 'spawn pnpm ENOENT' })) })
  578. await expect(erroring.manager.add('x')).rejects.toMatchObject({ code: 'plugins/install-failed', details: { exitCode: null } })
  579. expect(erroring.log.some(chunk => chunk.text.includes('ENOENT'))).toBe(true)
  580. const hangingHome = await stageHome()
  581. const hanging = await bootProfile(hangingHome, { spawn: fakePnpm(hangingHome.profileDir, () => ({ code: null, hang: true })) })
  582. await expect(hanging.manager.add('x')).rejects.toMatchObject({ code: 'plugins/install-failed' })
  583. expect(hanging.log.some(chunk => chunk.text.includes('timed out'))).toBe(true)
  584. })
  585. it('keeps only the tail of a long log in the failure', async () => {
  586. const staged = await stageHome()
  587. const { manager } = await bootProfile(staged, {
  588. spawn: fakePnpm(staged.profileDir, () => ({ code: 2, stdout: 'a'.repeat(300), stderr: 'b'.repeat(300) })),
  589. }, { installLogTailBytes: 256 })
  590. await expect(manager.add('x')).rejects.toMatchObject({ details: { log: 'b'.repeat(300) } })
  591. })
  592. })
  593. describe('enable, disable, and retry', () => {
  594. it('composes an installed bundle live, and takes it out again', async () => {
  595. const staged = await stageHome()
  596. stagePackage(staged.profileDir, 'ext-bundle', { patch: BUNDLE_ONE_ROW })
  597. addDependency(staged.profileDir, 'ext-bundle')
  598. const { ctx, manager, changes } = await bootProfile(staged)
  599. expect(await manager.enable('ext-bundle')).toEqual({ changed: true, effect: 'live' })
  600. expect(entryIds(ctx)).toContain('include:hello')
  601. expect(await manager.enable('ext-bundle')).toEqual({ changed: false, effect: 'live' })
  602. expect(await manager.disable('ext-bundle')).toEqual({ changed: true, effect: 'live' })
  603. expect(entryIds(ctx)).not.toContain('include:hello')
  604. expect(await manager.disable('ext-bundle')).toEqual({ changed: false, effect: 'live' })
  605. expect(changes.map(change => [change.reason, change.packageName])).toEqual([
  606. ['enable', 'ext-bundle'], ['enable', 'ext-bundle'], ['disable', 'ext-bundle'], ['disable', 'ext-bundle'],
  607. ])
  608. })
  609. it('only writes the manifest on a startup-reload profile', async () => {
  610. const staged = await stageHome('startup')
  611. stagePackage(staged.profileDir, 'ext-bundle', { patch: BUNDLE_ONE_ROW })
  612. addDependency(staged.profileDir, 'ext-bundle')
  613. const { ctx, manager } = await bootProfile(staged)
  614. expect(await manager.enable('ext-bundle')).toEqual({ changed: true, effect: 'restart' })
  615. expect(manifestOf(staged.profileDir).dsh.profile.bundles).toEqual(['ext-bundle'])
  616. expect(entryIds(ctx)).not.toContain('include:hello')
  617. expect(await manager.disable('ext-bundle')).toEqual({ changed: true, effect: 'restart' })
  618. })
  619. it('refuses what cannot be enabled or disabled', async () => {
  620. const staged = await stageHome()
  621. stagePackage(staged.profileDir, 'ext-lib', { main: 'export const x = 1\n' })
  622. addDependency(staged.profileDir, 'ext-lib')
  623. stagePackage(staged.profileDir, 'ext-broken', { patch: BUNDLE_ONE_ROW, main: 'throw new Error("no import for you")\n' })
  624. addDependency(staged.profileDir, 'ext-broken')
  625. const { manager } = await bootProfile(staged)
  626. await expect(manager.enable('absent')).rejects.toMatchObject({ code: 'plugins/not-installed' })
  627. await expect(manager.enable('ext-lib')).rejects.toMatchObject({ code: 'plugins/not-enableable', details: { reason: expect.stringContaining('declares no dsh.bundle') as string } })
  628. await expect(manager.enable('ext-broken')).rejects.toMatchObject({ code: 'plugins/not-enableable', details: { reason: expect.stringContaining('no import for you') as string } })
  629. // A template bundle is not a dependency and cannot be disabled.
  630. const manifest = manifestOf(staged.profileDir)
  631. manifest.dsh.profile.bundles.push('template')
  632. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  633. await expect(manager.disable('template')).rejects.toMatchObject({ code: 'plugins/bad-request' })
  634. await expect(manager.retry('ext-lib')).rejects.toMatchObject({ code: 'plugins/bad-request' })
  635. })
  636. it('restores the layer list when the tree rejects a boot-stage bundle', async () => {
  637. const staged = await stageHome()
  638. stagePackage(staged.profileDir, 'ext-fatal', { patch: '- insert:\n - id: bad\n name: cordis:throws\n', stage: 'boot' })
  639. addDependency(staged.profileDir, 'ext-fatal')
  640. stagePackage(staged.profileDir, 'ext-fine', { patch: BUNDLE_ONE_ROW })
  641. addDependency(staged.profileDir, 'ext-fine')
  642. const { ctx, manager } = await bootProfile(staged)
  643. await manager.enable('ext-fine')
  644. await expect(manager.enable('ext-fatal')).rejects.toMatchObject({
  645. code: 'plugins/enable-failed', details: { packageName: 'ext-fatal', reason: expect.stringContaining('boom at apply') as string },
  646. })
  647. expect(manifestOf(staged.profileDir).dsh.profile.bundles).toEqual(['ext-fine'])
  648. expect(entryIds(ctx)).toContain('include:hello')
  649. expect(entryIds(ctx)).not.toContain('include:bad')
  650. })
  651. it('retries an isolated bundle by composing it again', async () => {
  652. const staged = await stageHome()
  653. stagePackage(staged.profileDir, 'ext-flaky', { patch: '- insert:\n - id: once\n name: cordis:flaky\n' })
  654. addDependency(staged.profileDir, 'ext-flaky')
  655. flakyCalls = 0
  656. const { manager, changes } = await bootProfile(staged)
  657. await manager.enable('ext-flaky')
  658. expect((await manager.list())[0]).toMatchObject({ status: 'failed', reason: expect.stringContaining('flaky first start') as string })
  659. expect(await manager.retry('ext-flaky')).toEqual({ changed: true, effect: 'live' })
  660. expect((await manager.list())[0]).toMatchObject({ status: 'running' })
  661. expect(changes.map(change => change.reason)).toEqual(['enable', 'disable', 'enable', 'retry'])
  662. })
  663. })
  664. describe('rows in user layers', () => {
  665. it('adds, disables, re-enables, and removes a row in the live global layer', async () => {
  666. const staged = await stageHome()
  667. stagePackage(staged.profileDir, '@acme/ext-plugin', { main: 'export const name = "p"\nexport function apply() {}\n' })
  668. addDependency(staged.profileDir, '@acme/ext-plugin')
  669. const { ctx, manager, changes } = await bootProfile(staged)
  670. const added = await manager.addRow('@acme/ext-plugin', { kind: 'global' })
  671. expect(added).toEqual({ target: { kind: 'global' }, rowId: 'acme/ext-plugin', file: join(staged.profileDir, 'cordis.patch.yml') })
  672. expect(readFileSync(added.file, 'utf8')).toBe('- insert:\n - id: acme/ext-plugin\n name: "@acme/ext-plugin"\n config: {}\n')
  673. // Composed live: the row is in the tree, though its module cannot import from the temp home.
  674. expect(entryIds(ctx)).toContain('include:acme/ext-plugin')
  675. await expect(manager.addRow('@acme/ext-plugin', { kind: 'global' })).rejects.toMatchObject({ code: 'plugins/row-conflict' })
  676. await manager.setRowDisabled({ kind: 'global' }, 'acme/ext-plugin', true)
  677. expect(ctx.loader.resolve('include:acme/ext-plugin')?.disabled).toBe(true)
  678. expect(readFileSync(added.file, 'utf8')).toContain('- id: acme/ext-plugin\n disabled: true\n')
  679. await manager.setRowDisabled({ kind: 'global' }, 'acme/ext-plugin', false)
  680. expect(ctx.loader.resolve('include:acme/ext-plugin')?.disabled).toBe(false)
  681. expect(readFileSync(added.file, 'utf8')).not.toContain('disabled')
  682. await manager.removeRow({ kind: 'global' }, 'acme/ext-plugin')
  683. expect(entryIds(ctx)).not.toContain('include:acme/ext-plugin')
  684. await expect(manager.removeRow({ kind: 'global' }, 'acme/ext-plugin')).rejects.toMatchObject({ code: 'plugins/bad-request' })
  685. expect(changes.map(change => change.reason)).toEqual(['row', 'row', 'row', 'row'])
  686. })
  687. it('detects a conflict through the layer file when the tree was not recomposed', async () => {
  688. const staged = await stageHome('startup')
  689. stagePackage(staged.profileDir, 'ext-plugin', { main: 'export const name = "p"\nexport function apply() {}\n' })
  690. addDependency(staged.profileDir, 'ext-plugin')
  691. const { ctx, manager } = await bootProfile(staged)
  692. await manager.addRow('ext-plugin', { kind: 'global' })
  693. expect(entryIds(ctx)).not.toContain('include:ext-plugin')
  694. await expect(manager.addRow('ext-plugin', { kind: 'global' })).rejects.toMatchObject({ code: 'plugins/row-conflict' })
  695. })
  696. it('adds a declared addable module with its default config and an explicit id, and refuses the rest', async () => {
  697. const staged = await stageHome()
  698. stagePackage(staged.profileDir, 'ext-bundle', {
  699. patch: BUNDLE_ONE_ROW,
  700. plugins: [
  701. { name: './tools/sql.js', title: 'SQL', config: { dsn: 'sqlite://' } },
  702. { name: './missing.js' },
  703. ],
  704. files: { 'tools/sql.js': 'export const name = "sql"\nexport function apply() {}\n' },
  705. })
  706. addDependency(staged.profileDir, 'ext-bundle')
  707. const { manager } = await bootProfile(staged)
  708. const added = await manager.addRow('ext-bundle', { kind: 'global' }, { module: './tools/sql.js', id: 'sql' })
  709. expect(added.rowId).toBe('sql')
  710. expect(readFileSync(added.file, 'utf8')).toContain('- id: sql\n name: ext-bundle/tools/sql.js\n config:\n dsn: sqlite://\n')
  711. await expect(manager.addRow('ext-bundle', { kind: 'global' })).rejects.toMatchObject({ code: 'plugins/not-enableable' })
  712. await expect(manager.addRow('ext-bundle', { kind: 'global' }, { module: './missing.js' })).rejects.toMatchObject({ code: 'plugins/not-enableable' })
  713. await expect(manager.addRow('absent', { kind: 'global' })).rejects.toMatchObject({ code: 'plugins/not-installed' })
  714. })
  715. it('writes a preset\'s layer through the roster, and refuses a preset target without one', async () => {
  716. const staged = await stageHome()
  717. stagePackage(staged.profileDir, 'ext-plugin', { main: 'export const name = "p"\nexport function apply() {}\n' })
  718. addDependency(staged.profileDir, 'ext-plugin')
  719. const { ctx, manager } = await bootProfile(staged)
  720. await expect(manager.addRow('ext-plugin', { kind: 'preset', preset: 'standard' })).rejects.toMatchObject({ code: 'plugins/unavailable' })
  721. const overlay = join(staged.home, '.agent-presets', 'standard', 'cordis.patch.yml')
  722. const roster = {
  723. overlayPathFor: (id: string) => Promise.resolve(join(staged.home, '.agent-presets', id, 'cordis.patch.yml')),
  724. compositionInventory: () => Promise.resolve([{ id: 'standard', rows: [{ entryId: 'tool-web' }] }]),
  725. list: () => Promise.resolve([{ id: 'standard', overlayPath: existsSync(overlay) ? overlay : undefined }]),
  726. }
  727. ctx.provide('agentPresets', roster)
  728. // No layer exists yet: nothing references the package.
  729. expect((await manager.dependents('ext-plugin')).references).toEqual([])
  730. // A preset the inventory does not know has no rows to conflict with.
  731. const elsewhere = await manager.addRow('ext-plugin', { kind: 'preset', preset: 'other' })
  732. expect(elsewhere.file).toBe(join(staged.home, '.agent-presets', 'other', 'cordis.patch.yml'))
  733. const added = await manager.addRow('ext-plugin', { kind: 'preset', preset: 'standard' })
  734. expect(added).toEqual({ target: { kind: 'preset', preset: 'standard' }, rowId: 'ext-plugin', file: overlay })
  735. await expect(manager.addRow('ext-plugin', { kind: 'preset', preset: 'standard' }, { id: 'tool-web' })).rejects.toMatchObject({ code: 'plugins/row-conflict' })
  736. await manager.setRowDisabled({ kind: 'preset', preset: 'standard' }, 'tool-web', true)
  737. expect(readFileSync(overlay, 'utf8')).toBe('- insert:\n - id: ext-plugin\n name: ext-plugin\n config: {}\n- id: tool-web\n disabled: true\n')
  738. // The preset's layer is not part of the host tree.
  739. expect(entryIds(ctx)).not.toContain('include:ext-plugin')
  740. const dependents = await manager.dependents('ext-plugin')
  741. expect(dependents.references).toEqual([{ target: { kind: 'preset', preset: 'standard' }, rowId: 'ext-plugin', moduleName: 'ext-plugin' }])
  742. await manager.removeRow({ kind: 'preset', preset: 'standard' }, 'ext-plugin')
  743. expect(readFileSync(overlay, 'utf8')).toBe('- id: tool-web\n disabled: true\n')
  744. })
  745. })
  746. describe('dependents and uninstall', () => {
  747. it('names the services other rows inject and the user-layer rows that reference the package', async () => {
  748. const staged = await stageHome()
  749. // Beside the provider: a row nobody injects, and a row switched off (no fiber to read).
  750. stagePackage(staged.profileDir, 'ext-provider', { patch: '- insert:\n - id: svc\n name: cordis:provider\n - id: lonely\n name: cordis:lonely-provider\n - id: off\n name: cordis:good\n disabled: true\n' })
  751. addDependency(staged.profileDir, 'ext-provider')
  752. writeFileSync(join(staged.profileDir, 'cordis.patch.yml'), [
  753. '- insert:',
  754. ' - name: ext-provider/anonymous.js',
  755. ' disabled: true',
  756. ' - id: ref',
  757. ' name: ext-provider/tools/x.js',
  758. ' disabled: true',
  759. ' - id: grp',
  760. ' name: cordis:group',
  761. ' group: true',
  762. ' config:',
  763. ' - id: nested-ref',
  764. ' name: ext-provider',
  765. ' disabled: true',
  766. '',
  767. ].join('\n'))
  768. const { manager, runtime } = await bootProfile(staged)
  769. await manager.enable('ext-provider')
  770. // A built-in row injecting the bundle's service, composed once the
  771. // provider is up (a boot would refuse a row left waiting).
  772. writeFileSync(join(staged.profileDir, 'cordis.patch.yml'), `${readFileSync(join(staged.profileDir, 'cordis.patch.yml'), 'utf8')}- insert:\n - id: needs-svc\n name: cordis:consumer\n`)
  773. await runtime.recompose()
  774. const dependents = await manager.dependents('ext-provider')
  775. expect(dependents.services).toEqual([{ service: 'fixtureSvc', providedBy: 'include:svc', injectedBy: ['include:needs-svc'] }])
  776. expect(dependents.references.map(reference => reference.rowId)).toEqual(['ref', 'nested-ref'])
  777. expect(dependents.references[0]).toEqual({ target: { kind: 'global' }, rowId: 'ref', moduleName: 'ext-provider/tools/x.js' })
  778. })
  779. it('ignores an unreadable user layer while collecting references', async () => {
  780. const staged = await stageHome()
  781. stagePackage(staged.profileDir, 'ext-lib', { main: 'export const x = 1\n' })
  782. addDependency(staged.profileDir, 'ext-lib')
  783. const { manager } = await bootProfile(staged)
  784. writeFileSync(join(staged.profileDir, 'cordis.patch.yml'), 'a: [\n')
  785. expect((await manager.dependents('ext-lib')).references).toEqual([])
  786. })
  787. it('disables, drops references, removes the package, and forgets its probe', async () => {
  788. const staged = await stageHome()
  789. stagePackage(staged.profileDir, 'ext-bundle', { patch: BUNDLE_ONE_ROW, plugins: [{ name: './extra.js' }], files: { 'extra.js': 'export function apply() {}\n' } })
  790. addDependency(staged.profileDir, 'ext-bundle')
  791. const calls: string[][] = []
  792. const { ctx, manager, changes } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir, calls) })
  793. await manager.enable('ext-bundle')
  794. await manager.addRow('ext-bundle', { kind: 'global' }, { module: './extra.js' })
  795. expect(entryIds(ctx)).toEqual(expect.arrayContaining(['include:hello', 'include:ext-bundle/extra.js']))
  796. expect(existsSync(join(staged.profileDir, '.dsh-plugins', 'ext-bundle.json'))).toBe(true)
  797. await manager.uninstall('ext-bundle')
  798. expect(calls).toEqual([['pnpm', 'remove', 'ext-bundle']])
  799. expect(manifestOf(staged.profileDir)).toMatchObject({ dependencies: {}, dsh: { profile: { bundles: [] } } })
  800. expect(entryIds(ctx)).not.toContain('include:hello')
  801. expect(entryIds(ctx)).not.toContain('include:ext-bundle/extra.js')
  802. expect(readFileSync(join(staged.profileDir, 'cordis.patch.yml'), 'utf8')).toBe('[]\n')
  803. expect(existsSync(join(staged.profileDir, '.dsh-plugins', 'ext-bundle.json'))).toBe(false)
  804. expect(changes.map(change => change.reason)).toEqual(['enable', 'row', 'disable', 'uninstall'])
  805. await expect(manager.uninstall('ext-bundle')).rejects.toMatchObject({ code: 'plugins/not-installed' })
  806. })
  807. })
  808. })