plugin-manager.spec.ts 50 KB

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