plugin-manager.spec.ts 56 KB

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