plugin-manager.spec.ts 53 KB

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