manager.spec.ts 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. /** Persistent manager behavior through a real profile Include and Loader. */
  2. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  3. import { realpath } from 'node:fs/promises'
  4. import { join } from 'node:path'
  5. import { tmpdir } from 'node:os'
  6. import { pathToFileURL } from 'node:url'
  7. import type { Context } from '@deepseek-ai/cordis'
  8. import { expect, it, onTestFinished, vi } from 'vitest'
  9. import {
  10. boot, composeEntries, initProfile, readProfilePatches, readProfileManifest, reconcileProfilePatches, OPTIONAL_BUNDLES,
  11. type ProfileContext,
  12. } from '@deepseek-ai/dsh-app-boot'
  13. import PluginManager, { type Config, type PluginChange, type PluginInstallLogChunk, type PluginInstallProgress, type PluginInstallRequestId } from '../src/index.ts'
  14. import Hmr from '@deepseek-ai/dsh-hmr'
  15. import Timer from '@deepseek-ai/cordis-plugin-timer'
  16. import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  17. import { Group } from '@deepseek-ai/cordis-plugin-loader'
  18. import * as operations from '../src/operations.ts'
  19. import { parse, parseDocument } from 'yaml'
  20. async function fixture(reload: 'live' | 'startup' = 'live', overlay = false, prepare?: (ctx: Context) => void, config: Config = {}) {
  21. // pnpm resolves workspace roots through native realpath, including Windows 8.3 aliases.
  22. const home = await realpath(mkdtempSync(join(tmpdir(), 'plugin-manager-')))
  23. const dir = join(home, 'profiles', 'test')
  24. const anchor = join(home, 'package.json')
  25. writeFileSync(anchor, '{"name":"installation","dependencies":{}}\n')
  26. initProfile(dir, ['core', 'extra'])
  27. const bundle = (name: string, rows: unknown[]) => {
  28. const path = join(dir, 'node_modules', name)
  29. mkdirSync(path, { recursive: true })
  30. writeFileSync(join(path, 'package.json'), JSON.stringify({ name, version: '1.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } } }))
  31. writeFileSync(join(path, 'cordis.patch.yml'), JSON.stringify([{ insert: rows }]))
  32. 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')
  33. }
  34. bundle('core', [{ id: 'manager', name: 'cordis:manager', config }])
  35. bundle('extra', [{ id: 'managed', name: './plugin.mjs' }])
  36. const manifest = readProfileManifest('test', dir)
  37. manifest.dependencies = { extra: '1.0.0' }
  38. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  39. writeFileSync(join(dir, 'cordis.yml'), '[]\n')
  40. const overlays: PatchOptions[] = overlay ? [{ id: 'managed', disabled: true }] : []
  41. const profile: ProfileContext = {
  42. name: 'test',
  43. startedBundles: ['core', 'extra'],
  44. dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor: anchor, cwd: home, home,
  45. overlays, telemetryDisabledEnv: undefined,
  46. }
  47. const ctx = await boot('test', join(dir, 'cordis.yml'), readProfilePatches('test', profile), (ctx) => {
  48. ctx.provide('appReady', { onReady: (listener: () => void) => { listener(); return () => {} } })
  49. prepare?.(ctx)
  50. ctx.provide('profileContext', profile)
  51. ctx.loader.builtins.manager = PluginManager
  52. })
  53. onTestFinished(async () => { await ctx.fiber.dispose(); rmSync(home, { recursive: true, force: true }) })
  54. let stopHmr = async () => {}
  55. if (reload === 'live') {
  56. await ctx.plugin(Timer)
  57. const owner = await ctx.plugin(Hmr, { root: [], ignored: [], debounce: 0 })
  58. stopHmr = () => owner.dispose()
  59. await ctx.hmr.runExclusive(async () => {})
  60. }
  61. return { ctx, dir, manager: ctx.pluginManager, bundle, profile, stopHmr, overlays }
  62. }
  63. it('lists bundle versions and current-profile plugin targets', async () => {
  64. const { manager, dir } = await fixture()
  65. const plugins = await manager.listPlugins()
  66. expect(plugins.find(row => row.entryId === 'include:managed')).toMatchObject({ patchId: 'managed', enabled: true })
  67. expect(plugins.find(row => row.entryId === 'include:manager')?.readOnlyReason).toBe('management-required')
  68. expect(await manager.listBundles()).toEqual([
  69. {
  70. name: 'core', version: '1.0.0', enabled: true, installed: false, optional: false, removable: false, readOnlyReason: 'management-required',
  71. rows: [{ rowId: 'manager', moduleName: 'cordis:manager', entryId: 'include:manager' }], overrides: [],
  72. },
  73. {
  74. name: 'extra', version: '1.0.0', enabled: true, installed: true, optional: false, removable: true,
  75. rows: [{ rowId: 'managed', moduleName: pathToFileURL(join(dir, 'node_modules', 'extra', 'plugin.mjs')).href, entryId: 'include:managed' }], overrides: [],
  76. },
  77. ])
  78. })
  79. it('describes a bundle by its manifest and patch: one-liner, rows without a live entry, and the built-in rows it changes', async () => {
  80. const { manager, dir, bundle } = await fixture()
  81. bundle('described', [{ id: 'described-row', name: './plugin.mjs' }])
  82. writeFileSync(join(dir, 'node_modules', 'described', 'package.json'), JSON.stringify({
  83. name: 'described', version: '2.0.0', description: 'Describes itself.', dsh: { bundle: { patch: './cordis.patch.yml' } },
  84. }))
  85. // An anonymous row is not addressable and is left out of the rows.
  86. writeFileSync(join(dir, 'node_modules', 'described', 'cordis.patch.yml'), JSON.stringify([
  87. { insert: [{ id: 'described-row', name: './plugin.mjs' }, { name: './plugin.mjs' }] }, { id: 'managed', disabled: true }, { id: 'described-row', config: {} },
  88. ]))
  89. const manifest = readProfileManifest('test', dir)
  90. manifest.dependencies = { ...manifest.dependencies, described: '2.0.0' }
  91. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  92. const moduleName = pathToFileURL(join(dir, 'node_modules', 'described', 'plugin.mjs')).href
  93. expect((await manager.listBundles()).find(row => row.name === 'described')).toEqual({
  94. name: 'described', version: '2.0.0', description: 'Describes itself.', enabled: false, installed: true, optional: false, removable: true,
  95. rows: [{ rowId: 'described-row', moduleName }], overrides: ['managed'],
  96. })
  97. await manager.setBundleEnabled('described', true)
  98. expect((await manager.listBundles()).find(row => row.name === 'described')?.rows).toEqual([
  99. { rowId: 'described-row', moduleName, entryId: 'include:described-row' },
  100. ])
  101. // Off again, the rows lose their entries.
  102. await manager.setBundleEnabled('described', false)
  103. expect((await manager.listBundles()).find(row => row.name === 'described')?.rows).toEqual([{ rowId: 'described-row', moduleName }])
  104. })
  105. it('turns a plugin off and on without duplicating patch overrides', async () => {
  106. const { manager, dir } = await fixture()
  107. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  108. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: true, application: 'applied' })
  109. expect((await manager.listPlugins()).find(row => row.entryId === id)?.enabled).toBe(false)
  110. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: false, application: 'applied' })
  111. expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'applied' })
  112. expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8').match(/id: managed/g)).toHaveLength(1)
  113. })
  114. it('retains installed dependencies when toggling a bundle and appends it when re-enabled', async () => {
  115. const { manager, dir, bundle } = await fixture()
  116. bundle('third', [])
  117. await manager.setBundleEnabled('third', true)
  118. expect(await manager.setBundleEnabled('extra', false)).toMatchObject({ changed: true, application: 'applied' })
  119. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  120. expect((await manager.listPlugins()).some(row => row.patchId === 'managed')).toBe(false)
  121. await manager.setBundleEnabled('extra', true)
  122. expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toEqual(['core', 'third', 'extra'])
  123. })
  124. it('reports an overlay overriding a saved plugin toggle', async () => {
  125. const { manager } = await fixture('live', true)
  126. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  127. expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'overridden' })
  128. })
  129. it('saves startup-only toggles and refuses removal of currently used packages', async () => {
  130. const { manager } = await fixture('startup')
  131. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  132. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ application: 'restart-required' })
  133. expect((await manager.listPlugins()).find(row => row.entryId === id)?.enabled).toBe(true)
  134. await manager.setBundleEnabled('extra', false)
  135. expect(await manager.removeBundle('extra')).toMatchObject({ changed: false, application: 'failed', error: { code: 'stop-profile' } })
  136. })
  137. it('refuses self-disable, unknown entries and removal of installation-owned bundles', async () => {
  138. const { manager } = await fixture()
  139. const id = (await manager.listPlugins()).find(row => row.entryId === 'include:manager')!.entryId
  140. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: false, application: 'failed', error: { code: 'management-required' } })
  141. expect(await manager.setPluginEnabled('missing' as typeof id, true)).toMatchObject({ changed: false, application: 'failed', error: { code: 'unknown-plugin' } })
  142. expect(await manager.removeBundle('core')).toMatchObject({ changed: false, application: 'failed', error: { code: 'not-removable' } })
  143. // A name no bundle directory answers to fails with the resolver's own diagnostic.
  144. expect(await manager.setBundleEnabled('unknown', true)).toMatchObject({ changed: false, application: 'failed', error: { code: 'operation-error' } })
  145. })
  146. it('installs only valid bundle declarations and honors installation without activation', async () => {
  147. const { manager, dir, bundle } = await fixture()
  148. const initial = readProfileManifest('test', dir)
  149. delete initial.dependencies
  150. writeFileSync(join(dir, 'package.json'), JSON.stringify(initial))
  151. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async (_context, args) => {
  152. const name = String(args[1])
  153. bundle(name, [{ id: name, name: './plugin.mjs', config: { service: name } }])
  154. const manifest = readProfileManifest('test', dir)
  155. manifest.dependencies = { ...manifest.dependencies, [name]: '1.0.0' }
  156. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  157. return { exitCode: 0, output: 'installed', truncated: false, logPath: join(dir, 'pnpm.log') }
  158. })
  159. onTestFinished(() => { install.mockRestore() })
  160. expect(await manager.installBundle('new-bundle', { enabled: false })).toMatchObject({
  161. changed: true, application: 'applied', stage: 'enable', target: 'new-bundle', bundle: 'new-bundle', packageResult: { exitCode: 0 },
  162. })
  163. expect((await manager.listBundles()).find(row => row.name === 'new-bundle')?.enabled).toBe(false)
  164. expect(await manager.setBundleEnabled('new-bundle', true)).toMatchObject({ application: 'applied' })
  165. expect((await manager.listPlugins()).find(row => row.patchId === 'new-bundle')?.fiberPhase).toBe('active')
  166. expect(await manager.installBundle('another-bundle')).toMatchObject({ application: 'applied' })
  167. expect((await manager.listBundles()).find(row => row.name === 'another-bundle')?.enabled).toBe(true)
  168. })
  169. it('reports blocked scripts after a failed installation and retries only after explicit profile build approval', async () => {
  170. const { manager, dir, bundle } = await fixture()
  171. const policy = join(dir, 'pnpm-workspace.yaml')
  172. const run = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  173. const manifest = readProfileManifest('test', dir)
  174. const completion = { exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') }
  175. manifest.dependencies = { ...manifest.dependencies, addon: '1.0.0' }
  176. if (run.mock.calls.length === 1) {
  177. writeFileSync(policy, 'allowBuilds:\n native: set this to true or false\n denied: false\n')
  178. completion.exitCode = 1
  179. completion.output = 'ERR_PNPM_IGNORED_BUILDS'
  180. } else {
  181. expect(parse(readFileSync(policy, 'utf8'))).toEqual({ allowBuilds: { native: true, denied: false } })
  182. bundle('addon', [])
  183. }
  184. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  185. return completion
  186. })
  187. onTestFinished(() => { run.mockRestore() })
  188. // The failed run's manifest change is put back; the policy pnpm wrote stays, so its undecided names can be offered.
  189. expect(await manager.installBundle('addon')).toMatchObject({ application: 'failed', pendingBuilds: ['native'] })
  190. expect(readProfileManifest('test', dir).dependencies).not.toHaveProperty('addon')
  191. expect(parse(readFileSync(policy, 'utf8'))).toMatchObject({ allowBuilds: { native: 'set this to true or false' } })
  192. expect(await manager.installBundle('addon', { approvedBuilds: ['denied'] })).toMatchObject({ application: 'failed', changed: false, error: { code: 'stale-approval' } })
  193. expect(run).toHaveBeenCalledTimes(1)
  194. expect(await manager.installBundle('addon', { approvedBuilds: ['native'], enabled: false })).toMatchObject({
  195. application: 'applied', changed: true, approvedBuilds: ['native'],
  196. })
  197. expect(readProfileManifest('test', dir).dsh?.profile?.bundles).not.toContain('addon')
  198. })
  199. it('retains approved policy and reports it as changed when the registry fails before adding a dependency', async () => {
  200. const { manager, dir } = await fixture()
  201. writeFileSync(join(dir, 'pnpm-workspace.yaml'), 'allowBuilds:\n native: set this to true or false\n')
  202. const run = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 1, output: 'registry unavailable', truncated: false, logPath: '/log' })
  203. onTestFinished(() => { run.mockRestore() })
  204. expect(await manager.installBundle('addon', { approvedBuilds: ['native'] })).toMatchObject({
  205. changed: true, application: 'failed', pendingBuilds: [], approvedBuilds: ['native'], error: { diagnostic: 'registry unavailable' },
  206. })
  207. expect(parse(readFileSync(join(dir, 'pnpm-workspace.yaml'), 'utf8'))).toEqual({ allowBuilds: { native: true } })
  208. })
  209. it('runs a real pnpm dependency script only after approval and retry', async () => {
  210. const { manager, dir, profile } = await fixture('startup')
  211. const addon = join(profile.cwd, 'addon')
  212. mkdirSync(addon)
  213. writeFileSync(join(addon, 'package.json'), JSON.stringify({ name: 'approval-fixture-addon', version: '1.0.0',
  214. scripts: { install: 'node build.cjs' }, dsh: { bundle: { patch: './cordis.patch.yml' } } }))
  215. writeFileSync(join(addon, 'build.cjs'), 'require("node:fs").writeFileSync("built.txt", "built")\n')
  216. writeFileSync(join(addon, 'cordis.patch.yml'), '[]\n')
  217. writeFileSync(join(dir, 'package.json'), '{"name":"approval-fixture","private":true}\n')
  218. const policy = parseDocument(readFileSync(join(dir, 'pnpm-workspace.yaml'), 'utf8'))
  219. policy.set('offline', true)
  220. policy.set('storeDir', join(profile.cwd, 'store'))
  221. writeFileSync(join(dir, 'pnpm-workspace.yaml'), String(policy))
  222. const blocked = await manager.installBundle('file:./addon', { enabled: false })
  223. expect(blocked, JSON.stringify(blocked)).toMatchObject({ application: 'failed', packageResult: { kind: 'build-blocked' } })
  224. expect(blocked.pendingBuilds).toHaveLength(1)
  225. const built = join(dir, 'node_modules', 'approval-fixture-addon', 'built.txt')
  226. expect(existsSync(built)).toBe(false)
  227. expect(readProfileManifest('test', dir).dependencies?.['approval-fixture-addon']).toBeUndefined()
  228. const allowed = await manager.installBundle('file:./addon', { enabled: false, approvedBuilds: blocked.pendingBuilds! })
  229. expect(allowed, JSON.stringify(allowed)).toMatchObject({ application: 'restart-required', packageResult: { exitCode: 0 } })
  230. expect(readFileSync(built, 'utf8')).toBe('built')
  231. })
  232. it.each(['[', 'allowBuilds: false\n'])('preserves pnpm diagnostics when pending approvals cannot be read: %s', async (policy) => {
  233. const { manager, dir } = await fixture()
  234. writeFileSync(join(dir, 'pnpm-workspace.yaml'), policy)
  235. const run = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 1, output: 'original pnpm failure', truncated: false, logPath: '/log' })
  236. onTestFinished(() => { run.mockRestore() })
  237. expect(await manager.installBundle('addon')).toMatchObject({ application: 'failed', error: { diagnostic: 'original pnpm failure' } })
  238. })
  239. it('unloads before removing packages and retries inactive dependencies whose files are missing', async () => {
  240. const { manager, dir, ctx } = await fixture()
  241. const remove = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  242. await ctx.hmr.runExclusive(async () => {
  243. expect([...ctx.loader.entries()].some(row => row.id === 'include:managed')).toBe(false)
  244. })
  245. return { exitCode: 1, output: 'removal failed', truncated: false, logPath: join(dir, 'pnpm.log') }
  246. })
  247. onTestFinished(() => { remove.mockRestore() })
  248. expect(await manager.removeBundle('extra')).toMatchObject({ changed: true, application: 'failed', packageResult: { exitCode: 1 } })
  249. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  250. expect((await manager.listBundles()).find(row => row.name === 'extra')?.enabled).toBe(false)
  251. rmSync(join(dir, 'node_modules', 'extra'), { recursive: true })
  252. remove.mockImplementationOnce(async () => {
  253. const manifest = readProfileManifest('test', dir)
  254. delete manifest.dependencies?.extra
  255. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  256. return { exitCode: 0, output: 'removed', truncated: false, logPath: join(dir, 'pnpm.log') }
  257. })
  258. expect(await manager.removeBundle('extra')).toMatchObject({ changed: true, application: 'applied' })
  259. expect((await manager.listBundles()).some(row => row.name === 'extra')).toBe(false)
  260. })
  261. it('restores the manifest and lockfile after a failed package run, classifying the failure', async () => {
  262. const { manager, dir } = await fixture()
  263. const lockPath = join(dir, 'pnpm-lock.yaml')
  264. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  265. const manifest = readProfileManifest('test', dir)
  266. manifest.dependencies = { ...manifest.dependencies, partial: '1' }
  267. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  268. writeFileSync(lockPath, 'partial lockfile\n')
  269. return { exitCode: 42, output: 'ERR_PNPM_META_FETCH_FAIL GET https://registry/partial: ENOTFOUND', truncated: false, logPath: join(dir, 'pnpm.log') }
  270. })
  271. onTestFinished(() => { install.mockRestore() })
  272. const before = readFileSync(join(dir, 'package.json'), 'utf8')
  273. expect(await manager.installBundle('partial')).toMatchObject({
  274. changed: false, application: 'failed', stage: 'install', target: 'partial',
  275. error: { code: 'operation-error', diagnostic: expect.stringContaining('ENOTFOUND') as string },
  276. packageResult: { exitCode: 42, kind: 'network' },
  277. })
  278. expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(before)
  279. // A lockfile the run created is removed; one that existed is put back.
  280. expect(existsSync(lockPath)).toBe(false)
  281. writeFileSync(lockPath, 'original lockfile\n')
  282. expect(await manager.installBundle('partial')).toMatchObject({ changed: false, application: 'failed' })
  283. expect(readFileSync(lockPath, 'utf8')).toBe('original lockfile\n')
  284. expect((await manager.listBundles()).some(row => row.name === 'partial')).toBe(false)
  285. expect(install).toHaveBeenCalledTimes(2)
  286. })
  287. it('keeps saved changes after activation failure and allows a corrected configuration to retry', async () => {
  288. const { manager, dir } = await fixture()
  289. writeFileSync(join(dir, 'cordis.patch.yml'), '- id: managed\n disabled: true\n config: { fail: true }\n')
  290. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  291. expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: true, application: 'failed' })
  292. expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')).toContain('disabled: false')
  293. writeFileSync(join(dir, 'cordis.patch.yml'), '- id: managed\n disabled: true\n config: { fail: false }\n')
  294. const result = await manager.setPluginEnabled(id, true)
  295. expect(result, JSON.stringify(result)).toMatchObject({ application: 'applied' })
  296. })
  297. it('reports a selected plain dependency as a problem, omits an unselected one, and reports missing versions', async () => {
  298. const { manager, dir, profile } = await fixture()
  299. writeFileSync(profile.installAnchor, '{}')
  300. writeFileSync(join(dir, 'node_modules', 'extra', 'package.json'), '{"name":"extra"}')
  301. expect((await manager.listBundles()).find(row => row.name === 'extra')).toMatchObject({ enabled: true, error: { code: 'not-bundle' } })
  302. expect(await manager.setBundleEnabled('extra', false)).toMatchObject({ application: 'applied' })
  303. // Switched off, a dependency without a bundle patch is a library the page has no business with.
  304. expect((await manager.listBundles()).some(row => row.name === 'extra')).toBe(false)
  305. expect(await manager.setBundleEnabled('extra', true)).toMatchObject({ changed: false, application: 'failed' })
  306. writeFileSync(join(dir, 'node_modules', 'core', 'package.json'), '{"name":"core","dsh":{"bundle":{"patch":"./cordis.patch.yml"}}}')
  307. expect((await manager.listBundles())[0]?.version).toBeUndefined()
  308. writeFileSync(join(dir, 'package.json'), '{}')
  309. expect(await manager.listBundles()).toEqual([])
  310. expect(await manager.setBundleEnabled('unknown', false)).toMatchObject({ application: 'failed' })
  311. writeFileSync(profile.installAnchor, '{"dependencies":{"missing-builtin":"1"}}')
  312. expect(await manager.listBundles()).toEqual([])
  313. })
  314. it('refuses management bundle disablement and permits repeated bundle selections', async () => {
  315. const { manager } = await fixture()
  316. expect(await manager.setBundleEnabled('core', false)).toMatchObject({ application: 'failed', changed: false })
  317. expect(await manager.setBundleEnabled('extra', true)).toMatchObject({ application: 'applied', changed: false })
  318. })
  319. it.each([
  320. '@deepseek-ai/dsh-host-plugin-inventory',
  321. '@deepseek-ai/dsh-typert-registry',
  322. '@deepseek-ai/dsh-api-remotes',
  323. ])('protects the management dependency %s and its containing bundle', async (name) => {
  324. const { ctx, manager, bundle, profile, dir } = await fixture('startup')
  325. bundle('extra', [{ id: 'dependency', name, disabled: true }])
  326. await reconcileProfilePatches(ctx, readProfilePatches('test', profile), 'test')
  327. const entry = (await manager.listPlugins()).find(row => row.moduleName === name)!
  328. expect(entry).toMatchObject({ readOnlyReason: 'management-required' })
  329. const manifest = readFileSync(join(dir, 'package.json'), 'utf8')
  330. const patch = readFileSync(profile.patchPath, 'utf8')
  331. expect(await manager.setPluginEnabled(entry.entryId, false)).toMatchObject({
  332. changed: false, application: 'failed', error: { code: 'management-required' },
  333. })
  334. expect((await manager.listBundles()).find(row => row.name === 'extra')).toMatchObject({
  335. removable: false, readOnlyReason: 'management-required',
  336. })
  337. expect(await manager.setBundleEnabled('extra', false)).toMatchObject({
  338. changed: false, application: 'failed', error: { code: 'management-required' },
  339. })
  340. expect(await manager.removeBundle('extra')).toMatchObject({
  341. changed: false, application: 'failed', error: { code: 'not-removable' },
  342. })
  343. expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(manifest)
  344. expect(readFileSync(profile.patchPath, 'utf8')).toBe(patch)
  345. })
  346. it('addresses children inside profile groups and marks ambiguous ids read-only', async () => {
  347. const { manager, bundle, profile } = await fixture('live', false, (ctx) => { ctx.loader.builtins.group = Group })
  348. bundle('grouped', [{ id: 'group', name: 'cordis:group', group: true,
  349. config: [{ id: 'child', name: './plugin.mjs', config: { service: 'child' } }] }])
  350. expect(await manager.setBundleEnabled('grouped', true)).toMatchObject({ application: 'applied' })
  351. expect((await manager.listPlugins()).find(row => row.patchId === 'child')).toBeDefined()
  352. const entries = composeEntries([readProfilePatches('test', profile)])
  353. const duplicate = entries.find(row => row.id === 'managed')!
  354. writeFileSync(profile.patchPath, JSON.stringify([{ insert: [duplicate] }]))
  355. expect((await manager.listPlugins()).find(row => row.entryId === 'include:managed')?.readOnlyReason).toBe('unaddressable')
  356. })
  357. it.each(['', '-g'])('rejects an invalid installation spec before calling pnpm: %j', async (spec) => {
  358. const { manager } = await fixture()
  359. expect(await manager.installBundle(spec)).toMatchObject({ changed: false, application: 'failed', error: { code: 'invalid-spec' } })
  360. })
  361. it('restores the manifest when the package pnpm added declares no bundle', async () => {
  362. const { manager, dir, bundle } = await fixture()
  363. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  364. bundle('plain', [])
  365. writeFileSync(join(dir, 'node_modules', 'plain', 'package.json'), '{"name":"plain"}')
  366. const manifest = readProfileManifest('test', dir)
  367. manifest.dependencies = { ...manifest.dependencies, plain: '1' }
  368. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  369. return { exitCode: 0, output: 'installed', truncated: false, logPath: join(dir, 'pnpm.log') }
  370. })
  371. onTestFinished(() => { install.mockRestore() })
  372. expect(await manager.installBundle('plain')).toMatchObject({
  373. changed: false, application: 'failed', stage: 'install', error: { code: 'not-bundle' }, packageResult: { exitCode: 0 },
  374. })
  375. // The manifest is put back rather than cleaned through another pnpm run.
  376. expect(install).toHaveBeenCalledOnce()
  377. expect(readProfileManifest('test', dir)).toMatchObject({ dependencies: { extra: '1.0.0' }, dsh: { profile: { bundles: ['core', 'extra'] } } })
  378. expect((await manager.listBundles()).some(row => row.name === 'plain')).toBe(false)
  379. })
  380. it('never removes an existing dependency after installation validation fails', async () => {
  381. const { manager, dir } = await fixture()
  382. writeFileSync(join(dir, 'node_modules', 'extra', 'package.json'), '{"name":"extra"}')
  383. const install = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 0, output: '', truncated: false, logPath: '/operation.log' })
  384. onTestFinished(() => { install.mockRestore() })
  385. const result = await manager.installBundle('extra')
  386. expect(result).toMatchObject({ application: 'failed', stage: 'install', error: { code: 'not-bundle' } })
  387. expect(install).toHaveBeenCalledOnce()
  388. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  389. })
  390. it('keeps a valid installed bundle when its subsequent activation fails', async () => {
  391. const { manager, dir, bundle } = await fixture()
  392. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  393. bundle('broken', [{ id: 'broken', name: './plugin.mjs', config: { fail: true } }])
  394. const manifest = readProfileManifest('test', dir)
  395. manifest.dependencies = { ...manifest.dependencies, broken: '1' }
  396. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  397. return { exitCode: 0, output: '', truncated: false, logPath: '/operation.log' }
  398. })
  399. onTestFinished(() => { install.mockRestore() })
  400. const result = await manager.installBundle('broken')
  401. expect(result).toMatchObject({ application: 'failed', stage: 'enable', target: 'broken', bundle: 'broken', packageResult: { exitCode: 0 } })
  402. expect(install).toHaveBeenCalledOnce()
  403. expect((await manager.listBundles()).find(row => row.name === 'broken')).toMatchObject({ enabled: true, removable: true })
  404. })
  405. it('returns unchanged failures as warnings while toggling and removing another bundle', async () => {
  406. const { manager, dir, bundle, ctx } = await fixture()
  407. bundle('broken', [
  408. { id: 'broken', name: './plugin.mjs', config: { fail: true } },
  409. { id: 'missing', name: './missing.mjs' },
  410. { id: 'pending', name: './pending.mjs' },
  411. ])
  412. writeFileSync(join(dir, 'node_modules/broken/pending.mjs'), 'export const inject = ["unavailable"]; export function apply() {}')
  413. expect(await manager.setBundleEnabled('broken', true)).toMatchObject({ application: 'failed' })
  414. const brokenId = (await manager.listPlugins()).find(row => row.patchId === 'broken')!.entryId
  415. expect(await manager.setPluginEnabled(brokenId, true)).toMatchObject({ application: 'failed' })
  416. expect(await manager.setBundleEnabled('broken', true)).toMatchObject({ application: 'failed' })
  417. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  418. const changed = await manager.setPluginEnabled(id, false)
  419. expect(changed).toMatchObject({ application: 'applied' })
  420. expect(changed.warnings).toHaveLength(3)
  421. expect(await manager.setPluginEnabled(id, true)).toMatchObject({ application: 'applied' })
  422. const remove = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  423. expect([...ctx.loader.entries()].some(row => row.id === 'include:managed')).toBe(false)
  424. const manifest = readProfileManifest('test', dir)
  425. delete manifest.dependencies?.extra
  426. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  427. return { exitCode: 0, output: '', truncated: false, logPath: '/operation.log' }
  428. })
  429. onTestFinished(() => { remove.mockRestore() })
  430. const removed = await manager.removeBundle('extra')
  431. expect(removed.application).toBe('applied')
  432. expect(removed.warnings).toHaveLength(3)
  433. expect(remove).toHaveBeenCalledOnce()
  434. })
  435. it('reports repeated installs as requiring restart and ambiguous package changes as failures', async () => {
  436. const { manager, dir } = await fixture()
  437. const install = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue({ exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') })
  438. onTestFinished(() => { install.mockRestore() })
  439. expect(await manager.installBundle('extra')).toMatchObject({ changed: false, application: 'restart-required' })
  440. expect(await manager.installBundle('extra@1')).toMatchObject({ changed: false, application: 'restart-required' })
  441. expect(await manager.installBundle('extra-long@1')).toMatchObject({ changed: false, application: 'failed', error: { code: 'ambiguous-install' } })
  442. install.mockImplementationOnce(async () => {
  443. writeFileSync(join(dir, 'package.json'), '{}')
  444. return { exitCode: 0, output: '', truncated: false, logPath: join(dir, 'pnpm.log') }
  445. })
  446. expect(await manager.installBundle('unknown')).toMatchObject({ changed: false, application: 'failed', error: { code: 'ambiguous-install' } })
  447. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  448. })
  449. it('streams pnpm output, reports the installation phases, and names the installed bundle', async () => {
  450. const { ctx, manager, dir, bundle } = await fixture()
  451. const chunks: PluginInstallLogChunk[] = []
  452. const phases: PluginInstallProgress[] = []
  453. const changes: PluginChange[] = []
  454. ctx.on('plugin-manager/install-log', (chunk) => { chunks.push(chunk) })
  455. ctx.on('plugin-manager/install-state', (progress) => { phases.push(progress) })
  456. ctx.on('plugin-manager/changed', (change) => { changes.push(change) })
  457. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async (_context, args, options) => {
  458. options.onOutput?.('Progress: resolved 1\n', 'stdout')
  459. options.onOutput?.('warning\n', 'stderr')
  460. const name = String(args[1])
  461. bundle(name, [{ id: name, name: './plugin.mjs', config: { service: name } }])
  462. const manifest = readProfileManifest('test', dir)
  463. manifest.dependencies = { ...manifest.dependencies, [name]: '1.0.0' }
  464. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  465. return { exitCode: 0, output: 'installed', truncated: false, logPath: join(dir, 'pnpm.log') }
  466. })
  467. onTestFinished(() => { install.mockRestore() })
  468. const requestId = 'f2340b6d-40bb-46b7-8b94-217bdf5010bd' as PluginInstallRequestId
  469. expect(await manager.installBundle('streamed', { enabled: false, requestId })).toMatchObject({ application: 'applied', changed: true, bundle: 'streamed' })
  470. expect(install).toHaveBeenCalledWith(expect.objectContaining({ profile: 'test' }), ['add', 'streamed'],
  471. expect.objectContaining({ command: 'pnpm', execution: 'service' }))
  472. const jobId = chunks[0]?.jobId
  473. expect(chunks).toEqual([
  474. { requestId, jobId, argv: ['pnpm', 'add', 'streamed'], cwd: dir, stream: 'stdout', text: 'Progress: resolved 1\n' },
  475. { requestId, jobId, argv: ['pnpm', 'add', 'streamed'], cwd: dir, stream: 'stderr', text: 'warning\n' },
  476. { requestId, jobId, argv: ['pnpm', 'add', 'streamed'], cwd: dir, stream: 'stdout', text: '', exitCode: 0 },
  477. ])
  478. expect(phases).toEqual([{ requestId, phase: 'installing' }, { requestId, phase: 'applying' }])
  479. expect(changes).toEqual([{ reason: 'install' }])
  480. // A run without a request id streams too, unidentified.
  481. await manager.removeBundle('streamed')
  482. expect(chunks.at(-1)).toMatchObject({ argv: ['pnpm', 'remove', 'streamed'], stream: 'stdout', exitCode: 0 })
  483. expect(chunks.at(-1)).not.toHaveProperty('requestId')
  484. expect(changes).toEqual([{ reason: 'install' }, { reason: 'remove' }])
  485. })
  486. it('stops a run on request, restores the files, and answers not-running or too-late otherwise', async () => {
  487. const { ctx, manager, dir, bundle } = await fixture()
  488. const phases: PluginInstallProgress[] = []
  489. ctx.on('plugin-manager/install-state', (progress) => { phases.push(progress) })
  490. const started = Promise.withResolvers<undefined>()
  491. const install = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async (_context, _args, options) => {
  492. const manifest = readProfileManifest('test', dir)
  493. manifest.dependencies = { ...manifest.dependencies, slow: '1' }
  494. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  495. started.resolve(undefined)
  496. await new Promise<undefined>((resolve) => { options.signal?.addEventListener('abort', () => { resolve(undefined) }, { once: true }) })
  497. return { exitCode: 1, output: 'killed', truncated: false, logPath: join(dir, 'pnpm.log') }
  498. })
  499. onTestFinished(() => { install.mockRestore() })
  500. const requestId = 'f2340b6d-40bb-46b7-8b94-217bdf5010bd' as PluginInstallRequestId
  501. const before = readFileSync(join(dir, 'package.json'), 'utf8')
  502. const run = manager.installBundle('slow', { requestId })
  503. await started.promise
  504. expect(await manager.cancelInstall('00000000-0000-4000-8000-000000000000' as PluginInstallRequestId)).toEqual({ status: 'not-running' })
  505. expect(await manager.cancelInstall(requestId)).toEqual({ status: 'cancelled' })
  506. expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(before)
  507. const cancelled = await run
  508. expect(cancelled).toMatchObject({ application: 'cancelled', changed: false, stage: 'install', packageResult: { exitCode: 1 } })
  509. expect(cancelled.error).toBeUndefined()
  510. expect(phases).toEqual([{ requestId, phase: 'installing' }, { requestId, phase: 'cancelling' }])
  511. expect(await manager.cancelInstall(requestId)).toEqual({ status: 'not-running' })
  512. // Once pnpm has exited and the bundle is being applied, the run cannot be stopped.
  513. install.mockImplementation(async (_context, args) => {
  514. const name = String(args[1])
  515. bundle(name, [{ id: name, name: './plugin.mjs', config: { service: name } }])
  516. const manifest = readProfileManifest('test', dir)
  517. manifest.dependencies = { ...manifest.dependencies, [name]: '1.0.0' }
  518. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  519. return { exitCode: 0, output: 'installed', truncated: false, logPath: join(dir, 'pnpm.log') }
  520. })
  521. let tooLate: Promise<unknown> | undefined
  522. ctx.on('plugin-manager/install-state', (progress) => { if (progress.phase === 'applying') tooLate = manager.cancelInstall(progress.requestId) })
  523. expect(await manager.installBundle('late', { requestId })).toMatchObject({ application: 'applied', bundle: 'late' })
  524. expect(await tooLate).toEqual({ status: 'too-late' })
  525. // A request aborted before its turn under the lock never starts pnpm.
  526. const early = manager.installBundle('never', { requestId })
  527. const queued = manager.installBundle('after', { requestId: '11111111-1111-4111-8111-111111111111' as PluginInstallRequestId })
  528. expect(await manager.cancelInstall('11111111-1111-4111-8111-111111111111' as PluginInstallRequestId)).toEqual({ status: 'cancelled' })
  529. await early
  530. expect(await queued).toMatchObject({ application: 'cancelled', changed: false })
  531. })
  532. it('reads what a spec names before installing it', async () => {
  533. const { manager, dir, profile } = await fixture(undefined, false, undefined, { inspectTimeoutMs: 1000, pnpmCommand: 'pnpm-test' })
  534. const view = vi.spyOn(operations, 'viewProfilePackage')
  535. onTestFinished(() => { view.mockRestore() })
  536. const answers = (stdout: string) => view.mockResolvedValueOnce({ exitCode: 0, stdout, stderr: '', timedOut: false })
  537. answers(JSON.stringify({ name: 'dsh-x', version: '1.4.2', description: 'A sidebar.', dsh: { bundle: { patch: './cordis.patch.yml' } } }))
  538. expect(await manager.inspect('dsh-x')).toEqual({
  539. status: 'accepted', kind: 'registry', name: 'dsh-x', version: '1.4.2', description: 'A sidebar.', bundle: true,
  540. })
  541. expect(view).toHaveBeenCalledWith(dir, 'dsh-x', { command: 'pnpm-test', timeoutMs: 1000 })
  542. const signal = AbortSignal.abort()
  543. answers(JSON.stringify([{ name: 'dsh-lib', version: '1.0.0', dsh: { bundle: {} } }, { name: 'dsh-lib', version: '1.1.0', dsh: null }]))
  544. expect(await manager.inspect('dsh-lib@^1', signal)).toEqual({ status: 'refused', problem: 'not-a-bundle', reason: 'dsh-lib declares no dsh.bundle' })
  545. expect(view).toHaveBeenLastCalledWith(dir, 'dsh-lib@^1', { command: 'pnpm-test', timeoutMs: 1000, signal })
  546. // An answer that names no package keeps the name the spec gave; colour escapes around the JSON are dropped.
  547. answers('\x1b[36m' + JSON.stringify({ version: '0.0.1', description: '', dsh: { bundle: { patch: './p.yml' } } }) + '\x1b[39m\n')
  548. expect(await manager.inspect('dsh-bare')).toEqual({ status: 'accepted', kind: 'registry', name: 'dsh-bare', version: '0.0.1', bundle: true })
  549. const failure = (stderr: string, exitCode: number | null = 1, more: Partial<operations.PackageViewResult> = {}) =>
  550. view.mockResolvedValueOnce({ exitCode, stdout: '', stderr, timedOut: false, ...more })
  551. failure('npm error code E404\nnpm error 404 Not Found - GET https://registry/nope\n')
  552. expect(await manager.inspect('nope')).toMatchObject({ status: 'refused', problem: 'not-found', reason: expect.stringContaining('E404') as string })
  553. failure('ERR_PNPM_NO_MATCHING_VERSION No matching version found for old@9\n')
  554. expect(await manager.inspect('old@9')).toMatchObject({ status: 'refused', problem: 'not-found' })
  555. failure('ERR_PNPM_META_FETCH_FAIL request failed, reason: getaddrinfo ENOTFOUND registry\n')
  556. expect(await manager.inspect('far')).toMatchObject({ status: 'refused', problem: 'network' })
  557. view.mockResolvedValueOnce({ exitCode: 3, stdout: 'plain text\n', stderr: '', timedOut: false })
  558. expect(await manager.inspect('odd')).toEqual({ status: 'refused', problem: 'unknown', reason: 'plain text' })
  559. failure('', 4)
  560. expect(await manager.inspect('quiet')).toEqual({ status: 'refused', problem: 'unknown', reason: 'pnpm view exited with 4' })
  561. failure('', null, { timedOut: true })
  562. expect(await manager.inspect('slow')).toEqual({ status: 'refused', problem: 'unknown', reason: 'pnpm view timed out after 1000ms' })
  563. failure('', null, { cause: Object.assign(new Error('spawn pnpm ENOENT'), { code: 'ENOENT' }) })
  564. expect(await manager.inspect('gone')).toMatchObject({ status: 'refused', problem: 'unknown', reason: expect.stringContaining('ENOENT') as string })
  565. answers('not json')
  566. expect(await manager.inspect('garbled')).toMatchObject({ status: 'refused', problem: 'unknown', reason: expect.stringContaining('unreadable pnpm view output') as string })
  567. answers('"just a string"')
  568. expect(await manager.inspect('scalar')).toEqual({ status: 'refused', problem: 'unknown', reason: 'pnpm view answered no package' })
  569. answers('')
  570. expect(await manager.inspect('silent')).toEqual({ status: 'refused', problem: 'unknown', reason: 'pnpm view answered no package' })
  571. // What is installed, or supplied by the installation, is refused before the registry is asked.
  572. expect(await manager.inspect('extra')).toEqual({ status: 'refused', problem: 'already-installed', reason: 'extra is already installed' })
  573. expect(await manager.inspect('./relative')).toEqual({ status: 'refused', problem: 'invalid-spec', reason: 'a local path must be absolute' })
  574. expect(await manager.inspect('github:acme/dsh-remote')).toEqual({ status: 'accepted', kind: 'git', bundle: null })
  575. const tarball = join(profile.home, 'pack.tgz')
  576. expect(await manager.inspect(tarball)).toEqual({ status: 'refused', problem: 'not-a-package', reason: 'the tarball does not exist' })
  577. writeFileSync(tarball, '')
  578. expect(await manager.inspect(tarball)).toEqual({ status: 'accepted', kind: 'tarball', bundle: null })
  579. expect(await manager.inspect('https://cdn.example.com/x/y/z/dsh-x-1.0.0.tgz')).toEqual({ status: 'accepted', kind: 'tarball', bundle: null })
  580. // A directory answers from its own manifest.
  581. const local = join(profile.home, 'dev', 'dsh-local')
  582. mkdirSync(local, { recursive: true })
  583. expect(await manager.inspect(join(profile.home, 'dev', 'missing'))).toEqual({ status: 'refused', problem: 'not-a-package', reason: 'the path does not exist' })
  584. expect(await manager.inspect(local)).toMatchObject({ status: 'refused', problem: 'not-a-package', reason: expect.stringContaining('no readable package.json') as string })
  585. writeFileSync(join(local, 'package.json'), '{"version":"1.0.0"}')
  586. expect(await manager.inspect(local)).toEqual({ status: 'refused', problem: 'not-a-package', reason: 'the package.json names no package' })
  587. writeFileSync(join(local, 'package.json'), JSON.stringify({ name: 'dsh-local', version: '0.1.0', description: 'Local.' }))
  588. expect(await manager.inspect(local)).toEqual({ status: 'refused', problem: 'not-a-bundle', reason: 'dsh-local declares no dsh.bundle' })
  589. writeFileSync(join(local, 'package.json'), JSON.stringify({ name: 'dsh-local', version: '0.1.0', description: 'Local.', dsh: { bundle: { patch: './p.yml' } } }))
  590. expect(await manager.inspect(`file:${local}`)).toEqual({ status: 'accepted', kind: 'path', name: 'dsh-local', version: '0.1.0', description: 'Local.', bundle: true })
  591. writeFileSync(join(local, 'package.json'), JSON.stringify({ name: 'core', dsh: { bundle: { patch: './p.yml' } } }))
  592. expect(await manager.inspect(local)).toEqual({ status: 'refused', problem: 'already-installed', reason: 'core is already installed' })
  593. // A profile and an installation that list nothing know nothing.
  594. writeFileSync(join(dir, 'package.json'), '{}')
  595. writeFileSync(profile.installAnchor, '{}')
  596. expect(await manager.inspect(local)).toEqual({ status: 'accepted', kind: 'path', name: 'core', bundle: true })
  597. expect(view).toHaveBeenCalledTimes(13)
  598. })
  599. it('announces each manager operation as a change, and a patch generation applied outside it not at all', async () => {
  600. const { ctx, manager, profile } = await fixture('startup')
  601. const changes: PluginChange[] = []
  602. ctx.on('plugin-manager/changed', (change) => { changes.push(change) })
  603. await reconcileProfilePatches(ctx, readProfilePatches('test', profile), 'test')
  604. expect(changes).toEqual([])
  605. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  606. await manager.setPluginEnabled(id, false)
  607. expect(changes).toEqual([{ reason: 'plugin' }])
  608. await manager.setBundleEnabled('extra', false)
  609. expect(changes).toEqual([{ reason: 'plugin' }, { reason: 'bundle' }])
  610. })
  611. it('handles missing patch files and retains non-Error package diagnostics', async () => {
  612. const { manager, dir } = await fixture()
  613. rmSync(join(dir, 'cordis.patch.yml'))
  614. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  615. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: true, application: 'applied' })
  616. const install = vi.spyOn(operations, 'runProfilePnpm').mockRejectedValueOnce('pnpm rejected operation')
  617. onTestFinished(() => { install.mockRestore() })
  618. expect(await manager.installBundle('new')).toMatchObject({ changed: false, application: 'failed', error: { code: 'operation-error', diagnostic: 'pnpm rejected operation' } })
  619. rmSync(join(dir, 'cordis.patch.yml'))
  620. mkdirSync(join(dir, 'cordis.patch.yml'))
  621. await expect(manager.setPluginEnabled(id, true)).rejects.toThrow()
  622. })
  623. it('applies a manager change through the active HMR service', async () => {
  624. const { manager } = await fixture()
  625. const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId
  626. expect(await manager.setPluginEnabled(id, false)).toMatchObject({ changed: true, application: 'applied' })
  627. expect((await manager.listPlugins()).find(row => row.entryId === id)?.enabled).toBe(false)
  628. })
  629. it('refuses removal of a hot-installed bundle after HMR is disabled', async () => {
  630. const { ctx, manager, dir, bundle, stopHmr } = await fixture()
  631. bundle('later', [{ id: 'later', name: './plugin.mjs', config: { service: 'laterProbe' } }])
  632. const manifest = readProfileManifest('test', dir)
  633. manifest.dependencies = { ...manifest.dependencies, later: '1' }
  634. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  635. expect(await manager.setBundleEnabled('later', true)).toMatchObject({ application: 'applied' })
  636. await stopHmr()
  637. expect(ctx.get('hmr')).toBeUndefined()
  638. expect(await manager.setBundleEnabled('later', false)).toMatchObject({ application: 'restart-required' })
  639. expect(ctx.get('laterProbe')).toBe(true)
  640. expect(await manager.removeBundle('later')).toMatchObject({ changed: false, application: 'failed' })
  641. })
  642. it('offers the launcher\'s optional bundles switched off and never removable', async () => {
  643. const { manager, profile } = await fixture()
  644. // The launcher names the bundles the installation ships; the fixture supplies one of them from the
  645. // installation's own node_modules, which the resolver consults before the profile's and before the repository's.
  646. const offered = OPTIONAL_BUNDLES[0]!
  647. const supplied = join(profile.home, 'node_modules', offered)
  648. mkdirSync(supplied, { recursive: true })
  649. writeFileSync(join(supplied, 'package.json'), JSON.stringify({
  650. name: offered, version: '3.0.0', description: 'Package one-liner.', dsh: { bundle: { patch: './cordis.patch.yml' } },
  651. }))
  652. writeFileSync(join(supplied, 'cordis.patch.yml'), JSON.stringify([{ insert: [{ id: 'offered-row', name: './plugin.mjs', config: { service: 'offeredProbe' } }] }]))
  653. writeFileSync(join(supplied, 'plugin.mjs'), 'export function apply(ctx, config) { ctx.provide(config?.service ?? "offeredProbe", true) }\n')
  654. writeFileSync(profile.installAnchor, JSON.stringify({ name: 'installation', dependencies: { [offered]: '3.0.0' } }))
  655. expect((await manager.listBundles()).find(row => row.name === offered)).toEqual({
  656. name: offered, version: '3.0.0', description: 'Package one-liner.',
  657. enabled: false, installed: false, optional: true, removable: false,
  658. rows: [{ rowId: 'offered-row', moduleName: pathToFileURL(join(supplied, 'plugin.mjs')).href }], overrides: [],
  659. })
  660. expect(await manager.setBundleEnabled(offered, true)).toMatchObject({ application: 'applied' })
  661. expect((await manager.listBundles()).find(row => row.name === offered)).toMatchObject({ enabled: true, optional: true, removable: false })
  662. expect(await manager.removeBundle(offered)).toMatchObject({ changed: false, application: 'failed' })
  663. })
  664. it('omits installation-owned plain packages from the bundle inventory', async () => {
  665. const { manager, dir, profile, bundle } = await fixture()
  666. bundle('installation-plain', [])
  667. writeFileSync(join(dir, 'node_modules/installation-plain/package.json'), '{"name":"installation-plain"}')
  668. writeFileSync(profile.installAnchor, '{"dependencies":{"installation-plain":"1"}}')
  669. expect((await manager.listBundles()).some(row => row.name === 'installation-plain')).toBe(false)
  670. })
  671. it('does not delete a bundle retained by a higher-priority overlay', async () => {
  672. const { ctx, manager, overlays, dir } = await fixture()
  673. const entry = [...ctx.loader.entries()].find(row => row.id === 'include:managed')!
  674. overlays.push({ insert: [{ ...entry.options }] })
  675. const remove = vi.spyOn(operations, 'runProfilePnpm')
  676. onTestFinished(() => { remove.mockRestore() })
  677. expect(await manager.removeBundle('extra')).toMatchObject({ changed: true, application: 'failed', error: { code: 'bundle-in-use' } })
  678. expect(await manager.removeBundle('extra')).toMatchObject({ changed: false, application: 'failed', error: { code: 'bundle-in-use' } })
  679. expect(remove).not.toHaveBeenCalled()
  680. expect(readProfileManifest('test', dir).dependencies).toEqual({ extra: '1.0.0' })
  681. expect(ctx.get('managedProbe')).toBe(true)
  682. })
  683. it('applies watched configuration while pnpm installation is still running', async () => {
  684. const { ctx, manager, dir, profile, bundle } = await fixture()
  685. const entered = Promise.withResolvers<undefined>()
  686. const release = Promise.withResolvers<undefined>()
  687. const pnpm = vi.spyOn(operations, 'runProfilePnpm').mockImplementation(async () => {
  688. entered.resolve(undefined)
  689. await release.promise
  690. bundle('new-bundle', [])
  691. const manifest = readProfileManifest('test', dir)
  692. manifest.dependencies = { ...manifest.dependencies, 'new-bundle': '1.0.0' }
  693. writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest))
  694. return { exitCode: 0, output: 'installed', truncated: false, logPath: join(dir, 'pnpm.log') }
  695. })
  696. const installing = manager.installBundle('new-bundle')
  697. onTestFinished(async () => { release.resolve(undefined); await installing; pnpm.mockRestore() })
  698. await entered.promise
  699. writeFileSync(profile.patchPath, '- id: managed\n disabled: true\n')
  700. await vi.waitFor(() => { expect(ctx.get('managedProbe')).toBeUndefined() }, { timeout: 10000 })
  701. expect(pnpm).toHaveBeenCalledOnce()
  702. release.resolve(undefined)
  703. expect(await installing).toMatchObject({ application: 'applied', changed: true })
  704. expect(readProfileManifest('test', dir).dsh?.profile?.bundles).toEqual(['core', 'extra', 'new-bundle'])
  705. expect(ctx.get('managedProbe')).toBeUndefined()
  706. })