plugin-manager.spec.ts 50 KB

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