plugin-manager.spec.ts 53 KB

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