plugin-manager.spec.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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, recordRowConflicts, 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. stage?: 'boot' | 'runtime'
  81. plugins?: { name: string; title?: string; config?: unknown }[]
  82. files?: Record<string, string>
  83. }
  84. /** Stage one package under the profile's node_modules, the way pnpm leaves it. */
  85. function stagePackage(profileDir: string, name: string, staged: StagedPackage): void {
  86. const dir = join(profileDir, 'node_modules', name)
  87. mkdirSync(dir, { recursive: true })
  88. writeFileSync(join(dir, 'package.json'), JSON.stringify({
  89. name,
  90. version: staged.version ?? '1.0.0',
  91. description: `staged ${name}`,
  92. type: 'module',
  93. ...staged.main === undefined ? {} : { main: 'index.js' },
  94. dsh: {
  95. title: `Title of ${name}`,
  96. ...staged.patch === undefined ? {} : { bundle: { patch: './cordis.patch.yml', ...staged.stage === undefined ? {} : { stage: staged.stage } } },
  97. ...staged.plugins === undefined ? {} : { plugins: staged.plugins },
  98. },
  99. }, null, 2))
  100. if (staged.patch !== undefined) writeFileSync(join(dir, 'cordis.patch.yml'), staged.patch)
  101. if (staged.main !== undefined) writeFileSync(join(dir, 'index.js'), staged.main)
  102. for (const [file, text] of Object.entries(staged.files ?? {})) {
  103. mkdirSync(join(dir, file, '..'), { recursive: true })
  104. writeFileSync(join(dir, file), text)
  105. }
  106. }
  107. /** Add a dependency to the profile manifest, as `pnpm add` does. */
  108. function addDependency(profileDir: string, name: string, spec = '1.0.0'): void {
  109. const path = join(profileDir, 'package.json')
  110. const manifest = JSON.parse(readFileSync(path, 'utf8')) as { dependencies: Record<string, string> }
  111. manifest.dependencies[name] = spec
  112. writeFileSync(path, JSON.stringify(manifest, null, 2))
  113. }
  114. function manifestOf(profileDir: string): { dependencies: Record<string, string>; dsh: { profile: { bundles: string[] } } } {
  115. return JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as ReturnType<typeof manifestOf>
  116. }
  117. /** What the fake pnpm does for one invocation. */
  118. type PnpmBehavior = (args: readonly string[]) => { code: number | null; stdout?: string; stderr?: string; hang?: boolean; error?: unknown }
  119. /** A fake `spawn` that runs `behavior` on the next tick and reports through a child-like emitter. */
  120. function fakePnpm(profileDir: string, behavior: PnpmBehavior, calls: string[][] = []): SpawnLike {
  121. return (command, args, options) => {
  122. calls.push([command, ...args])
  123. expect(options.cwd).toBe(profileDir)
  124. const child = new EventEmitter() as EventEmitter & { stdout: PassThrough; stderr: PassThrough; kill: (signal?: string) => boolean }
  125. child.stdout = new PassThrough()
  126. child.stderr = new PassThrough()
  127. let killed = false
  128. child.kill = () => { killed = true; return true }
  129. setTimeout(() => {
  130. const outcome = behavior(args)
  131. if (outcome.error !== undefined) {
  132. child.emit('error', outcome.error)
  133. return
  134. }
  135. if (outcome.stdout !== undefined) child.stdout.write(outcome.stdout)
  136. if (outcome.stderr !== undefined) child.stderr.write(outcome.stderr)
  137. if (outcome.hang === true) {
  138. // Report the kill the timeout sends, as a real child would.
  139. const poll = setInterval(() => {
  140. if (!killed) return
  141. clearInterval(poll)
  142. child.emit('close', null)
  143. }, 10)
  144. return
  145. }
  146. setTimeout(() => { child.emit('close', outcome.code) }, 5)
  147. }, 5)
  148. return child as unknown as ChildProcess
  149. }
  150. }
  151. /** The pnpm every install test shares: `add <name>` stages nothing (the test did) and records the dependency. */
  152. function recordingPnpm(profileDir: string, calls: string[][] = []): SpawnLike {
  153. return fakePnpm(profileDir, (args) => {
  154. const [verb, target] = args
  155. if (verb === 'add' && target !== undefined) {
  156. addDependency(profileDir, target)
  157. return { code: 0, stdout: `+ ${target} 1.0.0\n` }
  158. }
  159. if (verb === 'remove' && target !== undefined) {
  160. const path = join(profileDir, 'package.json')
  161. const manifest = JSON.parse(readFileSync(path, 'utf8')) as { dependencies: Record<string, string> }
  162. const { [target]: _removed, ...remaining } = manifest.dependencies
  163. writeFileSync(path, JSON.stringify({ ...manifest, dependencies: remaining }, null, 2))
  164. rmSync(join(profileDir, 'node_modules', target), { recursive: true, force: true })
  165. return { code: 0, stdout: `- ${target}\n` }
  166. }
  167. return { code: 1, stderr: 'unexpected pnpm invocation\n' }
  168. }, calls)
  169. }
  170. interface Booted {
  171. ctx: Context
  172. manager: PluginManager
  173. runtime: ProfileRuntime
  174. changes: { reason: string; packageName?: string }[]
  175. log: PluginInstallLogChunk[]
  176. }
  177. /** Boot the profile the way the launcher does, then mount the manager over it. */
  178. async function bootProfile(staged: StagedHome, internals: PluginManagerInternals = {}, config: Partial<PluginManager['config']> = {}): Promise<Booted> {
  179. const load = (): Profile => loadProfile(NAME, 'web', staged.anchor, staged.home)
  180. const composeFor = (profile: Profile): ComposedStack => {
  181. const stack = composeProfileStack(NAME, profile.layers, [
  182. { label: profile.patchPath, patches: loadOptionalPatches(NAME, profile.patchPath) ?? [] },
  183. ])
  184. return { ...stack, patches: structuredClone(stack.patches) }
  185. }
  186. const profile = load()
  187. const ctx = await boot(NAME, join(staged.profileDir, 'cordis.yml'), composeFor(profile).patches, prepare)
  188. contexts.push(ctx)
  189. await ctx.plugin(ProfileRuntime, {
  190. profile,
  191. installAnchor: staged.anchor,
  192. loadProfile: load,
  193. compose: composeFor,
  194. rootEntry: () => rootIncludeEntry(ctx),
  195. readUserPatches: () => loadOptionalPatches(NAME, profile.patchPath) ?? [],
  196. })
  197. // As the launcher does after boot: the runtime records conflicts only on its own recompositions.
  198. recordRowConflicts(ctx, composeFor(profile).conflicts)
  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. // A plugin module offers its main export as `.`, the entry addRow accepts without a declaration.
  253. expect(views[2]?.addable).toMatchObject([{ moduleName: 'ext-plugin', declaredName: '.', ok: true }])
  254. expect(views[1]?.addable).toEqual([])
  255. expect(bundle?.probedAt).toEqual(expect.any(String) as string)
  256. expect(readProbeCache(staged.profileDir, 'ext-bundle', '1.0.0')?.kind).toBe('bundle')
  257. })
  258. it('reads a composed bundle\'s rows from the live tree with their failures', async () => {
  259. const staged = await stageHome()
  260. stagePackage(staged.profileDir, 'ext-mixed', { patch: '- insert:\n - id: ok\n name: cordis:good\n - id: bad\n name: cordis:throws\n' })
  261. addDependency(staged.profileDir, 'ext-mixed')
  262. const manifest = manifestOf(staged.profileDir)
  263. manifest.dsh.profile.bundles.push('ext-mixed')
  264. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  265. const { manager } = await bootProfile(staged)
  266. const [view] = await manager.list()
  267. expect(view).toMatchObject({ name: 'ext-mixed', status: 'partial', enabled: true })
  268. expect(view?.reason).toContain('boom at apply')
  269. expect(view?.rows.map(row => [row.entryId, row.phase, row.failure?.stage])).toEqual([
  270. ['include:ok', 'active', undefined],
  271. ['include:bad', 'failed', 'apply'],
  272. ])
  273. })
  274. it('lists a bundle left out by an id conflict as failed, with the conflict as its row', async () => {
  275. const staged = await stageHome()
  276. stagePackage(staged.profileDir, 'ext-one', { patch: BUNDLE_ONE_ROW })
  277. addDependency(staged.profileDir, 'ext-one')
  278. stagePackage(staged.profileDir, 'ext-two', { patch: BUNDLE_ONE_ROW })
  279. addDependency(staged.profileDir, 'ext-two')
  280. const manifest = manifestOf(staged.profileDir)
  281. manifest.dsh.profile.bundles.push('ext-one', 'ext-two')
  282. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  283. const { ctx, manager } = await bootProfile(staged)
  284. const views = await manager.list()
  285. expect(entryIds(ctx)).toContain('include:hello')
  286. expect(views.find(view => view.name === 'ext-one')).toMatchObject({ status: 'running' })
  287. const two = views.find(view => view.name === 'ext-two')
  288. expect(two).toMatchObject({ status: 'failed', enabled: true })
  289. expect(two?.reason).toContain('already declared by ext-one')
  290. expect(two?.rows).toEqual([{
  291. entryId: 'conflict:bundle/ext-two:hello', rowId: 'hello', moduleName: 'cordis:good', enabled: true, phase: 'failed',
  292. failure: { stage: 'conflict', message: 'row "hello" is already declared by ext-one' },
  293. }])
  294. })
  295. it('reports a package the probe refuses as not enableable, and a stale layer as restart-required', async () => {
  296. const staged = await stageHome('startup')
  297. stagePackage(staged.profileDir, 'ext-broken', { patch: BUNDLE_ONE_ROW, main: 'throw new Error("no import for you")\n' })
  298. addDependency(staged.profileDir, 'ext-broken')
  299. stagePackage(staged.profileDir, 'ext-later', { patch: BUNDLE_ONE_ROW })
  300. addDependency(staged.profileDir, 'ext-later')
  301. const { manager } = await bootProfile(staged)
  302. // Enabled after boot on a startup-reload profile: the manifest says yes, the tree says no.
  303. const manifest = manifestOf(staged.profileDir)
  304. manifest.dsh.profile.bundles.push('ext-later')
  305. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  306. const views = await manager.list()
  307. expect(views.find(view => view.name === 'ext-broken')).toMatchObject({ status: 'not-enableable', reason: expect.stringContaining('no import for you') as string })
  308. expect(views.find(view => view.name === 'ext-later')).toMatchObject({ status: 'restart-required', liveReload: false })
  309. })
  310. it('reports a package whose probe cannot run with the probe\'s failure', async () => {
  311. const staged = await stageHome()
  312. stagePackage(staged.profileDir, 'ext-odd', { patch: BUNDLE_ONE_ROW })
  313. addDependency(staged.profileDir, 'ext-odd')
  314. stagePackage(staged.profileDir, 'ext-refused', { patch: BUNDLE_ONE_ROW })
  315. addDependency(staged.profileDir, 'ext-refused')
  316. const { manager } = await bootProfile(staged, {
  317. probe: ({ packageName }) => packageName === 'ext-odd'
  318. ? Promise.reject(new Error('probe exploded'))
  319. : Promise.resolve({ packageName, kind: 'bundle', ok: false, reason: 'foreign cordis', cordisSameCopy: false, rows: [], overrides: [], addable: [], checkedAt: 'now' }),
  320. })
  321. const views = await manager.list()
  322. expect(views.find(view => view.name === 'ext-odd')).toMatchObject({ status: 'not-enableable', reason: 'probe exploded', cordisSameCopy: null, rows: [] })
  323. expect(views.find(view => view.name === 'ext-refused')).toMatchObject({ status: 'not-enableable', reason: 'foreign cordis', cordisSameCopy: false })
  324. await expect(manager.enable('ext-odd')).rejects.toMatchObject({ code: 'plugins/not-enableable', details: { reason: 'cannot be probed: probe exploded' } })
  325. await expect(manager.enable('ext-refused')).rejects.toMatchObject({ code: 'plugins/not-enableable', details: { reason: 'foreign cordis' } })
  326. })
  327. it('reads a hand-written manifest: no dependencies, a template bundle, a ghost, and a builtin layer added after boot', async () => {
  328. const staged = await stageHome('startup')
  329. stagePackage(staged.profileDir, 'tpl', { patch: BUNDLE_ONE_ROW })
  330. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-web', dsh: { profile: { bundles: ['tpl'], patchReload: 'startup' } } }))
  331. const { manager } = await bootProfile(staged)
  332. expect((await manager.list()).map(view => [view.name, view.trust, view.status, view.installed, view.rows.length])).toEqual([['tpl', 'builtin', 'running', false, 1]])
  333. // A manifest with no dsh section at all knows no bundles.
  334. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-web' }))
  335. expect(await manager.list()).toEqual([])
  336. // Bundles the manifest names after boot: one staged, one that resolves to nothing.
  337. stagePackage(staged.profileDir, 'tpl-later', { patch: BUNDLE_ONE_ROW })
  338. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-web', dsh: { profile: { bundles: ['tpl', 'tpl-later', 'ghost'], patchReload: 'startup' } } }))
  339. const views = await manager.list()
  340. expect(views.map(view => [view.name, view.trust, view.kind, view.status])).toEqual([
  341. ['tpl', 'builtin', 'bundle', 'running'],
  342. ['tpl-later', 'builtin', 'bundle', 'restart-required'],
  343. ['ghost', 'builtin', 'library', 'plain'],
  344. ])
  345. await expect(manager.uninstall('ghost')).rejects.toMatchObject({ code: 'plugins/not-installed' })
  346. // Retrying takes the bundle out first, which a template bundle refuses.
  347. await expect(manager.retry('ghost')).rejects.toMatchObject({ code: 'gateway/bad-request' })
  348. })
  349. it('folds disabled, user-disabled, and waiting rows', async () => {
  350. const staged = await stageHome()
  351. 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' })
  352. addDependency(staged.profileDir, 'ext-off')
  353. stagePackage(staged.profileDir, 'ext-waiting', { patch: '- insert:\n - id: w\n name: cordis:consumer\n' })
  354. addDependency(staged.profileDir, 'ext-waiting')
  355. const { manager } = await bootProfile(staged)
  356. await manager.enable('ext-off')
  357. await manager.enable('ext-waiting')
  358. await manager.setRowDisabled({ kind: 'global' }, 'b', true)
  359. const views = await manager.list()
  360. const off = views.find(view => view.name === 'ext-off')
  361. expect(off).toMatchObject({ status: 'running' })
  362. expect(off?.rows.map(row => [row.rowId, row.enabled, row.disabledBy, row.phase])).toEqual([
  363. ['a', false, 'composition', null],
  364. ['b', false, 'user', null],
  365. ])
  366. await manager.setRowDisabled({ kind: 'global' }, 'b', true)
  367. const waiting = views.find(view => view.name === 'ext-waiting')
  368. expect(waiting).toMatchObject({ status: 'failed', reason: expect.stringContaining('fixtureSvc') as string })
  369. expect(waiting?.rows).toEqual([expect.objectContaining({ entryId: 'include:w', phase: 'pending', failure: expect.objectContaining({ stage: 'inject-pending' }) as object })])
  370. // Another bundle's recorded failure is not this one's row.
  371. expect(off?.rows.some(row => row.failure !== undefined)).toBe(false)
  372. })
  373. it('reads anonymous and gated probe rows', async () => {
  374. const staged = await stageHome()
  375. stagePackage(staged.profileDir, 'ext-anon', { patch: '- insert:\n - name: cordis:good\n - id: gated\n name: cordis:good\n disabled: true\n' })
  376. addDependency(staged.profileDir, 'ext-anon')
  377. stagePackage(staged.profileDir, 'fp-bundle', { patch: BUNDLE_ONE_ROW })
  378. addDependency(staged.profileDir, 'fp-bundle')
  379. const manifest = JSON.parse(readFileSync(join(staged.profileDir, 'package.json'), 'utf8')) as { dsh: { profile: Record<string, unknown> } }
  380. manifest.dsh.profile.firstParty = ['fp-bundle']
  381. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest))
  382. const { manager } = await bootProfile(staged)
  383. const views = await manager.list()
  384. expect(views.find(view => view.name === 'ext-anon')?.rows).toEqual([
  385. { entryId: 'cordis:good', rowId: 'cordis:good', moduleName: 'cordis:good', enabled: true, phase: null },
  386. { entryId: 'gated', rowId: 'gated', moduleName: 'cordis:good', enabled: false, disabledBy: 'composition', phase: null },
  387. ])
  388. await manager.enable('fp-bundle')
  389. const firstParty = (await manager.list()).find(view => view.name === 'fp-bundle')
  390. expect(firstParty).toMatchObject({ trust: 'builtin', status: 'running' })
  391. expect(firstParty?.rows.map(row => row.entryId)).toEqual(['include:hello'])
  392. await manager.disable('fp-bundle')
  393. expect((await manager.list()).find(view => view.name === 'fp-bundle')?.rows.map(row => row.entryId)).toEqual(['hello'])
  394. })
  395. })
  396. describe('add', () => {
  397. it('runs pnpm add, records the dependency, probes the package, and leaves it disabled', async () => {
  398. const staged = await stageHome()
  399. stagePackage(staged.profileDir, 'ext-new', { patch: BUNDLE_ONE_ROW })
  400. const calls: string[][] = []
  401. const { manager, changes, log } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir, calls) })
  402. const result = await manager.add('github:acme/ext-new')
  403. expect(calls).toEqual([['pnpm', 'add', 'github:acme/ext-new']])
  404. // The fake pnpm records the spec itself as the dependency name, which
  405. // resolves to nothing: a plain dependency whose probe cannot run.
  406. expect(result).toEqual({ installed: ['github:acme/ext-new'], enabled: [], installedOnly: [], plain: ['github:acme/ext-new'], jobId: expect.any(String) as string })
  407. expect(log.map(chunk => [chunk.stream, chunk.text, chunk.exitCode])).toEqual([
  408. ['stdout', '+ github:acme/ext-new 1.0.0\n', undefined],
  409. ['stdout', '', 0],
  410. ])
  411. expect(changes).toEqual([{ reason: 'install' }])
  412. })
  413. it('reconciles by the installed name, and enables the new bundle when asked', async () => {
  414. const staged = await stageHome()
  415. stagePackage(staged.profileDir, 'ext-new', { patch: BUNDLE_ONE_ROW })
  416. const { ctx, manager, changes } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir) })
  417. const result = await manager.add('ext-new', { enable: true })
  418. expect(result).toMatchObject({ installed: ['ext-new'], enabled: ['ext-new'], installedOnly: [], plain: [] })
  419. expect(manifestOf(staged.profileDir).dsh.profile.bundles).toEqual(['ext-new'])
  420. expect(entryIds(ctx)).toEqual(expect.arrayContaining(['include:bundle/ext-new', 'include:hello']))
  421. expect(readProbeCache(staged.profileDir, 'ext-new')).toBeDefined()
  422. expect(changes.map(change => change.reason)).toEqual(['enable', 'install'])
  423. expect((await manager.list()).find(view => view.name === 'ext-new')?.status).toBe('running')
  424. })
  425. it('reports a plain dependency and a non-zero exit with the log tail', async () => {
  426. const staged = await stageHome()
  427. stagePackage(staged.profileDir, 'ext-lib', { main: 'export const x = 1\n' })
  428. const { manager } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir) })
  429. expect(await manager.add('ext-lib')).toMatchObject({ installed: ['ext-lib'], plain: ['ext-lib'], installedOnly: [] })
  430. expect((await manager.list()).find(view => view.name === 'ext-lib')?.status).toBe('plain')
  431. await manager.uninstall('ext-lib')
  432. expect((await manager.list()).some(view => view.name === 'ext-lib')).toBe(false)
  433. })
  434. it('installs into a manifest that declares no dependencies yet', async () => {
  435. const staged = await stageHome()
  436. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-web', dsh: { profile: { bundles: [], patchReload: 'live' } } }))
  437. stagePackage(staged.profileDir, 'ext-new', { patch: BUNDLE_ONE_ROW })
  438. const { manager } = await bootProfile(staged, { spawn: fakePnpm(staged.profileDir, () => {
  439. const path = join(staged.profileDir, 'package.json')
  440. const manifest = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
  441. writeFileSync(path, JSON.stringify({ ...manifest, dependencies: { 'ext-new': '1.0.0' } }))
  442. return { code: 0 }
  443. }) })
  444. expect(await manager.add('ext-new')).toMatchObject({ installed: ['ext-new'], installedOnly: ['ext-new'] })
  445. })
  446. it('fails loud on a non-zero exit, a spawn error, a timeout, and an empty spec', async () => {
  447. const staged = await stageHome()
  448. const exits = await bootProfile(staged, { spawn: fakePnpm(staged.profileDir, () => ({ code: 1, stderr: 'ERR_PNPM_NO_MATCHING_VERSION\n' })) })
  449. await expect(exits.manager.add('nope')).rejects.toMatchObject({
  450. code: 'plugins/install-failed', details: { spec: 'nope', exitCode: 1, log: 'ERR_PNPM_NO_MATCHING_VERSION\n' },
  451. })
  452. expect(exits.log.at(-1)).toMatchObject({ exitCode: 1 })
  453. await expect(exits.manager.add(' ')).rejects.toMatchObject({ code: 'gateway/bad-request' })
  454. const erroringHome = await stageHome()
  455. const erroring = await bootProfile(erroringHome, { spawn: fakePnpm(erroringHome.profileDir, () => ({ code: null, error: 'spawn pnpm ENOENT' })) })
  456. await expect(erroring.manager.add('x')).rejects.toMatchObject({ code: 'plugins/install-failed', details: { exitCode: null } })
  457. expect(erroring.log.some(chunk => chunk.text.includes('ENOENT'))).toBe(true)
  458. const hangingHome = await stageHome()
  459. const hanging = await bootProfile(hangingHome, { spawn: fakePnpm(hangingHome.profileDir, () => ({ code: null, hang: true })) })
  460. await expect(hanging.manager.add('x')).rejects.toMatchObject({ code: 'plugins/install-failed' })
  461. expect(hanging.log.some(chunk => chunk.text.includes('timed out'))).toBe(true)
  462. })
  463. it('keeps only the tail of a long log in the failure', async () => {
  464. const staged = await stageHome()
  465. const { manager } = await bootProfile(staged, {
  466. spawn: fakePnpm(staged.profileDir, () => ({ code: 2, stdout: 'a'.repeat(300), stderr: 'b'.repeat(300) })),
  467. }, { installLogTailBytes: 256 })
  468. await expect(manager.add('x')).rejects.toMatchObject({ details: { log: 'b'.repeat(300) } })
  469. })
  470. })
  471. describe('enable, disable, and retry', () => {
  472. it('composes an installed bundle live, and takes it out again', async () => {
  473. const staged = await stageHome()
  474. stagePackage(staged.profileDir, 'ext-bundle', { patch: BUNDLE_ONE_ROW })
  475. addDependency(staged.profileDir, 'ext-bundle')
  476. const { ctx, manager, changes } = await bootProfile(staged)
  477. expect(await manager.enable('ext-bundle')).toEqual({ changed: true, effect: 'live' })
  478. expect(entryIds(ctx)).toContain('include:hello')
  479. expect(await manager.enable('ext-bundle')).toEqual({ changed: false, effect: 'live' })
  480. expect(await manager.disable('ext-bundle')).toEqual({ changed: true, effect: 'live' })
  481. expect(entryIds(ctx)).not.toContain('include:hello')
  482. expect(await manager.disable('ext-bundle')).toEqual({ changed: false, effect: 'live' })
  483. expect(changes.map(change => [change.reason, change.packageName])).toEqual([
  484. ['enable', 'ext-bundle'], ['enable', 'ext-bundle'], ['disable', 'ext-bundle'], ['disable', 'ext-bundle'],
  485. ])
  486. })
  487. it('only writes the manifest on a startup-reload profile', async () => {
  488. const staged = await stageHome('startup')
  489. stagePackage(staged.profileDir, 'ext-bundle', { patch: BUNDLE_ONE_ROW })
  490. addDependency(staged.profileDir, 'ext-bundle')
  491. const { ctx, manager } = await bootProfile(staged)
  492. expect(await manager.enable('ext-bundle')).toEqual({ changed: true, effect: 'restart' })
  493. expect(manifestOf(staged.profileDir).dsh.profile.bundles).toEqual(['ext-bundle'])
  494. expect(entryIds(ctx)).not.toContain('include:hello')
  495. expect(await manager.disable('ext-bundle')).toEqual({ changed: true, effect: 'restart' })
  496. })
  497. it('refuses what cannot be enabled or disabled', async () => {
  498. const staged = await stageHome()
  499. stagePackage(staged.profileDir, 'ext-lib', { main: 'export const x = 1\n' })
  500. addDependency(staged.profileDir, 'ext-lib')
  501. stagePackage(staged.profileDir, 'ext-broken', { patch: BUNDLE_ONE_ROW, main: 'throw new Error("no import for you")\n' })
  502. addDependency(staged.profileDir, 'ext-broken')
  503. const { manager } = await bootProfile(staged)
  504. await expect(manager.enable('absent')).rejects.toMatchObject({ code: 'plugins/not-installed' })
  505. await expect(manager.enable('ext-lib')).rejects.toMatchObject({ code: 'plugins/not-enableable', details: { reason: expect.stringContaining('declares no dsh.bundle') as string } })
  506. await expect(manager.enable('ext-broken')).rejects.toMatchObject({ code: 'plugins/not-enableable', details: { reason: expect.stringContaining('no import for you') as string } })
  507. // A template bundle is not a dependency and cannot be disabled.
  508. const manifest = manifestOf(staged.profileDir)
  509. manifest.dsh.profile.bundles.push('template')
  510. writeFileSync(join(staged.profileDir, 'package.json'), JSON.stringify(manifest, null, 2))
  511. await expect(manager.disable('template')).rejects.toMatchObject({ code: 'gateway/bad-request' })
  512. await expect(manager.retry('ext-lib')).rejects.toMatchObject({ code: 'gateway/bad-request' })
  513. })
  514. it('restores the layer list when the tree rejects a boot-stage bundle', async () => {
  515. const staged = await stageHome()
  516. stagePackage(staged.profileDir, 'ext-fatal', { patch: '- insert:\n - id: bad\n name: cordis:throws\n', stage: 'boot' })
  517. addDependency(staged.profileDir, 'ext-fatal')
  518. stagePackage(staged.profileDir, 'ext-fine', { patch: BUNDLE_ONE_ROW })
  519. addDependency(staged.profileDir, 'ext-fine')
  520. const { ctx, manager } = await bootProfile(staged)
  521. await manager.enable('ext-fine')
  522. await expect(manager.enable('ext-fatal')).rejects.toMatchObject({
  523. code: 'plugins/enable-failed', details: { packageName: 'ext-fatal', reason: expect.stringContaining('boom at apply') as string },
  524. })
  525. expect(manifestOf(staged.profileDir).dsh.profile.bundles).toEqual(['ext-fine'])
  526. expect(entryIds(ctx)).toContain('include:hello')
  527. expect(entryIds(ctx)).not.toContain('include:bad')
  528. })
  529. it('retries an isolated bundle by composing it again', async () => {
  530. const staged = await stageHome()
  531. stagePackage(staged.profileDir, 'ext-flaky', { patch: '- insert:\n - id: once\n name: cordis:flaky\n' })
  532. addDependency(staged.profileDir, 'ext-flaky')
  533. flakyCalls = 0
  534. const { manager, changes } = await bootProfile(staged)
  535. await manager.enable('ext-flaky')
  536. expect((await manager.list())[0]).toMatchObject({ status: 'failed', reason: expect.stringContaining('flaky first start') as string })
  537. expect(await manager.retry('ext-flaky')).toEqual({ changed: true, effect: 'live' })
  538. expect((await manager.list())[0]).toMatchObject({ status: 'running' })
  539. expect(changes.map(change => change.reason)).toEqual(['enable', 'disable', 'enable', 'retry'])
  540. })
  541. })
  542. describe('rows in user layers', () => {
  543. it('adds, disables, re-enables, and removes a row in the live global layer', async () => {
  544. const staged = await stageHome()
  545. stagePackage(staged.profileDir, '@acme/ext-plugin', { main: 'export const name = "p"\nexport function apply() {}\n' })
  546. addDependency(staged.profileDir, '@acme/ext-plugin')
  547. const { ctx, manager, changes } = await bootProfile(staged)
  548. const added = await manager.addRow('@acme/ext-plugin', { kind: 'global' })
  549. expect(added).toEqual({ target: { kind: 'global' }, rowId: 'acme/ext-plugin', file: join(staged.profileDir, 'cordis.patch.yml') })
  550. expect(readFileSync(added.file, 'utf8')).toBe('- insert:\n - id: acme/ext-plugin\n name: "@acme/ext-plugin"\n config: {}\n')
  551. // Composed live: the row is in the tree, though its module cannot import from the temp home.
  552. expect(entryIds(ctx)).toContain('include:acme/ext-plugin')
  553. await expect(manager.addRow('@acme/ext-plugin', { kind: 'global' })).rejects.toMatchObject({ code: 'plugins/row-conflict' })
  554. await manager.setRowDisabled({ kind: 'global' }, 'acme/ext-plugin', true)
  555. expect(ctx.loader.resolve('include:acme/ext-plugin')?.disabled).toBe(true)
  556. expect(readFileSync(added.file, 'utf8')).toContain('- id: acme/ext-plugin\n disabled: true\n')
  557. await manager.setRowDisabled({ kind: 'global' }, 'acme/ext-plugin', false)
  558. expect(ctx.loader.resolve('include:acme/ext-plugin')?.disabled).toBe(false)
  559. expect(readFileSync(added.file, 'utf8')).not.toContain('disabled')
  560. await manager.removeRow({ kind: 'global' }, 'acme/ext-plugin')
  561. expect(entryIds(ctx)).not.toContain('include:acme/ext-plugin')
  562. await expect(manager.removeRow({ kind: 'global' }, 'acme/ext-plugin')).rejects.toMatchObject({ code: 'gateway/bad-request' })
  563. expect(changes.map(change => change.reason)).toEqual(['row', 'row', 'row', 'row'])
  564. })
  565. it('detects a conflict through the layer file when the tree was not recomposed', async () => {
  566. const staged = await stageHome('startup')
  567. stagePackage(staged.profileDir, 'ext-plugin', { main: 'export const name = "p"\nexport function apply() {}\n' })
  568. addDependency(staged.profileDir, 'ext-plugin')
  569. const { ctx, manager } = await bootProfile(staged)
  570. await manager.addRow('ext-plugin', { kind: 'global' })
  571. expect(entryIds(ctx)).not.toContain('include:ext-plugin')
  572. await expect(manager.addRow('ext-plugin', { kind: 'global' })).rejects.toMatchObject({ code: 'plugins/row-conflict' })
  573. })
  574. it('adds a declared addable module with its default config and an explicit id, and refuses the rest', async () => {
  575. const staged = await stageHome()
  576. stagePackage(staged.profileDir, 'ext-bundle', {
  577. patch: BUNDLE_ONE_ROW,
  578. plugins: [
  579. { name: './tools/sql.js', title: 'SQL', config: { dsn: 'sqlite://' } },
  580. { name: './missing.js' },
  581. ],
  582. files: { 'tools/sql.js': 'export const name = "sql"\nexport function apply() {}\n' },
  583. })
  584. addDependency(staged.profileDir, 'ext-bundle')
  585. const { manager } = await bootProfile(staged)
  586. const added = await manager.addRow('ext-bundle', { kind: 'global' }, { module: './tools/sql.js', id: 'sql' })
  587. expect(added.rowId).toBe('sql')
  588. expect(readFileSync(added.file, 'utf8')).toContain('- id: sql\n name: ext-bundle/tools/sql.js\n config:\n dsn: sqlite://\n')
  589. await expect(manager.addRow('ext-bundle', { kind: 'global' })).rejects.toMatchObject({ code: 'plugins/not-enableable' })
  590. await expect(manager.addRow('ext-bundle', { kind: 'global' }, { module: './missing.js' })).rejects.toMatchObject({ code: 'plugins/not-enableable' })
  591. await expect(manager.addRow('absent', { kind: 'global' })).rejects.toMatchObject({ code: 'plugins/not-installed' })
  592. })
  593. it('writes a preset\'s layer through the roster, and refuses a preset target without one', async () => {
  594. const staged = await stageHome()
  595. stagePackage(staged.profileDir, 'ext-plugin', { main: 'export const name = "p"\nexport function apply() {}\n' })
  596. addDependency(staged.profileDir, 'ext-plugin')
  597. const { ctx, manager } = await bootProfile(staged)
  598. await expect(manager.addRow('ext-plugin', { kind: 'preset', preset: 'standard' })).rejects.toMatchObject({ code: 'plugins/unavailable' })
  599. const overlay = join(staged.home, '.agent-presets', 'standard', 'cordis.patch.yml')
  600. const roster = {
  601. overlayPathFor: (id: string) => Promise.resolve(join(staged.home, '.agent-presets', id, 'cordis.patch.yml')),
  602. compositionInventory: () => Promise.resolve([{ id: 'standard', rows: [{ entryId: 'tool-web' }] }]),
  603. list: () => Promise.resolve([{ id: 'standard', overlayPath: existsSync(overlay) ? overlay : undefined }]),
  604. }
  605. ctx.provide('agentPresets', roster)
  606. // No layer exists yet: nothing references the package.
  607. expect((await manager.dependents('ext-plugin')).references).toEqual([])
  608. // A preset the inventory does not know has no rows to conflict with.
  609. const elsewhere = await manager.addRow('ext-plugin', { kind: 'preset', preset: 'other' })
  610. expect(elsewhere.file).toBe(join(staged.home, '.agent-presets', 'other', 'cordis.patch.yml'))
  611. const added = await manager.addRow('ext-plugin', { kind: 'preset', preset: 'standard' })
  612. expect(added).toEqual({ target: { kind: 'preset', preset: 'standard' }, rowId: 'ext-plugin', file: overlay })
  613. await expect(manager.addRow('ext-plugin', { kind: 'preset', preset: 'standard' }, { id: 'tool-web' })).rejects.toMatchObject({ code: 'plugins/row-conflict' })
  614. await manager.setRowDisabled({ kind: 'preset', preset: 'standard' }, 'tool-web', true)
  615. expect(readFileSync(overlay, 'utf8')).toBe('- insert:\n - id: ext-plugin\n name: ext-plugin\n config: {}\n- id: tool-web\n disabled: true\n')
  616. // The preset's layer is not part of the host tree.
  617. expect(entryIds(ctx)).not.toContain('include:ext-plugin')
  618. const dependents = await manager.dependents('ext-plugin')
  619. expect(dependents.references).toEqual([{ target: { kind: 'preset', preset: 'standard' }, rowId: 'ext-plugin', moduleName: 'ext-plugin' }])
  620. await manager.removeRow({ kind: 'preset', preset: 'standard' }, 'ext-plugin')
  621. expect(readFileSync(overlay, 'utf8')).toBe('- id: tool-web\n disabled: true\n')
  622. })
  623. })
  624. describe('dependents and uninstall', () => {
  625. it('names the services other rows inject and the user-layer rows that reference the package', async () => {
  626. const staged = await stageHome()
  627. // Beside the provider: a row nobody injects, and a row switched off (no fiber to read).
  628. 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' })
  629. addDependency(staged.profileDir, 'ext-provider')
  630. writeFileSync(join(staged.profileDir, 'cordis.patch.yml'), [
  631. '- insert:',
  632. ' - name: ext-provider/anonymous.js',
  633. ' disabled: true',
  634. ' - id: ref',
  635. ' name: ext-provider/tools/x.js',
  636. ' disabled: true',
  637. ' - id: grp',
  638. ' name: cordis:group',
  639. ' group: true',
  640. ' config:',
  641. ' - id: nested-ref',
  642. ' name: ext-provider',
  643. ' disabled: true',
  644. '',
  645. ].join('\n'))
  646. const { manager, runtime } = await bootProfile(staged)
  647. await manager.enable('ext-provider')
  648. // A built-in row injecting the bundle's service, composed once the
  649. // provider is up (a boot would refuse a row left waiting).
  650. 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`)
  651. await runtime.recompose()
  652. const dependents = await manager.dependents('ext-provider')
  653. expect(dependents.services).toEqual([{ service: 'fixtureSvc', providedBy: 'include:svc', injectedBy: ['include:needs-svc'] }])
  654. expect(dependents.references.map(reference => reference.rowId)).toEqual(['ref', 'nested-ref'])
  655. expect(dependents.references[0]).toEqual({ target: { kind: 'global' }, rowId: 'ref', moduleName: 'ext-provider/tools/x.js' })
  656. })
  657. it('ignores an unreadable user layer while collecting references', async () => {
  658. const staged = await stageHome()
  659. stagePackage(staged.profileDir, 'ext-lib', { main: 'export const x = 1\n' })
  660. addDependency(staged.profileDir, 'ext-lib')
  661. const { manager } = await bootProfile(staged)
  662. writeFileSync(join(staged.profileDir, 'cordis.patch.yml'), 'a: [\n')
  663. expect((await manager.dependents('ext-lib')).references).toEqual([])
  664. })
  665. it('disables, drops references, removes the package, and forgets its probe', async () => {
  666. const staged = await stageHome()
  667. stagePackage(staged.profileDir, 'ext-bundle', { patch: BUNDLE_ONE_ROW, plugins: [{ name: './extra.js' }], files: { 'extra.js': 'export function apply() {}\n' } })
  668. addDependency(staged.profileDir, 'ext-bundle')
  669. const calls: string[][] = []
  670. const { ctx, manager, changes } = await bootProfile(staged, { spawn: recordingPnpm(staged.profileDir, calls) })
  671. await manager.enable('ext-bundle')
  672. await manager.addRow('ext-bundle', { kind: 'global' }, { module: './extra.js' })
  673. expect(entryIds(ctx)).toEqual(expect.arrayContaining(['include:hello', 'include:ext-bundle/extra.js']))
  674. expect(existsSync(join(staged.profileDir, '.dsh-plugins', 'ext-bundle.json'))).toBe(true)
  675. await manager.uninstall('ext-bundle')
  676. expect(calls).toEqual([['pnpm', 'remove', 'ext-bundle']])
  677. expect(manifestOf(staged.profileDir)).toMatchObject({ dependencies: {}, dsh: { profile: { bundles: [] } } })
  678. expect(entryIds(ctx)).not.toContain('include:hello')
  679. expect(entryIds(ctx)).not.toContain('include:ext-bundle/extra.js')
  680. expect(readFileSync(join(staged.profileDir, 'cordis.patch.yml'), 'utf8')).toBe('[]\n')
  681. expect(existsSync(join(staged.profileDir, '.dsh-plugins', 'ext-bundle.json'))).toBe(false)
  682. expect(changes.map(change => change.reason)).toEqual(['enable', 'row', 'disable', 'uninstall'])
  683. await expect(manager.uninstall('ext-bundle')).rejects.toMatchObject({ code: 'plugins/not-installed' })
  684. })
  685. })
  686. })
  687. describe('RemoteError codes', () => {
  688. it('declare their details', () => {
  689. const error = new RemoteError('plugins/row-conflict', 'taken', { rowId: 'x', target: { kind: 'global' } })
  690. expect(error.details).toEqual({ rowId: 'x', target: { kind: 'global' } })
  691. })
  692. })