@linxin666/dsh-client-ui-plugin-manager 0.2.9 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +2 -2
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/lib/client.js.map +1 -1
- package/lib/index.js +143 -68
- package/lib/types/host/gateway.d.ts +9 -1
- package/lib/types/host/http.d.ts +42 -0
- package/lib/types/host/profile.d.ts +5 -0
- package/package.json +1 -1
package/README.i18n.yaml
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
|
3
3
|
# after editing either side, bring the other along and re-record with:
|
|
4
4
|
# node scripts/verify-docs.mjs --write <dir>
|
|
5
|
-
README.md:
|
|
6
|
-
README.zh.md:
|
|
5
|
+
README.md: 06a644dc005ff50c66bec1b258bd72eda3053096
|
|
6
|
+
README.zh.md: e5a1315b1f05c1de53751131156d17786ed88509
|
package/README.md
CHANGED
|
@@ -71,7 +71,7 @@ The contract source of truth is `src/core/service.ts` (`PluginManagerService`).
|
|
|
71
71
|
|
|
72
72
|
## Security model
|
|
73
73
|
|
|
74
|
-
- Trust boundary is the loopback fence: every gateway route requires a loopback socket address, a loopback Host header, and a non-cross-site origin (socket + Host + Origin + `sec-fetch-site`), the same authority the official installer channels enforce. There is no browser-reachable path from a remote origin
|
|
74
|
+
- Trust boundary is the loopback fence: every gateway route requires a loopback socket address, a loopback Host header, and a non-cross-site origin (socket + Host + Origin + `sec-fetch-site`), the same authority the official installer channels enforce. There is no browser-reachable path from a remote origin; rejected requests receive HTTP 403 with `{ ok: false, error: "forbidden: loopback-only" }`.
|
|
75
75
|
- Mutation routes (install / update / remove / set-enabled) carry no token: the loopback authority *is* the local user, matching the official channels. Any local process can therefore drive plugin installs and removals, and npm installs run package install scripts — treat the gateway as local code execution by design and never expose it beyond loopback.
|
|
76
76
|
- Install specs and package ids are rejected when they contain command-shell expansion characters or control characters. On Windows, npm shims are resolved to `node.exe` plus the package `bin.js`; packaged Desktop shims have no adjacent npm layout, so they run through `cmd.exe /d /s /c` with a pre-quoted, verbatim argument envelope. Desktop profile discovery reads the packaged launcher's profile environment value or persisted profile selection, and its in-process official installer is confirmed through the browser RPC capability probe.
|
|
77
77
|
- Mutations are serialized through one queue, so concurrent jobs never interleave their before/after profile captures. An install is only `done` when the new dependency actually landed in the profile (and a removal only when it is gone); a success exit code alone is never trusted.
|
package/README.zh.md
CHANGED
|
@@ -71,7 +71,7 @@ dsh plugin --profile web add link:$(pwd)/packages/dsh-plugin-manager
|
|
|
71
71
|
|
|
72
72
|
## 安全模型
|
|
73
73
|
|
|
74
|
-
- 信任边界是 loopback 门禁:每条网关路由都要求 loopback socket 地址、loopback Host 头与非跨站来源(socket + Host + Origin + `sec-fetch-site`
|
|
74
|
+
- 信任边界是 loopback 门禁:每条网关路由都要求 loopback socket 地址、loopback Host 头与非跨站来源(socket + Host + Origin + `sec-fetch-site` 四重),与官方安装器通道同一权威。远程来源的浏览器没有可达路径;被拒请求返回 HTTP 403 与 `{ ok: false, error: "forbidden: loopback-only" }`。
|
|
75
75
|
- 变更类路由(install / update / remove / set-enabled)不带 token:loopback 权威即本机用户,与官方通道同模型。因此任何本机进程都能驱动插件安装与卸载,且 npm 安装会执行包的 install 脚本——请将本网关视为「设计上即本机代码执行」,绝不暴露到 loopback 之外。
|
|
76
76
|
- 安装 spec 与包 id 含命令行展开字符或控制字符时一律拒绝。Windows 下,npm shim 会解析为 `node.exe` 加包内 `bin.js`;DSH Desktop 打包 shim 附近没有 npm 布局,因此通过带完整预引用、逐字参数封套的 `cmd.exe /d /s /c` 执行。桌面 profile 从打包启动器环境值或持久化的 profile 选择中读取,进程内官方安装器则由浏览器 RPC 能力探测确认。
|
|
77
77
|
- 变更经同一队列串行,并发任务的 before/after profile 快照绝不交错。安装只有在依赖真实落入 profile 后才判 done(卸载以依赖消失为准),绝不轻信成功退出码。
|
package/lib/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["css","Button","Modal"],"sources":["../../../packages/dsh-plugin-manager/src/core/conflict.ts","../../../packages/dsh-plugin-manager/src/core/repair.ts","../../../packages/dsh-plugin-manager/src/core/version.ts","../../../packages/dsh-plugin-manager/src/client/PluginManagerTab.tsx","../../../packages/dsh-plugin-manager/src/client/locales.ts","../../../packages/dsh-plugin-manager/src/core/protocol.ts","../../../packages/dsh-plugin-manager/src/core/service.ts","../../../packages/dsh-plugin-manager/src/client/index.ts"],"sourcesContent":["/**\n * Conflict-ledger diffing. The official host applies structural conflict\n * rules at install time (disableControlsOnInstall: installing the dsh-web-ui\n * family disables the built-in web-ui product rows so the two never\n * double-mount), but no UI surfaces what the rules just did. This module\n * diffs the plugin-control snapshots taken before and after an install and\n * classifies every state change so the tab can render it as a reversible,\n * attributable conflict notice.\n *\n * The install-time authority ends here: duplicate insert-id claims between\n * two user plugins carry no at-install signal through the RPC channels (the\n * Loader only re-reads the composition at the next start), so that failure\n * shape is left to the boot-failure ring — the real start is the authoritative\n * conflict detector.\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\nimport type { PluginControlItem } from './protocol.ts'\n\n/** One observed product-control state change between two snapshots. */\nexport interface ControlChange {\n id: string\n name: string\n from: PluginControlItem['state']\n to: PluginControlItem['state']\n}\n\n/** Meaningful change kinds a conflict notice distinguishes. */\nexport type ControlChangeKind = 'rule-disabled' | 'rule-enabled' | 'state-change'\n\n/**\n * Diff two plugin-control snapshots by id. Only entries present in both\n * snapshots with a changed state are reported; entries appearing or\n * disappearing are ordinary install/uninstall outcomes, not conflicts.\n * @param before - snapshot taken before the install.\n * @param after - snapshot taken after the install.\n * @returns one change per id whose state moved, in id order.\n */\nexport function diffControls(before: readonly PluginControlItem[], after: readonly PluginControlItem[]): ControlChange[] {\n const afterById = new Map(after.map(item => [item.id, item]))\n const changes: ControlChange[] = []\n for (const item of before) {\n const current = afterById.get(item.id)\n if (current === undefined || current.state === item.state) continue\n changes.push({ id: item.id, name: item.name, from: item.state, to: current.state })\n }\n return changes\n}\n\n/**\n * Classify one control-state change for messaging. A change into `disabled`\n * is the conflict rule's action (reversible by re-enabling); a change out of\n * `disabled` is a manual undo; anything else is reported neutrally.\n * @param change - one diff entry.\n * @returns the message kind.\n */\nexport function classifyChange(change: ControlChange): ControlChangeKind {\n if (change.to === 'disabled') return 'rule-disabled'\n if (change.from === 'disabled') return 'rule-enabled'\n return 'state-change'\n}\n","/**\n * Repair-conversation seed text. Two failure surfaces hand off to the agent\n * through the same shape: a failed install (target spec + install error) and\n * a recorded boot failure (the failure-ring row). The seeded message must be\n * self-contained — the repair session's workspace is the plugin install root,\n * so the agent's file tools reach the plugin code without leaving the\n * workspace boundary.\n *\n * Secret discipline: the seed carries only the spec, the host's truncated\n * failure message/stack, and paths. Callers must never append credentials,\n * tokens, or environment contents; the failure ring is the host's bounded,\n * pruned record and nothing else is added.\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\nimport type { PluginFailureItem } from './protocol.ts'\nimport type { LayerState } from './patch-diff.ts'\n\n/** Localized fragments the builders assemble. */\nexport interface RepairCopy {\n installTitle: string\n installSpecLabel: string\n installErrorLabel: string\n installAsk: string\n failureTitle: string\n failurePluginLabel: string\n failureKindLabel: string\n failureAtLabel: string\n failureMessageLabel: string\n failureStackLabel: string\n failurePathLabel: string\n failureAsk: string\n conflictTitle: string\n conflictPluginLabel: string\n conflictChangeLabel: string\n conflictAsk: string\n /** Localized names of the failure kinds. */\n kindNames: Record<PluginFailureItem['kind'], string>\n /** Localized names of the layer states a conflict change traverses. */\n stateNames: Record<LayerState, string>\n}\n\n/** Default copy (zh): the package's zh dictionary keys map onto these strings. */\nexport const DEFAULT_REPAIR_COPY: RepairCopy = {\n installTitle: '正在修复插件安装失败',\n installSpecLabel: '安装目标',\n installErrorLabel: '安装错误',\n installAsk: '请在插件安装根目录内检查插件包或依赖并修复,然后重试安装。',\n failureTitle: '正在修复插件启动失败',\n failurePluginLabel: '插件',\n failureKindLabel: '失败类型',\n failureAtLabel: '时间',\n failureMessageLabel: '错误信息',\n failureStackLabel: '堆栈',\n failurePathLabel: '安装路径',\n failureAsk: '请修复插件后重新启用并重启 dsh web。',\n conflictTitle: '正在处理插件安装冲突',\n conflictPluginLabel: '冲突条目',\n conflictChangeLabel: '状态变化',\n conflictAsk: '请检查冲突双方的入口行 id 与挂载方式,消除重复挂载后告诉我如何重新启用。',\n kindNames: {\n 'load-failure': '加载失败',\n hang: '启动挂起',\n 'late-rejection': '迟到拒绝',\n },\n stateNames: {\n enabled: '已开启',\n disabled: '已关闭',\n uninstalled: '已卸载',\n },\n}\n\n/**\n * Seed text for a failed install: the target and the rendered error,\n * self-contained for the agent.\n * @param spec - the install target (npm spec or git URL) that failed.\n * @param error - the rendered install error text.\n * @param copy - localized fragments.\n * @returns the repair prompt text.\n */\nexport function installRepairMessage(spec: string, error: string, copy: RepairCopy = DEFAULT_REPAIR_COPY): string {\n return [\n copy.installTitle,\n `${copy.installSpecLabel}: ${spec}`,\n `${copy.installErrorLabel}:\\n${error}`,\n copy.installAsk,\n ].join('\\n\\n')\n}\n\n/**\n * Seed text for one boot-failure ring row: the failure record, so the agent\n * can attribute and fix it in place.\n * @param failure - the recorded failure row.\n * @param copy - localized fragments.\n * @returns the repair prompt text.\n */\nexport function failureRepairMessage(failure: PluginFailureItem, copy: RepairCopy = DEFAULT_REPAIR_COPY): string {\n const parts = [\n copy.failureTitle,\n `${copy.failurePluginLabel}: ${failure.pluginId || '-'}`,\n `${copy.failureKindLabel}: ${copy.kindNames[failure.kind] ?? failure.kind}`,\n `${copy.failureAtLabel}: ${failure.at}`,\n `${copy.failureMessageLabel}:\\n${failure.message}`,\n ]\n if (failure.stack !== '') parts.push(`${copy.failureStackLabel}:\\n${failure.stack}`)\n if (failure.installPath !== '') parts.push(`${copy.failurePathLabel}: ${failure.installPath}`)\n parts.push(copy.failureAsk)\n return parts.join('\\n\\n')\n}\n\n/**\n * Seed text for one install-conflict notice: the entry and its state change,\n * so the agent can attribute the conflict and resolve the double mount.\n * @param change - the conflict change (id, display name, from/to states).\n * @param copy - localized fragments.\n * @returns the repair prompt text.\n */\nexport function conflictRepairMessage(\n change: { id: string; name: string; from: LayerState; to: LayerState },\n copy: RepairCopy = DEFAULT_REPAIR_COPY,\n): string {\n return [\n copy.conflictTitle,\n `${copy.conflictPluginLabel}: ${change.name} (${change.id})`,\n `${copy.conflictChangeLabel}: ${copy.stateNames[change.from] ?? change.from} -> ${copy.stateNames[change.to] ?? change.to}`,\n copy.conflictAsk,\n ].join('\\n\\n')\n}\n","/**\n * DSH host version parsing and comparison for the update compatibility\n * check. The declared minimum lives in the published package manifest under\n * `dsh.engines.dsh`, falling back to the top-level `engines.dsh`; the only\n * supported form is `>=X.Y.Z[-prerelease]`.\n *\n * Comparison deliberately uses plain semver ordering instead of\n * `semver.satisfies`: npm's prerelease rule only allows a prerelease version\n * to satisfy a comparator set carrying a prerelease on the same\n * major.minor.patch tuple, which would reject a newer host line (0.1.1-rc.2)\n * against a declared `>=0.1.0-rc.8` — exactly the cross-cohort upgrade path\n * this check must allow. Everything here is pure and tolerant of untrusted\n * input: a malformed value means \"cannot verify\", which the callers treat as\n * a fail-closed verdict when a requirement was declared (issue #754).\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\n/** One parsed DSH host or package version. */\nexport interface DshVersion {\n major: number\n minor: number\n patch: number\n /** Prerelease identifiers, numeric identifiers kept as numbers (semver order). */\n prerelease: readonly (number | string)[]\n}\n\nconst VERSION_PATTERN = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?$/\n\n/**\n * Parse a DSH host or package version string.\n * @param value - e.g. `0.1.0-rc.8`, `v1.2.3`.\n * @returns the parsed version, or undefined when malformed.\n */\nexport function parseDshVersion(value: string): DshVersion | undefined {\n const match = VERSION_PATTERN.exec(value.trim())\n if (match === null) return undefined\n const prereleaseParts = match[4] === undefined ? [] : match[4].split('.')\n if (prereleaseParts.some(part => part === '')) return undefined\n return {\n major: Number(match[1]),\n minor: Number(match[2]),\n patch: Number(match[3]),\n prerelease: prereleaseParts.map(part => /^\\d+$/.test(part) ? Number(part) : part),\n }\n}\n\n/**\n * Compare two version strings by semver order (a release is newer than any\n * prerelease of the same tuple).\n * @returns -1 / 0 / 1, or undefined when either side is malformed.\n */\nexport function compareVersions(left: string, right: string): number | undefined {\n const a = parseDshVersion(left)\n const b = parseDshVersion(right)\n if (a === undefined || b === undefined) return undefined\n for (const key of ['major', 'minor', 'patch'] as const) {\n if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1\n }\n return comparePrerelease(a.prerelease, b.prerelease)\n}\n\n/**\n * Semver prerelease ordering: numeric identifiers compare numerically,\n * numeric identifiers rank below alphanumeric ones, alphanumeric identifiers\n * compare lexically, and a longer list wins when the shared prefix is equal.\n */\nfunction comparePrerelease(left: readonly (number | string)[], right: readonly (number | string)[]): number {\n if (left.length === 0 && right.length === 0) return 0\n if (left.length === 0) return 1\n if (right.length === 0) return -1\n const length = Math.max(left.length, right.length)\n for (let index = 0; index < length; index += 1) {\n const a = left[index]\n const b = right[index]\n if (a === undefined) return -1\n if (b === undefined) return 1\n if (typeof a === 'number' && typeof b === 'number') {\n if (a !== b) return a < b ? -1 : 1\n } else if (typeof a === 'number') {\n return -1\n } else if (typeof b === 'number') {\n return 1\n } else if (a !== b) {\n return a < b ? -1 : 1\n }\n }\n return 0\n}\n\nconst MINIMUM_RANGE_PATTERN = /^>=\\s*(v?\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)$/\n\n/**\n * Whether a host version satisfies a declared `>=X.Y.Z[-prerelease]` minimum.\n * @param host - the running DSH host version.\n * @param minimum - the declared minimum; any form other than `>=<semver>`\n * (plain semver, `^`, `~`, multi-comparator ranges, empty) returns undefined.\n * @returns true / false, or undefined when the host version is malformed or\n * the minimum uses an unsupported form — callers treat undefined as\n * \"cannot verify\" and fail closed for declared requirements.\n */\nexport function meetsMinimumDsh(host: string, minimum: string): boolean | undefined {\n const match = MINIMUM_RANGE_PATTERN.exec(minimum.trim())\n if (match === null) return undefined\n const compared = compareVersions(host, match[1])\n if (compared === undefined) return undefined\n return compared >= 0\n}\n\n/**\n * The bare minimum version for display: strips the `>=` operator (and an\n * optional leading `v`) from a declared requirement so UI copy that already\n * contains the comparison operator renders `0.1.1-rc.1` instead of\n * `>= >=0.1.1-rc.1`. Unsupported range forms render unchanged.\n * @param minimum - the declared minimum range.\n * @returns the version portion for display.\n */\nexport function displayMinimumVersion(minimum: string): string {\n const match = MINIMUM_RANGE_PATTERN.exec(minimum.trim())\n return match === null ? minimum.trim() : match[1].replace(/^v/, '')\n}\n\n/**\n * Read the declared DSH minimum from a published registry manifest:\n * `dsh.engines.dsh` first, top-level `engines.dsh` as the fallback.\n * Defensive against malformed or untrusted metadata: anything that is not a\n * non-empty string reads as absent.\n * @param manifest - the decoded registry version manifest.\n * @returns the declared minimum, or undefined when not declared.\n */\nexport function dshRequirementOf(manifest: { dsh?: unknown; engines?: unknown }): string | undefined {\n const dshEngines = (manifest.dsh as { engines?: unknown } | undefined)?.engines as { dsh?: unknown } | undefined\n const engines = (manifest.engines as { dsh?: unknown } | undefined)?.dsh\n const value = dshEngines?.dsh ?? engines\n return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined\n}\n","/**\n * The plugin-manager tab: an install box, one row per installed user plugin\n * (next-start enablement switch, source badge, update availability, update and\n * uninstall actions, per-plugin boot-failure block), the built-in product\n * switches, an install-conflict notice (the diff of the plugin-control\n * snapshot around each install, reversible through the product switch), and\n * the failure-repair affordances. Enablement switches and installs persist\n * through the official host channels and apply at the next restart; the web\n * build shows a restart hint instead of an in-place restart.\n *\n * This tab registers into the official Plugins settings section\n * (`settings.plugins.tab` slot) next to the official installer tab; its added\n * value over that tab is the conflict ledger, the bilingual repair seeds, and\n * the family card vocabulary.\n */\nimport { useEffect, useRef, useState } from 'react'\nimport { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport { classifyChange, diffControls, type ControlChange } from '../core/conflict.ts'\nimport type {\n InstallProgressItem,\n InstalledPluginItem,\n PluginControlItem,\n PluginFailureItem,\n PluginFailuresSnapshot,\n PluginUpdateItem,\n} from '../core/protocol.ts'\nimport { conflictRepairMessage, failureRepairMessage, installRepairMessage, type RepairCopy } from '../core/repair.ts'\nimport { displayMinimumVersion } from '../core/version.ts'\nimport type { PluginManagerKey } from './locales.ts'\nimport css from './plugin-manager.module.css'\n\n/** Registration-side wire face used by the tab. */\nexport interface PluginManagerTabInjected {\n /** Whether this browser has loopback authority to use the host routes. */\n isLoopback: boolean\n /** Read the installed snapshot. */\n list: () => Promise<InstalledPluginItem[]>\n /** Install one plugin from an npm spec or git URL. */\n install: (spec: string) => Promise<InstalledPluginItem>\n /** Re-install one plugin from its recorded source. */\n update: (id: string) => Promise<InstalledPluginItem>\n /** Remove one plugin. */\n uninstall: (id: string) => Promise<InstalledPluginItem[]>\n /** Persist one user plugin's next-start enablement. */\n setEnabled: (id: string, enabled: boolean) => Promise<InstalledPluginItem>\n /** Compare installed versions against their sources. */\n checkUpdates: () => Promise<PluginUpdateItem[]>\n /** Read the current install/update progress. */\n status: () => Promise<InstallProgressItem>\n /** Read the recorded boot failures, plugin root, and safe-mode state. */\n failures: () => Promise<PluginFailuresSnapshot>\n /** Persist the safe-mode marker (web: applied at the next manual restart). */\n setSafeMode: (enabled: boolean) => Promise<void>\n /** Start a repair conversation over the plugin install root. */\n repairPlugin: (pluginRoot: string, message: string) => Promise<void>\n /** Read the deployment-configured built-in product switches. */\n controlsList: () => Promise<PluginControlItem[]>\n /** Persist one product's next-start enablement. */\n controlsSetEnabled: (pluginId: string, enabled: boolean) => Promise<PluginControlItem[]>\n /** Conflicts the gateway host computed around the last install (gateway mode only). */\n lastInstallConflicts?: () => readonly ControlChange[]\n}\n\n/** Full component props assembled by the Settings slot renderer. */\nexport type PluginManagerTabProps =\n PropsRuntime<'settings.plugins.tab'>\n & PropsLocale<'settings.pluginManager'>\n & InjectFace<PluginManagerTabInjected>\n\ntype ViewState =\n | { readonly status: 'loading' }\n | { readonly status: 'error' }\n | {\n readonly status: 'ready'\n readonly plugins: readonly InstalledPluginItem[]\n readonly controls: readonly PluginControlItem[]\n readonly failures: PluginFailuresSnapshot\n }\n\n/** One row operation in flight. */\ntype BusyAction = { readonly kind: 'install' | 'update' | 'uninstall' | 'check'; readonly id?: string }\n\n/** One enablement switch in flight: a user plugin or a built-in product. */\ntype ToggleBusy = { readonly kind: 'user' | 'product'; readonly id: string }\n\n/** One uninstall target awaiting confirmation. */\ninterface UninstallTarget {\n readonly id: string\n readonly name: string\n}\n\n/** Error text for a caught request or lifecycle failure. */\nfunction messageOf(error: unknown): string {\n if (error instanceof AggregateError) {\n const details = error.errors.map(messageOf).join('; ')\n return details === '' ? error.message : `${error.message}: ${details}`\n }\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Localized fragments for the repair seed builders, read from the tab's dictionaries. */\nfunction repairCopy(t: PluginManagerTabProps['t']): RepairCopy {\n return {\n installTitle: t('repairInstallTitle'),\n installSpecLabel: t('repairInstallSpecLabel'),\n installErrorLabel: t('repairInstallErrorLabel'),\n installAsk: t('repairInstallAsk'),\n failureTitle: t('repairFailureTitle'),\n failurePluginLabel: t('repairFailurePluginLabel'),\n failureKindLabel: t('repairFailureKindLabel'),\n failureAtLabel: t('repairFailureAtLabel'),\n failureMessageLabel: t('repairFailureMessageLabel'),\n failureStackLabel: t('repairFailureStackLabel'),\n failurePathLabel: t('repairFailurePathLabel'),\n failureAsk: t('repairFailureAsk'),\n kindNames: {\n 'load-failure': t('repairKindLoad'),\n hang: t('repairKindHang'),\n 'late-rejection': t('repairKindLate'),\n },\n conflictTitle: t('repairConflictTitle'),\n conflictPluginLabel: t('repairConflictPluginLabel'),\n conflictChangeLabel: t('repairConflictChangeLabel'),\n conflictAsk: t('repairConflictAsk'),\n stateNames: {\n enabled: t('repairStateEnabled'),\n disabled: t('repairStateDisabled'),\n uninstalled: t('repairStateUninstalled'),\n },\n }\n}\n\n/** Localized label for one install phase, with percent when the download has one. */\nfunction progressLabel(progress: InstallProgressItem, t: PluginManagerTabProps['t']): string {\n if (progress.stage === 'fetch') return t('fetching')\n if (progress.stage === 'extract') return t('extracting')\n if (progress.stage === 'write') return t('writing')\n return progress.percent === undefined ? t('downloading') : t('downloadingPercent', { percent: String(progress.percent) })\n}\n\n/** The plugin-manager settings tab. */\nexport function PluginManagerTab(props: PluginManagerTabProps) {\n const {\n t,\n isLoopback,\n list,\n install,\n update,\n uninstall,\n setEnabled,\n checkUpdates,\n status,\n failures,\n setSafeMode,\n repairPlugin,\n controlsList,\n controlsSetEnabled,\n lastInstallConflicts,\n } = props\n\n const [view, setView] = useState<ViewState>({ status: 'loading' })\n const [busy, setBusy] = useState<BusyAction | undefined>(undefined)\n const [toggleBusy, setToggleBusy] = useState<ToggleBusy | undefined>(undefined)\n const [error, setError] = useState<string | undefined>(undefined)\n const [failedSpec, setFailedSpec] = useState<string | undefined>(undefined)\n const [installError, setInstallError] = useState<string | undefined>(undefined)\n const [spec, setSpec] = useState('')\n const [dirty, setDirty] = useState(false)\n const [repairing, setRepairing] = useState<string | undefined>(undefined)\n const [copied, setCopied] = useState<string | undefined>(undefined)\n const [updates, setUpdates] = useState<ReadonlyMap<string, PluginUpdateItem>>(new Map())\n const [uninstallTarget, setUninstallTarget] = useState<UninstallTarget | undefined>(undefined)\n const [conflicts, setConflicts] = useState<readonly ControlChange[]>([])\n const [progress, setProgress] = useState<InstallProgressItem>({ kind: 'idle', stage: 'fetch' })\n /** Synchronous in-flight mirror of `busy`: the render-time guard alone lets a\n * click and an Enter land in the same frame and double-fire. */\n const busyRef = useRef(false)\n\n /** Reload every snapshot into the ready view. */\n const reload = async (): Promise<void> => {\n const [plugins, controls, failureSnapshot] = await Promise.all([list(), controlsList(), failures()])\n setView({ status: 'ready', plugins, controls, failures: failureSnapshot })\n }\n\n useEffect(() => {\n let cancelled = false\n void reload().catch(() => {\n if (!cancelled) setView({ status: 'error' })\n })\n return () => { cancelled = true }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n /** One row/form operation: busy state, error row, dirty flag on success. */\n const run = async (action: BusyAction, body: () => Promise<void>): Promise<void> => {\n if (busyRef.current) return\n busyRef.current = true\n setBusy(action)\n setError(undefined)\n try {\n await body()\n setDirty(true)\n } catch (reason) {\n setError(t('failed', { reason: messageOf(reason) }))\n } finally {\n busyRef.current = false\n setBusy(undefined)\n }\n }\n\n /** Install one spec, then diff the product snapshot into a conflict notice. */\n const onInstall = (): void => {\n const target = spec.trim()\n if (target === '' || busy !== undefined || busyRef.current) return\n void (async () => {\n busyRef.current = true\n const before = view.status === 'ready' ? view.controls : await controlsList().catch(() => [])\n setBusy({ kind: 'install' })\n setError(undefined)\n setFailedSpec(undefined)\n setInstallError(undefined)\n try {\n await install(target)\n setSpec('')\n setDirty(true)\n const after = await controlsList().catch(() => [] as readonly PluginControlItem[])\n setConflicts(lastInstallConflicts !== undefined ? lastInstallConflicts() : diffControls(before, after))\n await reload()\n } catch (reason) {\n const reasonText = messageOf(reason)\n setFailedSpec(target)\n setInstallError(reasonText)\n setError(t('failed', { reason: reasonText }))\n } finally {\n busyRef.current = false\n setBusy(undefined)\n }\n })()\n }\n\n /** Poll install/update progress while such an operation is in flight. */\n useEffect(() => {\n if (busy === undefined || (busy.kind !== 'install' && busy.kind !== 'update')) {\n setProgress({ kind: 'idle', stage: 'fetch' })\n return\n }\n let stopped = false\n let timer: ReturnType<typeof setTimeout> | undefined\n const tick = (delay: number): void => {\n timer = setTimeout(() => {\n void status().then(next => {\n if (!stopped && next !== undefined) {\n setProgress(next)\n tick(400)\n }\n }).catch(() => { /* status polling fails silently; the operation itself owns the error row */ })\n }, delay)\n }\n tick(100)\n return () => {\n stopped = true\n if (timer !== undefined) clearTimeout(timer)\n }\n }, [busy, status])\n\n const toggleDisabled = busy !== undefined || toggleBusy !== undefined\n || (view.status === 'ready' && view.failures.safeMode)\n\n const onUserToggle = (id: string, enabled: boolean): void => {\n setToggleBusy({ kind: 'user', id })\n setError(undefined)\n void setEnabled(id, enabled).then(plugin => {\n setView(current => current.status === 'ready'\n ? { ...current, plugins: current.plugins.map(item => item.id === id ? plugin : item) }\n : current)\n setDirty(true)\n setToggleBusy(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setToggleBusy(undefined)\n })\n }\n\n const onProductToggle = (id: string, enabled: boolean): void => {\n setToggleBusy({ kind: 'product', id })\n setError(undefined)\n void controlsSetEnabled(id, enabled).then(controls => {\n setView(current => current.status === 'ready' ? { ...current, controls } : current)\n setConflicts(previous => previous.filter(change => change.id !== id))\n setDirty(true)\n setToggleBusy(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setToggleBusy(undefined)\n })\n }\n\n const onCheck = (): void => {\n void run({ kind: 'check' }, async () => {\n const found = await checkUpdates()\n setUpdates(new Map(found.map(item => [item.id, item])))\n })\n }\n\n const onUpdate = (id: string): void => {\n void run({ kind: 'update', id }, async () => {\n await update(id)\n setUpdates(previous => {\n const next = new Map(previous)\n next.delete(id)\n return next\n })\n await reload()\n })\n }\n\n const onUninstall = (): void => {\n const target = uninstallTarget\n if (target === undefined) return\n void run({ kind: 'uninstall', id: target.id }, async () => {\n await uninstall(target.id)\n setUninstallTarget(undefined)\n await reload()\n })\n }\n\n /** Open a repair conversation seeded with one boot-failure record. `token`\n * identifies the row for the in-flight label (plugin id, or a row key for\n * unattributable failures). */\n const onRepair = (failure: PluginFailureItem, token: string): void => {\n if (view.status !== 'ready' || busy !== undefined || repairing !== undefined) return\n setError(undefined)\n setRepairing(token)\n void repairPlugin(view.failures.pluginRoot, failureRepairMessage(failure, repairCopy(t))).then(() => {\n setRepairing(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setRepairing(undefined)\n })\n }\n\n /** Hand the latest failed install off to a repair conversation over the\n * install root. The seed carries the install's own error (installError), not\n * whatever error the row currently shows. */\n const onRepairInstall = (): void => {\n if (view.status !== 'ready' || repairing !== undefined) return\n setError(undefined)\n setRepairing('install')\n void repairPlugin(view.failures.pluginRoot, installRepairMessage(failedSpec ?? '', installError ?? '', repairCopy(t))).then(() => {\n setError(undefined)\n setFailedSpec(undefined)\n setInstallError(undefined)\n setRepairing(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setRepairing(undefined)\n })\n }\n\n /** Copy a boot failure's message and stack for a manual repair conversation. */\n const onCopy = (failure: PluginFailureItem, token: string): void => {\n void navigator.clipboard.writeText(`${failure.message}\\n\\n${failure.stack}`).then(() => {\n setCopied(token)\n }).catch(() => {\n setError(t('failed', { reason: 'clipboard unavailable' }))\n })\n }\n\n const onExitSafeMode = (): void => {\n if (busy !== undefined) return\n setError(undefined)\n void setSafeMode(false).then(() => {\n setDirty(true)\n void reload().catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n })\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n })\n }\n\n /** Undo one conflict action by flipping the product switch back. */\n const onUndoConflict = (change: ControlChange): void => {\n if (change.to !== 'disabled') return\n onProductToggle(change.id, true)\n }\n\n /** Hand one conflict notice off to a repair conversation over the plugin root. */\n const onRepairConflict = (change: ControlChange): void => {\n if (view.status !== 'ready' || busy !== undefined || repairing !== undefined) return\n setError(undefined)\n const token = `conflict:${change.id}`\n setRepairing(token)\n void repairPlugin(view.failures.pluginRoot, conflictRepairMessage({\n id: change.id,\n name: change.name,\n from: change.from === 'enabled' || change.from === 'disabled' ? change.from : 'uninstalled',\n to: change.to === 'enabled' || change.to === 'disabled' ? change.to : 'uninstalled',\n }, repairCopy(t))).then(() => {\n setRepairing(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setRepairing(undefined)\n })\n }\n\n if (!isLoopback) {\n return (\n <div className={css.notice}>\n <strong>{t('localOnlyTitle')}</strong>\n <p>{t('localOnlyBody')}</p>\n </div>\n )\n }\n if (view.status === 'loading') return <div className={css.state}>{t('loading')}</div>\n if (view.status === 'error') return <div className={css.state}>{t('failed', { reason: 'load' })}</div>\n\n const attributable = new Map(view.failures.items.filter(item => item.pluginId !== '').map(item => [item.pluginId, item]))\n const unattributable = view.failures.items.filter(item => item.pluginId === '')\n\n return (\n <div className={css.section} aria-busy={busy !== undefined || toggleBusy !== undefined}>\n {view.failures.safeMode && (\n <div className={css.safeModeBanner} data-safe-mode>\n <p>{t('safeModeBanner')}</p>\n <Button variant=\"primary\" disabled={busy !== undefined} onClick={onExitSafeMode}>\n {t('exitSafeMode')}\n </Button>\n </div>\n )}\n\n <div className={css.installRow}>\n <input\n className={css.spec}\n type=\"text\"\n value={spec}\n placeholder={t('installPlaceholder')}\n disabled={busy !== undefined}\n onChange={event => { setSpec(event.target.value) }}\n onKeyDown={event => {\n if (event.key === 'Enter' && spec.trim() !== '' && busy === undefined) onInstall()\n }}\n />\n <Button\n variant=\"primary\"\n disabled={spec.trim() === '' || busy !== undefined}\n onClick={onInstall}\n >\n {busy !== undefined && busy.kind === 'install' ? t('installing') : t('install')}\n </Button>\n </div>\n <p className={css.hint}>{t('installHint')}</p>\n\n {(busy?.kind === 'install' || busy?.kind === 'update') && (\n <div className={css.progressRow} role=\"status\">\n <div className={css.progressTrack}>\n <div\n className={css.progressBar}\n style={progress.percent === undefined ? undefined : { width: `${progress.percent}%` }}\n data-indeterminate={progress.percent === undefined ? 'true' : undefined}\n />\n </div>\n <p className={css.progressLabel}>{progressLabel(progress, t)}</p>\n </div>\n )}\n\n {error !== undefined && (\n <div className={css.errorRow}>\n <span className={css.error}>{error}</span>\n {failedSpec !== undefined && (\n <Button variant=\"outline\" disabled={repairing !== undefined} onClick={onRepairInstall}>\n {repairing === 'install' ? t('repairing') : t('repair')}\n </Button>\n )}\n </div>\n )}\n\n {conflicts.length > 0 && (\n <div className={css.conflicts}>\n <h3 className={css.sectionTitle}>{t('conflictTitle')}</h3>\n <ul className={css.list}>\n {conflicts.map(change => (\n <li key={change.id} className={css.row} data-conflict={change.id}>\n <div className={css.meta}>\n <span className={css.name}>{change.name}</span>\n <span className={css.sub}>\n {classifyChange(change) === 'rule-disabled'\n ? t('conflictDisabled', { name: change.name })\n : classifyChange(change) === 'rule-enabled'\n ? t('conflictEnabled', { name: change.name })\n : t('conflictChanged', { name: change.name })}\n </span>\n </div>\n <div className={css.actions}>\n {change.to === 'disabled' && (\n <Button\n variant=\"outline\"\n disabled={toggleDisabled}\n onClick={() => { onUndoConflict(change) }}\n >\n {t('undoConflict')}\n </Button>\n )}\n <Button\n variant=\"outline\"\n disabled={busy !== undefined || repairing !== undefined}\n onClick={() => { onRepairConflict(change) }}\n >\n {repairing === `conflict:${change.id}` ? t('repairing') : t('repair')}\n </Button>\n </div>\n </li>\n ))}\n </ul>\n <p className={css.hint}>{t('conflictHint')}</p>\n </div>\n )}\n\n <div className={css.group}>\n <h3 className={css.sectionTitle}>{t('userPlugins')}</h3>\n {view.plugins.length === 0\n ? <p className={css.empty}>{t('empty')}</p>\n : (\n <ul className={css.list}>\n {view.plugins.map(plugin => {\n const updateItem = updates.get(plugin.id)\n const latest = updateItem?.latest\n const dshRequirement = updateItem?.requiresDsh\n const failure = attributable.get(plugin.id)\n return (\n <li key={plugin.id} className={css.row} data-plugin-id={plugin.id}>\n <div className={css.meta}>\n <span className={css.name}>{plugin.name}</span>\n <span className={css.sub}>\n <span className={css.version}>{t('version', { version: plugin.version })}</span>\n <span className={css.sourceBadge} data-source={plugin.source.kind}>\n {plugin.source.kind === 'npm' ? t('npmSource') : t('gitSource')}\n </span>\n <span className={css.specText} title={plugin.source.spec}>{plugin.source.spec}</span>\n </span>\n {latest !== undefined && <span className={css.latest}>{t('latest', { version: latest })}</span>}\n {updateItem !== undefined && dshRequirement !== undefined && (\n <span className={updateItem.compatible === false ? css.compatBlocked : css.compatHint}>\n {updateItem.compatible === false\n ? t('updateBlockedDsh', { min: displayMinimumVersion(dshRequirement) })\n : t('updateRequiresDsh', { min: displayMinimumVersion(dshRequirement) })}\n </span>\n )}\n {failure !== undefined && (\n <div className={css.failure} data-plugin-failure={plugin.id}>\n <span className={css.badge}>{t('failureBadge')}</span>\n <span className={css.failureMessage} title={failure.message}>{failure.message}</span>\n <div className={css.failureActions}>\n <Button\n variant=\"primary\"\n disabled={busy !== undefined || repairing !== undefined}\n onClick={() => { onRepair(failure, plugin.id) }}\n >\n {repairing === plugin.id ? t('repairing') : t('repair')}\n </Button>\n <Button variant=\"outline\" disabled={busy !== undefined} onClick={() => { onCopy(failure, plugin.id) }}>\n {copied === plugin.id ? t('copied') : t('copyError')}\n </Button>\n </div>\n </div>\n )}\n </div>\n <div className={css.actions}>\n <span className={css.stateLabel} data-state={plugin.enabled ? 'enabled' : 'disabled'}>\n {plugin.enabled ? t('enabled') : t('disabled')}\n </span>\n <button\n type=\"button\"\n role=\"switch\"\n aria-checked={plugin.enabled}\n aria-label={plugin.enabled ? t('disableSwitch', { name: plugin.name }) : t('enableSwitch', { name: plugin.name })}\n className={css.switch}\n disabled={toggleDisabled}\n onClick={() => { onUserToggle(plugin.id, !plugin.enabled) }}\n />\n {latest !== undefined && (\n <Button\n variant=\"outline\"\n disabled={busy !== undefined || updateItem?.compatible === false}\n onClick={() => { onUpdate(plugin.id) }}\n >\n {busy?.kind === 'update' && busy.id === plugin.id ? t('updating') : t('update')}\n </Button>\n )}\n <Button\n variant=\"outline\"\n disabled={busy !== undefined}\n onClick={() => { setUninstallTarget({ id: plugin.id, name: plugin.name }) }}\n >\n {t('uninstall')}\n </Button>\n </div>\n </li>\n )\n })}\n </ul>\n )}\n </div>\n\n {view.controls.length > 0 && (\n <div className={css.group}>\n <h3 className={css.sectionTitle}>{t('products')}</h3>\n <ul className={css.list}>\n {view.controls.map(control => (\n <li key={control.id} className={css.row} data-product-id={control.id}>\n <div className={css.meta}>\n <span className={css.name}>{control.name}</span>\n <span className={css.sub}>\n <a className={css.link} href={control.repository} target=\"_blank\" rel=\"noreferrer\">{t('source')}</a>\n </span>\n </div>\n <div className={css.actions}>\n <span className={css.stateLabel} data-state={control.state}>\n {t(control.state)}\n </span>\n {control.state === 'enabled' || control.state === 'disabled'\n ? (\n <button\n type=\"button\"\n role=\"switch\"\n aria-checked={control.state === 'enabled'}\n aria-label={control.state === 'enabled'\n ? t('disableSwitch', { name: control.name })\n : t('enableSwitch', { name: control.name })}\n className={css.switch}\n disabled={toggleDisabled}\n onClick={() => { onProductToggle(control.id, control.state !== 'enabled') }}\n />\n )\n : null}\n </div>\n </li>\n ))}\n </ul>\n </div>\n )}\n\n {unattributable.length > 0 && (\n <div className={css.group}>\n <h3 className={css.sectionTitle}>{t('failureGroupTitle')}</h3>\n <ul className={css.list}>\n {unattributable.map((failure, index) => {\n const token = `other:${index}`\n return (\n <li key={`${failure.at}-${index}`} className={css.row} data-plugin-failure=\"other\">\n <div className={css.meta}>\n <span className={css.badge}>{t('failureBadge')}</span>\n <span className={css.failureMessage} title={failure.message}>{failure.message}</span>\n <div className={css.failureActions}>\n <Button\n variant=\"primary\"\n disabled={busy !== undefined || repairing !== undefined}\n onClick={() => { onRepair(failure, token) }}\n >\n {repairing === token ? t('repairing') : t('repair')}\n </Button>\n <Button variant=\"outline\" disabled={busy !== undefined} onClick={() => { onCopy(failure, token) }}>\n {copied === token ? t('copied') : t('copyError')}\n </Button>\n </div>\n </div>\n </li>\n )\n })}\n </ul>\n </div>\n )}\n\n <div className={css.actionsRow}>\n <Button variant=\"outline\" disabled={busy !== undefined} onClick={onCheck}>\n {busy?.kind === 'check' ? t('checking') : t('checkUpdates')}\n </Button>\n {updates.size === 0 && busy === undefined && view.plugins.length > 0 && (\n <p className={css.ok}>{t('noUpdates')}</p>\n )}\n </div>\n\n {toggleBusy !== undefined && <p className={css.applying} aria-live=\"polite\">{t('applying')}</p>}\n\n {dirty && (\n <div className={css.restartRow}>\n <p>{t('restartHint')}</p>\n </div>\n )}\n\n <Modal\n title={t('uninstallConfirmTitle')}\n open={uninstallTarget !== undefined}\n onClose={() => { setUninstallTarget(undefined) }}\n >\n <p className={css.confirmBody}>{t('uninstallConfirmBody', { name: uninstallTarget?.name ?? '' })}</p>\n <div className={css.modalActions}>\n <Button variant=\"outline\" disabled={busy !== undefined} onClick={() => { setUninstallTarget(undefined) }}>\n {t('cancel')}\n </Button>\n <Button variant=\"primary\" className={css.dangerButton} disabled={busy !== undefined} onClick={onUninstall}>\n {t('confirm')}\n </Button>\n </div>\n </Modal>\n </div>\n )\n}\n","/**\n * Locale dictionaries for the plugin-manager tab. The zh dictionary is the\n * key source; the en dictionary mirrors the exact key set.\n * @module @linxin666/dsh-client-ui-plugin-manager/client\n */\n\n/** Simplified Chinese copy (the key-set source of truth). */\nconst STATIC_ZH = {\n tab: '插件管理',\n loading: '正在读取插件…',\n empty: '尚未安装任何用户插件。',\n userPlugins: '用户插件',\n products: '内置产品',\n conflictTitle: '安装冲突',\n conflictDisabled: '已自动禁用 {name},避免重复挂载。',\n conflictEnabled: '已重新启用 {name}。',\n conflictChanged: '{name} 的状态已变更。',\n undoConflict: '撤销',\n conflictHint: '冲突动作在安装时自动执行,撤销会写回开关并在重启后生效。',\n installPlaceholder: 'npm 包名(如 @scope/name)或 git 仓库 URL',\n install: '安装',\n installing: '安装中…',\n installHint: '在 GitHub 或 npm 找到插件后,粘贴其 npm 包名或仓库地址安装;应用重启后插件生效。',\n version: '已安装 {version}',\n latest: '最新 {version}',\n update: '更新',\n updating: '更新中…',\n checkUpdates: '检查更新',\n checking: '检查中…',\n noUpdates: '所有插件都是最新版本。',\n updateRequiresDsh: '需要 DSH ≥ {min}',\n updateBlockedDsh: '需要 DSH ≥ {min},请先升级 DSH 再更新',\n uninstall: '卸载',\n uninstallConfirmTitle: '卸载插件',\n uninstallConfirmBody: '将删除 {name} 的安装目录与配置行,并在重启后生效。',\n confirm: '确认卸载',\n cancel: '取消',\n restartHint: '插件变更将在重启应用后生效。',\n failed: '操作失败:{reason}',\n enabled: '已开启',\n disabled: '已关闭',\n mixed: '部分开启',\n unavailable: '不可用',\n uninstalled: '已卸载',\n source: '查看源码',\n applying: '正在应用更改…',\n fetching: '正在获取插件信息…',\n downloading: '正在下载…',\n downloadingPercent: '正在下载 {percent}%',\n extracting: '正在解压…',\n writing: '正在写入配置…',\n localOnlyTitle: '仅限本机操作',\n localOnlyBody: '为了保护主机配置,插件管理只能从本机打开。',\n failureBadge: '启动失败',\n failureGroupTitle: '其他启动失败',\n repair: '让 Agent 修复',\n repairing: '正在创建修复对话…',\n copyError: '复制错误',\n copied: '已复制',\n safeModeBanner: '安全模式:用户插件配置已跳过,插件开关不可用。',\n exitSafeMode: '恢复正常模式并重启',\n npmSource: 'npm',\n gitSource: 'git',\n enableSwitch: '开启 {name}',\n disableSwitch: '关闭 {name}',\n repairInstallTitle: '插件安装失败,请帮我诊断并修复。',\n repairInstallSpecLabel: '安装目标',\n repairInstallErrorLabel: '错误信息',\n repairInstallAsk: '请检查该插件并重新安装;完成后告诉我结果。',\n repairFailureTitle: '插件上次启动失败。请修复它。',\n repairFailurePluginLabel: '插件',\n repairFailureKindLabel: '失败类型',\n repairFailureAtLabel: '时间',\n repairFailureMessageLabel: '失败详情',\n repairFailureStackLabel: '原始堆栈',\n repairFailurePathLabel: '插件安装目录',\n repairFailureAsk: '请检查并修复该插件;修复完成后告诉我如何重新启用。',\n repairKindLoad: '加载失败',\n repairKindHang: '启动挂起',\n repairKindLate: '迟到拒绝',\n repairConflictTitle: '正在处理插件安装冲突',\n repairConflictPluginLabel: '冲突条目',\n repairConflictChangeLabel: '状态变化',\n repairConflictAsk: '请检查冲突双方的入口行 id 与挂载方式,消除重复挂载后告诉我如何重新启用。',\n repairStateEnabled: '已开启',\n repairStateDisabled: '已关闭',\n repairStateUninstalled: '已卸载',\n} satisfies Record<string, string>\n\n/** English copy, checked complete against the zh key set. */\nconst STATIC_EN = {\n tab: 'Plugin manager',\n loading: 'Reading plugins…',\n empty: 'No user plugins installed yet.',\n userPlugins: 'User plugins',\n products: 'Built-in products',\n conflictTitle: 'Install conflicts',\n conflictDisabled: 'Automatically disabled {name} to avoid double mounting.',\n conflictEnabled: 'Re-enabled {name}.',\n conflictChanged: 'The state of {name} changed.',\n undoConflict: 'Undo',\n conflictHint: 'Conflict actions run automatically at install time; undoing writes the switch back and applies after a restart.',\n installPlaceholder: 'npm package (e.g. @scope/name) or git repository URL',\n install: 'Install',\n installing: 'Installing…',\n installHint: 'Find a plugin on GitHub or npm, then paste its npm package name or repository URL; plugins load after a restart.',\n version: 'Installed {version}',\n latest: 'Latest {version}',\n update: 'Update',\n updating: 'Updating…',\n checkUpdates: 'Check for updates',\n checking: 'Checking…',\n noUpdates: 'All plugins are up to date.',\n updateRequiresDsh: 'Requires DSH >= {min}',\n updateBlockedDsh: 'Requires DSH >= {min}; upgrade DSH before updating',\n uninstall: 'Uninstall',\n uninstallConfirmTitle: 'Uninstall plugin',\n uninstallConfirmBody: '{name} and its configuration row will be removed; the change applies after a restart.',\n confirm: 'Uninstall',\n cancel: 'Cancel',\n restartHint: 'Plugin changes take effect after restarting the application.',\n failed: 'Operation failed: {reason}',\n enabled: 'On',\n disabled: 'Off',\n mixed: 'Partially on',\n unavailable: 'Unavailable',\n uninstalled: 'Uninstalled',\n source: 'View source',\n applying: 'Applying change…',\n fetching: 'Fetching plugin metadata…',\n downloading: 'Downloading…',\n downloadingPercent: 'Downloading {percent}%',\n extracting: 'Extracting…',\n writing: 'Writing configuration…',\n localOnlyTitle: 'Available on this computer only',\n localOnlyBody: 'To protect host configuration, plugin management is only available from a local browser.',\n failureBadge: 'Startup failure',\n failureGroupTitle: 'Other startup failures',\n repair: 'Ask the agent to fix',\n repairing: 'Opening repair conversation…',\n copyError: 'Copy error',\n copied: 'Copied',\n safeModeBanner: 'Safe mode: user plugin configuration is skipped; plugin switches are disabled.',\n exitSafeMode: 'Restore normal mode and restart',\n npmSource: 'npm',\n gitSource: 'git',\n enableSwitch: 'Turn on {name}',\n disableSwitch: 'Turn off {name}',\n repairInstallTitle: 'The plugin installation failed. Please diagnose and fix it.',\n repairInstallSpecLabel: 'Install target',\n repairInstallErrorLabel: 'Error message',\n repairInstallAsk: 'Please inspect the plugin and reinstall it; tell me when it is done.',\n repairFailureTitle: 'A plugin failed to start last time. Please fix it.',\n repairFailurePluginLabel: 'Plugin',\n repairFailureKindLabel: 'Failure kind',\n repairFailureAtLabel: 'At',\n repairFailureMessageLabel: 'Failure details',\n repairFailureStackLabel: 'Original stack',\n repairFailurePathLabel: 'Plugin install directory',\n repairFailureAsk: 'Please inspect and fix the plugin; tell me how to re-enable it afterwards.',\n repairKindLoad: 'Load failure',\n repairKindHang: 'Startup hang',\n repairKindLate: 'Late rejection',\n repairConflictTitle: 'Handling a plugin install conflict',\n repairConflictPluginLabel: 'Conflicting entry',\n repairConflictChangeLabel: 'State change',\n repairConflictAsk: 'Inspect the entry ids and mounting of both sides, resolve the double mount, and tell me how to re-enable.',\n repairStateEnabled: 'On',\n repairStateDisabled: 'Off',\n repairStateUninstalled: 'Uninstalled',\n} satisfies Record<keyof typeof STATIC_ZH, string>\n\nexport const zh = STATIC_ZH\nexport const en = STATIC_EN\nexport type PluginManagerKey = keyof typeof STATIC_ZH\n","/**\n * Wire parsing for the official plugin-installer / plugin-control RPC\n * channels. This package is a browser-side consumer of those channels: every\n * response is decoded but untrusted, so each parser validates the shape it\n * needs and throws a typed error on mismatch. Callers treat a parse failure\n * as \"channel unavailable or drifted\" and degrade to command hints.\n *\n * The shapes mirror the official web installer tab's wire protocol (see the\n * DSH checkout's packages/client/ui-settings-plugin-installer/src/client/\n * protocol.ts); they are a contract observation, not an import.\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\n/** One installed user-plugin row served by `/plugin-installer list`. */\nexport interface InstalledPluginItem {\n id: string\n name: string\n version: string\n source: { kind: 'npm' | 'git'; spec: string }\n installedAt: string\n /** Saved next-start enablement from the managed profile patch row. */\n enabled: boolean\n commit?: string\n}\n\n/** Point-in-time install/update progress reported by the host. */\nexport interface InstallProgressItem {\n kind: 'idle' | 'install' | 'update'\n stage: 'fetch' | 'download' | 'extract' | 'write'\n percent?: number\n}\n\n/** One plugin with a newer version available. */\nexport interface PluginUpdateItem {\n id: string\n current: string\n latest: string\n /** Declared DSH minimum the update needs (package manifest's `dsh.engines.dsh`). */\n requiresDsh?: string\n /** Whether the running DSH host satisfies requiresDsh; absent when unknown. */\n compatible?: boolean\n}\n\n/** One recorded plugin boot failure served by the host. */\nexport interface PluginFailureItem {\n /** Installed plugin id (package name); empty for unattributable failures. */\n pluginId: string\n kind: 'load-failure' | 'hang' | 'late-rejection'\n message: string\n stack: string\n installPath: string\n at: string\n}\n\n/** Recovery facts served by the host: the failure ring, the plugin root, and safe mode. */\nexport interface PluginFailuresSnapshot {\n items: PluginFailureItem[]\n /** Absolute plugin install root — the repair conversation's workspace. */\n pluginRoot: string\n /** Whether the host is running in safe mode (user plugins skipped). */\n safeMode: boolean\n}\n\n/** One deployment-configured logical product switch. */\nexport interface PluginControlItem {\n id: string\n name: string\n repository: string\n state: 'enabled' | 'disabled' | 'mixed' | 'unavailable' | 'uninstalled'\n}\n\n/** Whether a decoded value is a non-array object. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Whether a decoded value is a string. */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string'\n}\n\n/** Validate one installed-plugin row. */\nfunction parsePlugin(value: unknown, index: number): InstalledPluginItem {\n if (!isRecord(value) || !isString(value.id) || !isString(value.name)\n || !isString(value.version) || !isString(value.installedAt)\n || typeof value.enabled !== 'boolean'\n || !isRecord(value.source) || (value.source.kind !== 'npm' && value.source.kind !== 'git')\n || !isString(value.source.spec)) {\n throw new Error(`plugin-manager: plugin row ${String(index)} is invalid`)\n }\n return {\n id: value.id,\n name: value.name,\n version: value.version,\n source: { kind: value.source.kind, spec: value.source.spec },\n installedAt: value.installedAt,\n enabled: value.enabled,\n ...isString(value.commit) ? { commit: value.commit } : {},\n }\n}\n\n/**\n * Validate and normalize a `list` / `uninstall` response value.\n * @param value - decoded but untrusted response value.\n * @returns typed installed-plugin rows.\n */\nexport function parsePluginList(value: unknown): InstalledPluginItem[] {\n if (!isRecord(value) || !Array.isArray(value.plugins)) {\n throw new Error('plugin-manager: response must contain a plugins array')\n }\n return value.plugins.map((plugin, index) => parsePlugin(plugin, index))\n}\n\n/**\n * Validate and normalize an `install` / `update` / `set-enabled` response value.\n * @param value - decoded but untrusted response value.\n * @returns the typed installed-plugin row.\n */\nexport function parseInstalledPlugin(value: unknown): InstalledPluginItem {\n if (!isRecord(value) || value.plugin === undefined) {\n throw new Error('plugin-manager: response must contain a plugin row')\n }\n return parsePlugin(value.plugin, 0)\n}\n\n/**\n * Validate and normalize a plugin-control `list` / `set-enabled` response value.\n * @param value - decoded but untrusted response value.\n * @returns the typed control items.\n */\nexport function parsePluginControlSnapshot(value: unknown): PluginControlItem[] {\n if (!isRecord(value) || !Array.isArray(value.controls)) {\n throw new Error('plugin-manager: response must contain a controls array')\n }\n return value.controls.map((control, index) => {\n if (!isRecord(control) || !isString(control.id) || !isString(control.name)\n || !isString(control.repository)\n || (control.state !== 'enabled' && control.state !== 'disabled'\n && control.state !== 'mixed' && control.state !== 'unavailable'\n && control.state !== 'uninstalled')) {\n throw new Error(`plugin-manager: control row ${String(index)} is invalid`)\n }\n return {\n id: control.id,\n name: control.name,\n repository: control.repository,\n state: control.state,\n }\n })\n}\n\n/**\n * Validate and normalize a `status` response value.\n * @param value - decoded but untrusted response value.\n * @returns the typed progress state.\n */\nexport function parseInstallStatus(value: unknown): InstallProgressItem {\n if (!isRecord(value) || !isRecord(value.progress)\n || (value.progress.kind !== 'idle' && value.progress.kind !== 'install' && value.progress.kind !== 'update')\n || (value.progress.stage !== 'fetch' && value.progress.stage !== 'download'\n && value.progress.stage !== 'extract' && value.progress.stage !== 'write')\n || (value.progress.percent !== undefined\n && (typeof value.progress.percent !== 'number' || !Number.isFinite(value.progress.percent)))) {\n throw new Error('plugin-manager: response must contain a valid progress state')\n }\n return {\n kind: value.progress.kind,\n stage: value.progress.stage,\n ...typeof value.progress.percent === 'number' ? { percent: value.progress.percent } : {},\n }\n}\n\n/**\n * Validate and normalize a `check-updates` response value.\n * @param value - decoded but untrusted response value.\n * @returns typed update rows.\n */\nexport function parseUpdateList(value: unknown): PluginUpdateItem[] {\n if (!isRecord(value) || !Array.isArray(value.updates)) {\n throw new Error('plugin-manager: response must contain an updates array')\n }\n return value.updates.map((update, index) => {\n if (!isRecord(update) || !isString(update.id) || !isString(update.current) || !isString(update.latest)) {\n throw new Error(`plugin-manager: update row ${String(index)} is invalid`)\n }\n const row: PluginUpdateItem = { id: update.id, current: update.current, latest: update.latest }\n if (update.requiresDsh !== undefined) {\n if (!isString(update.requiresDsh)) {\n throw new Error(`plugin-manager: update row ${String(index)} is invalid`)\n }\n row.requiresDsh = update.requiresDsh\n }\n if (update.compatible !== undefined) {\n if (typeof update.compatible !== 'boolean') {\n throw new Error(`plugin-manager: update row ${String(index)} is invalid`)\n }\n row.compatible = update.compatible\n }\n return row\n })\n}\n\n/**\n * Validate and normalize a `failures` response value.\n * @param value - decoded but untrusted response value.\n * @returns the typed failures snapshot.\n */\nexport function parseFailuresSnapshot(value: unknown): PluginFailuresSnapshot {\n if (!isRecord(value) || !Array.isArray(value.items)\n || !isString(value.pluginRoot) || typeof value.safeMode !== 'boolean') {\n throw new Error('plugin-manager: response must contain a failures snapshot')\n }\n return {\n items: value.items.map((item, index) => {\n if (!isRecord(item) || !isString(item.pluginId)\n || (item.kind !== 'load-failure' && item.kind !== 'hang' && item.kind !== 'late-rejection')\n || !isString(item.message) || !isString(item.stack)\n || !isString(item.installPath) || !isString(item.at)) {\n throw new Error(`plugin-manager: failure row ${String(index)} is invalid`)\n }\n return {\n pluginId: item.pluginId,\n kind: item.kind,\n message: item.message,\n stack: item.stack,\n installPath: item.installPath,\n at: item.at,\n }\n }),\n pluginRoot: value.pluginRoot,\n safeMode: value.safeMode,\n }\n}\n","/**\n * The cordis service contract this package exposes to sibling client plugins\n * under the name `'pluginManager'`. The browser half builds one dual-channel\n * face (official /plugin-installer + /plugin-control RPC channels when\n * available, else this package's loopback HTTP gateway) and provides it via\n * `ctx.provide('pluginManager', face)`; consumers resolve it with\n * `ctx.inject(['pluginManager'], cb)` and read `ctx.pluginManager`.\n *\n * The interface is intentionally narrower than the face the Plugin manager\n * tab receives (`PluginManagerFace` in the client half): it is the stable\n * cross-plugin surface, so it only carries the operations a sibling plugin\n * needs to observe and drive the installed-plugin set.\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\nimport type { InstallProgressItem, InstalledPluginItem, PluginFailuresSnapshot } from './protocol.ts'\n\n/** The cordis service name the browser half provides the face under. */\nexport const PLUGIN_MANAGER_SERVICE = 'pluginManager'\n\n/**\n * The dual-channel plugin-management face, shared between the Plugin manager\n * tab and sibling client plugins.\n */\nexport interface PluginManagerService {\n /** Whether this browser has loopback authority to use the host routes. */\n readonly isLoopback: boolean\n /** Read the installed snapshot. */\n list(): Promise<InstalledPluginItem[]>\n /** Install one plugin from an npm spec or git URL. */\n install(spec: string): Promise<InstalledPluginItem>\n /** Remove one plugin. */\n uninstall(id: string): Promise<InstalledPluginItem[]>\n /** Read the current install/update progress. */\n status(): Promise<InstallProgressItem>\n /**\n * Read the recorded plugin boot-failure ring (plugin id, message, stack,\n * install path). On runtimes without a failure ring the host answers an\n * empty snapshot.\n */\n failures(): Promise<PluginFailuresSnapshot>\n /**\n * Flip one plugin's next-start enablement through the active channel (the\n * official installer RPC when available, else the loopback gateway's patch\n * `disabled` override row). The change takes effect after the host restart;\n * a running plugin is not stopped.\n */\n setEnabled(id: string, enabled: boolean): Promise<InstalledPluginItem>\n /**\n * Subscribe to successful mutations: the callback runs after install(),\n * update(), uninstall(), or setEnabled() resolves. One listener throwing\n * never breaks the others. Returns the unsubscribe function.\n */\n onChange(cb: () => void): () => void\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n /** The plugin-manager face (provided by the dsh-plugin-manager client half). */\n pluginManager: PluginManagerService\n }\n}\n","/**\n * Plugin-manager browser half: contributes the family plugin-manager tab to\n * the official Plugins settings section (`settings.plugins.tab` slot) and\n * provides the same dual-channel face as the `'pluginManager'` cordis\n * service for sibling client plugins. It is dual-channel: on runtimes with\n * the official installer services (DSHCode, the 1.0.4 checkout web) every\n * operation rides the official `/plugin-installer` and `/plugin-control`\n * loopback RPC channels (the single writer); on the npm-published web runtime\n * those channels do not exist, so the same face falls back to this package's\n * own loopback HTTP gateway, which spawns the official CLI for writes.\n * Neither the tab nor service consumers know which mode the face runs in.\n * @module @linxin666/dsh-client-ui-plugin-manager/client\n */\n\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\n// Type-only: pulls the settings surface's slot contracts (settings.plugins.tab).\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\n// Type-only: pulls the client runtime Context merge (ctx.workspaces, ctx.sessions).\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\nimport type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'\nimport { PluginManagerTab, type PluginManagerTabInjected } from './PluginManagerTab.tsx'\nimport { en, zh, type PluginManagerKey } from './locales.ts'\nimport {\n parseFailuresSnapshot,\n parseInstallStatus,\n parseInstalledPlugin,\n parsePluginControlSnapshot,\n parsePluginList,\n parseUpdateList,\n type InstalledPluginItem,\n type InstallProgressItem,\n type PluginControlItem,\n type PluginFailuresSnapshot,\n type PluginUpdateItem,\n} from '../core/protocol.ts'\nimport { PLUGIN_MANAGER_SERVICE, type PluginManagerService } from '../core/service.ts'\nimport type { ControlChange } from '../core/conflict.ts'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** Copy for the family plugin-manager tab. */\n 'settings.pluginManager': PluginManagerKey\n }\n}\n\nconst NS = 'settings.pluginManager'\nconst CHANNEL = '/plugin-installer'\nconst CONTROL_CHANNEL = '/plugin-control'\nconst LIST_ENDPOINT = 'list'\nconst INSTALL_ENDPOINT = 'install'\nconst UPDATE_ENDPOINT = 'update'\nconst UNINSTALL_ENDPOINT = 'uninstall'\nconst SET_ENABLED_ENDPOINT = 'set-enabled'\nconst CHECK_UPDATES_ENDPOINT = 'check-updates'\nconst STATUS_ENDPOINT = 'status'\nconst FAILURES_ENDPOINT = 'failures'\nconst SET_SAFE_MODE_ENDPOINT = 'set-safe-mode'\n\nconst GATEWAY_PREFIX = '/api/plugin-manager'\n/** Gateway job polling cadence. */\nconst JOB_POLL_MS = 500\n/** Gateway job wait ceiling (the host add deadline is six minutes). */\nconst JOB_WAIT_MS = 7 * 60_000\n\n/** Services required by the slot registration and both channels. */\nexport const inject = ['slots', 'locale', 'connection', 'workspaces', 'sessions']\n\n/** The gateway job wire shape served by /status. */\ninterface GatewayJobWire {\n phase: 'running' | 'done' | 'error'\n plugin?: unknown\n conflicts?: unknown\n error?: string\n}\n\n/**\n * The face the Plugin manager tab and the `'pluginManager'` cordis service\n * share: the full tab surface plus the cross-plugin service contract.\n */\nexport type PluginManagerFace = PluginManagerTabInjected & PluginManagerService\n\n/**\n * Build the dual-channel face once: official-channel and gateway-channel\n * implementations, the mode detection that picks between them, the repair\n * handoff, and the change-notification listener set. The returned face is\n * both the tab's injected props and the value provided as the\n * `'pluginManager'` cordis service.\n * @param ctx - the client context (connection, workspaces, sessions).\n * @returns the shared face.\n */\nexport function createPluginManagerFace(ctx: ClientContext): PluginManagerFace {\n const connection = ctx.get('connection') as ConnectionHandle\n\n // ── official channel implementations ──────────────────────────────────────\n\n const call = async (endpoint: string, payload: unknown): Promise<unknown> => {\n const result = await connection.rpc.call(CHANNEL, endpoint, payload)\n if (!result.ok) {\n throw new Error(`plugin-installer ${endpoint} failed: ${result.error.code}: ${result.error.message}`)\n }\n return result.value\n }\n const official = {\n list: async (): Promise<InstalledPluginItem[]> => parsePluginList(await call(LIST_ENDPOINT, {})),\n install: async (spec: string): Promise<InstalledPluginItem> => parseInstalledPlugin(await call(INSTALL_ENDPOINT, { spec })),\n update: async (id: string): Promise<InstalledPluginItem> => parseInstalledPlugin(await call(UPDATE_ENDPOINT, { id })),\n uninstall: async (id: string): Promise<InstalledPluginItem[]> => parsePluginList(await call(UNINSTALL_ENDPOINT, { id })),\n setEnabled: async (id: string, enabled: boolean): Promise<InstalledPluginItem> =>\n parseInstalledPlugin(await call(SET_ENABLED_ENDPOINT, { id, enabled })),\n checkUpdates: async (): Promise<PluginUpdateItem[]> => parseUpdateList(await call(CHECK_UPDATES_ENDPOINT, {})),\n status: async (): Promise<InstallProgressItem> => parseInstallStatus(await call(STATUS_ENDPOINT, {})),\n failures: async (): Promise<PluginFailuresSnapshot> => parseFailuresSnapshot(await call(FAILURES_ENDPOINT, {})),\n setSafeMode: async (enabled: boolean): Promise<void> => {\n await call(SET_SAFE_MODE_ENDPOINT, { enabled })\n },\n controlsList: async (): Promise<PluginControlItem[]> =>\n parsePluginControlSnapshot(await connection.rpc.call(CONTROL_CHANNEL, 'list', {}).then(result => {\n if (!result.ok) throw new Error(`plugin-control list failed: ${result.error.code}: ${result.error.message}`)\n return result.value\n })),\n controlsSetEnabled: async (pluginId: string, enabled: boolean): Promise<PluginControlItem[]> =>\n parsePluginControlSnapshot(await connection.rpc.call(CONTROL_CHANNEL, 'set-enabled', { pluginId, enabled }).then(result => {\n if (!result.ok) throw new Error(`plugin-control set-enabled failed: ${result.error.code}: ${result.error.message}`)\n return result.value\n })),\n }\n\n // ── gateway channel implementations ──────────────────────────────────────\n\n const gatewayJson = async (path: string, init?: RequestInit): Promise<unknown> => {\n const response = await fetch(path, {\n ...init,\n headers: { 'content-type': 'application/json', ...init?.headers },\n })\n if (response.status === 403) {\n throw new Error('plugin-manager: plugin management is only available from a local browser')\n }\n if (!response.ok) {\n const body = await response.json().catch(() => ({})) as { error?: string }\n throw new Error(body.error ?? `plugin-manager: gateway ${path} failed: HTTP ${String(response.status)}`)\n }\n return response.json()\n }\n\n /** Wait for one gateway job to settle, returning its wire state. */\n const waitJob = async (jobId: string): Promise<GatewayJobWire> => {\n const deadline = Date.now() + JOB_WAIT_MS\n for (;;) {\n const body = await gatewayJson(`${GATEWAY_PREFIX}/status?job=${encodeURIComponent(jobId)}`) as { job?: GatewayJobWire }\n const job = body.job\n if (job === undefined) throw new Error('plugin-manager: gateway job vanished')\n if (job.phase === 'done') return job\n if (job.phase === 'error') throw new Error(job.error ?? 'plugin-manager: gateway job failed')\n if (Date.now() > deadline) throw new Error('plugin-manager: gateway job timed out')\n await new Promise(resolve => { setTimeout(resolve, JOB_POLL_MS) })\n }\n }\n\n /** The conflict ledger of the last settled gateway install. */\n let lastInstallConflicts: ControlChange[] = []\n /** Whether a gateway install/remove is in flight (drives the progress row). */\n let gatewayInflight = false\n\n const gateway = {\n list: async (): Promise<InstalledPluginItem[]> =>\n parsePluginList(await gatewayJson(`${GATEWAY_PREFIX}/list`)),\n install: async (spec: string): Promise<InstalledPluginItem> => {\n gatewayInflight = true\n try {\n const started = await gatewayJson(`${GATEWAY_PREFIX}/install`, {\n method: 'POST',\n body: JSON.stringify({ spec }),\n }) as { jobId?: string }\n if (started.jobId === undefined) throw new Error('plugin-manager: gateway install returned no job')\n const job = await waitJob(started.jobId)\n lastInstallConflicts = Array.isArray(job.conflicts) ? job.conflicts as ControlChange[] : []\n return parseInstalledPlugin({ plugin: job.plugin })\n } finally {\n gatewayInflight = false\n }\n },\n update: async (id: string): Promise<InstalledPluginItem> => {\n gatewayInflight = true\n try {\n const started = await gatewayJson(`${GATEWAY_PREFIX}/update`, {\n method: 'POST',\n body: JSON.stringify({ id }),\n }) as { jobId?: string }\n if (started.jobId === undefined) throw new Error('plugin-manager: gateway update returned no job')\n const job = await waitJob(started.jobId)\n lastInstallConflicts = Array.isArray(job.conflicts) ? job.conflicts as ControlChange[] : []\n return parseInstalledPlugin({ plugin: job.plugin })\n } finally {\n gatewayInflight = false\n }\n },\n uninstall: async (id: string): Promise<InstalledPluginItem[]> => {\n gatewayInflight = true\n try {\n const started = await gatewayJson(`${GATEWAY_PREFIX}/remove`, {\n method: 'POST',\n body: JSON.stringify({ id }),\n }) as { jobId?: string }\n if (started.jobId === undefined) throw new Error('plugin-manager: gateway remove returned no job')\n await waitJob(started.jobId)\n return gateway.list()\n } finally {\n gatewayInflight = false\n }\n },\n setEnabled: async (id: string, enabled: boolean): Promise<InstalledPluginItem> =>\n parseInstalledPlugin(await gatewayJson(`${GATEWAY_PREFIX}/set-enabled`, {\n method: 'POST',\n body: JSON.stringify({ id, enabled }),\n })),\n checkUpdates: async (): Promise<PluginUpdateItem[]> =>\n parseUpdateList(await gatewayJson(`${GATEWAY_PREFIX}/check-updates`)),\n status: async (): Promise<InstallProgressItem> =>\n gatewayInflight ? { kind: 'install', stage: 'download' } : { kind: 'idle', stage: 'fetch' },\n failures: async (): Promise<PluginFailuresSnapshot> =>\n parseFailuresSnapshot(await gatewayJson(`${GATEWAY_PREFIX}/failures`)),\n setSafeMode: async (): Promise<void> => {\n throw new Error('plugin-manager: safe mode is unavailable in this runtime')\n },\n controlsList: async (): Promise<PluginControlItem[]> => [],\n controlsSetEnabled: async (pluginId: string, enabled: boolean): Promise<PluginControlItem[]> => {\n await gateway.setEnabled(pluginId, enabled)\n return []\n },\n }\n\n // ── mode selection ────────────────────────────────────────────────────────\n\n let modePromise: Promise<'official' | 'gateway'> | undefined\n const ensureMode = (): Promise<'official' | 'gateway'> => {\n if (modePromise === undefined) {\n modePromise = (async () => {\n // Prefer the host verdict: the gateway's /mode route reports whether\n // the official installer channels exist, so the direct channel probe\n // below (which 405s into the browser console on the npm web runtime)\n // only runs when the host half is absent or explicitly returns null\n // for a desktop runtime whose services are registered in-process.\n try {\n const mode = await gatewayJson(`${GATEWAY_PREFIX}/mode`) as { official?: boolean | null }\n if (mode.official === true) return 'official' as const\n if (mode.official === false) return 'gateway' as const\n } catch {\n // Host half absent (an official runtime without a boot profile):\n // fall back to the direct channel probe.\n }\n try {\n const result = await connection.rpc.call(CHANNEL, LIST_ENDPOINT, {})\n return result.ok ? 'official' as const : 'gateway' as const\n } catch {\n return 'gateway' as const\n }\n })()\n }\n return modePromise\n }\n\n /**\n * Start a repair conversation for a failed plugin: resolve a workspace over\n * the plugin install root (created once, reused after), open a fresh\n * session there, and seed its first prompt with the failure details. The\n * session's workspace is the plugin home so the agent's file tools reach\n * the plugin code without leaving the workspace boundary.\n * @param pluginRoot - absolute plugin install root.\n * @param message - the seeded first user message.\n * @returns resolution after the prompt is accepted and the session opens.\n */\n const repairPlugin = async (pluginRoot: string, message: string): Promise<void> => {\n const workspace = await ctx.workspaces.create({ path: pluginRoot })\n const sessionId = await ctx.workspaces.connectWorkspace(workspace.workspaceId)\n const binding = ctx.sessions.binding(sessionId)\n if (binding === undefined) throw new Error(`plugin-manager: repair session ${sessionId} is unavailable`)\n const result = await binding.session.prompt([{ type: 'text', text: message }], 'queue')\n if (!result.ok) throw new Error(`plugin-manager: repair prompt failed: ${result.error.code}: ${result.error.message}`)\n ctx.sessions.open(sessionId)\n }\n\n // ── change notification ───────────────────────────────────────────────────\n\n /** Listeners subscribed through onChange; fired after successful mutations. */\n const listeners = new Set<() => void>()\n /** Notify every listener; one listener throwing never breaks the others. */\n const notifyChange = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener()\n } catch {\n // A consumer's listener failure is its own; keep notifying the rest.\n }\n }\n }\n\n // ── the shared face ───────────────────────────────────────────────────────\n\n return {\n isLoopback: connection.isLoopback,\n list: async () => (await ensureMode()) === 'official' ? official.list() : gateway.list(),\n install: async spec => {\n const item = await ((await ensureMode()) === 'official' ? official.install(spec) : gateway.install(spec))\n notifyChange()\n return item\n },\n update: async id => {\n const item = await ((await ensureMode()) === 'official' ? official.update(id) : gateway.update(id))\n notifyChange()\n return item\n },\n uninstall: async id => {\n const rows = await ((await ensureMode()) === 'official' ? official.uninstall(id) : gateway.uninstall(id))\n notifyChange()\n return rows\n },\n setEnabled: async (id, enabled) => {\n const item = await ((await ensureMode()) === 'official' ? official.setEnabled(id, enabled) : gateway.setEnabled(id, enabled))\n notifyChange()\n return item\n },\n checkUpdates: async () => (await ensureMode()) === 'official' ? official.checkUpdates() : gateway.checkUpdates(),\n status: async () => (await ensureMode()) === 'official' ? official.status() : gateway.status(),\n failures: async () => (await ensureMode()) === 'official' ? official.failures() : gateway.failures(),\n setSafeMode: async enabled => (await ensureMode()) === 'official' ? official.setSafeMode(enabled) : gateway.setSafeMode(),\n repairPlugin,\n controlsList: async () => (await ensureMode()) === 'official' ? official.controlsList() : gateway.controlsList(),\n controlsSetEnabled: async (id, enabled) => (await ensureMode()) === 'official' ? official.controlsSetEnabled(id, enabled) : gateway.controlsSetEnabled(id, enabled),\n lastInstallConflicts: () => lastInstallConflicts,\n onChange: cb => {\n listeners.add(cb)\n return () => { listeners.delete(cb) }\n },\n }\n}\n\n/** Contribute the family plugin-manager tab and provide the shared face. */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'plugin-manager: dictionaries')\n\n // Built once: the tab and the 'pluginManager' cordis service share one\n // face, so consumers observe exactly the mutations the tab performs.\n const face = createPluginManagerFace(ctx)\n ctx.provide(PLUGIN_MANAGER_SERVICE, face)\n\n ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({\n name: 'settings.plugins.tab',\n id: 'family-plugins',\n order: 20,\n label: () => ctx.locale.bind(NS)('tab'),\n locale: NS,\n inject: () => face,\n }, PluginManagerTab))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;EAsCA,SAAgB,aAAa,QAAsC,OAAsD;GACvH,MAAM,YAAY,IAAI,IAAI,MAAM,KAAI,SAAQ,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;GAC5D,MAAM,UAA2B,CAAC;GAClC,KAAK,MAAM,QAAQ,QAAQ;IACzB,MAAM,UAAU,UAAU,IAAI,KAAK,EAAE;IACrC,IAAI,YAAY,KAAA,K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,aAAa;IAC/G,QAAQ,YAAa,MAAM,WAAW,MAAO,aAAa,SAAS,OAAO,IAAI,QAAQ,OAAO;IAC7F,UAAU,YAAa,MAAM,WAAW,MAAO,aAAa,SAAS,SAAS,IAAI,QAAQ,SAAS;IACnG,aAAa,OAAM,YAAY,MAAM,WAAW,MAAO,aAAa,SAAS,YAAY,OAAO,IAAI,QAAQ,YAAY;IACxH;IACA,cAAc,YAAa,MAAM,WAAW,MAAO,aAAa,SAAS,aAAa,IAAI,QAAQ,aAAa;IAC/G,oBAAoB,OAAO,IAAI,YAAa,MAAM,WAAW,MAAO,aAAa,SAAS,mBAAmB,IAAI,OAAO,IAAI,QAAQ,mBAAmB,IAAI,OAAO;IAClK,4BAA4B;IAC5B,WAAU,OAAM;KACd,UAAU,IAAI,EAAE;KAChB,aAAa;MAAE,UAAU,OAAO,EAAE;KAAE;IACtC;GACF;EACF;;EAGA,SAAgB,MAAM,KAA0B;GAC9C,IAAI,aAAa,IAAI,OAAO,SAAS,IAAI;IAAE;IAAI;GAAG,CAAC,GAAG,8BAA8B;GAIpF,MAAM,OAAO,wBAAwB,GAAG;GACxC,IAAI,QAAQ,wBAAwB,IAAI;GAExC,IAAI,MAAM,OAAO,8BAA8B,IAAI,MAAM,SAAS;IAChE,MAAM;IACN,IAAI;IACJ,OAAO;IACP,aAAa,IAAI,OAAO,KAAK,EAAE,CAAC,CAAC,KAAK;IACtC,QAAQ;IACR,cAAc;GAChB,GAAG,gBAAgB,CAAC;EACtB"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["css","Button","Modal"],"sources":["../../../packages/dsh-plugin-manager/src/core/conflict.ts","../../../packages/dsh-plugin-manager/src/core/repair.ts","../../../packages/dsh-plugin-manager/src/core/version.ts","../../../packages/dsh-plugin-manager/src/client/PluginManagerTab.tsx","../../../packages/dsh-plugin-manager/src/client/locales.ts","../../../packages/dsh-plugin-manager/src/core/protocol.ts","../../../packages/dsh-plugin-manager/src/core/service.ts","../../../packages/dsh-plugin-manager/src/client/index.ts"],"sourcesContent":["/**\n * Conflict-ledger diffing. The official host applies structural conflict\n * rules at install time (disableControlsOnInstall: installing the dsh-web-ui\n * family disables the built-in web-ui product rows so the two never\n * double-mount), but no UI surfaces what the rules just did. This module\n * diffs the plugin-control snapshots taken before and after an install and\n * classifies every state change so the tab can render it as a reversible,\n * attributable conflict notice.\n *\n * The install-time authority ends here: duplicate insert-id claims between\n * two user plugins carry no at-install signal through the RPC channels (the\n * Loader only re-reads the composition at the next start), so that failure\n * shape is left to the boot-failure ring — the real start is the authoritative\n * conflict detector.\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\nimport type { PluginControlItem } from './protocol.ts'\n\n/** One observed product-control state change between two snapshots. */\nexport interface ControlChange {\n id: string\n name: string\n from: PluginControlItem['state']\n to: PluginControlItem['state']\n}\n\n/** Meaningful change kinds a conflict notice distinguishes. */\nexport type ControlChangeKind = 'rule-disabled' | 'rule-enabled' | 'state-change'\n\n/**\n * Diff two plugin-control snapshots by id. Only entries present in both\n * snapshots with a changed state are reported; entries appearing or\n * disappearing are ordinary install/uninstall outcomes, not conflicts.\n * @param before - snapshot taken before the install.\n * @param after - snapshot taken after the install.\n * @returns one change per id whose state moved, in id order.\n */\nexport function diffControls(before: readonly PluginControlItem[], after: readonly PluginControlItem[]): ControlChange[] {\n const afterById = new Map(after.map(item => [item.id, item]))\n const changes: ControlChange[] = []\n for (const item of before) {\n const current = afterById.get(item.id)\n if (current === undefined || current.state === item.state) continue\n changes.push({ id: item.id, name: item.name, from: item.state, to: current.state })\n }\n return changes\n}\n\n/**\n * Classify one control-state change for messaging. A change into `disabled`\n * is the conflict rule's action (reversible by re-enabling); a change out of\n * `disabled` is a manual undo; anything else is reported neutrally.\n * @param change - one diff entry.\n * @returns the message kind.\n */\nexport function classifyChange(change: ControlChange): ControlChangeKind {\n if (change.to === 'disabled') return 'rule-disabled'\n if (change.from === 'disabled') return 'rule-enabled'\n return 'state-change'\n}\n","/**\n * Repair-conversation seed text. Two failure surfaces hand off to the agent\n * through the same shape: a failed install (target spec + install error) and\n * a recorded boot failure (the failure-ring row). The seeded message must be\n * self-contained — the repair session's workspace is the plugin install root,\n * so the agent's file tools reach the plugin code without leaving the\n * workspace boundary.\n *\n * Secret discipline: the seed carries only the spec, the host's truncated\n * failure message/stack, and paths. Callers must never append credentials,\n * tokens, or environment contents; the failure ring is the host's bounded,\n * pruned record and nothing else is added.\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\nimport type { PluginFailureItem } from './protocol.ts'\nimport type { LayerState } from './patch-diff.ts'\n\n/** Localized fragments the builders assemble. */\nexport interface RepairCopy {\n installTitle: string\n installSpecLabel: string\n installErrorLabel: string\n installAsk: string\n failureTitle: string\n failurePluginLabel: string\n failureKindLabel: string\n failureAtLabel: string\n failureMessageLabel: string\n failureStackLabel: string\n failurePathLabel: string\n failureAsk: string\n conflictTitle: string\n conflictPluginLabel: string\n conflictChangeLabel: string\n conflictAsk: string\n /** Localized names of the failure kinds. */\n kindNames: Record<PluginFailureItem['kind'], string>\n /** Localized names of the layer states a conflict change traverses. */\n stateNames: Record<LayerState, string>\n}\n\n/** Default copy (zh): the package's zh dictionary keys map onto these strings. */\nexport const DEFAULT_REPAIR_COPY: RepairCopy = {\n installTitle: '正在修复插件安装失败',\n installSpecLabel: '安装目标',\n installErrorLabel: '安装错误',\n installAsk: '请在插件安装根目录内检查插件包或依赖并修复,然后重试安装。',\n failureTitle: '正在修复插件启动失败',\n failurePluginLabel: '插件',\n failureKindLabel: '失败类型',\n failureAtLabel: '时间',\n failureMessageLabel: '错误信息',\n failureStackLabel: '堆栈',\n failurePathLabel: '安装路径',\n failureAsk: '请修复插件后重新启用并重启 dsh web。',\n conflictTitle: '正在处理插件安装冲突',\n conflictPluginLabel: '冲突条目',\n conflictChangeLabel: '状态变化',\n conflictAsk: '请检查冲突双方的入口行 id 与挂载方式,消除重复挂载后告诉我如何重新启用。',\n kindNames: {\n 'load-failure': '加载失败',\n hang: '启动挂起',\n 'late-rejection': '迟到拒绝',\n },\n stateNames: {\n enabled: '已开启',\n disabled: '已关闭',\n uninstalled: '已卸载',\n },\n}\n\n/**\n * Seed text for a failed install: the target and the rendered error,\n * self-contained for the agent.\n * @param spec - the install target (npm spec or git URL) that failed.\n * @param error - the rendered install error text.\n * @param copy - localized fragments.\n * @returns the repair prompt text.\n */\nexport function installRepairMessage(spec: string, error: string, copy: RepairCopy = DEFAULT_REPAIR_COPY): string {\n return [\n copy.installTitle,\n `${copy.installSpecLabel}: ${spec}`,\n `${copy.installErrorLabel}:\\n${error}`,\n copy.installAsk,\n ].join('\\n\\n')\n}\n\n/**\n * Seed text for one boot-failure ring row: the failure record, so the agent\n * can attribute and fix it in place.\n * @param failure - the recorded failure row.\n * @param copy - localized fragments.\n * @returns the repair prompt text.\n */\nexport function failureRepairMessage(failure: PluginFailureItem, copy: RepairCopy = DEFAULT_REPAIR_COPY): string {\n const parts = [\n copy.failureTitle,\n `${copy.failurePluginLabel}: ${failure.pluginId || '-'}`,\n `${copy.failureKindLabel}: ${copy.kindNames[failure.kind] ?? failure.kind}`,\n `${copy.failureAtLabel}: ${failure.at}`,\n `${copy.failureMessageLabel}:\\n${failure.message}`,\n ]\n if (failure.stack !== '') parts.push(`${copy.failureStackLabel}:\\n${failure.stack}`)\n if (failure.installPath !== '') parts.push(`${copy.failurePathLabel}: ${failure.installPath}`)\n parts.push(copy.failureAsk)\n return parts.join('\\n\\n')\n}\n\n/**\n * Seed text for one install-conflict notice: the entry and its state change,\n * so the agent can attribute the conflict and resolve the double mount.\n * @param change - the conflict change (id, display name, from/to states).\n * @param copy - localized fragments.\n * @returns the repair prompt text.\n */\nexport function conflictRepairMessage(\n change: { id: string; name: string; from: LayerState; to: LayerState },\n copy: RepairCopy = DEFAULT_REPAIR_COPY,\n): string {\n return [\n copy.conflictTitle,\n `${copy.conflictPluginLabel}: ${change.name} (${change.id})`,\n `${copy.conflictChangeLabel}: ${copy.stateNames[change.from] ?? change.from} -> ${copy.stateNames[change.to] ?? change.to}`,\n copy.conflictAsk,\n ].join('\\n\\n')\n}\n","/**\n * DSH host version parsing and comparison for the update compatibility\n * check. The declared minimum lives in the published package manifest under\n * `dsh.engines.dsh`, falling back to the top-level `engines.dsh`; the only\n * supported form is `>=X.Y.Z[-prerelease]`.\n *\n * Comparison deliberately uses plain semver ordering instead of\n * `semver.satisfies`: npm's prerelease rule only allows a prerelease version\n * to satisfy a comparator set carrying a prerelease on the same\n * major.minor.patch tuple, which would reject a newer host line (0.1.1-rc.2)\n * against a declared `>=0.1.0-rc.8` — exactly the cross-cohort upgrade path\n * this check must allow. Everything here is pure and tolerant of untrusted\n * input: a malformed value means \"cannot verify\", which the callers treat as\n * a fail-closed verdict when a requirement was declared (issue #754).\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\n/** One parsed DSH host or package version. */\nexport interface DshVersion {\n major: number\n minor: number\n patch: number\n /** Prerelease identifiers, numeric identifiers kept as numbers (semver order). */\n prerelease: readonly (number | string)[]\n}\n\nconst VERSION_PATTERN = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?$/\n\n/**\n * Parse a DSH host or package version string.\n * @param value - e.g. `0.1.0-rc.8`, `v1.2.3`.\n * @returns the parsed version, or undefined when malformed.\n */\nexport function parseDshVersion(value: string): DshVersion | undefined {\n const match = VERSION_PATTERN.exec(value.trim())\n if (match === null) return undefined\n const prereleaseParts = match[4] === undefined ? [] : match[4].split('.')\n if (prereleaseParts.some(part => part === '')) return undefined\n return {\n major: Number(match[1]),\n minor: Number(match[2]),\n patch: Number(match[3]),\n prerelease: prereleaseParts.map(part => /^\\d+$/.test(part) ? Number(part) : part),\n }\n}\n\n/**\n * Compare two version strings by semver order (a release is newer than any\n * prerelease of the same tuple).\n * @returns -1 / 0 / 1, or undefined when either side is malformed.\n */\nexport function compareVersions(left: string, right: string): number | undefined {\n const a = parseDshVersion(left)\n const b = parseDshVersion(right)\n if (a === undefined || b === undefined) return undefined\n for (const key of ['major', 'minor', 'patch'] as const) {\n if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1\n }\n return comparePrerelease(a.prerelease, b.prerelease)\n}\n\n/**\n * Semver prerelease ordering: numeric identifiers compare numerically,\n * numeric identifiers rank below alphanumeric ones, alphanumeric identifiers\n * compare lexically, and a longer list wins when the shared prefix is equal.\n */\nfunction comparePrerelease(left: readonly (number | string)[], right: readonly (number | string)[]): number {\n if (left.length === 0 && right.length === 0) return 0\n if (left.length === 0) return 1\n if (right.length === 0) return -1\n const length = Math.max(left.length, right.length)\n for (let index = 0; index < length; index += 1) {\n const a = left[index]\n const b = right[index]\n if (a === undefined) return -1\n if (b === undefined) return 1\n if (typeof a === 'number' && typeof b === 'number') {\n if (a !== b) return a < b ? -1 : 1\n } else if (typeof a === 'number') {\n return -1\n } else if (typeof b === 'number') {\n return 1\n } else if (a !== b) {\n return a < b ? -1 : 1\n }\n }\n return 0\n}\n\nconst MINIMUM_RANGE_PATTERN = /^>=\\s*(v?\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)$/\n\n/**\n * Whether a host version satisfies a declared `>=X.Y.Z[-prerelease]` minimum.\n * @param host - the running DSH host version.\n * @param minimum - the declared minimum; any form other than `>=<semver>`\n * (plain semver, `^`, `~`, multi-comparator ranges, empty) returns undefined.\n * @returns true / false, or undefined when the host version is malformed or\n * the minimum uses an unsupported form — callers treat undefined as\n * \"cannot verify\" and fail closed for declared requirements.\n */\nexport function meetsMinimumDsh(host: string, minimum: string): boolean | undefined {\n const match = MINIMUM_RANGE_PATTERN.exec(minimum.trim())\n if (match === null) return undefined\n const compared = compareVersions(host, match[1])\n if (compared === undefined) return undefined\n return compared >= 0\n}\n\n/**\n * The bare minimum version for display: strips the `>=` operator (and an\n * optional leading `v`) from a declared requirement so UI copy that already\n * contains the comparison operator renders `0.1.1-rc.1` instead of\n * `>= >=0.1.1-rc.1`. Unsupported range forms render unchanged.\n * @param minimum - the declared minimum range.\n * @returns the version portion for display.\n */\nexport function displayMinimumVersion(minimum: string): string {\n const match = MINIMUM_RANGE_PATTERN.exec(minimum.trim())\n return match === null ? minimum.trim() : match[1].replace(/^v/, '')\n}\n\n/**\n * Read the declared DSH minimum from a published registry manifest:\n * `dsh.engines.dsh` first, top-level `engines.dsh` as the fallback.\n * Defensive against malformed or untrusted metadata: anything that is not a\n * non-empty string reads as absent.\n * @param manifest - the decoded registry version manifest.\n * @returns the declared minimum, or undefined when not declared.\n */\nexport function dshRequirementOf(manifest: { dsh?: unknown; engines?: unknown }): string | undefined {\n const dshEngines = (manifest.dsh as { engines?: unknown } | undefined)?.engines as { dsh?: unknown } | undefined\n const engines = (manifest.engines as { dsh?: unknown } | undefined)?.dsh\n const value = dshEngines?.dsh ?? engines\n return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined\n}\n","/**\n * The plugin-manager tab: an install box, one row per installed user plugin\n * (next-start enablement switch, source badge, update availability, update and\n * uninstall actions, per-plugin boot-failure block), the built-in product\n * switches, an install-conflict notice (the diff of the plugin-control\n * snapshot around each install, reversible through the product switch), and\n * the failure-repair affordances. Enablement switches and installs persist\n * through the official host channels and apply at the next restart; the web\n * build shows a restart hint instead of an in-place restart.\n *\n * This tab registers into the official Plugins settings section\n * (`settings.plugins.tab` slot) next to the official installer tab; its added\n * value over that tab is the conflict ledger, the bilingual repair seeds, and\n * the family card vocabulary.\n */\nimport { useEffect, useRef, useState } from 'react'\nimport { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport { classifyChange, diffControls, type ControlChange } from '../core/conflict.ts'\nimport type {\n InstallProgressItem,\n InstalledPluginItem,\n PluginControlItem,\n PluginFailureItem,\n PluginFailuresSnapshot,\n PluginUpdateItem,\n} from '../core/protocol.ts'\nimport { conflictRepairMessage, failureRepairMessage, installRepairMessage, type RepairCopy } from '../core/repair.ts'\nimport { displayMinimumVersion } from '../core/version.ts'\nimport css from './plugin-manager.module.css'\n\n/** Registration-side wire face used by the tab. */\nexport interface PluginManagerTabInjected {\n /** Whether this browser has loopback authority to use the host routes. */\n isLoopback: boolean\n /** Read the installed snapshot. */\n list: () => Promise<InstalledPluginItem[]>\n /** Install one plugin from an npm spec or git URL. */\n install: (spec: string) => Promise<InstalledPluginItem>\n /** Re-install one plugin from its recorded source. */\n update: (id: string) => Promise<InstalledPluginItem>\n /** Remove one plugin. */\n uninstall: (id: string) => Promise<InstalledPluginItem[]>\n /** Persist one user plugin's next-start enablement. */\n setEnabled: (id: string, enabled: boolean) => Promise<InstalledPluginItem>\n /** Compare installed versions against their sources. */\n checkUpdates: () => Promise<PluginUpdateItem[]>\n /** Read the current install/update progress. */\n status: () => Promise<InstallProgressItem>\n /** Read the recorded boot failures, plugin root, and safe-mode state. */\n failures: () => Promise<PluginFailuresSnapshot>\n /** Persist the safe-mode marker (web: applied at the next manual restart). */\n setSafeMode: (enabled: boolean) => Promise<void>\n /** Start a repair conversation over the plugin install root. */\n repairPlugin: (pluginRoot: string, message: string) => Promise<void>\n /** Read the deployment-configured built-in product switches. */\n controlsList: () => Promise<PluginControlItem[]>\n /** Persist one product's next-start enablement. */\n controlsSetEnabled: (pluginId: string, enabled: boolean) => Promise<PluginControlItem[]>\n /** Conflicts the gateway host computed around the last install (gateway mode only). */\n lastInstallConflicts?: () => readonly ControlChange[]\n}\n\n/** Full component props assembled by the Settings slot renderer. */\nexport type PluginManagerTabProps =\n PropsRuntime<'settings.plugins.tab'>\n & PropsLocale<'settings.pluginManager'>\n & InjectFace<PluginManagerTabInjected>\n\ntype ViewState =\n | { readonly status: 'loading' }\n | { readonly status: 'error' }\n | {\n readonly status: 'ready'\n readonly plugins: readonly InstalledPluginItem[]\n readonly controls: readonly PluginControlItem[]\n readonly failures: PluginFailuresSnapshot\n }\n\n/** One row operation in flight. */\ntype BusyAction = { readonly kind: 'install' | 'update' | 'uninstall' | 'check'; readonly id?: string }\n\n/** One enablement switch in flight: a user plugin or a built-in product. */\ntype ToggleBusy = { readonly kind: 'user' | 'product'; readonly id: string }\n\n/** One uninstall target awaiting confirmation. */\ninterface UninstallTarget {\n readonly id: string\n readonly name: string\n}\n\n/** Error text for a caught request or lifecycle failure. */\nfunction messageOf(error: unknown): string {\n if (error instanceof AggregateError) {\n const details = error.errors.map(messageOf).join('; ')\n return details === '' ? error.message : `${error.message}: ${details}`\n }\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Localized fragments for the repair seed builders, read from the tab's dictionaries. */\nfunction repairCopy(t: PluginManagerTabProps['t']): RepairCopy {\n return {\n installTitle: t('repairInstallTitle'),\n installSpecLabel: t('repairInstallSpecLabel'),\n installErrorLabel: t('repairInstallErrorLabel'),\n installAsk: t('repairInstallAsk'),\n failureTitle: t('repairFailureTitle'),\n failurePluginLabel: t('repairFailurePluginLabel'),\n failureKindLabel: t('repairFailureKindLabel'),\n failureAtLabel: t('repairFailureAtLabel'),\n failureMessageLabel: t('repairFailureMessageLabel'),\n failureStackLabel: t('repairFailureStackLabel'),\n failurePathLabel: t('repairFailurePathLabel'),\n failureAsk: t('repairFailureAsk'),\n kindNames: {\n 'load-failure': t('repairKindLoad'),\n hang: t('repairKindHang'),\n 'late-rejection': t('repairKindLate'),\n },\n conflictTitle: t('repairConflictTitle'),\n conflictPluginLabel: t('repairConflictPluginLabel'),\n conflictChangeLabel: t('repairConflictChangeLabel'),\n conflictAsk: t('repairConflictAsk'),\n stateNames: {\n enabled: t('repairStateEnabled'),\n disabled: t('repairStateDisabled'),\n uninstalled: t('repairStateUninstalled'),\n },\n }\n}\n\n/** Localized label for one install phase, with percent when the download has one. */\nfunction progressLabel(progress: InstallProgressItem, t: PluginManagerTabProps['t']): string {\n if (progress.stage === 'fetch') return t('fetching')\n if (progress.stage === 'extract') return t('extracting')\n if (progress.stage === 'write') return t('writing')\n return progress.percent === undefined ? t('downloading') : t('downloadingPercent', { percent: String(progress.percent) })\n}\n\n/** The plugin-manager settings tab. */\nexport function PluginManagerTab(props: PluginManagerTabProps) {\n const {\n t,\n isLoopback,\n list,\n install,\n update,\n uninstall,\n setEnabled,\n checkUpdates,\n status,\n failures,\n setSafeMode,\n repairPlugin,\n controlsList,\n controlsSetEnabled,\n lastInstallConflicts,\n } = props\n\n const [view, setView] = useState<ViewState>({ status: 'loading' })\n const [busy, setBusy] = useState<BusyAction | undefined>(undefined)\n const [toggleBusy, setToggleBusy] = useState<ToggleBusy | undefined>(undefined)\n const [error, setError] = useState<string | undefined>(undefined)\n const [failedSpec, setFailedSpec] = useState<string | undefined>(undefined)\n const [installError, setInstallError] = useState<string | undefined>(undefined)\n const [spec, setSpec] = useState('')\n const [dirty, setDirty] = useState(false)\n const [repairing, setRepairing] = useState<string | undefined>(undefined)\n const [copied, setCopied] = useState<string | undefined>(undefined)\n const [updates, setUpdates] = useState<ReadonlyMap<string, PluginUpdateItem>>(new Map())\n const [uninstallTarget, setUninstallTarget] = useState<UninstallTarget | undefined>(undefined)\n const [conflicts, setConflicts] = useState<readonly ControlChange[]>([])\n const [progress, setProgress] = useState<InstallProgressItem>({ kind: 'idle', stage: 'fetch' })\n /** Synchronous in-flight mirror of `busy`: the render-time guard alone lets a\n * click and an Enter land in the same frame and double-fire. */\n const busyRef = useRef(false)\n\n /** Reload every snapshot into the ready view. */\n const reload = async (): Promise<void> => {\n const [plugins, controls, failureSnapshot] = await Promise.all([list(), controlsList(), failures()])\n setView({ status: 'ready', plugins, controls, failures: failureSnapshot })\n }\n\n useEffect(() => {\n let cancelled = false\n void reload().catch(() => {\n if (!cancelled) setView({ status: 'error' })\n })\n return () => { cancelled = true }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [])\n\n /** One row/form operation: busy state, error row, dirty flag on success. */\n const run = async (action: BusyAction, body: () => Promise<void>): Promise<void> => {\n if (busyRef.current) return\n busyRef.current = true\n setBusy(action)\n setError(undefined)\n try {\n await body()\n setDirty(true)\n } catch (reason) {\n setError(t('failed', { reason: messageOf(reason) }))\n } finally {\n busyRef.current = false\n setBusy(undefined)\n }\n }\n\n /** Install one spec, then diff the product snapshot into a conflict notice. */\n const onInstall = (): void => {\n const target = spec.trim()\n if (target === '' || busy !== undefined || busyRef.current) return\n void (async () => {\n busyRef.current = true\n const before = view.status === 'ready' ? view.controls : await controlsList().catch(() => [])\n setBusy({ kind: 'install' })\n setError(undefined)\n setFailedSpec(undefined)\n setInstallError(undefined)\n try {\n await install(target)\n setSpec('')\n setDirty(true)\n const after = await controlsList().catch(() => [] as readonly PluginControlItem[])\n setConflicts(lastInstallConflicts !== undefined ? lastInstallConflicts() : diffControls(before, after))\n await reload()\n } catch (reason) {\n const reasonText = messageOf(reason)\n setFailedSpec(target)\n setInstallError(reasonText)\n setError(t('failed', { reason: reasonText }))\n } finally {\n busyRef.current = false\n setBusy(undefined)\n }\n })()\n }\n\n /** Poll install/update progress while such an operation is in flight. */\n useEffect(() => {\n if (busy === undefined || (busy.kind !== 'install' && busy.kind !== 'update')) {\n setProgress({ kind: 'idle', stage: 'fetch' })\n return\n }\n let stopped = false\n let timer: ReturnType<typeof setTimeout> | undefined\n const tick = (delay: number): void => {\n timer = setTimeout(() => {\n void status().then(next => {\n if (!stopped && next !== undefined) {\n setProgress(next)\n tick(400)\n }\n }).catch(() => { /* status polling fails silently; the operation itself owns the error row */ })\n }, delay)\n }\n tick(100)\n return () => {\n stopped = true\n if (timer !== undefined) clearTimeout(timer)\n }\n }, [busy, status])\n\n const toggleDisabled = busy !== undefined || toggleBusy !== undefined\n || (view.status === 'ready' && view.failures.safeMode)\n\n const onUserToggle = (id: string, enabled: boolean): void => {\n setToggleBusy({ kind: 'user', id })\n setError(undefined)\n void setEnabled(id, enabled).then(plugin => {\n setView(current => current.status === 'ready'\n ? { ...current, plugins: current.plugins.map(item => item.id === id ? plugin : item) }\n : current)\n setDirty(true)\n setToggleBusy(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setToggleBusy(undefined)\n })\n }\n\n const onProductToggle = (id: string, enabled: boolean): void => {\n setToggleBusy({ kind: 'product', id })\n setError(undefined)\n void controlsSetEnabled(id, enabled).then(controls => {\n setView(current => current.status === 'ready' ? { ...current, controls } : current)\n setConflicts(previous => previous.filter(change => change.id !== id))\n setDirty(true)\n setToggleBusy(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setToggleBusy(undefined)\n })\n }\n\n const onCheck = (): void => {\n void run({ kind: 'check' }, async () => {\n const found = await checkUpdates()\n setUpdates(new Map(found.map(item => [item.id, item])))\n })\n }\n\n const onUpdate = (id: string): void => {\n void run({ kind: 'update', id }, async () => {\n await update(id)\n setUpdates(previous => {\n const next = new Map(previous)\n next.delete(id)\n return next\n })\n await reload()\n })\n }\n\n const onUninstall = (): void => {\n const target = uninstallTarget\n if (target === undefined) return\n void run({ kind: 'uninstall', id: target.id }, async () => {\n await uninstall(target.id)\n setUninstallTarget(undefined)\n await reload()\n })\n }\n\n /** Open a repair conversation seeded with one boot-failure record. `token`\n * identifies the row for the in-flight label (plugin id, or a row key for\n * unattributable failures). */\n const onRepair = (failure: PluginFailureItem, token: string): void => {\n if (view.status !== 'ready' || busy !== undefined || repairing !== undefined) return\n setError(undefined)\n setRepairing(token)\n void repairPlugin(view.failures.pluginRoot, failureRepairMessage(failure, repairCopy(t))).then(() => {\n setRepairing(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setRepairing(undefined)\n })\n }\n\n /** Hand the latest failed install off to a repair conversation over the\n * install root. The seed carries the install's own error (installError), not\n * whatever error the row currently shows. */\n const onRepairInstall = (): void => {\n if (view.status !== 'ready' || repairing !== undefined) return\n setError(undefined)\n setRepairing('install')\n void repairPlugin(view.failures.pluginRoot, installRepairMessage(failedSpec ?? '', installError ?? '', repairCopy(t))).then(() => {\n setError(undefined)\n setFailedSpec(undefined)\n setInstallError(undefined)\n setRepairing(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setRepairing(undefined)\n })\n }\n\n /** Copy a boot failure's message and stack for a manual repair conversation. */\n const onCopy = (failure: PluginFailureItem, token: string): void => {\n void navigator.clipboard.writeText(`${failure.message}\\n\\n${failure.stack}`).then(() => {\n setCopied(token)\n }).catch(() => {\n setError(t('failed', { reason: 'clipboard unavailable' }))\n })\n }\n\n const onExitSafeMode = (): void => {\n if (busy !== undefined) return\n setError(undefined)\n void setSafeMode(false).then(() => {\n setDirty(true)\n void reload().catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n })\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n })\n }\n\n /** Undo one conflict action by flipping the product switch back. */\n const onUndoConflict = (change: ControlChange): void => {\n if (change.to !== 'disabled') return\n onProductToggle(change.id, true)\n }\n\n /** Hand one conflict notice off to a repair conversation over the plugin root. */\n const onRepairConflict = (change: ControlChange): void => {\n if (view.status !== 'ready' || busy !== undefined || repairing !== undefined) return\n setError(undefined)\n const token = `conflict:${change.id}`\n setRepairing(token)\n void repairPlugin(view.failures.pluginRoot, conflictRepairMessage({\n id: change.id,\n name: change.name,\n from: change.from === 'enabled' || change.from === 'disabled' ? change.from : 'uninstalled',\n to: change.to === 'enabled' || change.to === 'disabled' ? change.to : 'uninstalled',\n }, repairCopy(t))).then(() => {\n setRepairing(undefined)\n }).catch(reason => {\n setError(t('failed', { reason: messageOf(reason) }))\n setRepairing(undefined)\n })\n }\n\n if (!isLoopback) {\n return (\n <div className={css.notice}>\n <strong>{t('localOnlyTitle')}</strong>\n <p>{t('localOnlyBody')}</p>\n </div>\n )\n }\n if (view.status === 'loading') return <div className={css.state}>{t('loading')}</div>\n if (view.status === 'error') return <div className={css.state}>{t('failed', { reason: 'load' })}</div>\n\n const attributable = new Map(view.failures.items.filter(item => item.pluginId !== '').map(item => [item.pluginId, item]))\n const unattributable = view.failures.items.filter(item => item.pluginId === '')\n\n return (\n <div className={css.section} aria-busy={busy !== undefined || toggleBusy !== undefined}>\n {view.failures.safeMode && (\n <div className={css.safeModeBanner} data-safe-mode>\n <p>{t('safeModeBanner')}</p>\n <Button variant=\"primary\" disabled={busy !== undefined} onClick={onExitSafeMode}>\n {t('exitSafeMode')}\n </Button>\n </div>\n )}\n\n <div className={css.installRow}>\n <input\n className={css.spec}\n type=\"text\"\n value={spec}\n placeholder={t('installPlaceholder')}\n disabled={busy !== undefined}\n onChange={event => { setSpec(event.target.value) }}\n onKeyDown={event => {\n if (event.key === 'Enter' && spec.trim() !== '' && busy === undefined) onInstall()\n }}\n />\n <Button\n variant=\"primary\"\n disabled={spec.trim() === '' || busy !== undefined}\n onClick={onInstall}\n >\n {busy !== undefined && busy.kind === 'install' ? t('installing') : t('install')}\n </Button>\n </div>\n <p className={css.hint}>{t('installHint')}</p>\n\n {(busy?.kind === 'install' || busy?.kind === 'update') && (\n <div className={css.progressRow} role=\"status\">\n <div className={css.progressTrack}>\n <div\n className={css.progressBar}\n style={progress.percent === undefined ? undefined : { width: `${progress.percent}%` }}\n data-indeterminate={progress.percent === undefined ? 'true' : undefined}\n />\n </div>\n <p className={css.progressLabel}>{progressLabel(progress, t)}</p>\n </div>\n )}\n\n {error !== undefined && (\n <div className={css.errorRow}>\n <span className={css.error}>{error}</span>\n {failedSpec !== undefined && (\n <Button variant=\"outline\" disabled={repairing !== undefined} onClick={onRepairInstall}>\n {repairing === 'install' ? t('repairing') : t('repair')}\n </Button>\n )}\n </div>\n )}\n\n {conflicts.length > 0 && (\n <div className={css.conflicts}>\n <h3 className={css.sectionTitle}>{t('conflictTitle')}</h3>\n <ul className={css.list}>\n {conflicts.map(change => (\n <li key={change.id} className={css.row} data-conflict={change.id}>\n <div className={css.meta}>\n <span className={css.name}>{change.name}</span>\n <span className={css.sub}>\n {classifyChange(change) === 'rule-disabled'\n ? t('conflictDisabled', { name: change.name })\n : classifyChange(change) === 'rule-enabled'\n ? t('conflictEnabled', { name: change.name })\n : t('conflictChanged', { name: change.name })}\n </span>\n </div>\n <div className={css.actions}>\n {change.to === 'disabled' && (\n <Button\n variant=\"outline\"\n disabled={toggleDisabled}\n onClick={() => { onUndoConflict(change) }}\n >\n {t('undoConflict')}\n </Button>\n )}\n <Button\n variant=\"outline\"\n disabled={busy !== undefined || repairing !== undefined}\n onClick={() => { onRepairConflict(change) }}\n >\n {repairing === `conflict:${change.id}` ? t('repairing') : t('repair')}\n </Button>\n </div>\n </li>\n ))}\n </ul>\n <p className={css.hint}>{t('conflictHint')}</p>\n </div>\n )}\n\n <div className={css.group}>\n <h3 className={css.sectionTitle}>{t('userPlugins')}</h3>\n {view.plugins.length === 0\n ? <p className={css.empty}>{t('empty')}</p>\n : (\n <ul className={css.list}>\n {view.plugins.map(plugin => {\n const updateItem = updates.get(plugin.id)\n const latest = updateItem?.latest\n const dshRequirement = updateItem?.requiresDsh\n const failure = attributable.get(plugin.id)\n return (\n <li key={plugin.id} className={css.row} data-plugin-id={plugin.id}>\n <div className={css.meta}>\n <span className={css.name}>{plugin.name}</span>\n <span className={css.sub}>\n <span className={css.version}>{t('version', { version: plugin.version })}</span>\n <span className={css.sourceBadge} data-source={plugin.source.kind}>\n {plugin.source.kind === 'npm' ? t('npmSource') : t('gitSource')}\n </span>\n <span className={css.specText} title={plugin.source.spec}>{plugin.source.spec}</span>\n </span>\n {latest !== undefined && <span className={css.latest}>{t('latest', { version: latest })}</span>}\n {updateItem !== undefined && dshRequirement !== undefined && (\n <span className={updateItem.compatible === false ? css.compatBlocked : css.compatHint}>\n {updateItem.compatible === false\n ? t('updateBlockedDsh', { min: displayMinimumVersion(dshRequirement) })\n : t('updateRequiresDsh', { min: displayMinimumVersion(dshRequirement) })}\n </span>\n )}\n {failure !== undefined && (\n <div className={css.failure} data-plugin-failure={plugin.id}>\n <span className={css.badge}>{t('failureBadge')}</span>\n <span className={css.failureMessage} title={failure.message}>{failure.message}</span>\n <div className={css.failureActions}>\n <Button\n variant=\"primary\"\n disabled={busy !== undefined || repairing !== undefined}\n onClick={() => { onRepair(failure, plugin.id) }}\n >\n {repairing === plugin.id ? t('repairing') : t('repair')}\n </Button>\n <Button variant=\"outline\" disabled={busy !== undefined} onClick={() => { onCopy(failure, plugin.id) }}>\n {copied === plugin.id ? t('copied') : t('copyError')}\n </Button>\n </div>\n </div>\n )}\n </div>\n <div className={css.actions}>\n <span className={css.stateLabel} data-state={plugin.enabled ? 'enabled' : 'disabled'}>\n {plugin.enabled ? t('enabled') : t('disabled')}\n </span>\n <button\n type=\"button\"\n role=\"switch\"\n aria-checked={plugin.enabled}\n aria-label={plugin.enabled ? t('disableSwitch', { name: plugin.name }) : t('enableSwitch', { name: plugin.name })}\n className={css.switch}\n disabled={toggleDisabled}\n onClick={() => { onUserToggle(plugin.id, !plugin.enabled) }}\n />\n {latest !== undefined && (\n <Button\n variant=\"outline\"\n disabled={busy !== undefined || updateItem?.compatible === false}\n onClick={() => { onUpdate(plugin.id) }}\n >\n {busy?.kind === 'update' && busy.id === plugin.id ? t('updating') : t('update')}\n </Button>\n )}\n <Button\n variant=\"outline\"\n disabled={busy !== undefined}\n onClick={() => { setUninstallTarget({ id: plugin.id, name: plugin.name }) }}\n >\n {t('uninstall')}\n </Button>\n </div>\n </li>\n )\n })}\n </ul>\n )}\n </div>\n\n {view.controls.length > 0 && (\n <div className={css.group}>\n <h3 className={css.sectionTitle}>{t('products')}</h3>\n <ul className={css.list}>\n {view.controls.map(control => (\n <li key={control.id} className={css.row} data-product-id={control.id}>\n <div className={css.meta}>\n <span className={css.name}>{control.name}</span>\n <span className={css.sub}>\n <a className={css.link} href={control.repository} target=\"_blank\" rel=\"noreferrer\">{t('source')}</a>\n </span>\n </div>\n <div className={css.actions}>\n <span className={css.stateLabel} data-state={control.state}>\n {t(control.state)}\n </span>\n {control.state === 'enabled' || control.state === 'disabled'\n ? (\n <button\n type=\"button\"\n role=\"switch\"\n aria-checked={control.state === 'enabled'}\n aria-label={control.state === 'enabled'\n ? t('disableSwitch', { name: control.name })\n : t('enableSwitch', { name: control.name })}\n className={css.switch}\n disabled={toggleDisabled}\n onClick={() => { onProductToggle(control.id, control.state !== 'enabled') }}\n />\n )\n : null}\n </div>\n </li>\n ))}\n </ul>\n </div>\n )}\n\n {unattributable.length > 0 && (\n <div className={css.group}>\n <h3 className={css.sectionTitle}>{t('failureGroupTitle')}</h3>\n <ul className={css.list}>\n {unattributable.map((failure, index) => {\n const token = `other:${index}`\n return (\n <li key={`${failure.at}-${index}`} className={css.row} data-plugin-failure=\"other\">\n <div className={css.meta}>\n <span className={css.badge}>{t('failureBadge')}</span>\n <span className={css.failureMessage} title={failure.message}>{failure.message}</span>\n <div className={css.failureActions}>\n <Button\n variant=\"primary\"\n disabled={busy !== undefined || repairing !== undefined}\n onClick={() => { onRepair(failure, token) }}\n >\n {repairing === token ? t('repairing') : t('repair')}\n </Button>\n <Button variant=\"outline\" disabled={busy !== undefined} onClick={() => { onCopy(failure, token) }}>\n {copied === token ? t('copied') : t('copyError')}\n </Button>\n </div>\n </div>\n </li>\n )\n })}\n </ul>\n </div>\n )}\n\n <div className={css.actionsRow}>\n <Button variant=\"outline\" disabled={busy !== undefined} onClick={onCheck}>\n {busy?.kind === 'check' ? t('checking') : t('checkUpdates')}\n </Button>\n {updates.size === 0 && busy === undefined && view.plugins.length > 0 && (\n <p className={css.ok}>{t('noUpdates')}</p>\n )}\n </div>\n\n {toggleBusy !== undefined && <p className={css.applying} aria-live=\"polite\">{t('applying')}</p>}\n\n {dirty && (\n <div className={css.restartRow}>\n <p>{t('restartHint')}</p>\n </div>\n )}\n\n <Modal\n title={t('uninstallConfirmTitle')}\n open={uninstallTarget !== undefined}\n onClose={() => { setUninstallTarget(undefined) }}\n >\n <p className={css.confirmBody}>{t('uninstallConfirmBody', { name: uninstallTarget?.name ?? '' })}</p>\n <div className={css.modalActions}>\n <Button variant=\"outline\" disabled={busy !== undefined} onClick={() => { setUninstallTarget(undefined) }}>\n {t('cancel')}\n </Button>\n <Button variant=\"primary\" className={css.dangerButton} disabled={busy !== undefined} onClick={onUninstall}>\n {t('confirm')}\n </Button>\n </div>\n </Modal>\n </div>\n )\n}\n","/**\n * Locale dictionaries for the plugin-manager tab. The zh dictionary is the\n * key source; the en dictionary mirrors the exact key set.\n * @module @linxin666/dsh-client-ui-plugin-manager/client\n */\n\n/** Simplified Chinese copy (the key-set source of truth). */\nconst STATIC_ZH = {\n tab: '插件管理',\n loading: '正在读取插件…',\n empty: '尚未安装任何用户插件。',\n userPlugins: '用户插件',\n products: '内置产品',\n conflictTitle: '安装冲突',\n conflictDisabled: '已自动禁用 {name},避免重复挂载。',\n conflictEnabled: '已重新启用 {name}。',\n conflictChanged: '{name} 的状态已变更。',\n undoConflict: '撤销',\n conflictHint: '冲突动作在安装时自动执行,撤销会写回开关并在重启后生效。',\n installPlaceholder: 'npm 包名(如 @scope/name)或 git 仓库 URL',\n install: '安装',\n installing: '安装中…',\n installHint: '在 GitHub 或 npm 找到插件后,粘贴其 npm 包名或仓库地址安装;应用重启后插件生效。',\n version: '已安装 {version}',\n latest: '最新 {version}',\n update: '更新',\n updating: '更新中…',\n checkUpdates: '检查更新',\n checking: '检查中…',\n noUpdates: '所有插件都是最新版本。',\n updateRequiresDsh: '需要 DSH ≥ {min}',\n updateBlockedDsh: '需要 DSH ≥ {min},请先升级 DSH 再更新',\n uninstall: '卸载',\n uninstallConfirmTitle: '卸载插件',\n uninstallConfirmBody: '将删除 {name} 的安装目录与配置行,并在重启后生效。',\n confirm: '确认卸载',\n cancel: '取消',\n restartHint: '插件变更将在重启应用后生效。',\n failed: '操作失败:{reason}',\n enabled: '已开启',\n disabled: '已关闭',\n mixed: '部分开启',\n unavailable: '不可用',\n uninstalled: '已卸载',\n source: '查看源码',\n applying: '正在应用更改…',\n fetching: '正在获取插件信息…',\n downloading: '正在下载…',\n downloadingPercent: '正在下载 {percent}%',\n extracting: '正在解压…',\n writing: '正在写入配置…',\n localOnlyTitle: '仅限本机操作',\n localOnlyBody: '为了保护主机配置,插件管理只能从本机打开。',\n failureBadge: '启动失败',\n failureGroupTitle: '其他启动失败',\n repair: '让 Agent 修复',\n repairing: '正在创建修复对话…',\n copyError: '复制错误',\n copied: '已复制',\n safeModeBanner: '安全模式:用户插件配置已跳过,插件开关不可用。',\n exitSafeMode: '恢复正常模式并重启',\n npmSource: 'npm',\n gitSource: 'git',\n enableSwitch: '开启 {name}',\n disableSwitch: '关闭 {name}',\n repairInstallTitle: '插件安装失败,请帮我诊断并修复。',\n repairInstallSpecLabel: '安装目标',\n repairInstallErrorLabel: '错误信息',\n repairInstallAsk: '请检查该插件并重新安装;完成后告诉我结果。',\n repairFailureTitle: '插件上次启动失败。请修复它。',\n repairFailurePluginLabel: '插件',\n repairFailureKindLabel: '失败类型',\n repairFailureAtLabel: '时间',\n repairFailureMessageLabel: '失败详情',\n repairFailureStackLabel: '原始堆栈',\n repairFailurePathLabel: '插件安装目录',\n repairFailureAsk: '请检查并修复该插件;修复完成后告诉我如何重新启用。',\n repairKindLoad: '加载失败',\n repairKindHang: '启动挂起',\n repairKindLate: '迟到拒绝',\n repairConflictTitle: '正在处理插件安装冲突',\n repairConflictPluginLabel: '冲突条目',\n repairConflictChangeLabel: '状态变化',\n repairConflictAsk: '请检查冲突双方的入口行 id 与挂载方式,消除重复挂载后告诉我如何重新启用。',\n repairStateEnabled: '已开启',\n repairStateDisabled: '已关闭',\n repairStateUninstalled: '已卸载',\n} satisfies Record<string, string>\n\n/** English copy, checked complete against the zh key set. */\nconst STATIC_EN = {\n tab: 'Plugin manager',\n loading: 'Reading plugins…',\n empty: 'No user plugins installed yet.',\n userPlugins: 'User plugins',\n products: 'Built-in products',\n conflictTitle: 'Install conflicts',\n conflictDisabled: 'Automatically disabled {name} to avoid double mounting.',\n conflictEnabled: 'Re-enabled {name}.',\n conflictChanged: 'The state of {name} changed.',\n undoConflict: 'Undo',\n conflictHint: 'Conflict actions run automatically at install time; undoing writes the switch back and applies after a restart.',\n installPlaceholder: 'npm package (e.g. @scope/name) or git repository URL',\n install: 'Install',\n installing: 'Installing…',\n installHint: 'Find a plugin on GitHub or npm, then paste its npm package name or repository URL; plugins load after a restart.',\n version: 'Installed {version}',\n latest: 'Latest {version}',\n update: 'Update',\n updating: 'Updating…',\n checkUpdates: 'Check for updates',\n checking: 'Checking…',\n noUpdates: 'All plugins are up to date.',\n updateRequiresDsh: 'Requires DSH >= {min}',\n updateBlockedDsh: 'Requires DSH >= {min}; upgrade DSH before updating',\n uninstall: 'Uninstall',\n uninstallConfirmTitle: 'Uninstall plugin',\n uninstallConfirmBody: '{name} and its configuration row will be removed; the change applies after a restart.',\n confirm: 'Uninstall',\n cancel: 'Cancel',\n restartHint: 'Plugin changes take effect after restarting the application.',\n failed: 'Operation failed: {reason}',\n enabled: 'On',\n disabled: 'Off',\n mixed: 'Partially on',\n unavailable: 'Unavailable',\n uninstalled: 'Uninstalled',\n source: 'View source',\n applying: 'Applying change…',\n fetching: 'Fetching plugin metadata…',\n downloading: 'Downloading…',\n downloadingPercent: 'Downloading {percent}%',\n extracting: 'Extracting…',\n writing: 'Writing configuration…',\n localOnlyTitle: 'Available on this computer only',\n localOnlyBody: 'To protect host configuration, plugin management is only available from a local browser.',\n failureBadge: 'Startup failure',\n failureGroupTitle: 'Other startup failures',\n repair: 'Ask the agent to fix',\n repairing: 'Opening repair conversation…',\n copyError: 'Copy error',\n copied: 'Copied',\n safeModeBanner: 'Safe mode: user plugin configuration is skipped; plugin switches are disabled.',\n exitSafeMode: 'Restore normal mode and restart',\n npmSource: 'npm',\n gitSource: 'git',\n enableSwitch: 'Turn on {name}',\n disableSwitch: 'Turn off {name}',\n repairInstallTitle: 'The plugin installation failed. Please diagnose and fix it.',\n repairInstallSpecLabel: 'Install target',\n repairInstallErrorLabel: 'Error message',\n repairInstallAsk: 'Please inspect the plugin and reinstall it; tell me when it is done.',\n repairFailureTitle: 'A plugin failed to start last time. Please fix it.',\n repairFailurePluginLabel: 'Plugin',\n repairFailureKindLabel: 'Failure kind',\n repairFailureAtLabel: 'At',\n repairFailureMessageLabel: 'Failure details',\n repairFailureStackLabel: 'Original stack',\n repairFailurePathLabel: 'Plugin install directory',\n repairFailureAsk: 'Please inspect and fix the plugin; tell me how to re-enable it afterwards.',\n repairKindLoad: 'Load failure',\n repairKindHang: 'Startup hang',\n repairKindLate: 'Late rejection',\n repairConflictTitle: 'Handling a plugin install conflict',\n repairConflictPluginLabel: 'Conflicting entry',\n repairConflictChangeLabel: 'State change',\n repairConflictAsk: 'Inspect the entry ids and mounting of both sides, resolve the double mount, and tell me how to re-enable.',\n repairStateEnabled: 'On',\n repairStateDisabled: 'Off',\n repairStateUninstalled: 'Uninstalled',\n} satisfies Record<keyof typeof STATIC_ZH, string>\n\nexport const zh = STATIC_ZH\nexport const en = STATIC_EN\nexport type PluginManagerKey = keyof typeof STATIC_ZH\n","/**\n * Wire parsing for the official plugin-installer / plugin-control RPC\n * channels. This package is a browser-side consumer of those channels: every\n * response is decoded but untrusted, so each parser validates the shape it\n * needs and throws a typed error on mismatch. Callers treat a parse failure\n * as \"channel unavailable or drifted\" and degrade to command hints.\n *\n * The shapes mirror the official web installer tab's wire protocol (see the\n * DSH checkout's packages/client/ui-settings-plugin-installer/src/client/\n * protocol.ts); they are a contract observation, not an import.\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\n/** One installed user-plugin row served by `/plugin-installer list`. */\nexport interface InstalledPluginItem {\n id: string\n name: string\n version: string\n source: { kind: 'npm' | 'git'; spec: string }\n installedAt: string\n /** Saved next-start enablement from the managed profile patch row. */\n enabled: boolean\n commit?: string\n}\n\n/** Point-in-time install/update progress reported by the host. */\nexport interface InstallProgressItem {\n kind: 'idle' | 'install' | 'update'\n stage: 'fetch' | 'download' | 'extract' | 'write'\n percent?: number\n}\n\n/** One plugin with a newer version available. */\nexport interface PluginUpdateItem {\n id: string\n current: string\n latest: string\n /** Declared DSH minimum the update needs (package manifest's `dsh.engines.dsh`). */\n requiresDsh?: string\n /** Whether the running DSH host satisfies requiresDsh; absent when unknown. */\n compatible?: boolean\n}\n\n/** One recorded plugin boot failure served by the host. */\nexport interface PluginFailureItem {\n /** Installed plugin id (package name); empty for unattributable failures. */\n pluginId: string\n kind: 'load-failure' | 'hang' | 'late-rejection'\n message: string\n stack: string\n installPath: string\n at: string\n}\n\n/** Recovery facts served by the host: the failure ring, the plugin root, and safe mode. */\nexport interface PluginFailuresSnapshot {\n items: PluginFailureItem[]\n /** Absolute plugin install root — the repair conversation's workspace. */\n pluginRoot: string\n /** Whether the host is running in safe mode (user plugins skipped). */\n safeMode: boolean\n}\n\n/** One deployment-configured logical product switch. */\nexport interface PluginControlItem {\n id: string\n name: string\n repository: string\n state: 'enabled' | 'disabled' | 'mixed' | 'unavailable' | 'uninstalled'\n}\n\n/** Whether a decoded value is a non-array object. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Whether a decoded value is a string. */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string'\n}\n\n/** Validate one installed-plugin row. */\nfunction parsePlugin(value: unknown, index: number): InstalledPluginItem {\n if (!isRecord(value) || !isString(value.id) || !isString(value.name)\n || !isString(value.version) || !isString(value.installedAt)\n || typeof value.enabled !== 'boolean'\n || !isRecord(value.source) || (value.source.kind !== 'npm' && value.source.kind !== 'git')\n || !isString(value.source.spec)) {\n throw new Error(`plugin-manager: plugin row ${String(index)} is invalid`)\n }\n return {\n id: value.id,\n name: value.name,\n version: value.version,\n source: { kind: value.source.kind, spec: value.source.spec },\n installedAt: value.installedAt,\n enabled: value.enabled,\n ...isString(value.commit) ? { commit: value.commit } : {},\n }\n}\n\n/**\n * Validate and normalize a `list` / `uninstall` response value.\n * @param value - decoded but untrusted response value.\n * @returns typed installed-plugin rows.\n */\nexport function parsePluginList(value: unknown): InstalledPluginItem[] {\n if (!isRecord(value) || !Array.isArray(value.plugins)) {\n throw new Error('plugin-manager: response must contain a plugins array')\n }\n return value.plugins.map((plugin, index) => parsePlugin(plugin, index))\n}\n\n/**\n * Validate and normalize an `install` / `update` / `set-enabled` response value.\n * @param value - decoded but untrusted response value.\n * @returns the typed installed-plugin row.\n */\nexport function parseInstalledPlugin(value: unknown): InstalledPluginItem {\n if (!isRecord(value) || value.plugin === undefined) {\n throw new Error('plugin-manager: response must contain a plugin row')\n }\n return parsePlugin(value.plugin, 0)\n}\n\n/**\n * Validate and normalize a plugin-control `list` / `set-enabled` response value.\n * @param value - decoded but untrusted response value.\n * @returns the typed control items.\n */\nexport function parsePluginControlSnapshot(value: unknown): PluginControlItem[] {\n if (!isRecord(value) || !Array.isArray(value.controls)) {\n throw new Error('plugin-manager: response must contain a controls array')\n }\n return value.controls.map((control, index) => {\n if (!isRecord(control) || !isString(control.id) || !isString(control.name)\n || !isString(control.repository)\n || (control.state !== 'enabled' && control.state !== 'disabled'\n && control.state !== 'mixed' && control.state !== 'unavailable'\n && control.state !== 'uninstalled')) {\n throw new Error(`plugin-manager: control row ${String(index)} is invalid`)\n }\n return {\n id: control.id,\n name: control.name,\n repository: control.repository,\n state: control.state,\n }\n })\n}\n\n/**\n * Validate and normalize a `status` response value.\n * @param value - decoded but untrusted response value.\n * @returns the typed progress state.\n */\nexport function parseInstallStatus(value: unknown): InstallProgressItem {\n if (!isRecord(value) || !isRecord(value.progress)\n || (value.progress.kind !== 'idle' && value.progress.kind !== 'install' && value.progress.kind !== 'update')\n || (value.progress.stage !== 'fetch' && value.progress.stage !== 'download'\n && value.progress.stage !== 'extract' && value.progress.stage !== 'write')\n || (value.progress.percent !== undefined\n && (typeof value.progress.percent !== 'number' || !Number.isFinite(value.progress.percent)))) {\n throw new Error('plugin-manager: response must contain a valid progress state')\n }\n return {\n kind: value.progress.kind,\n stage: value.progress.stage,\n ...typeof value.progress.percent === 'number' ? { percent: value.progress.percent } : {},\n }\n}\n\n/**\n * Validate and normalize a `check-updates` response value.\n * @param value - decoded but untrusted response value.\n * @returns typed update rows.\n */\nexport function parseUpdateList(value: unknown): PluginUpdateItem[] {\n if (!isRecord(value) || !Array.isArray(value.updates)) {\n throw new Error('plugin-manager: response must contain an updates array')\n }\n return value.updates.map((update, index) => {\n if (!isRecord(update) || !isString(update.id) || !isString(update.current) || !isString(update.latest)) {\n throw new Error(`plugin-manager: update row ${String(index)} is invalid`)\n }\n const row: PluginUpdateItem = { id: update.id, current: update.current, latest: update.latest }\n if (update.requiresDsh !== undefined) {\n if (!isString(update.requiresDsh)) {\n throw new Error(`plugin-manager: update row ${String(index)} is invalid`)\n }\n row.requiresDsh = update.requiresDsh\n }\n if (update.compatible !== undefined) {\n if (typeof update.compatible !== 'boolean') {\n throw new Error(`plugin-manager: update row ${String(index)} is invalid`)\n }\n row.compatible = update.compatible\n }\n return row\n })\n}\n\n/**\n * Validate and normalize a `failures` response value.\n * @param value - decoded but untrusted response value.\n * @returns the typed failures snapshot.\n */\nexport function parseFailuresSnapshot(value: unknown): PluginFailuresSnapshot {\n if (!isRecord(value) || !Array.isArray(value.items)\n || !isString(value.pluginRoot) || typeof value.safeMode !== 'boolean') {\n throw new Error('plugin-manager: response must contain a failures snapshot')\n }\n return {\n items: value.items.map((item, index) => {\n if (!isRecord(item) || !isString(item.pluginId)\n || (item.kind !== 'load-failure' && item.kind !== 'hang' && item.kind !== 'late-rejection')\n || !isString(item.message) || !isString(item.stack)\n || !isString(item.installPath) || !isString(item.at)) {\n throw new Error(`plugin-manager: failure row ${String(index)} is invalid`)\n }\n return {\n pluginId: item.pluginId,\n kind: item.kind,\n message: item.message,\n stack: item.stack,\n installPath: item.installPath,\n at: item.at,\n }\n }),\n pluginRoot: value.pluginRoot,\n safeMode: value.safeMode,\n }\n}\n","/**\n * The cordis service contract this package exposes to sibling client plugins\n * under the name `'pluginManager'`. The browser half builds one dual-channel\n * face (official /plugin-installer + /plugin-control RPC channels when\n * available, else this package's loopback HTTP gateway) and provides it via\n * `ctx.provide('pluginManager', face)`; consumers resolve it with\n * `ctx.inject(['pluginManager'], cb)` and read `ctx.pluginManager`.\n *\n * The interface is intentionally narrower than the face the Plugin manager\n * tab receives (`PluginManagerFace` in the client half): it is the stable\n * cross-plugin surface, so it only carries the operations a sibling plugin\n * needs to observe and drive the installed-plugin set.\n * @module @linxin666/dsh-client-ui-plugin-manager/core\n */\n\nimport type { InstallProgressItem, InstalledPluginItem, PluginFailuresSnapshot } from './protocol.ts'\n\n/** The cordis service name the browser half provides the face under. */\nexport const PLUGIN_MANAGER_SERVICE = 'pluginManager'\n\n/**\n * The dual-channel plugin-management face, shared between the Plugin manager\n * tab and sibling client plugins.\n */\nexport interface PluginManagerService {\n /** Whether this browser has loopback authority to use the host routes. */\n readonly isLoopback: boolean\n /** Read the installed snapshot. */\n list(): Promise<InstalledPluginItem[]>\n /** Install one plugin from an npm spec or git URL. */\n install(spec: string): Promise<InstalledPluginItem>\n /** Remove one plugin. */\n uninstall(id: string): Promise<InstalledPluginItem[]>\n /** Read the current install/update progress. */\n status(): Promise<InstallProgressItem>\n /**\n * Read the recorded plugin boot-failure ring (plugin id, message, stack,\n * install path). On runtimes without a failure ring the host answers an\n * empty snapshot.\n */\n failures(): Promise<PluginFailuresSnapshot>\n /**\n * Flip one plugin's next-start enablement through the active channel (the\n * official installer RPC when available, else the loopback gateway's patch\n * `disabled` override row). The change takes effect after the host restart;\n * a running plugin is not stopped.\n */\n setEnabled(id: string, enabled: boolean): Promise<InstalledPluginItem>\n /**\n * Subscribe to successful mutations: the callback runs after install(),\n * update(), uninstall(), or setEnabled() resolves. One listener throwing\n * never breaks the others. Returns the unsubscribe function.\n */\n onChange(cb: () => void): () => void\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n /** The plugin-manager face (provided by the dsh-plugin-manager client half). */\n pluginManager: PluginManagerService\n }\n}\n","/**\n * Plugin-manager browser half: contributes the family plugin-manager tab to\n * the official Plugins settings section (`settings.plugins.tab` slot) and\n * provides the same dual-channel face as the `'pluginManager'` cordis\n * service for sibling client plugins. It is dual-channel: on runtimes with\n * the official installer services (DSHCode, the 1.0.4 checkout web) every\n * operation rides the official `/plugin-installer` and `/plugin-control`\n * loopback RPC channels (the single writer); on the npm-published web runtime\n * those channels do not exist, so the same face falls back to this package's\n * own loopback HTTP gateway, which spawns the official CLI for writes.\n * Neither the tab nor service consumers know which mode the face runs in.\n * @module @linxin666/dsh-client-ui-plugin-manager/client\n */\n\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\n// Type-only: pulls the settings surface's slot contracts (settings.plugins.tab).\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\n// Type-only: pulls the client runtime Context merge (ctx.workspaces, ctx.sessions).\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\nimport type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'\nimport { PluginManagerTab, type PluginManagerTabInjected } from './PluginManagerTab.tsx'\nimport { en, zh, type PluginManagerKey } from './locales.ts'\nimport {\n parseFailuresSnapshot,\n parseInstallStatus,\n parseInstalledPlugin,\n parsePluginControlSnapshot,\n parsePluginList,\n parseUpdateList,\n type InstalledPluginItem,\n type InstallProgressItem,\n type PluginControlItem,\n type PluginFailuresSnapshot,\n type PluginUpdateItem,\n} from '../core/protocol.ts'\nimport { PLUGIN_MANAGER_SERVICE, type PluginManagerService } from '../core/service.ts'\nimport type { ControlChange } from '../core/conflict.ts'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** Copy for the family plugin-manager tab. */\n 'settings.pluginManager': PluginManagerKey\n }\n}\n\nconst NS = 'settings.pluginManager'\nconst CHANNEL = '/plugin-installer'\nconst CONTROL_CHANNEL = '/plugin-control'\nconst LIST_ENDPOINT = 'list'\nconst INSTALL_ENDPOINT = 'install'\nconst UPDATE_ENDPOINT = 'update'\nconst UNINSTALL_ENDPOINT = 'uninstall'\nconst SET_ENABLED_ENDPOINT = 'set-enabled'\nconst CHECK_UPDATES_ENDPOINT = 'check-updates'\nconst STATUS_ENDPOINT = 'status'\nconst FAILURES_ENDPOINT = 'failures'\nconst SET_SAFE_MODE_ENDPOINT = 'set-safe-mode'\n\nconst GATEWAY_PREFIX = '/api/plugin-manager'\n/** Gateway job polling cadence. */\nconst JOB_POLL_MS = 500\n/** Gateway job wait ceiling (the host add deadline is six minutes). */\nconst JOB_WAIT_MS = 7 * 60_000\n\n/** Services required by the slot registration and both channels. */\nexport const inject = ['slots', 'locale', 'connection', 'workspaces', 'sessions']\n\n/** The gateway job wire shape served by /status. */\ninterface GatewayJobWire {\n phase: 'running' | 'done' | 'error'\n plugin?: unknown\n conflicts?: unknown\n error?: string\n}\n\n/**\n * The face the Plugin manager tab and the `'pluginManager'` cordis service\n * share: the full tab surface plus the cross-plugin service contract.\n */\nexport type PluginManagerFace = PluginManagerTabInjected & PluginManagerService\n\n/**\n * Build the dual-channel face once: official-channel and gateway-channel\n * implementations, the mode detection that picks between them, the repair\n * handoff, and the change-notification listener set. The returned face is\n * both the tab's injected props and the value provided as the\n * `'pluginManager'` cordis service.\n * @param ctx - the client context (connection, workspaces, sessions).\n * @returns the shared face.\n */\nexport function createPluginManagerFace(ctx: ClientContext): PluginManagerFace {\n const connection = ctx.get('connection') as ConnectionHandle\n\n // ── official channel implementations ──────────────────────────────────────\n\n const call = async (endpoint: string, payload: unknown): Promise<unknown> => {\n const result = await connection.rpc.call(CHANNEL, endpoint, payload)\n if (!result.ok) {\n throw new Error(`plugin-installer ${endpoint} failed: ${result.error.code}: ${result.error.message}`)\n }\n return result.value\n }\n const official = {\n list: async (): Promise<InstalledPluginItem[]> => parsePluginList(await call(LIST_ENDPOINT, {})),\n install: async (spec: string): Promise<InstalledPluginItem> => parseInstalledPlugin(await call(INSTALL_ENDPOINT, { spec })),\n update: async (id: string): Promise<InstalledPluginItem> => parseInstalledPlugin(await call(UPDATE_ENDPOINT, { id })),\n uninstall: async (id: string): Promise<InstalledPluginItem[]> => parsePluginList(await call(UNINSTALL_ENDPOINT, { id })),\n setEnabled: async (id: string, enabled: boolean): Promise<InstalledPluginItem> =>\n parseInstalledPlugin(await call(SET_ENABLED_ENDPOINT, { id, enabled })),\n checkUpdates: async (): Promise<PluginUpdateItem[]> => parseUpdateList(await call(CHECK_UPDATES_ENDPOINT, {})),\n status: async (): Promise<InstallProgressItem> => parseInstallStatus(await call(STATUS_ENDPOINT, {})),\n failures: async (): Promise<PluginFailuresSnapshot> => parseFailuresSnapshot(await call(FAILURES_ENDPOINT, {})),\n setSafeMode: async (enabled: boolean): Promise<void> => {\n await call(SET_SAFE_MODE_ENDPOINT, { enabled })\n },\n controlsList: async (): Promise<PluginControlItem[]> =>\n parsePluginControlSnapshot(await connection.rpc.call(CONTROL_CHANNEL, 'list', {}).then(result => {\n if (!result.ok) throw new Error(`plugin-control list failed: ${result.error.code}: ${result.error.message}`)\n return result.value\n })),\n controlsSetEnabled: async (pluginId: string, enabled: boolean): Promise<PluginControlItem[]> =>\n parsePluginControlSnapshot(await connection.rpc.call(CONTROL_CHANNEL, 'set-enabled', { pluginId, enabled }).then(result => {\n if (!result.ok) throw new Error(`plugin-control set-enabled failed: ${result.error.code}: ${result.error.message}`)\n return result.value\n })),\n }\n\n // ── gateway channel implementations ──────────────────────────────────────\n\n const gatewayJson = async (path: string, init?: RequestInit): Promise<unknown> => {\n const response = await fetch(path, {\n ...init,\n headers: { 'content-type': 'application/json', ...init?.headers },\n })\n if (response.status === 403) {\n throw new Error('plugin-manager: plugin management is only available from a local browser')\n }\n if (!response.ok) {\n const body = await response.json().catch(() => ({})) as { error?: string }\n throw new Error(body.error ?? `plugin-manager: gateway ${path} failed: HTTP ${String(response.status)}`)\n }\n return response.json()\n }\n\n /** Wait for one gateway job to settle, returning its wire state. */\n const waitJob = async (jobId: string): Promise<GatewayJobWire> => {\n const deadline = Date.now() + JOB_WAIT_MS\n for (;;) {\n const body = await gatewayJson(`${GATEWAY_PREFIX}/status?job=${encodeURIComponent(jobId)}`) as { job?: GatewayJobWire }\n const job = body.job\n if (job === undefined) throw new Error('plugin-manager: gateway job vanished')\n if (job.phase === 'done') return job\n if (job.phase === 'error') throw new Error(job.error ?? 'plugin-manager: gateway job failed')\n if (Date.now() > deadline) throw new Error('plugin-manager: gateway job timed out')\n await new Promise(resolve => { setTimeout(resolve, JOB_POLL_MS) })\n }\n }\n\n /** The conflict ledger of the last settled gateway install. */\n let lastInstallConflicts: ControlChange[] = []\n /** Whether a gateway install/remove is in flight (drives the progress row). */\n let gatewayInflight = false\n\n const gateway = {\n list: async (): Promise<InstalledPluginItem[]> =>\n parsePluginList(await gatewayJson(`${GATEWAY_PREFIX}/list`)),\n install: async (spec: string): Promise<InstalledPluginItem> => {\n gatewayInflight = true\n try {\n const started = await gatewayJson(`${GATEWAY_PREFIX}/install`, {\n method: 'POST',\n body: JSON.stringify({ spec }),\n }) as { jobId?: string }\n if (started.jobId === undefined) throw new Error('plugin-manager: gateway install returned no job')\n const job = await waitJob(started.jobId)\n lastInstallConflicts = Array.isArray(job.conflicts) ? job.conflicts as ControlChange[] : []\n return parseInstalledPlugin({ plugin: job.plugin })\n } finally {\n gatewayInflight = false\n }\n },\n update: async (id: string): Promise<InstalledPluginItem> => {\n gatewayInflight = true\n try {\n const started = await gatewayJson(`${GATEWAY_PREFIX}/update`, {\n method: 'POST',\n body: JSON.stringify({ id }),\n }) as { jobId?: string }\n if (started.jobId === undefined) throw new Error('plugin-manager: gateway update returned no job')\n const job = await waitJob(started.jobId)\n lastInstallConflicts = Array.isArray(job.conflicts) ? job.conflicts as ControlChange[] : []\n return parseInstalledPlugin({ plugin: job.plugin })\n } finally {\n gatewayInflight = false\n }\n },\n uninstall: async (id: string): Promise<InstalledPluginItem[]> => {\n gatewayInflight = true\n try {\n const started = await gatewayJson(`${GATEWAY_PREFIX}/remove`, {\n method: 'POST',\n body: JSON.stringify({ id }),\n }) as { jobId?: string }\n if (started.jobId === undefined) throw new Error('plugin-manager: gateway remove returned no job')\n await waitJob(started.jobId)\n return gateway.list()\n } finally {\n gatewayInflight = false\n }\n },\n setEnabled: async (id: string, enabled: boolean): Promise<InstalledPluginItem> =>\n parseInstalledPlugin(await gatewayJson(`${GATEWAY_PREFIX}/set-enabled`, {\n method: 'POST',\n body: JSON.stringify({ id, enabled }),\n })),\n checkUpdates: async (): Promise<PluginUpdateItem[]> =>\n parseUpdateList(await gatewayJson(`${GATEWAY_PREFIX}/check-updates`)),\n status: async (): Promise<InstallProgressItem> =>\n gatewayInflight ? { kind: 'install', stage: 'download' } : { kind: 'idle', stage: 'fetch' },\n failures: async (): Promise<PluginFailuresSnapshot> =>\n parseFailuresSnapshot(await gatewayJson(`${GATEWAY_PREFIX}/failures`)),\n setSafeMode: async (): Promise<void> => {\n throw new Error('plugin-manager: safe mode is unavailable in this runtime')\n },\n controlsList: async (): Promise<PluginControlItem[]> => [],\n controlsSetEnabled: async (pluginId: string, enabled: boolean): Promise<PluginControlItem[]> => {\n await gateway.setEnabled(pluginId, enabled)\n return []\n },\n }\n\n // ── mode selection ────────────────────────────────────────────────────────\n\n let modePromise: Promise<'official' | 'gateway'> | undefined\n const ensureMode = (): Promise<'official' | 'gateway'> => {\n if (modePromise === undefined) {\n modePromise = (async () => {\n // Prefer the host verdict: the gateway's /mode route reports whether\n // the official installer channels exist, so the direct channel probe\n // below (which 405s into the browser console on the npm web runtime)\n // only runs when the host half is absent or explicitly returns null\n // for a desktop runtime whose services are registered in-process.\n try {\n const mode = await gatewayJson(`${GATEWAY_PREFIX}/mode`) as { official?: boolean | null }\n if (mode.official === true) return 'official' as const\n if (mode.official === false) return 'gateway' as const\n } catch {\n // Host half absent (an official runtime without a boot profile):\n // fall back to the direct channel probe.\n }\n try {\n const result = await connection.rpc.call(CHANNEL, LIST_ENDPOINT, {})\n return result.ok ? 'official' as const : 'gateway' as const\n } catch {\n return 'gateway' as const\n }\n })()\n }\n return modePromise\n }\n\n /**\n * Start a repair conversation for a failed plugin: resolve a workspace over\n * the plugin install root (created once, reused after), open a fresh\n * session there, and seed its first prompt with the failure details. The\n * session's workspace is the plugin home so the agent's file tools reach\n * the plugin code without leaving the workspace boundary.\n * @param pluginRoot - absolute plugin install root.\n * @param message - the seeded first user message.\n * @returns resolution after the prompt is accepted and the session opens.\n */\n const repairPlugin = async (pluginRoot: string, message: string): Promise<void> => {\n const workspace = await ctx.workspaces.create({ path: pluginRoot })\n const sessionId = await ctx.workspaces.connectWorkspace(workspace.workspaceId)\n const binding = ctx.sessions.binding(sessionId)\n if (binding === undefined) throw new Error(`plugin-manager: repair session ${sessionId} is unavailable`)\n const result = await binding.session.prompt([{ type: 'text', text: message }], 'queue')\n if (!result.ok) throw new Error(`plugin-manager: repair prompt failed: ${result.error.code}: ${result.error.message}`)\n ctx.sessions.open(sessionId)\n }\n\n // ── change notification ───────────────────────────────────────────────────\n\n /** Listeners subscribed through onChange; fired after successful mutations. */\n const listeners = new Set<() => void>()\n /** Notify every listener; one listener throwing never breaks the others. */\n const notifyChange = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener()\n } catch {\n // A consumer's listener failure is its own; keep notifying the rest.\n }\n }\n }\n\n // ── the shared face ───────────────────────────────────────────────────────\n\n return {\n isLoopback: connection.isLoopback,\n list: async () => (await ensureMode()) === 'official' ? official.list() : gateway.list(),\n install: async spec => {\n const item = await ((await ensureMode()) === 'official' ? official.install(spec) : gateway.install(spec))\n notifyChange()\n return item\n },\n update: async id => {\n const item = await ((await ensureMode()) === 'official' ? official.update(id) : gateway.update(id))\n notifyChange()\n return item\n },\n uninstall: async id => {\n const rows = await ((await ensureMode()) === 'official' ? official.uninstall(id) : gateway.uninstall(id))\n notifyChange()\n return rows\n },\n setEnabled: async (id, enabled) => {\n const item = await ((await ensureMode()) === 'official' ? official.setEnabled(id, enabled) : gateway.setEnabled(id, enabled))\n notifyChange()\n return item\n },\n checkUpdates: async () => (await ensureMode()) === 'official' ? official.checkUpdates() : gateway.checkUpdates(),\n status: async () => (await ensureMode()) === 'official' ? official.status() : gateway.status(),\n failures: async () => (await ensureMode()) === 'official' ? official.failures() : gateway.failures(),\n setSafeMode: async enabled => (await ensureMode()) === 'official' ? official.setSafeMode(enabled) : gateway.setSafeMode(),\n repairPlugin,\n controlsList: async () => (await ensureMode()) === 'official' ? official.controlsList() : gateway.controlsList(),\n controlsSetEnabled: async (id, enabled) => (await ensureMode()) === 'official' ? official.controlsSetEnabled(id, enabled) : gateway.controlsSetEnabled(id, enabled),\n lastInstallConflicts: () => lastInstallConflicts,\n onChange: cb => {\n listeners.add(cb)\n return () => { listeners.delete(cb) }\n },\n }\n}\n\n/** Contribute the family plugin-manager tab and provide the shared face. */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'plugin-manager: dictionaries')\n\n // Built once: the tab and the 'pluginManager' cordis service share one\n // face, so consumers observe exactly the mutations the tab performs.\n const face = createPluginManagerFace(ctx)\n ctx.provide(PLUGIN_MANAGER_SERVICE, face)\n\n ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({\n name: 'settings.plugins.tab',\n id: 'family-plugins',\n order: 20,\n label: () => ctx.locale.bind(NS)('tab'),\n locale: NS,\n inject: () => face,\n }, PluginManagerTab))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;EAsCA,SAAgB,aAAa,QAAsC,OAAsD;GACvH,MAAM,YAAY,IAAI,IAAI,MAAM,KAAI,SAAQ,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;GAC5D,MAAM,UAA2B,CAAC;GAClC,KAAK,MAAM,QAAQ,QAAQ;IACzB,MAAM,UAAU,UAAU,IAAI,KAAK,EAAE;IACrC,IAAI,YAAY,KAAA,KAAa,QAAQ,UAAU,KAAK,OAAO;IAC3D,QAAQ,KAAK;KAAE,IAAI,KAAK;KAAI,MAAM,KAAK;KAAM,MAAM,KAAK;KAAO,IAAI,QAAQ;IAAM,CAAC;GACpF;GACA,OAAO;EACT;;;;;;;;EASA,SAAgB,eAAe,QAA0C;GACvE,IAAI,OAAO,OAAO,YAAY,OAAO;GACrC,IAAI,OAAO,SAAS,YAAY,OAAO;GACvC,OAAO;EACT;;;;ECjBA,MAAa,sBAAkC;GAC7C,cAAc;GACd,kBAAkB;GAClB,mBAAmB;GACnB,YAAY;G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,WAAW,MAAO,aAAa,SAAS,mBAAmB,IAAI,OAAO,IAAI,QAAQ,mBAAmB,IAAI,OAAO;IAClK,4BAA4B;IAC5B,WAAU,OAAM;KACd,UAAU,IAAI,EAAE;KAChB,aAAa;MAAE,UAAU,OAAO,EAAE;KAAE;IACtC;GACF;EACF;;EAGA,SAAgB,MAAM,KAA0B;GAC9C,IAAI,aAAa,IAAI,OAAO,SAAS,IAAI;IAAE;IAAI;GAAG,CAAC,GAAG,8BAA8B;GAIpF,MAAM,OAAO,wBAAwB,GAAG;GACxC,IAAI,QAAQ,wBAAwB,IAAI;GAExC,IAAI,MAAM,OAAO,8BAA8B,IAAI,MAAM,SAAS;IAChE,MAAM;IACN,IAAI;IACJ,OAAO;IACP,aAAa,IAAI,OAAO,KAAK,EAAE,CAAC,CAAC,KAAK;IACtC,QAAQ;IACR,cAAc;GAChB,GAAG,gBAAgB,CAAC;EACtB"}
|
package/lib/index.js
CHANGED
|
@@ -411,6 +411,13 @@ function resolveDshHome(env = process.env, home = homedir()) {
|
|
|
411
411
|
* write goes through the official CLI or the patch-row editor.
|
|
412
412
|
* @module @linxin666/dsh-client-ui-plugin-manager/host
|
|
413
413
|
*/
|
|
414
|
+
/**
|
|
415
|
+
* Strip a leading UTF-8 byte order mark (U+FEFF), which commonly appears in
|
|
416
|
+
* files edited or created on Windows (PowerShell / Notepad).
|
|
417
|
+
*/
|
|
418
|
+
function stripBom(text) {
|
|
419
|
+
return text.charCodeAt(0) === 65279 ? text.slice(1) : text;
|
|
420
|
+
}
|
|
414
421
|
/** Read the packaged desktop app's persisted active profile, when present. */
|
|
415
422
|
function desktopSelectedProfile(env = process.env) {
|
|
416
423
|
const explicit = env.DSH_DESKTOP_DEFAULT_PROFILE?.trim();
|
|
@@ -422,7 +429,7 @@ function desktopSelectedProfile(env = process.env) {
|
|
|
422
429
|
env.HOME && join(env.HOME, ".config", "DSH Desktop")
|
|
423
430
|
].filter((value) => typeof value === "string");
|
|
424
431
|
for (const root of appRoots) try {
|
|
425
|
-
const parsed = JSON.parse(readFileSync(join(root, "profile-selection", "state.json"), "utf8"));
|
|
432
|
+
const parsed = JSON.parse(stripBom(readFileSync(join(root, "profile-selection", "state.json"), "utf8")));
|
|
426
433
|
if (typeof parsed.active === "string" && parsed.active.trim() !== "") return parsed.active.trim();
|
|
427
434
|
} catch {}
|
|
428
435
|
}
|
|
@@ -466,7 +473,7 @@ function resolveProfile(argv = process.argv, env = process.env) {
|
|
|
466
473
|
*/
|
|
467
474
|
async function readProfileManifest(packageJsonPath) {
|
|
468
475
|
const text = await readFile(packageJsonPath, "utf8");
|
|
469
|
-
const parsed = JSON.parse(text);
|
|
476
|
+
const parsed = JSON.parse(stripBom(text));
|
|
470
477
|
const bundles = Array.isArray(parsed.dsh?.profile?.bundles) ? parsed.dsh.profile.bundles.filter((item) => typeof item === "string") : [];
|
|
471
478
|
const rawDeps = parsed.dependencies;
|
|
472
479
|
const dependencies = {};
|
|
@@ -489,7 +496,7 @@ async function readProfileManifest(packageJsonPath) {
|
|
|
489
496
|
*/
|
|
490
497
|
async function stripProfileBundles(packageJsonPath, names) {
|
|
491
498
|
const text = await readFile(packageJsonPath, "utf8");
|
|
492
|
-
const parsed = JSON.parse(text);
|
|
499
|
+
const parsed = JSON.parse(stripBom(text));
|
|
493
500
|
const profile = parsed.dsh?.profile;
|
|
494
501
|
if (profile === void 0 || !Array.isArray(profile.bundles)) return;
|
|
495
502
|
profile.bundles = profile.bundles.filter((entry) => !(typeof entry === "string" && names.includes(entry)));
|
|
@@ -504,7 +511,7 @@ async function stripProfileBundles(packageJsonPath, names) {
|
|
|
504
511
|
*/
|
|
505
512
|
async function readPatchText(patchPath) {
|
|
506
513
|
try {
|
|
507
|
-
return await readFile(patchPath, "utf8");
|
|
514
|
+
return stripBom(await readFile(patchPath, "utf8"));
|
|
508
515
|
} catch (error) {
|
|
509
516
|
if (error?.code === "ENOENT") return "[]\n";
|
|
510
517
|
throw error;
|
|
@@ -543,7 +550,7 @@ function sourceKindOf(spec) {
|
|
|
543
550
|
async function claimedEntryIdsOf(facts, name) {
|
|
544
551
|
const patchPath = join(modulePathOf(facts.profileDir, name), "cordis.patch.yml");
|
|
545
552
|
try {
|
|
546
|
-
const ids = claimedIdsOf(await readFile(patchPath, "utf8"));
|
|
553
|
+
const ids = claimedIdsOf(stripBom(await readFile(patchPath, "utf8")));
|
|
547
554
|
if (ids.length > 0) return ids;
|
|
548
555
|
} catch {}
|
|
549
556
|
return [name];
|
|
@@ -560,7 +567,7 @@ async function claimedEntryIdsOf(facts, name) {
|
|
|
560
567
|
async function claimedEntryRowsOf(facts, name) {
|
|
561
568
|
const patchPath = join(modulePathOf(facts.profileDir, name), "cordis.patch.yml");
|
|
562
569
|
try {
|
|
563
|
-
const claimed = insertRowsOf(await readFile(patchPath, "utf8")).filter((row) => row.id !== void 0);
|
|
570
|
+
const claimed = insertRowsOf(stripBom(await readFile(patchPath, "utf8"))).filter((row) => row.id !== void 0);
|
|
564
571
|
if (claimed.length > 0) return claimed.map((row) => ({
|
|
565
572
|
id: row.id,
|
|
566
573
|
name: row.name ?? name
|
|
@@ -585,7 +592,8 @@ async function buildPluginRow(facts, name, spec, rowEnabled) {
|
|
|
585
592
|
const moduleDir = modulePathOf(facts.profileDir, name);
|
|
586
593
|
let version = "unknown";
|
|
587
594
|
try {
|
|
588
|
-
const
|
|
595
|
+
const text = await readFile(join(moduleDir, "package.json"), "utf8");
|
|
596
|
+
const parsed = JSON.parse(stripBom(text));
|
|
589
597
|
if (typeof parsed.version === "string") version = parsed.version;
|
|
590
598
|
} catch {
|
|
591
599
|
version = "unknown";
|
|
@@ -593,7 +601,7 @@ async function buildPluginRow(facts, name, spec, rowEnabled) {
|
|
|
593
601
|
let bundlePatch = "[]";
|
|
594
602
|
const bundlePatchPath = join(moduleDir, "cordis.patch.yml");
|
|
595
603
|
if (existsSync(bundlePatchPath)) try {
|
|
596
|
-
bundlePatch = await readFile(bundlePatchPath, "utf8");
|
|
604
|
+
bundlePatch = stripBom(await readFile(bundlePatchPath, "utf8"));
|
|
597
605
|
} catch {
|
|
598
606
|
bundlePatch = "[]";
|
|
599
607
|
}
|
|
@@ -651,6 +659,8 @@ async function snapshotGateway(facts, patchText) {
|
|
|
651
659
|
const ADD_TIMEOUT_MS = 6 * 6e4;
|
|
652
660
|
/** Hard deadline for one CLI remove. */
|
|
653
661
|
const REMOVE_TIMEOUT_MS = 2 * 6e4;
|
|
662
|
+
/** Ring cap on finished jobs: the newest 100 settled jobs stay queryable; the oldest finished job is evicted beyond the cap so the job table cannot grow without bound. In-progress jobs are never evicted. */
|
|
663
|
+
const MAX_FINISHED_JOBS = 100;
|
|
654
664
|
/**
|
|
655
665
|
* Shell command-chaining metacharacters that must never reach a spawned CLI
|
|
656
666
|
* argument. The gateway spawns shell-free, but the official CLI forwards to
|
|
@@ -800,6 +810,8 @@ var CliGateway = class {
|
|
|
800
810
|
env;
|
|
801
811
|
deps;
|
|
802
812
|
jobs = /* @__PURE__ */ new Map();
|
|
813
|
+
/** Settlement order of finished jobs: the eviction ring keeps the newest {@link MAX_FINISHED_JOBS}. */
|
|
814
|
+
finishedOrder = [];
|
|
803
815
|
counter = 0;
|
|
804
816
|
/** Mutation queue: two CLI runs must never interleave their before/after captures. */
|
|
805
817
|
queue = Promise.resolve();
|
|
@@ -829,6 +841,14 @@ var CliGateway = class {
|
|
|
829
841
|
enqueue(task) {
|
|
830
842
|
this.withMutationLock(task).catch(() => {});
|
|
831
843
|
}
|
|
844
|
+
/** Register a settled job and evict the oldest finished one beyond the ring cap. */
|
|
845
|
+
retainFinished(jobId) {
|
|
846
|
+
this.finishedOrder.push(jobId);
|
|
847
|
+
while (this.finishedOrder.length > MAX_FINISHED_JOBS) {
|
|
848
|
+
const evicted = this.finishedOrder.shift();
|
|
849
|
+
if (evicted !== void 0) this.jobs.delete(evicted);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
832
852
|
/** The dsh CLI path, through the test seam when present. */
|
|
833
853
|
binary() {
|
|
834
854
|
return this.deps.findBinary !== void 0 ? this.deps.findBinary(this.env) : findDshBinary(this.env);
|
|
@@ -850,6 +870,7 @@ var CliGateway = class {
|
|
|
850
870
|
if (unsafe !== void 0) {
|
|
851
871
|
job.phase = "error";
|
|
852
872
|
job.error = unsafe;
|
|
873
|
+
this.retainFinished(job.id);
|
|
853
874
|
return { jobId: job.id };
|
|
854
875
|
}
|
|
855
876
|
this.enqueue(() => this.run(job, [
|
|
@@ -877,6 +898,7 @@ var CliGateway = class {
|
|
|
877
898
|
if (unsafe !== void 0) {
|
|
878
899
|
job.phase = "error";
|
|
879
900
|
job.error = unsafe;
|
|
901
|
+
this.retainFinished(job.id);
|
|
880
902
|
return { jobId: job.id };
|
|
881
903
|
}
|
|
882
904
|
this.enqueue(() => this.run(job, [
|
|
@@ -901,6 +923,7 @@ var CliGateway = class {
|
|
|
901
923
|
if (unsafe !== void 0) {
|
|
902
924
|
job.phase = "error";
|
|
903
925
|
job.error = unsafe;
|
|
926
|
+
this.retainFinished(job.id);
|
|
904
927
|
return { jobId: job.id };
|
|
905
928
|
}
|
|
906
929
|
this.enqueue(() => this.run(job, [
|
|
@@ -912,7 +935,11 @@ var CliGateway = class {
|
|
|
912
935
|
], REMOVE_TIMEOUT_MS));
|
|
913
936
|
return { jobId: job.id };
|
|
914
937
|
}
|
|
915
|
-
/**
|
|
938
|
+
/**
|
|
939
|
+
* Read one job's current state (a shallow copy). Finished jobs beyond the
|
|
940
|
+
* ring cap are evicted and read as not-found, the same as an id that never
|
|
941
|
+
* existed.
|
|
942
|
+
*/
|
|
916
943
|
status(jobId) {
|
|
917
944
|
const job = this.jobs.get(jobId);
|
|
918
945
|
if (job === void 0) return void 0;
|
|
@@ -974,6 +1001,7 @@ var CliGateway = class {
|
|
|
974
1001
|
job.phase = "error";
|
|
975
1002
|
job.error = `plugin-manager: unexpected gateway failure: ${error instanceof Error ? error.message : String(error)}`;
|
|
976
1003
|
}
|
|
1004
|
+
this.retainFinished(job.id);
|
|
977
1005
|
}
|
|
978
1006
|
/** The mutation body of {@link run}. */
|
|
979
1007
|
async runInner(job, args, timeoutMs) {
|
|
@@ -1244,6 +1272,63 @@ var CliGateway = class {
|
|
|
1244
1272
|
}
|
|
1245
1273
|
};
|
|
1246
1274
|
//#endregion
|
|
1275
|
+
//#region src/host/http.ts
|
|
1276
|
+
/** Default body cap for readJsonBody: 64 KiB. */
|
|
1277
|
+
const DEFAULT_JSON_BODY_MAX_BYTES = 64 * 1024;
|
|
1278
|
+
/** Family-default JSON response headers; callers may append or override. */
|
|
1279
|
+
const JSON_HEADERS = {
|
|
1280
|
+
"content-type": "application/json; charset=utf-8",
|
|
1281
|
+
"referrer-policy": "no-referrer"
|
|
1282
|
+
};
|
|
1283
|
+
/**
|
|
1284
|
+
* Lenient bounded body reader: parse a request body as JSON, or null on an
|
|
1285
|
+
* empty body, invalid JSON, or a body past maxBytes (default 64 KiB).
|
|
1286
|
+
* Overflow destroys the request instead of draining the remainder (no drain
|
|
1287
|
+
* call, matching the current repo-wide behavior); callers must not keep
|
|
1288
|
+
* reading the request afterwards. With objectOnly, non-JSON-object payloads
|
|
1289
|
+
* also yield null.
|
|
1290
|
+
*/
|
|
1291
|
+
async function readJsonBody(req, opts = {}) {
|
|
1292
|
+
const maxBytes = opts.maxBytes ?? DEFAULT_JSON_BODY_MAX_BYTES;
|
|
1293
|
+
const chunks = [];
|
|
1294
|
+
let size = 0;
|
|
1295
|
+
for await (const chunk of req) {
|
|
1296
|
+
const buffer = chunk;
|
|
1297
|
+
size += buffer.length;
|
|
1298
|
+
if (size > maxBytes) {
|
|
1299
|
+
req.destroy();
|
|
1300
|
+
return null;
|
|
1301
|
+
}
|
|
1302
|
+
chunks.push(buffer);
|
|
1303
|
+
}
|
|
1304
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
1305
|
+
if (text === "") return null;
|
|
1306
|
+
try {
|
|
1307
|
+
const parsed = JSON.parse(text);
|
|
1308
|
+
if (opts.objectOnly && !isJsonObject(parsed)) return null;
|
|
1309
|
+
return parsed;
|
|
1310
|
+
} catch {
|
|
1311
|
+
return null;
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
/** Whether a value is a JSON object: typeof object, not null, not an array. */
|
|
1315
|
+
function isJsonObject(value) {
|
|
1316
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Write one JSON response. Default headers are the family defaults
|
|
1320
|
+
* (content-type and referrer-policy); caller headers are appended or
|
|
1321
|
+
* override them.
|
|
1322
|
+
*/
|
|
1323
|
+
function writeJson(res, status, body, headers = {}) {
|
|
1324
|
+
const payload = JSON.stringify(body);
|
|
1325
|
+
res.writeHead(status, {
|
|
1326
|
+
...JSON_HEADERS,
|
|
1327
|
+
...headers
|
|
1328
|
+
});
|
|
1329
|
+
res.end(payload);
|
|
1330
|
+
}
|
|
1331
|
+
//#endregion
|
|
1247
1332
|
//#region src/host/loopback.ts
|
|
1248
1333
|
/** IPv4 127/8 predicate (four decimal octets, first == 127). */
|
|
1249
1334
|
function isIPv4Loopback(v4) {
|
|
@@ -1382,8 +1467,6 @@ function dshRequirementOf(manifest) {
|
|
|
1382
1467
|
//#region src/host/routes.ts
|
|
1383
1468
|
/** Route prefix the browser half mirrors. */
|
|
1384
1469
|
const GATEWAY_PREFIX = "/api/plugin-manager";
|
|
1385
|
-
/** Cap on JSON request bodies (an install spec or a toggle is tiny). */
|
|
1386
|
-
const MAX_JSON_BODY_BYTES = 64 * 1024;
|
|
1387
1470
|
/** Registry timeout for one update check. */
|
|
1388
1471
|
const REGISTRY_TIMEOUT_MS = 3e4;
|
|
1389
1472
|
/** Deadline for one dsh --version probe. */
|
|
@@ -1398,28 +1481,6 @@ const VERSION_PROBE_COOLDOWN_MS = 6e4;
|
|
|
1398
1481
|
function messageOf(error) {
|
|
1399
1482
|
return error instanceof Error ? error.message : String(error);
|
|
1400
1483
|
}
|
|
1401
|
-
/** Send one JSON response. */
|
|
1402
|
-
function sendJson(res, status, value) {
|
|
1403
|
-
const body = JSON.stringify(value);
|
|
1404
|
-
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
1405
|
-
res.end(body);
|
|
1406
|
-
}
|
|
1407
|
-
/** Read a bounded JSON request body; throws on oversized or invalid input. */
|
|
1408
|
-
async function readJsonBody(req) {
|
|
1409
|
-
const chunks = [];
|
|
1410
|
-
let size = 0;
|
|
1411
|
-
for await (const chunk of req) {
|
|
1412
|
-
const buffer = chunk;
|
|
1413
|
-
size += buffer.length;
|
|
1414
|
-
if (size > MAX_JSON_BODY_BYTES) throw new Error("plugin-manager: request body too large");
|
|
1415
|
-
chunks.push(buffer);
|
|
1416
|
-
}
|
|
1417
|
-
const text = Buffer.concat(chunks).toString("utf8");
|
|
1418
|
-
if (text.trim() === "") return {};
|
|
1419
|
-
const parsed = JSON.parse(text);
|
|
1420
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("plugin-manager: request body must be a JSON object");
|
|
1421
|
-
return parsed;
|
|
1422
|
-
}
|
|
1423
1484
|
/** Append bounded probe output. */
|
|
1424
1485
|
function captureProbe(chunk, buffer) {
|
|
1425
1486
|
buffer.value = (buffer.value + chunk.toString()).slice(-4096);
|
|
@@ -1538,51 +1599,59 @@ function makeGatewayRoutes(deps) {
|
|
|
1538
1599
|
/** Wrap a handler with the loopback fence and JSON error reporting. */
|
|
1539
1600
|
const guard = (handler) => async (req, res) => {
|
|
1540
1601
|
if (!isLoopbackRequest(req)) {
|
|
1541
|
-
res
|
|
1542
|
-
|
|
1602
|
+
writeJson(res, 403, {
|
|
1603
|
+
ok: false,
|
|
1604
|
+
error: "forbidden: loopback-only"
|
|
1605
|
+
});
|
|
1543
1606
|
return;
|
|
1544
1607
|
}
|
|
1545
1608
|
try {
|
|
1546
1609
|
await handler(req, res);
|
|
1547
1610
|
} catch (error) {
|
|
1548
|
-
|
|
1611
|
+
writeJson(res, 500, { error: messageOf(error) });
|
|
1549
1612
|
}
|
|
1550
1613
|
};
|
|
1551
|
-
const listHandler = async (
|
|
1614
|
+
const listHandler = async (_req, res) => {
|
|
1552
1615
|
const patchText = await readPatchText(facts.patchPath);
|
|
1553
|
-
|
|
1616
|
+
writeJson(res, 200, { plugins: (await snapshotGateway(facts, patchText)).plugins });
|
|
1554
1617
|
};
|
|
1555
1618
|
const installHandler = async (req, res) => {
|
|
1556
|
-
const spec = (await readJsonBody(req
|
|
1619
|
+
const spec = (await readJsonBody(req, {
|
|
1620
|
+
maxBytes: 64 * 1024,
|
|
1621
|
+
objectOnly: true
|
|
1622
|
+
}) ?? {})["spec"];
|
|
1557
1623
|
if (typeof spec !== "string" || spec.trim() === "") {
|
|
1558
|
-
|
|
1624
|
+
writeJson(res, 400, { error: "plugin-manager: install needs a spec" });
|
|
1559
1625
|
return;
|
|
1560
1626
|
}
|
|
1561
1627
|
const unsafeSpec = unsafeSpecReason(spec.trim());
|
|
1562
1628
|
if (unsafeSpec !== void 0) {
|
|
1563
|
-
|
|
1629
|
+
writeJson(res, 400, { error: unsafeSpec });
|
|
1564
1630
|
return;
|
|
1565
1631
|
}
|
|
1566
1632
|
if (!deps.cliAvailable()) {
|
|
1567
|
-
|
|
1633
|
+
writeJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
|
|
1568
1634
|
return;
|
|
1569
1635
|
}
|
|
1570
|
-
|
|
1636
|
+
writeJson(res, 200, gateway.install(spec.trim()));
|
|
1571
1637
|
};
|
|
1572
1638
|
const updateHandler = async (req, res) => {
|
|
1573
|
-
const id = (await readJsonBody(req
|
|
1639
|
+
const id = (await readJsonBody(req, {
|
|
1640
|
+
maxBytes: 64 * 1024,
|
|
1641
|
+
objectOnly: true
|
|
1642
|
+
}) ?? {})["id"];
|
|
1574
1643
|
if (typeof id !== "string" || id.trim() === "") {
|
|
1575
|
-
|
|
1644
|
+
writeJson(res, 400, { error: "plugin-manager: update needs an id" });
|
|
1576
1645
|
return;
|
|
1577
1646
|
}
|
|
1578
1647
|
const target = id.trim();
|
|
1579
1648
|
const unsafe = unsafeSpecReason(target);
|
|
1580
1649
|
if (unsafe !== void 0) {
|
|
1581
|
-
|
|
1650
|
+
writeJson(res, 400, { error: unsafe });
|
|
1582
1651
|
return;
|
|
1583
1652
|
}
|
|
1584
1653
|
if (!deps.cliAvailable()) {
|
|
1585
|
-
|
|
1654
|
+
writeJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
|
|
1586
1655
|
return;
|
|
1587
1656
|
}
|
|
1588
1657
|
const outcome = await gateway.withMutationLock(async () => {
|
|
@@ -1629,53 +1698,59 @@ function makeGatewayRoutes(deps) {
|
|
|
1629
1698
|
};
|
|
1630
1699
|
});
|
|
1631
1700
|
if ("error" in outcome) {
|
|
1632
|
-
|
|
1701
|
+
writeJson(res, outcome.status, { error: outcome.error });
|
|
1633
1702
|
return;
|
|
1634
1703
|
}
|
|
1635
|
-
|
|
1704
|
+
writeJson(res, outcome.status, outcome.job);
|
|
1636
1705
|
};
|
|
1637
1706
|
const removeHandler = async (req, res) => {
|
|
1638
|
-
const id = (await readJsonBody(req
|
|
1707
|
+
const id = (await readJsonBody(req, {
|
|
1708
|
+
maxBytes: 64 * 1024,
|
|
1709
|
+
objectOnly: true
|
|
1710
|
+
}) ?? {})["id"];
|
|
1639
1711
|
if (typeof id !== "string" || id.trim() === "") {
|
|
1640
|
-
|
|
1712
|
+
writeJson(res, 400, { error: "plugin-manager: remove needs an id" });
|
|
1641
1713
|
return;
|
|
1642
1714
|
}
|
|
1643
1715
|
const unsafeId = unsafeSpecReason(id.trim());
|
|
1644
1716
|
if (unsafeId !== void 0) {
|
|
1645
|
-
|
|
1717
|
+
writeJson(res, 400, { error: unsafeId });
|
|
1646
1718
|
return;
|
|
1647
1719
|
}
|
|
1648
1720
|
if (!deps.cliAvailable()) {
|
|
1649
|
-
|
|
1721
|
+
writeJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
|
|
1650
1722
|
return;
|
|
1651
1723
|
}
|
|
1652
|
-
|
|
1724
|
+
writeJson(res, 200, gateway.remove(id.trim()));
|
|
1653
1725
|
};
|
|
1654
1726
|
const statusHandler = async (req, res) => {
|
|
1655
1727
|
const jobId = new URL(req.url ?? "/", "http://localhost").searchParams.get("job");
|
|
1656
1728
|
if (jobId === null) {
|
|
1657
|
-
|
|
1729
|
+
writeJson(res, 400, { error: "plugin-manager: status needs a job id" });
|
|
1658
1730
|
return;
|
|
1659
1731
|
}
|
|
1660
1732
|
const job = gateway.status(jobId);
|
|
1661
1733
|
if (job === void 0) {
|
|
1662
|
-
|
|
1734
|
+
writeJson(res, 404, { error: "plugin-manager: unknown job" });
|
|
1663
1735
|
return;
|
|
1664
1736
|
}
|
|
1665
|
-
|
|
1737
|
+
writeJson(res, 200, { job });
|
|
1666
1738
|
};
|
|
1667
1739
|
const setEnabledHandler = async (req, res) => {
|
|
1668
|
-
const body = await readJsonBody(req
|
|
1740
|
+
const body = await readJsonBody(req, {
|
|
1741
|
+
maxBytes: 64 * 1024,
|
|
1742
|
+
objectOnly: true
|
|
1743
|
+
}) ?? {};
|
|
1669
1744
|
const id = body["id"];
|
|
1670
1745
|
const enabled = body["enabled"];
|
|
1671
1746
|
if (typeof id !== "string" || id.trim() === "" || typeof enabled !== "boolean") {
|
|
1672
|
-
|
|
1747
|
+
writeJson(res, 400, { error: "plugin-manager: set-enabled needs an id and a boolean enabled" });
|
|
1673
1748
|
return;
|
|
1674
1749
|
}
|
|
1675
1750
|
const target = id.trim();
|
|
1676
1751
|
const unsafeTarget = unsafeSpecReason(target);
|
|
1677
1752
|
if (unsafeTarget !== void 0) {
|
|
1678
|
-
|
|
1753
|
+
writeJson(res, 400, { error: unsafeTarget });
|
|
1679
1754
|
return;
|
|
1680
1755
|
}
|
|
1681
1756
|
const outcome = await gateway.withMutationLock(async () => {
|
|
@@ -1689,13 +1764,13 @@ function makeGatewayRoutes(deps) {
|
|
|
1689
1764
|
return plugin === void 0 ? { error: `plugin-manager: plugin ${target} is not installed` } : { plugin };
|
|
1690
1765
|
});
|
|
1691
1766
|
if ("error" in outcome) {
|
|
1692
|
-
|
|
1767
|
+
writeJson(res, 404, { error: outcome.error });
|
|
1693
1768
|
return;
|
|
1694
1769
|
}
|
|
1695
|
-
|
|
1770
|
+
writeJson(res, 200, { plugin: outcome.plugin });
|
|
1696
1771
|
};
|
|
1697
|
-
const failuresHandler = async (
|
|
1698
|
-
|
|
1772
|
+
const failuresHandler = async (_req, res) => {
|
|
1773
|
+
writeJson(res, 200, {
|
|
1699
1774
|
items: [],
|
|
1700
1775
|
pluginRoot: facts.profileDir,
|
|
1701
1776
|
safeMode: false
|
|
@@ -1707,12 +1782,12 @@ function makeGatewayRoutes(deps) {
|
|
|
1707
1782
|
if (binary === null) return Promise.resolve(false);
|
|
1708
1783
|
return detectOfficialChannels(binary, facts.profileName);
|
|
1709
1784
|
};
|
|
1710
|
-
const modeHandler = async (
|
|
1785
|
+
const modeHandler = async (_req, res) => {
|
|
1711
1786
|
if (modePromise === void 0) if (facts.desktop) modePromise = Promise.resolve({ official: null });
|
|
1712
1787
|
else modePromise = (deps.officialChannels ?? probeOfficialChannels)().then((official) => ({ official })).catch(() => ({ official: false }));
|
|
1713
|
-
|
|
1788
|
+
writeJson(res, 200, await modePromise);
|
|
1714
1789
|
};
|
|
1715
|
-
const checkUpdatesHandler = async (
|
|
1790
|
+
const checkUpdatesHandler = async (_req, res) => {
|
|
1716
1791
|
const patchText = await readPatchText(facts.patchPath);
|
|
1717
1792
|
const snapshot = await snapshotGateway(facts, patchText);
|
|
1718
1793
|
const updates = [];
|
|
@@ -1732,7 +1807,7 @@ function makeGatewayRoutes(deps) {
|
|
|
1732
1807
|
}
|
|
1733
1808
|
updates.push(update);
|
|
1734
1809
|
}
|
|
1735
|
-
|
|
1810
|
+
writeJson(res, 200, { updates });
|
|
1736
1811
|
};
|
|
1737
1812
|
return [
|
|
1738
1813
|
{
|
|
@@ -82,6 +82,8 @@ export declare class CliGateway {
|
|
|
82
82
|
private readonly env;
|
|
83
83
|
private readonly deps;
|
|
84
84
|
private readonly jobs;
|
|
85
|
+
/** Settlement order of finished jobs: the eviction ring keeps the newest {@link MAX_FINISHED_JOBS}. */
|
|
86
|
+
private readonly finishedOrder;
|
|
85
87
|
private counter;
|
|
86
88
|
/** Mutation queue: two CLI runs must never interleave their before/after captures. */
|
|
87
89
|
private queue;
|
|
@@ -104,6 +106,8 @@ export declare class CliGateway {
|
|
|
104
106
|
withMutationLock<T>(task: () => Promise<T>): Promise<T>;
|
|
105
107
|
/** Chain one fire-and-forget CLI mutation onto the shared queue. */
|
|
106
108
|
private enqueue;
|
|
109
|
+
/** Register a settled job and evict the oldest finished one beyond the ring cap. */
|
|
110
|
+
private retainFinished;
|
|
107
111
|
/** The dsh CLI path, through the test seam when present. */
|
|
108
112
|
private binary;
|
|
109
113
|
/** Spawn the CLI, through the test seam when present. */
|
|
@@ -120,7 +124,11 @@ export declare class CliGateway {
|
|
|
120
124
|
remove(id: string): {
|
|
121
125
|
jobId: string;
|
|
122
126
|
};
|
|
123
|
-
/**
|
|
127
|
+
/**
|
|
128
|
+
* Read one job's current state (a shallow copy). Finished jobs beyond the
|
|
129
|
+
* ring cap are evicted and read as not-found, the same as an id that never
|
|
130
|
+
* existed.
|
|
131
|
+
*/
|
|
124
132
|
status(jobId: string): GatewayJob | undefined;
|
|
125
133
|
/** Capture the layer snapshot and the dependency names (tolerant parse). */
|
|
126
134
|
private capture;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared JSON body/response helpers for the host route families: one strict
|
|
3
|
+
* bounded body reader, one lenient bounded body reader, one JSON object
|
|
4
|
+
* narrow, and one JSON writer. Previously these were copy-pasted across the
|
|
5
|
+
* package route files (routes.ts, update-routes.ts, mobile-api.ts, and each
|
|
6
|
+
* family's route module) with drifting contracts: body caps ranging 4 KiB to
|
|
7
|
+
* 1 MiB and four distinct overflow behaviors (reject, undefined, null, throw).
|
|
8
|
+
*
|
|
9
|
+
* Packages receive this file as a generated copy via scripts/sync-shared.mjs;
|
|
10
|
+
* edit this shared source and re-run the sync instead of editing a copy.
|
|
11
|
+
* Consumer code is migrated onto it in follow-up waves; no call site changes
|
|
12
|
+
* belong in the same change as its introduction.
|
|
13
|
+
* @module dsh-web-ui-shared/host/http
|
|
14
|
+
*/
|
|
15
|
+
import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http';
|
|
16
|
+
/**
|
|
17
|
+
* Strict bounded body reader: parse a request body of at most maxBytes as
|
|
18
|
+
* JSON.
|
|
19
|
+
* @throws 'body too large' past the cap, or the JSON.parse error for an
|
|
20
|
+
* invalid or empty payload.
|
|
21
|
+
*/
|
|
22
|
+
export declare function readBoundedJson(req: IncomingMessage, maxBytes: number): Promise<unknown>;
|
|
23
|
+
/**
|
|
24
|
+
* Lenient bounded body reader: parse a request body as JSON, or null on an
|
|
25
|
+
* empty body, invalid JSON, or a body past maxBytes (default 64 KiB).
|
|
26
|
+
* Overflow destroys the request instead of draining the remainder (no drain
|
|
27
|
+
* call, matching the current repo-wide behavior); callers must not keep
|
|
28
|
+
* reading the request afterwards. With objectOnly, non-JSON-object payloads
|
|
29
|
+
* also yield null.
|
|
30
|
+
*/
|
|
31
|
+
export declare function readJsonBody(req: IncomingMessage, opts?: {
|
|
32
|
+
maxBytes?: number;
|
|
33
|
+
objectOnly?: boolean;
|
|
34
|
+
}): Promise<unknown | null>;
|
|
35
|
+
/** Narrow a value to a JSON object, or undefined when it is not one. */
|
|
36
|
+
export declare function asJsonObject(value: unknown): Record<string, unknown> | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Write one JSON response. Default headers are the family defaults
|
|
39
|
+
* (content-type and referrer-policy); caller headers are appended or
|
|
40
|
+
* override them.
|
|
41
|
+
*/
|
|
42
|
+
export declare function writeJson(res: ServerResponse, status: number, body: unknown, headers?: OutgoingHttpHeaders): void;
|
|
@@ -19,6 +19,11 @@ export interface ProfileFacts {
|
|
|
19
19
|
/** True when the profile was inferred from the packaged desktop host. */
|
|
20
20
|
desktop?: boolean;
|
|
21
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Strip a leading UTF-8 byte order mark (U+FEFF), which commonly appears in
|
|
24
|
+
* files edited or created on Windows (PowerShell / Notepad).
|
|
25
|
+
*/
|
|
26
|
+
export declare function stripBom(text: string): string;
|
|
22
27
|
/** Read the packaged desktop app's persisted active profile, when present. */
|
|
23
28
|
export declare function desktopSelectedProfile(env?: NodeJS.ProcessEnv): string | undefined;
|
|
24
29
|
/**
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@linxin666/dsh-client-ui-plugin-manager",
|
|
3
3
|
"description": "Plugin manager tab for the dsh web GUI Plugins settings section: installs plugins from npm or git through the official host channels, lists installed plugins with next-start enablement switches, surfaces install-time conflict actions with undo, and hands failures off to repair conversations.",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
7
7
|
"types": "lib/types/index.d.ts",
|