manager.spec.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /** Persistent manager behavior through a real profile Include and Loader. */
  2. import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  3. import { join } from 'node:path'
  4. import { tmpdir } from 'node:os'
  5. import type { Context } from '@deepseek-ai/cordis'
  6. import type AgentRegistry from '@deepseek-ai/dsh-agent'
  7. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  8. import type { UserMessage } from '@deepseek-ai/dsh-llm'
  9. import { expect, it, onTestFinished, vi } from 'vitest'
  10. import {
  11. boot, composeEntries, initProfile, readProfilePatches, readProfileManifest, reconcileProfilePatches,
  12. type ProfileContext,
  13. } from '@deepseek-ai/dsh-app-boot'
  14. import PluginManager, { type Config } from '../src/index.ts'
  15. import Hmr from '@deepseek-ai/dsh-hmr'
  16. import Timer from '@deepseek-ai/cordis-plugin-timer'
  17. import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  18. import { Group } from '@deepseek-ai/cordis-plugin-loader'
  19. import * as operations from '../src/operations.ts'
  20. async function fixture(reload: 'live' | 'startup' = 'live', overlay = false, prepare?: (ctx: Context) => void, config: Config = {}) {
  21. const home = mkdtempSync(join(tmpdir(), 'plugin-manager-'))
  22. const dir = join(home, 'profiles', 'test')
  23. const anchor = join(home, 'package.json')
  24. writeFileSync(anchor, '{"name":"installation","dependencies":{}}\n')
  25. initProfile(dir, ['core', 'extra'])
  26. const bundle = (name: string, rows: unknown[]) => {
  27. const path = join(dir, 'node_modules', name)
  28. mkdirSync(path, { recursive: true })
  29. writeFileSync(join(path, 'package.json'), JSON.stringify({ name, version: '1.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } } }))
  30. writeFileSync(join(path, 'cordis.patch.yml'), JSON.stringify([{ insert: rows }]))
  31. writeFileSync(join(path, 'plugin.mjs'), 'export function apply(ctx, config) { if (config?.fail) throw new Error("test activation failed"); ctx.provide(config?.service ?? "managedProbe", true) }\n')
  32. }
  33. bundle('core', [{ id: 'manager', name: 'cordis:manager', config }])
  34. bundle('extra', [{ id: 'managed', name: './plugin.mjs' }])
  35. const manifest = readProfileManifest('test', dir)
  36. manifest.dependencies = { extra: '1.0.0' }
  37. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  38. writeFileSync(join(dir, 'cordis.yml'), '[]\n')
  39. const overlays: PatchOptions[] = overlay ? [{ id: 'managed', disabled: true }] : []
  40. const profile: ProfileContext = {
  41. name: 'test',
  42. startedBundles: ['core', 'extra'],
  43. dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor: anchor, cwd: home, home,
  44. overlays, telemetryDisabledEnv: undefined,
  45. }
  46. const ctx = await boot('test', join(dir, 'cordis.yml'), readProfilePatches('test', profile), (ctx) => {
  47. ctx.provide('appReady', { onReady: (listener: () => void) => { listener(); return () => {} } })
  48. prepare?.(ctx)
  49. ctx.provide('profileContext', profile)
  50. ctx.loader.builtins.manager = PluginManager
  51. })
  52. onTestFinished(async () => { await ctx.fiber.dispose(); rmSync(home, { recursive: true, force: true }) })
  53. let stopHmr = async () => {}
  54. if (reload === 'live') {
  55. await ctx.plugin(Timer)
  56. const owner = await ctx.plugin(Hmr, { root: [], ignored: [], debounce: 0 })
  57. stopHmr = () => owner.dispose()
  58. await ctx.hmr.runExclusive(async () => {})
  59. }
  60. return { ctx, dir, manager: ctx.pluginManager, bundle, profile, stopHmr, overlays }
  61. }
  62. it('lists bundle versions and current-profile plugin targets', async () => {
  63. const { manager } = await fixture()
  64. const plugins = await manager.listPlugins()
  65. expect(plugins.find(row => row.entryId === 'include:managed')).toMatchObject({ patchId: 'managed', enabled: true })
  66. expect(plugins.find(row => row.entryId === 'include:manager')?.readOnlyReason).toBeDefined()
  67. expect(await manager.listBundles()).toEqual([
  68. { name: 'core', version: '1.0.0', enabled: true, removable: false, readOnlyReason: 'management-required' },
  69. { name: 'extra', version: '1.0.0', enabled: true, removable: true },
  70. ])
  71. })
  72. it('turns a plugin off and on without duplicating patch overrides', async () => {
  73. const { manager, dir } = await fixture()
  74. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  75. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: true, application: 'applied' })
  76. expect((await manager.listPlugins()).find(row => row.entryId === id)?.enabled).toBe(false)
  77. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: false, application: 'applied' })
  78. expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'applied' })
  79. expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8').match(/id: managed/g)).toHaveLength(1)
  80. })
  81. it('retains installed dependencies when toggling a bundle and appends it when re-enabled', async () => {
  82. const { manager, dir, bundle } = await fixture()
  83. bundle('third', [])
  84. await manager.setBundleEnabled('third', true)
  85. expect(await manager.setBundleEnabled('extra', false)).toMatchObject({ changed: true, application: 'applied' })
  86. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  87. expect((await manager.listPlugins()).some(row => row.patchId === 'managed')).toBe(false)
  88. await manager.setBundleEnabled('extra', true)
  89. expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toEqual(['core', 'third', 'extra'])
  90. })
  91. it('reports an overlay overriding a saved plugin toggle', async () => {
  92. const { manager } = await fixture('live', true)
  93. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  94. expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'overridden' })
  95. })
  96. it('saves startup-only toggles and refuses removal of currently used packages', async () => {
  97. const { manager } = await fixture('startup')
  98. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  99. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ application: 'restart-required' })
  100. expect((await manager.listPlugins()).find(row => row.entryId === id)?.enabled).toBe(true)
  101. await manager.setBundleEnabled('extra', false)
  102. expect(await manager.removeBundle('extra')).toMatchObject({ changed: false, application: 'failed' })
  103. })
  104. it('refuses self-disable, unknown entries and removal of installation-owned bundles', async () => {
  105. const { manager } = await fixture()
  106. const id = (await manager.listPlugins()).find(row => row.entryId === 'include:manager')!.entryId
  107. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: false, application: 'failed' })
  108. expect(await manager.setPluginEnabled('missing' as typeof id, true)).toMatchObject({ changed: false, application: 'failed' })
  109. expect(await manager.removeBundle('core')).toMatchObject({ changed: false, application: 'failed' })
  110. expect(await manager.setBundleEnabled('unknown', true)).toMatchObject({ changed: false, application: 'failed' })
  111. })
  112. it('installs only valid bundle declarations and honors installation without activation', async () => {
  113. const { manager, dir, bundle } = await fixture()
  114. const initial = readProfileManifest('test', dir)
  115. delete initial.dependencies
  116. writeFileSync(join(dir, 'package.json'), JSON.stringify(initial))
  117. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async (_context, args) => {
  118. const name = String(args[1])
  119. bundle(name, [{ id: name, name: './plugin.mjs', config: { service: name } }])
  120. const manifest = readProfileManifest('test', dir)
  121. manifest.dependencies = { ...manifest.dependencies, [name]: '1.0.0' }
  122. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  123. return { exitCode: 0, output: 'installed', truncated: false, logPath: join(dir, 'pnpm.log') }
  124. })
  125. onTestFinished(() => { install.mockRestore() })
  126. expect(await manager.installBundle('new-bundle', { enabled: false })).toMatchObject({ changed: true, application: 'applied', packageResult: { exitCode: 0 } })
  127. expect((await manager.listBundles()).find(row => row.name === 'new-bundle')?.enabled).toBe(false)
  128. expect(await manager.setBundleEnabled('new-bundle', true)).toMatchObject({ application: 'applied' })
  129. expect((await manager.listPlugins()).find(row => row.patchId === 'new-bundle')?.fiberPhase).toBe('active')
  130. expect(await manager.installBundle('another-bundle')).toMatchObject({ application: 'applied' })
  131. expect((await manager.listBundles()).find(row => row.name === 'another-bundle')?.enabled).toBe(true)
  132. })
  133. it('unloads before removing packages and retries inactive dependencies whose files are missing', async () => {
  134. const { manager, dir, ctx } = await fixture()
  135. const remove = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  136. await ctx.hmr.runExclusive(async () => {
  137. expect([...ctx.loader.entries()].some(row => row.id === 'include:managed')).toBe(false)
  138. })
  139. return { exitCode: 1, output: 'removal failed', truncated: false, logPath: join(dir, 'pnpm.log') }
  140. })
  141. onTestFinished(() => { remove.mockRestore() })
  142. expect(await manager.removeBundle('extra')).toMatchObject({ changed: true, application: 'failed', packageResult: { exitCode: 1 } })
  143. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  144. expect((await manager.listBundles()).find(row => row.name === 'extra')?.enabled).toBe(false)
  145. rmSync(join(dir, 'node_modules', 'extra'), { recursive: true })
  146. remove.mockImplementationOnce(async () => {
  147. const manifest = readProfileManifest('test', dir)
  148. delete manifest.dependencies?.extra
  149. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  150. return { exitCode: 0, output: 'removed', truncated: false, logPath: join(dir, 'pnpm.log') }
  151. })
  152. expect(await manager.removeBundle('extra')).toMatchObject({ changed: true, application: 'applied' })
  153. expect((await manager.listBundles()).some(row => row.name === 'extra')).toBe(false)
  154. })
  155. it('reports package failure separately from partial disk changes', async () => {
  156. const { manager, dir } = await fixture()
  157. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  158. const manifest = readProfileManifest('test', dir)
  159. manifest.dependencies = { ...manifest.dependencies, partial: '1' }
  160. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  161. return { exitCode: 42, output: 'fetch failed', truncated: false, logPath: join(dir, 'pnpm.log') }
  162. })
  163. onTestFinished(() => { install.mockRestore() })
  164. expect(await manager.installBundle('partial')).toMatchObject({ changed: true, application: 'failed', packageResult: { exitCode: 42 } })
  165. expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toEqual(['core', 'extra'])
  166. expect((await manager.listBundles()).find(row => row.name === 'partial')?.error?.diagnostic).toContain('cannot resolve profile bundle')
  167. })
  168. it('keeps saved changes after activation failure and allows a corrected configuration to retry', async () => {
  169. const { manager, dir } = await fixture()
  170. writeFileSync(join(dir, 'cordis.patch.yml'), '- id: managed\n disabled: true\n config: { fail: true }\n')
  171. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  172. expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'failed' })
  173. expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')).toContain('disabled: false')
  174. writeFileSync(join(dir, 'cordis.patch.yml'), '- id: managed\n disabled: true\n config: { fail: false }\n')
  175. const result = await manager.setPluginEnabled(id, true)
  176. expect(result, JSON.stringify(result)).toMatchObject({ application: 'applied' })
  177. })
  178. it('combines concurrent changes into durable notices without waking Agents', async () => {
  179. const session = Session.create(SessionId('manager-notices'))
  180. const wake = vi.fn()
  181. const notices: UserMessage[] = []
  182. const liveAgents = [{
  183. inject(message: UserMessage) {
  184. notices.push(message)
  185. session.append('user/message', message, { surfaceOp: 'append' })
  186. }, followup: wake, steer: wake,
  187. }, { inject() { throw new Error('already disposed') } }]
  188. const agents = { list: () => liveAgents }
  189. const { manager } = await fixture('live', false, (ctx) => { ctx.provide('agents', agents as unknown as AgentRegistry) })
  190. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  191. await Promise.all([manager.setPluginEnabled(id, false), manager.setPluginEnabled(id, true)])
  192. expect(notices).toHaveLength(1)
  193. const noticeText = notices[0]?.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('')
  194. expect(noticeText).toContain('"enabled":false')
  195. expect(noticeText).toContain('"enabled":true')
  196. expect(wake).not.toHaveBeenCalled()
  197. expect(session.snapshotEvents().filter(row => row.type === 'user/message')).toHaveLength(1)
  198. })
  199. it('reports plain dependencies, missing versions and invalid selected bundles distinctly', async () => {
  200. const { manager, dir, profile } = await fixture()
  201. writeFileSync(profile.installAnchor, '{}')
  202. writeFileSync(join(dir, 'node_modules', 'extra', 'package.json'), '{"name":"extra"}')
  203. expect((await manager.listBundles()).find(row => row.name === 'extra')).toMatchObject({ enabled: true, error: { code: 'not-bundle' } })
  204. expect(await manager.setBundleEnabled('extra', false)).toMatchObject({ application: 'applied' })
  205. expect((await manager.listBundles()).find(row => row.name === 'extra')).toMatchObject({ enabled: false, removable: true, error: { code: 'not-bundle' } })
  206. expect(await manager.setBundleEnabled('extra', true)).toMatchObject({ changed: false, application: 'failed' })
  207. writeFileSync(join(dir, 'node_modules', 'core', 'package.json'), '{"name":"core","dsh":{"bundle":{"patch":"./cordis.patch.yml"}}}')
  208. expect((await manager.listBundles())[0]?.version).toBeUndefined()
  209. writeFileSync(join(dir, 'package.json'), '{}')
  210. expect(await manager.listBundles()).toEqual([])
  211. expect(await manager.setBundleEnabled('unknown', false)).toMatchObject({ application: 'failed' })
  212. writeFileSync(profile.installAnchor, '{"dependencies":{"missing-builtin":"1"}}')
  213. expect(await manager.listBundles()).toEqual([])
  214. })
  215. it('refuses management bundle disablement and permits repeated bundle selections', async () => {
  216. const { manager } = await fixture()
  217. expect(await manager.setBundleEnabled('core', false)).toMatchObject({ application: 'failed', changed: false })
  218. expect(await manager.setBundleEnabled('extra', true)).toMatchObject({ application: 'applied', changed: false })
  219. })
  220. it.each([
  221. '@deepseek-ai/dsh-host-plugin-inventory',
  222. '@deepseek-ai/dsh-typert-registry',
  223. '@deepseek-ai/dsh-api-remotes',
  224. ])('protects the management dependency %s and its containing bundle', async (name) => {
  225. const { ctx, manager, bundle, profile, dir } = await fixture('startup')
  226. bundle('extra', [{ id: 'dependency', name, disabled: true }])
  227. await reconcileProfilePatches(ctx, readProfilePatches('test', profile), 'test')
  228. const entry = (await manager.listPlugins()).find(row => row.moduleName === name)!
  229. expect(entry).toMatchObject({ readOnlyReason: 'management-required' })
  230. const manifest = readFileSync(join(dir, 'package.json'), 'utf8')
  231. const patch = readFileSync(profile.patchPath, 'utf8')
  232. expect(await manager.setPluginEnabled(entry.entryId, false)).toMatchObject({
  233. changed: false, application: 'failed', error: { code: 'management-required' },
  234. })
  235. expect((await manager.listBundles()).find(row => row.name === 'extra')).toMatchObject({
  236. removable: false, readOnlyReason: 'management-required',
  237. })
  238. expect(await manager.setBundleEnabled('extra', false)).toMatchObject({
  239. changed: false, application: 'failed', error: { code: 'management-required' },
  240. })
  241. expect(await manager.removeBundle('extra')).toMatchObject({
  242. changed: false, application: 'failed', error: { code: 'not-removable' },
  243. })
  244. expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(manifest)
  245. expect(readFileSync(profile.patchPath, 'utf8')).toBe(patch)
  246. })
  247. it('addresses children inside profile groups and marks ambiguous ids read-only', async () => {
  248. const { manager, bundle, profile } = await fixture('live', false, (ctx) => { ctx.loader.builtins.group = Group })
  249. bundle('grouped', [{ id: 'group', name: 'cordis:group', group: true,
  250. config: [{ id: 'child', name: './plugin.mjs', config: { service: 'child' } }] }])
  251. expect(await manager.setBundleEnabled('grouped', true)).toMatchObject({ application: 'applied' })
  252. expect((await manager.listPlugins()).find(row => row.patchId === 'child')).toBeDefined()
  253. const entries = composeEntries([readProfilePatches('test', profile)])
  254. const duplicate = entries.find(row => row.id === 'managed')!
  255. writeFileSync(profile.patchPath, JSON.stringify([{ insert: [duplicate] }]))
  256. expect((await manager.listPlugins()).find(row => row.entryId === 'include:managed')?.readOnlyReason).toBe('unaddressable')
  257. })
  258. it.each(['', '-g'])('rejects an invalid installation spec before calling pnpm: %j', async (spec) => {
  259. const { manager } = await fixture()
  260. expect(await manager.installBundle(spec)).toMatchObject({ changed: false, application: 'failed' })
  261. })
  262. it.each([0, 1])('cleans a newly added non-bundle once and exposes leftovers when cleanup exits %i', async (cleanupExit) => {
  263. const { manager, dir, bundle } = await fixture()
  264. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async (_context, args) => {
  265. const manifest = readProfileManifest('test', dir)
  266. if (args[0] === 'add') {
  267. bundle('plain', [])
  268. writeFileSync(join(dir, 'node_modules', 'plain', 'package.json'), '{"name":"plain"}')
  269. manifest.dependencies = { ...manifest.dependencies, plain: '1' }
  270. } else if (cleanupExit === 0) {
  271. delete manifest.dependencies?.plain
  272. rmSync(join(dir, 'node_modules', 'plain'), { recursive: true })
  273. }
  274. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  275. return { exitCode: args[0] === 'add' ? 0 : cleanupExit, output: 'package diagnostic', truncated: false, logPath: join(dir, `${args[0]}.log`) }
  276. })
  277. onTestFinished(() => { install.mockRestore() })
  278. expect(await manager.installBundle('plain')).toMatchObject({ changed: cleanupExit !== 0, application: 'failed', stage: 'install',
  279. error: { code: 'not-bundle' }, packageResult: { exitCode: 0 },
  280. cleanup: { name: 'plain', packageResult: { exitCode: cleanupExit } },
  281. remainingDependencies: cleanupExit === 0 ? [] : ['plain'] })
  282. expect(install.mock.calls.map(call => call[1])).toEqual([['add', 'plain'], ['remove', 'plain']])
  283. expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toEqual(['core', 'extra'])
  284. const leftover = (await manager.listBundles()).find(row => row.name === 'plain')
  285. if (cleanupExit === 0) expect(leftover).toBeUndefined()
  286. else {
  287. expect(leftover).toMatchObject({ enabled: false, removable: true, error: { code: 'not-bundle' } })
  288. expect(await manager.removeBundle('plain')).toMatchObject({ stage: 'remove', application: 'failed' })
  289. }
  290. })
  291. it('never removes an existing dependency after installation validation fails', async () => {
  292. const { manager, dir } = await fixture()
  293. writeFileSync(join(dir, 'node_modules', 'extra', 'package.json'), '{"name":"extra"}')
  294. const install = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 0, output: '', truncated: false, logPath: '/operation.log' })
  295. onTestFinished(() => { install.mockRestore() })
  296. const result = await manager.installBundle('extra')
  297. expect(result).toMatchObject({ application: 'failed', stage: 'install', error: { code: 'not-bundle' } })
  298. expect(result.cleanup).toBeUndefined()
  299. expect(install).toHaveBeenCalledOnce()
  300. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  301. })
  302. it('keeps a valid installed bundle when its subsequent activation fails', async () => {
  303. const { manager, dir, bundle } = await fixture()
  304. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  305. bundle('broken', [{ id: 'broken', name: './plugin.mjs', config: { fail: true } }])
  306. const manifest = readProfileManifest('test', dir)
  307. manifest.dependencies = { ...manifest.dependencies, broken: '1' }
  308. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  309. return { exitCode: 0, output: '', truncated: false, logPath: '/operation.log' }
  310. })
  311. onTestFinished(() => { install.mockRestore() })
  312. const result = await manager.installBundle('broken')
  313. expect(result).toMatchObject({ application: 'failed', stage: 'enable', packageResult: { exitCode: 0 } })
  314. expect(result.cleanup).toBeUndefined()
  315. expect(install).toHaveBeenCalledOnce()
  316. expect((await manager.listBundles()).find(row => row.name === 'broken')).toMatchObject({ enabled: true, removable: true })
  317. })
  318. it('returns unchanged failures as warnings while toggling and removing another bundle', async () => {
  319. const { manager, dir, bundle, ctx } = await fixture()
  320. bundle('broken', [
  321. { id: 'broken', name: './plugin.mjs', config: { fail: true } },
  322. { id: 'missing', name: './missing.mjs' },
  323. { id: 'pending', name: './pending.mjs' },
  324. ])
  325. writeFileSync(join(dir, 'node_modules/broken/pending.mjs'), 'export const inject = ["unavailable"]; export function apply() {}')
  326. expect(await manager.setBundleEnabled('broken', true)).toMatchObject({ application: 'failed' })
  327. const brokenId = (await manager.listPlugins()).find(row => row.patchId === 'broken')!.entryId
  328. expect(await manager.setPluginEnabled(brokenId, true)).toMatchObject({ application: 'failed' })
  329. expect(await manager.setBundleEnabled('broken', true)).toMatchObject({ application: 'failed' })
  330. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  331. const changed = await manager.setPluginEnabled(id, false)
  332. expect(changed).toMatchObject({ application: 'applied' })
  333. expect(changed.warnings).toHaveLength(3)
  334. expect(await manager.setPluginEnabled(id, true)).toMatchObject({ application: 'applied' })
  335. const remove = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  336. expect([...ctx.loader.entries()].some(row => row.id === 'include:managed')).toBe(false)
  337. const manifest = readProfileManifest('test', dir)
  338. delete manifest.dependencies?.extra
  339. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  340. return { exitCode: 0, output: '', truncated: false, logPath: '/operation.log' }
  341. })
  342. onTestFinished(() => { remove.mockRestore() })
  343. const removed = await manager.removeBundle('extra')
  344. expect(removed.application).toBe('applied')
  345. expect(removed.warnings).toHaveLength(3)
  346. expect(remove).toHaveBeenCalledOnce()
  347. })
  348. it('reports repeated installs as requiring restart and ambiguous package changes as failures', async () => {
  349. const { manager, dir } = await fixture()
  350. const install = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') })
  351. onTestFinished(() => { install.mockRestore() })
  352. expect(await manager.installBundle('extra')).toMatchObject({ changed: false, application: 'restart-required' })
  353. expect(await manager.installBundle('extra@1')).toMatchObject({ changed: false, application: 'restart-required' })
  354. expect(await manager.installBundle('extra-long@1')).toMatchObject({ changed: false, application: 'failed' })
  355. install.mockImplementationOnce(async () => {
  356. writeFileSync(join(dir, 'package.json'), '{}')
  357. return { exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') }
  358. })
  359. expect(await manager.installBundle('unknown')).toMatchObject({ changed: true, application: 'failed' })
  360. })
  361. it('handles missing patch files and retains non-Error package diagnostics', async () => {
  362. const { manager, dir } = await fixture()
  363. rmSync(join(dir, 'cordis.patch.yml'))
  364. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  365. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: true, application: 'applied' })
  366. const install = vi.spyOn(operations, 'runProfilePnpm').mockRejectedValueOnce('pnpm rejected operation')
  367. onTestFinished(() => { install.mockRestore() })
  368. expect(await manager.installBundle('new')).toMatchObject({ changed: false, application: 'failed', error: { code: 'operation-error', diagnostic: 'pnpm rejected operation' } })
  369. rmSync(join(dir, 'cordis.patch.yml'))
  370. mkdirSync(join(dir, 'cordis.patch.yml'))
  371. await expect(manager.setPluginEnabled(id, true)).rejects.toThrow()
  372. })
  373. it('bounds batched notices and discloses omitted operation results', async () => {
  374. const messages: UserMessage[] = []
  375. const { manager } = await fixture('live', false, (ctx) => {
  376. ctx.provide('agents', { list: () => [{ inject: (message: UserMessage) => { messages.push(message) } }] } as unknown as AgentRegistry)
  377. }, { outputBytes: 1, notificationDelayMs: 0 })
  378. await manager.setBundleEnabled('extra', false)
  379. expect(messages[0]?.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('')).toContain('"omitted":1')
  380. })
  381. it('applies a manager change through the active HMR service', async () => {
  382. const { manager } = await fixture()
  383. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  384. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: true, application: 'applied' })
  385. expect((await manager.listPlugins()).find(row => row.entryId === id)?.enabled).toBe(false)
  386. })
  387. it('refuses removal of a hot-installed bundle after HMR is disabled', async () => {
  388. const { ctx, manager, dir, bundle, stopHmr } = await fixture()
  389. bundle('later', [{ id: 'later', name: './plugin.mjs', config: { service: 'laterProbe' } }])
  390. const manifest = readProfileManifest('test', dir)
  391. manifest.dependencies = { ...manifest.dependencies, later: '1' }
  392. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  393. expect(await manager.setBundleEnabled('later', true)).toMatchObject({ application: 'applied' })
  394. await stopHmr()
  395. expect(ctx.get('hmr')).toBeUndefined()
  396. expect(await manager.setBundleEnabled('later', false)).toMatchObject({ application: 'restart-required' })
  397. expect(ctx.get('laterProbe')).toBe(true)
  398. expect(await manager.removeBundle('later')).toMatchObject({ changed: false, application: 'failed' })
  399. })
  400. it('omits installation-owned plain packages from the bundle inventory', async () => {
  401. const { manager, dir, profile, bundle } = await fixture()
  402. bundle('installation-plain', [])
  403. writeFileSync(join(dir, 'node_modules/installation-plain/package.json'), '{"name":"installation-plain"}')
  404. writeFileSync(profile.installAnchor, '{"dependencies":{"installation-plain":"1"}}')
  405. expect((await manager.listBundles()).some(row => row.name === 'installation-plain')).toBe(false)
  406. })
  407. it.each(['throw', 'remove-manifest-dependencies', 'invalid-manifest'] as const)('preserves the original installation failure when cleanup encounters %s', async (failure) => {
  408. const { manager, dir, profile } = await fixture()
  409. writeFileSync(profile.installAnchor, '{}')
  410. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async (_context, args) => {
  411. if (args[0] === 'add') {
  412. const manifest = readProfileManifest('test', dir)
  413. manifest.dependencies = { ...manifest.dependencies, partial: '1' }
  414. writeFileSync(join(dir, 'package.json'), failure === 'invalid-manifest' ? '{' : JSON.stringify(manifest))
  415. } else if (failure === 'throw') throw new Error('cleanup unavailable')
  416. else writeFileSync(join(dir, 'package.json'), '{}')
  417. return { exitCode: args[0] === 'add' ? 42 : 0, output: 'fetch failed', truncated: false, logPath: '/operation.log' }
  418. })
  419. onTestFinished(() => { install.mockRestore() })
  420. const result = await manager.installBundle('partial')
  421. expect(result).toMatchObject({ application: 'failed', error: { code: 'operation-error', diagnostic: 'fetch failed' } })
  422. if (failure === 'throw') {
  423. expect(result.cleanup).toMatchObject({ name: 'partial', error: { diagnostic: 'cleanup unavailable' } })
  424. expect(result.remainingDependencies).toEqual(['partial'])
  425. } else if (failure === 'invalid-manifest') {
  426. expect(result.warnings?.[0]).toContain('SyntaxError')
  427. expect(install).toHaveBeenCalledOnce()
  428. } else expect(result.remainingDependencies).toEqual([])
  429. })
  430. it.each(['ambiguous', 'selected', 'installation-owned'] as const)('does not clean newly declared dependencies that are %s', async (reason) => {
  431. const { manager, dir, profile } = await fixture()
  432. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  433. const manifest = readProfileManifest('test', dir)
  434. manifest.dependencies = { ...manifest.dependencies, partial: '1', ...reason === 'ambiguous' ? { another: '1' } : {} }
  435. if (reason === 'selected') manifest.dsh!.profile!.bundles!.push('partial')
  436. if (reason === 'installation-owned') writeFileSync(profile.installAnchor, '{"dependencies":{"partial":"1"}}')
  437. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  438. return { exitCode: 42, output: 'fetch failed', truncated: false, logPath: '/operation.log' }
  439. })
  440. onTestFinished(() => { install.mockRestore() })
  441. const result = await manager.installBundle('partial')
  442. expect(result.application).toBe('failed')
  443. expect(result.cleanup).toBeUndefined()
  444. expect(result.remainingDependencies).toContain('partial')
  445. expect(install).toHaveBeenCalledOnce()
  446. })
  447. it('does not delete a bundle retained by a higher-priority overlay', async () => {
  448. const { ctx, manager, overlays, dir } = await fixture()
  449. const entry = [...ctx.loader.entries()].find(row => row.id === 'include:managed')!
  450. overlays.push({ insert: [{ ...entry.options }] })
  451. const remove = vi.spyOn(operations, 'runProfilePnpm')
  452. onTestFinished(() => { remove.mockRestore() })
  453. expect(await manager.removeBundle('extra')).toMatchObject({ changed: true, application: 'failed', error: { code: 'bundle-in-use' } })
  454. expect(await manager.removeBundle('extra')).toMatchObject({ changed: false, application: 'failed', error: { code: 'bundle-in-use' } })
  455. expect(remove).not.toHaveBeenCalled()
  456. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  457. expect(ctx.get('managedProbe')).toBe(true)
  458. })
  459. it('applies watched configuration while pnpm installation is still running', async () => {
  460. const { ctx, manager, dir, profile, bundle } = await fixture()
  461. const entered = Promise.withResolvers<undefined>()
  462. const release = Promise.withResolvers<undefined>()
  463. const pnpm = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  464. entered.resolve(undefined)
  465. await release.promise
  466. bundle('new-bundle', [])
  467. const manifest = readProfileManifest('test', dir)
  468. manifest.dependencies = { ...manifest.dependencies, 'new-bundle': '1.0.0' }
  469. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  470. return { exitCode: 0, output: 'installed', truncated: false, logPath: join(dir, 'pnpm.log') }
  471. })
  472. const installing = manager.installBundle('new-bundle')
  473. onTestFinished(async () => { release.resolve(undefined); await installing; pnpm.mockRestore() })
  474. await entered.promise
  475. writeFileSync(profile.patchPath, '- id: managed\n disabled: true\n')
  476. await vi.waitFor(() => { expect(ctx.get('managedProbe')).toBeUndefined() }, { timeout: 10000 })
  477. expect(pnpm).toHaveBeenCalledOnce()
  478. release.resolve(undefined)
  479. expect(await installing).toMatchObject({ application: 'applied', changed: true })
  480. expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toEqual(['core', 'extra', 'new-bundle'])
  481. expect(ctx.get('managedProbe')).toBeUndefined()
  482. })