feat(plugin-inventory): offline bundle and pnpm plugin install for the desktop

Adds an install surface to the plugin-inventory gateway: availableBundles lists
the curated offline-installable optional bundles (AVAILABLE_BUNDLES); install
composes an offline bundle into the profile's dsh.profile.bundles, or for a
registry spec runs pnpm against the writable profile via the bundled Node and a
vendored pnpm (gated behind the dshAllowPluginInstall context flag, set only by
the desktop boot); uninstall removes a bundle layer. The reconcile logic from
`dsh plugin add` moves into app-boot as shared helpers. The desktop vendored
pnpm into the harness and sets the allow-install env; the plugin-list SPA gains
an installable-bundles section. Tests cover the guard, install helpers, and the
SPA section at 100% host coverage.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Pine
2026-08-14 18:46:39 +08:00
parent 8f1c764614
commit 6cd7c5a590
25 changed files with 929 additions and 110 deletions
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/host/plugin-inventory/README.md
README.md: a91c02df5e7a57db89c9a63af6c4355573b843da
README.zh.md: 261db0b92cf025606b7fc18c5754d54f8cd34e48
README.md: 3d899ac7404acd16047efce09e4c6d0dd0508db2
README.zh.md: ceb69499e3b2209c58d37e9c6d4b18cc599d7dc5
+3 -1
View File
@@ -6,7 +6,9 @@ Host projection of the current Cordis Loader tree with per-plugin enable/disable
The phase is `pending`, `loading`, `active`, `failed`, or `unloading`; it is `null` when the entry has no live root Fiber. The snapshot is intentionally point-in-time: Loader remains the sole lifecycle authority, while this package owns no cache, history, provenance model, or event stream. `setEnabled` toggles one entry live through `ctx.loader.update` and persists an explicit `disabled` override into the profile's user patch layer so the choice survives a restart (a bundle-default disable needs the `disabled: false` override to stick).
Every entry carries a `protected` flag. The guard is default-open: every plugin is toggleable unless its module name is in the small `REQUIRED_PLUGINS` set in `src/required.ts` — the load-bearing core (the entry tree, the Remote RPC spine, the session and agent spines) that must never be disabled. `setEnabled` refuses to disable a required plugin and, after enabling, verifies the fiber becomes active (reverting a dependency-missing enable). The Web plugin-list tab renders one flat list of every entry: each shows its real enabled state, a toggleable plugin carries an enable or disable button (so a bundle-default-disabled plugin can be re-enabled), and a required plugin shows only a read-only note. Its public payload types live under `./types`, and Typert generates the Host and Client Remote artifacts exposed by `./typert` and `./remote`.
Every entry carries a `protected` flag. The guard in `src/required.ts` is default-open with two code-editable lists: `REQUIRED_PLUGINS` (the blacklist of load-bearing core that must never be disabled — the entry tree, the Remote RPC spine, the session and agent spines) and `USER_TOGGLEABLE_PLUGINS` (the whitelist, which overrides the blacklist for an explicitly toggleable plugin); a plugin on neither list is toggleable by default. The full dependency-derived taxonomy of the shipped base bundle is in [`docs/plugin-system.md`](../../../docs/plugin-system.md). `setEnabled` refuses to disable a required plugin and, after enabling, verifies the fiber becomes active (reverting a dependency-missing enable). The Web plugin-list tab renders one flat list of every entry: each shows its real enabled state, a toggleable plugin carries an enable or disable button (so a bundle-default-disabled plugin can be re-enabled), and a required plugin shows only a read-only note.
The gateway also manages installation through `availableBundles`/`install`/`uninstall`. `availableBundles` lists the curated offline-installable optional bundles in `src/bundles.ts` (`AVAILABLE_BUNDLES`), each marked installed when present in the profile's `dsh.profile.bundles`. `install` composes an offline bundle into that list (no network), or for a registry spec runs pnpm against the writable profile directory via the bundled Node and vendored pnpm — a registry install is gated behind the `dshAllowPluginInstall` context flag, which only the desktop boot sets. These writes persist the profile manifest and require a restart to take effect. Its public payload types live under `./types`, and Typert generates the Host and Client Remote artifacts exposed by `./typert` and `./remote`.
The service is Remote-only and deliberately declares no same-process Cordis `Context` merge. Client packages consume it through the explicit [`api-remotes`](../../api/remotes/README.md) assembly rather than importing the Host implementation.
+3 -1
View File
@@ -6,7 +6,9 @@
阶段为 `pending`、`loading`、`active`、`failed` 或 `unloading`;条目没有存活的根 Fiber 时则为 `null`。该快照刻意只表示调用当下:Loader 仍是唯一的生命周期权威,本包不拥有缓存、历史、来源模型或事件流。`setEnabled` 通过 `ctx.loader.update` 实时切换单条条目,并把显式 `disabled` 覆盖写进 profile 的用户补丁层,使选择在重启后保留(bundle 默认禁用的行需要 `disabled: false` 覆盖才能保持启用)。
每条条目带 `protected` 标记。守卫默认开放:除 `src/required.ts` 中 `REQUIRED_PLUGINS` 这个小型集合(入口树、Remote RPC 主干、session 与 agent 主干等必须保留的核心)外,所有插件都可切换。`setEnabled` 拒绝停用必需插件;启用后会校验 fiber 变为 active(依赖缺失的启用会回滚)。Web 插件列表 tab 渲染单一扁平列表,包含所有条目:每项按真实启用状态显示,可切换插件带"启用"或"停用"按钮(这样 bundle 默认禁用的插件也能重新启用),必需插件只显示只读说明。公开 payload 类型位于 `./types`,Typert 生成由 `./typert` 与 `./remote` 导出的 Host 和 Client Remote 产物。
每条条目带 `protected` 标记。`src/required.ts` 中的守卫默认开放,含两个可由代码编辑的名单:`REQUIRED_PLUGINS`(黑名单,即不可停用的承重核心——入口树、Remote RPC 主干、session 与 agent 主干)与 `USER_TOGGLEABLE_PLUGINS`(白名单,覆盖黑名单、对显式可开关的插件生效);未列入任何名单的插件默认可切换。随包 base bundle 的完整依赖图分类见 [`docs/plugin-system.md`](../../../docs/plugin-system.md)。`setEnabled` 拒绝停用必需插件;启用后会校验 fiber 变为 active(依赖缺失的启用会回滚)。Web 插件列表 tab 渲染单一扁平列表,包含所有条目:每项按真实启用状态显示,可切换插件带"启用"或"停用"按钮(这样 bundle 默认禁用的插件也能重新启用),必需插件只显示只读说明。
网关还通过 `availableBundles`/`install`/`uninstall` 管理安装。`availableBundles` 列出 `src/bundles.ts`(`AVAILABLE_BUNDLES`)中策展的离线可安装可选 bundle,每项在存在于 profile 的 `dsh.profile.bundles` 时标记为已安装。`install` 把离线 bundle 组合进该列表(无需网络);对 registry spec 则用内置 Node 与 vendored pnpm 在可写的 profile 目录运行 pnpm——registry 安装受 `dshAllowPluginInstall` 上下文标志门禁,仅桌面启动会开启。这些写入持久化 profile 清单,需重启生效。公开 payload 类型位于 `./types`,Typert 生成由 `./typert` 与 `./remote` 导出的 Host 和 Client Remote 产物。
该服务仅供 Remote 使用,刻意不声明同进程 Cordis `Context` merge。Client 包通过显式的 [`api-remotes`](../../api/remotes/README.md) 组合消费它,而不导入 Host 实现。
@@ -54,6 +54,7 @@
},
"peerDependencies": {
"@deepseek-ai/cordis-plugin-loader": "workspace:^",
"@deepseek-ai/dsh-app-boot": "workspace:^",
"@deepseek-ai/dsh-brand": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-typert-protocol": "workspace:^",
@@ -61,6 +62,7 @@
},
"devDependencies": {
"@deepseek-ai/cordis-plugin-loader": "workspace:^",
"@deepseek-ai/dsh-app-boot": "workspace:^",
"@deepseek-ai/dsh-brand": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-typert-protocol": "workspace:^",
@@ -0,0 +1,19 @@
/**
* The curated catalog of optional bundles a deployment may install offline.
*
* A bundle here is an npm package that is already resolvable from the running
* installation (it is shipped in the harness or declared as a dependency of the
* app), so "installing" it only means composing it into the profile's
* `dsh.profile.bundles` — no network or package manager required. Add a new
* shipped optional bundle to {@link AVAILABLE_BUNDLES} to make it installable
* from the plugin list.
* @module @deepseek-ai/dsh-plugin-inventory/bundles
*/
/**
* Bundle package names a deployment may compose offline. Keep this to bundles
* that are guaranteed resolvable from the installation anchor.
*/
export const AVAILABLE_BUNDLES: readonly string[] = [
'@deepseek-ai/dsh-image-recognition-bundle',
]
+95 -3
View File
@@ -3,12 +3,18 @@
import type { Context, FiberState } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/cordis-plugin-loader'
import { fileURLToPath } from 'node:url'
import { readProfileManifest, type ProfileManifest } from '@deepseek-ai/dsh-app-boot'
import { TypertRemoteService, Remote } from '@deepseek-ai/dsh-typert-protocol'
// Typert-generated ./typert and ./remote artifacts import Zod at runtime.
import type {} from 'zod'
import { AVAILABLE_BUNDLES } from './bundles.ts'
import { composeOfflineBundle, resolvePnpm, runPnpmInstall, uninstallBundle } from './install.ts'
import { persistPluginDisabled } from './persist.ts'
import { isRequiredPlugin } from './required.ts'
import type {
AvailableBundlesSnapshot,
InstallResult,
InstallSpec,
PluginEntryId,
PluginFiberPhase,
PluginInventoryEntry,
@@ -16,6 +22,8 @@ import type {
} from './types.ts'
export type * from './types.ts'
export { AVAILABLE_BUNDLES } from './bundles.ts'
export type { AvailableBundle, AvailableBundlesSnapshot, InstallResult, InstallSpec } from './types.ts'
/** Brand an existing Loader-tree entry id at the owning boundary. */
function pluginEntryId(value: string): PluginEntryId {
@@ -85,10 +93,8 @@ export class PluginInventoryGateway extends TypertRemoteService {
*/
@Remote('setEnabled')
async setEnabled(entryId: PluginEntryId, enabled: boolean): Promise<{ ok: true }> {
// resolve() throws for an unknown id, so the entry is always defined.
const entry = this.ctx.loader.resolve(entryId)
if (entry === undefined) {
throw new Error(`plugin entry ${String(entryId)} not found`)
}
// Disabling a required system plugin tears the process down; refuse it.
// Re-enabling a disabled plugin is what this surface is for.
if (!enabled && isRequiredPlugin(entry.options.name)) {
@@ -107,6 +113,92 @@ export class PluginInventoryGateway extends TypertRemoteService {
}
return { ok: true }
}
/**
* List the offline-installable optional bundles, each marked installed when
* it is already composed in the profile's `dsh.profile.bundles`.
* @returns the curated bundle catalog with installed state.
*/
@Remote('availableBundles')
availableBundles(): AvailableBundlesSnapshot {
const profileDir = this.profileDir()
const installed = new Set(this.profileManifest(profileDir)?.dsh?.profile?.bundles ?? [])
return {
available: AVAILABLE_BUNDLES.map(name => ({ name, installed: installed.has(name) })),
}
}
/**
* Install a plugin. A `bundle` spec composes an offline optional bundle into
* the profile's bundle layer list (no network); a `registry` spec runs pnpm
* against the writable profile directory via the bundled Node and vendored
* pnpm, which requires the `dshAllowPluginInstall` context flag (set only by
* the desktop boot). Persists the manifest; the running tree recomposes at
* the next boot.
* @param spec - the bundle name or registry package spec to install.
* @returns a confirmation; `restartRequired` tells the caller to restart.
*/
@Remote('install')
install(spec: InstallSpec): InstallResult {
const profileDir = this.profileDir()
const anchor = this.ctx.get('dshInstallAnchor') as string | undefined
if (anchor === undefined) {
throw new Error('dsh: install anchor is unavailable in this runtime')
}
if (spec.type === 'bundle') {
composeOfflineBundle('dsh', profileDir, anchor, spec.name)
return { ok: true, restartRequired: true }
}
if (this.ctx.get('dshAllowPluginInstall') !== true) {
throw new Error('dsh: plugin install is not permitted in this runtime')
}
const pnpmCjs = resolvePnpm(process.execPath)
if (pnpmCjs === undefined) {
throw new Error('dsh: bundled pnpm is unavailable in this runtime')
}
// The reconcile below re-reads the manifest, so a missing file fails there;
// this snapshot fallback is only reached in that same unreachable-to-succeed case.
/* v8 ignore next */
const before = this.profileManifest(profileDir) ?? { dependencies: {} }
runPnpmInstall({
binName: 'dsh',
profileDir,
installAnchor: anchor,
nodeBin: process.execPath,
pnpmCjs,
spec: spec.spec,
before,
})
return { ok: true, restartRequired: true }
}
/**
* Un-compose an offline optional bundle from the profile's bundle layer list.
* @param name - the bundle package name to remove.
* @returns a confirmation; `restartRequired` tells the caller to restart.
*/
@Remote('uninstall')
uninstall(name: string): InstallResult {
uninstallBundle('dsh', this.profileDir(), name)
return { ok: true, restartRequired: true }
}
/** The profile directory the Loader anchors on (its `baseUrl`). */
private profileDir(): string {
if (this.ctx.baseUrl === undefined) {
throw new Error('dsh: plugin management requires a profile directory')
}
return fileURLToPath(this.ctx.baseUrl)
}
/** Read the profile manifest, or undefined when absent. */
private profileManifest(profileDir: string): ProfileManifest | undefined {
try {
return readProfileManifest('dsh', profileDir)
} catch {
return undefined
}
}
}
export default PluginInventoryGateway
@@ -0,0 +1,121 @@
/**
* Pure helpers behind the plugin-inventory install/uninstall Remotes.
*
* Offline bundle install composes an already-shipped optional bundle into the
* profile's `dsh.profile.bundles` — a writable profile-manifest mutation with
* no network or package manager. Registry install runs pnpm against the
* writable profile directory via a bundled Node + vendored pnpm, then
* reconciles the bundle layer list exactly as `dsh plugin add` does. All
* functions are dependency-free of Cordis so they unit-test without a context.
* @module @deepseek-ai/dsh-plugin-inventory/install
*/
import { spawnSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import {
readProfileManifest,
reconcileProfileBundles,
resolveBundleDir,
writeProfileManifest,
type ProfileManifest,
} from '@deepseek-ai/dsh-app-boot'
/**
* Compose an offline optional bundle into the profile's bundle layer list.
* Validates that the bundle resolves from the installation anchor (so a bad
* name fails loud instead of silently corrupting the manifest), then appends
* the name when absent. Persists only — the running tree is recomposed at the
* next boot.
* @param binName - the diagnostic prefix on thrown errors.
* @param profileDir - the writable profile directory.
* @param installAnchor - absolute path of a file inside the dsh app package.
* @param name - the bundle package name to compose.
*/
export function composeOfflineBundle(
binName: string, profileDir: string, installAnchor: string, name: string,
): void {
resolveBundleDir(binName, name, installAnchor, profileDir)
const manifest = readProfileManifest(binName, profileDir)
const bundles = manifest.dsh?.profile?.bundles ?? []
if (bundles.includes(name)) return
manifest.dsh = { ...manifest.dsh, profile: { ...manifest.dsh?.profile, bundles: [...bundles, name] } }
writeProfileManifest(profileDir, manifest)
}
/**
* Remove an optional bundle from the profile's bundle layer list. Leaves the
* installed dependency (if any) in place; a later `dsh plugin remove` handles
* the package itself.
* @param binName - the diagnostic prefix on thrown errors.
* @param profileDir - the writable profile directory.
* @param name - the bundle package name to un-compose.
*/
export function uninstallBundle(binName: string, profileDir: string, name: string): void {
const manifest = readProfileManifest(binName, profileDir)
const bundles = (manifest.dsh?.profile?.bundles ?? []).filter(bundle => bundle !== name)
manifest.dsh = { ...manifest.dsh, profile: { ...manifest.dsh?.profile, bundles } }
writeProfileManifest(profileDir, manifest)
}
/** Options for one pnpm install run. */
export interface PnpmInstallOptions {
readonly binName: string
readonly profileDir: string
readonly installAnchor: string
/** Absolute path of the Node executable to run pnpm with (the bundled node). */
readonly nodeBin: string
/** Absolute path of the pnpm CLI entry (pnpm.cjs). */
readonly pnpmCjs: string
/** The package specifier to install. */
readonly spec: string
/** The profile manifest read before the install, for reconciliation. */
readonly before: ProfileManifest
}
/**
* Run `pnpm add <spec>` in the profile directory via a bundled Node, then
* reconcile `dsh.profile.bundles` against the installed state. Throws when the
* package manager fails (nonzero exit or spawn error).
* @param options - the run options.
*/
export function runPnpmInstall(options: PnpmInstallOptions): void {
const { binName, profileDir, installAnchor, nodeBin, pnpmCjs, spec, before } = options
const result = spawn(nodeBin, [pnpmCjs, 'add', spec], profileDir)
if (result.exitCode !== 0) {
throw new Error(`${binName}: pnpm install failed with exit code ${result.exitCode}`)
}
reconcileProfileBundles(binName, before, profileDir, installAnchor)
}
/** Spawn one synchronous child and return its exit code (0 on success). */
function spawn(command: string, args: readonly string[], cwd: string): { exitCode: number } {
const result = spawnSync(command, args, {
cwd,
stdio: 'inherit',
shell: process.platform === 'win32',
})
if (result.error !== undefined) {
throw result.error
}
// On a successful spawn status is always a number; null coincides with the
// spawn-error path above, so the fallback is unreachable.
/* v8 ignore next */
return { exitCode: result.status ?? 1 }
}
/**
* Locate the pnpm CLI bundled into the harness. Honors a `DSH_PNPM` override,
* then looks for the vendored pnpm beside the bundled Node's harness root.
* @param nodeBin - the bundled Node executable path (`process.execPath`).
* @param env - the process environment.
* @returns the pnpm.cjs path, or undefined when none is vendored.
*/
export function resolvePnpm(nodeBin: string, env: NodeJS.ProcessEnv = process.env): string | undefined {
if (env.DSH_PNPM) return env.DSH_PNPM
// nodeBin is harness/bin/node in the packaged app, so the harness root is
// one level up from bin/; pnpm is vendored under harness/pnpm/.
const harnessRoot = resolve(dirname(nodeBin), '..')
const candidate = join(harnessRoot, 'pnpm', 'node_modules', 'pnpm', 'bin', 'pnpm.cjs')
return existsSync(candidate) ? candidate : undefined
}
@@ -28,3 +28,28 @@ export interface PluginInventoryEntry {
export interface PluginInventorySnapshot {
readonly entries: readonly PluginInventoryEntry[]
}
/** One optional bundle in the offline-installable catalog. */
export interface AvailableBundle {
/** The bundle's npm package name. */
readonly name: string
/** Whether the bundle is already composed in the profile. */
readonly installed: boolean
}
/** Catalog snapshot returned by the available-bundles Remote. */
export interface AvailableBundlesSnapshot {
readonly available: readonly AvailableBundle[]
}
/** What a plugin-install request targets. */
export type InstallSpec =
| { readonly type: 'bundle'; readonly name: string }
| { readonly type: 'registry'; readonly spec: string }
/** Result of an install/uninstall request. */
export interface InstallResult {
readonly ok: true
/** Whether the app must restart for the change to take effect. */
readonly restartRequired: boolean
}
@@ -0,0 +1,146 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { readProfileManifest } from '@deepseek-ai/dsh-app-boot'
import { composeOfflineBundle, resolvePnpm, runPnpmInstall, uninstallBundle } from '../src/install.ts'
const dirs: string[] = []
function makeProfile(bundles: string[] = []): string {
const dir = mkdtempSync(join(tmpdir(), 'dsh-install-'))
dirs.push(dir)
writeFileSync(
join(dir, 'package.json'),
JSON.stringify({ name: 'dsh-profile-test', dsh: { profile: { bundles } } }, undefined, 2),
)
return dir
}
/** Make a bundle resolvable from a profile dir's node_modules. */
function makeBundle(dir: string, name: string): void {
const pkgDir = join(dir, 'node_modules', name)
mkdirSync(pkgDir, { recursive: true })
writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({
name,
dsh: { bundle: { patch: './cordis.patch.yml' } },
}))
writeFileSync(join(pkgDir, 'cordis.patch.yml'), '[]\n')
}
/** A fake pnpm CLI that exits with the given code. */
function makeFakePnpm(dir: string, exitCode: number): string {
const file = join(dir, `pnpm-${exitCode}.cjs`)
writeFileSync(file, `process.exit(${exitCode})\n`)
return file
}
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
describe('composeOfflineBundle', () => {
it('appends a resolvable bundle and stays idempotent', () => {
const dir = makeProfile()
makeBundle(dir, 'example-bundle')
composeOfflineBundle('dsh', dir, join(dir, 'package.json'), 'example-bundle')
expect(readProfileManifest('dsh', dir).dsh?.profile?.bundles).toEqual(['example-bundle'])
composeOfflineBundle('dsh', dir, join(dir, 'package.json'), 'example-bundle')
expect(readProfileManifest('dsh', dir).dsh?.profile?.bundles).toEqual(['example-bundle'])
})
it('fails loud for an unresolvable bundle', () => {
const dir = makeProfile()
expect(() => { composeOfflineBundle('dsh', dir, join(dir, 'package.json'), 'missing') }).toThrow(/cannot resolve/)
})
})
describe('uninstallBundle', () => {
it('removes a bundle from the layer list', () => {
const dir = makeProfile(['example-bundle'])
uninstallBundle('dsh', dir, 'example-bundle')
expect(readProfileManifest('dsh', dir).dsh?.profile?.bundles).toEqual([])
})
})
describe('runPnpmInstall', () => {
it('reconciles without throwing on pnpm success', () => {
const dir = makeProfile()
const before = readProfileManifest('dsh', dir)
const pnpm = makeFakePnpm(dir, 0)
runPnpmInstall({
binName: 'dsh', profileDir: dir, installAnchor: join(dir, 'package.json'),
nodeBin: process.execPath, pnpmCjs: pnpm, spec: 'example', before,
})
})
it('throws when pnpm fails', () => {
const dir = makeProfile()
const before = readProfileManifest('dsh', dir)
const pnpm = makeFakePnpm(dir, 1)
expect(() => { runPnpmInstall({
binName: 'dsh', profileDir: dir, installAnchor: join(dir, 'package.json'),
nodeBin: process.execPath, pnpmCjs: pnpm, spec: 'example', before,
}) }).toThrow(/pnpm install failed/)
})
})
describe('composeOfflineBundle with a bare manifest', () => {
it('initializes an absent bundle list', () => {
const dir = makeProfile()
rmSync(join(dir, 'package.json'))
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'dsh-profile-test' }))
makeBundle(dir, 'example-bundle')
composeOfflineBundle('dsh', dir, join(dir, 'package.json'), 'example-bundle')
expect(readProfileManifest('dsh', dir).dsh?.profile?.bundles).toEqual(['example-bundle'])
})
})
describe('uninstallBundle with a non-present bundle', () => {
it('leaves the list unchanged', () => {
const dir = makeProfile(['other'])
uninstallBundle('dsh', dir, 'absent')
expect(readProfileManifest('dsh', dir).dsh?.profile?.bundles).toEqual(['other'])
})
it('handles an absent bundle list', () => {
const dir = makeProfile()
rmSync(join(dir, 'package.json'))
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'dsh-profile-test' }))
uninstallBundle('dsh', dir, 'absent')
expect(readProfileManifest('dsh', dir).dsh?.profile?.bundles).toEqual([])
})
})
describe('runPnpmInstall spawn failure', () => {
it('throws the spawn error when node cannot start', () => {
const dir = makeProfile()
const before = readProfileManifest('dsh', dir)
expect(() => { runPnpmInstall({
binName: 'dsh', profileDir: dir, installAnchor: join(dir, 'package.json'),
nodeBin: '/nonexistent/node', pnpmCjs: '/x/pnpm.cjs', spec: 'x', before,
}) }).toThrow()
})
})
describe('resolvePnpm', () => {
it('honors a DSH_PNPM override', () => {
expect(resolvePnpm('/x/bin/node', { DSH_PNPM: '/vendored/pnpm.cjs' })).toBe('/vendored/pnpm.cjs')
})
it('derives the vendored pnpm beside the node harness root and misses when absent', () => {
expect(resolvePnpm('/nonexistent/bin/node', {})).toBeUndefined()
})
it('finds a vendored pnpm beside the node harness root', () => {
const dir = makeProfile()
const harnessRoot = join(dir, 'harness')
const pnpmDir = join(harnessRoot, 'pnpm', 'node_modules', 'pnpm', 'bin')
mkdirSync(pnpmDir, { recursive: true })
writeFileSync(join(pnpmDir, 'pnpm.cjs'), '')
const nodeBin = join(harnessRoot, 'bin', 'node')
mkdirSync(join(harnessRoot, 'bin'), { recursive: true })
writeFileSync(nodeBin, '')
expect(resolvePnpm(nodeBin, {})).toBe(join(pnpmDir, 'pnpm.cjs'))
})
})
@@ -1,6 +1,11 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { afterEach, describe, expect, it } from 'vitest'
import { Context, type Plugin } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import { readProfileManifest } from '@deepseek-ai/dsh-app-boot'
import { remoteMethods } from '@deepseek-ai/dsh-typert-protocol'
import PluginInventoryGateway, { type PluginEntryId } from '../src/index.ts'
@@ -34,7 +39,7 @@ async function harness(): Promise<{
}
describe('PluginInventoryGateway', () => {
it('publishes one direct list method under the pluginInventory namespace', async () => {
it('publishes direct methods under the pluginInventory namespace', async () => {
const { inventory } = await harness()
expect(inventory.typertRemote).toMatchObject({
serviceKey: 'pluginInventory',
@@ -43,6 +48,9 @@ describe('PluginInventoryGateway', () => {
expect(remoteMethods(inventory)).toEqual([
{ method: 'list', invocation: { kind: 'direct' } },
{ method: 'setEnabled', invocation: { kind: 'direct' } },
{ method: 'availableBundles', invocation: { kind: 'direct' } },
{ method: 'install', invocation: { kind: 'direct' } },
{ method: 'uninstall', invocation: { kind: 'direct' } },
])
})
@@ -117,4 +125,161 @@ describe('PluginInventoryGateway', () => {
await ctx.loader.remove(pendingId)
expect(inventory.list().entries.some(entry => entry.entryId === pendingId)).toBe(false)
})
it('availableBundles reports installed state from the profile manifest', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
contexts.push(ctx)
ctx.baseUrl = pathToFileURL(dir + '/').href
writeFileSync(join(dir, 'package.json'), JSON.stringify({
name: 'dsh-profile-test',
dsh: { profile: { bundles: ['@deepseek-ai/dsh-image-recognition-bundle'] } },
}))
try {
const snapshot = inventory.availableBundles()
expect(snapshot.available).toEqual([
{ name: '@deepseek-ai/dsh-image-recognition-bundle', installed: true },
])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('install requires an install anchor and gating for registry specs', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
ctx.baseUrl = pathToFileURL(dir + '/').href
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'dsh-profile-test', dsh: { profile: { bundles: [] } } }))
try {
expect(() => inventory.install({ type: 'bundle', name: 'x' })).toThrow(/install anchor is unavailable/)
ctx.provide('dshInstallAnchor', join(dir, 'package.json'))
expect(() => inventory.install({ type: 'registry', spec: 'x' })).toThrow(/not permitted/)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('uninstall removes a bundle from the profile manifest', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
ctx.baseUrl = pathToFileURL(dir + '/').href
writeFileSync(join(dir, 'package.json'), JSON.stringify({
name: 'dsh-profile-test',
dsh: { profile: { bundles: ['@deepseek-ai/dsh-image-recognition-bundle'] } },
}))
try {
expect(inventory.uninstall('@deepseek-ai/dsh-image-recognition-bundle').restartRequired).toBe(true)
expect(inventory.availableBundles().available[0]!.installed).toBe(false)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('composes an offline bundle when the anchor is available', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
ctx.baseUrl = pathToFileURL(dir + '/').href
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'dsh-profile-test', dsh: { profile: { bundles: [] } } }))
mkdirSync(join(dir, 'node_modules', 'b'), { recursive: true })
writeFileSync(join(dir, 'node_modules', 'b', 'package.json'), JSON.stringify({ name: 'b', dsh: { bundle: { patch: './cordis.patch.yml' } } }))
writeFileSync(join(dir, 'node_modules', 'b', 'cordis.patch.yml'), '[]\n')
ctx.provide('dshInstallAnchor', join(dir, 'package.json'))
try {
inventory.install({ type: 'bundle', name: 'b' })
expect(readProfileManifest('dsh', dir).dsh?.profile?.bundles).toEqual(['b'])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('installs a registry spec via bundled pnpm when permitted', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
ctx.baseUrl = pathToFileURL(dir + '/').href
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'dsh-profile-test', dsh: { profile: { bundles: [] } } }))
const fakePnpm = join(dir, 'pnpm.cjs')
writeFileSync(fakePnpm, 'process.exit(0)\n')
process.env.DSH_PNPM = fakePnpm
try {
ctx.provide('dshInstallAnchor', join(dir, 'package.json'))
ctx.provide('dshAllowPluginInstall', true)
expect(inventory.install({ type: 'registry', spec: 'some-pkg' }).restartRequired).toBe(true)
} finally {
delete process.env.DSH_PNPM
rmSync(dir, { recursive: true, force: true })
}
})
it('fails loud without a profile directory', async () => {
const { inventory } = await harness()
expect(() => inventory.availableBundles()).toThrow(/profile directory/)
})
it('treats a missing profile manifest as no installed bundles', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
ctx.baseUrl = pathToFileURL(dir + '/').href
try {
expect(inventory.availableBundles().available[0]!.installed).toBe(false)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('setEnabled fails loud for an unknown entry', async () => {
const { inventory } = await harness()
await expect(inventory.setEnabled('missing' as PluginEntryId, false)).rejects.toThrow(/cannot resolve entry missing/)
})
it('setEnabled persists the override when anchored to a profile directory', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
ctx.baseUrl = pathToFileURL(dir + '/').href
try {
const id = await ctx.loader.create({ name: 'cordis:user-toggleable' }) as PluginEntryId
await inventory.setEnabled(id, false)
expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')).toContain('disabled: true')
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('setEnabled reverts an enable whose fiber cannot activate', async () => {
const { ctx, inventory } = await harness()
const id = await ctx.loader.create({ name: 'cordis:pending' }) as PluginEntryId
await expect(inventory.setEnabled(id, true)).rejects.toThrow(/could not start/)
expect(inventory.list().entries.find(entry => entry.entryId === id)?.enabled).toBe(false)
})
it('registry install fails loud when bundled pnpm is absent', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
ctx.baseUrl = pathToFileURL(dir + '/').href
writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'dsh-profile-test', dsh: { profile: { bundles: [] } } }))
delete process.env.DSH_PNPM
try {
ctx.provide('dshInstallAnchor', join(dir, 'package.json'))
ctx.provide('dshAllowPluginInstall', true)
expect(() => inventory.install({ type: 'registry', spec: 'x' })).toThrow(/bundled pnpm is unavailable/)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('registry install fails loud when the profile manifest is missing', async () => {
const { ctx, inventory } = await harness()
const dir = mkdtempSync(join(tmpdir(), 'dsh-inv-'))
ctx.baseUrl = pathToFileURL(dir + '/').href
const fakePnpm = join(dir, 'pnpm.cjs')
writeFileSync(fakePnpm, 'process.exit(0)\n')
process.env.DSH_PNPM = fakePnpm
try {
ctx.provide('dshInstallAnchor', join(dir, 'package.json'))
ctx.provide('dshAllowPluginInstall', true)
expect(() => inventory.install({ type: 'registry', spec: 'x' })).toThrow(/failed to read profile manifest/)
} finally {
delete process.env.DSH_PNPM
rmSync(dir, { recursive: true, force: true })
}
})
})
@@ -1,4 +1,4 @@
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
@@ -35,4 +35,21 @@ describe('persistPluginDisabled', () => {
expect(text.match(/image-recognition-http/g)).toHaveLength(1)
expect(text).not.toContain('disabled: true')
})
it('creates the patch file when it does not yet exist', () => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-plugin-persist-'))
persistPluginDisabled(dir, 'image-recognition-http', true)
const text = readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')
expect(text).toContain('image-recognition-http')
expect(text).toContain('disabled: true')
rmSync(dir, { recursive: true, force: true })
})
it('treats a non-array patch file as empty', () => {
const dir = profile('not-an-array\n')
persistPluginDisabled(dir, 'image-recognition-http', true)
const text = readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')
expect(text).toContain('image-recognition-http')
expect(text).not.toContain('not-an-array')
})
})
@@ -14,6 +14,9 @@
{
"path": "../../../vendor/loader"
},
{
"path": "../../boot/app-boot"
},
{
"path": "../../util/brand"
},