dsh-cabinet-mode 0.5.4 → 0.6.1

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/CHANGELOG.md CHANGED
@@ -2,6 +2,27 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [0.6.1] - 2026-11-08
6
+
7
+ ### Fixed
8
+
9
+ - Add an optional host-local source for first-time Respire installation; dependencies can still require network access. Local-source updates are explicitly refused by the card.
10
+ - Use the current input even when browser storage fails; allow registry fallback only for pre-install inspection failure, never after installation or enablement.
11
+ - Exercise actual install calls and storage-denied, existing-install and enable-failure regressions.
12
+
13
+ ## [0.6.0] - 2026-11-08
14
+
15
+ ### Added
16
+
17
+ - Five member-settings tabs and an optional Respire memory-plugin card using the public pinned package source.
18
+ - Lead monitoring guidance that requires confirming stopped writers before reassignment; no runtime watchdog or scheduled wake-up is implied.
19
+
20
+ ### Fixed
21
+
22
+ - Read official remote result envelopes; use the host update API for installed bundles and confirm installation and enable outcomes separately.
23
+ - Bound remote waits, block duplicate uncertain operations, preserve restart notices across card remounts, and ignore stale UI writes after unmount.
24
+ - Report unknown installed versions honestly rather than substituting a developer-machine snapshot.
25
+
5
26
  ## [0.5.4] - 2026-11-07
6
27
 
7
28
  ### Fixed
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Cabinet Mode (内阁模式) for DeepSeek Harness
2
2
 
3
- **Version compatibility (0.5.4):** Targets DSH **0.2.2-rc.1**. This patch corrects dependency flow and opens teammate sessions from task titles and member cards; it retains the per-office model selection fix before the host freezes each step; 0.5.1/0.5.2 only repaired preset loading and display metadata. Verified with official host components and isolated profiles, without real model calls; see the model regression scope below. Earlier rc.3/rc.5 UI and installation results are historical evidence for earlier packages. On DSH 0.2.1-rc.3/rc.5 retain the previously verified package, including 0.5.0: the current preset omits the separate list_agents entry required on rc.5. Select the compatible version in the market.
3
+ **Version compatibility (0.6.1):** Targets DSH **0.2.2-rc.1**. This release adds five settings tabs and an optional Respire install card, and retains the per-office model selection fix before the host freezes each step; 0.5.1/0.5.2 only repaired preset loading and display metadata. Verified with official host components and isolated profiles, without real model calls; see the model regression scope below. Earlier rc.3/rc.5 UI and installation results are historical evidence for earlier packages. On DSH 0.2.1-rc.3/rc.5 retain the previously verified package, including 0.5.0: the current preset omits the separate list_agents entry required on rc.5. Select the compatible version in the market.
4
4
 
5
5
  [中文](README.zh.md) | English
6
6
 
@@ -37,7 +37,11 @@ and the rest) come from the profile-level
37
37
  ship them**.
38
38
 
39
39
  This bundle declares **no hard DSH version gate**: no `engines.dsh`, no DSH
40
- `peerDependencies`, no install-time version check. Earlier package releases were tested on DSH **0.2.1-rc.3**; use the compatibility guidance above for 0.5.4 (see [DSH-side constraints](#dsh-side-constraints)).
40
+ `peerDependencies`, no install-time version check. Earlier package releases were tested on DSH **0.2.1-rc.3**; use the compatibility guidance above for 0.6.1 (see [DSH-side constraints](#dsh-side-constraints)).
41
+
42
+ ## Optional memory plugin
43
+
44
+ The Plugin tab installs the public pinned `@rsrsai/dsh@0.1.13` package. Installing and enabling are confirmed separately; a restart notice must be followed. Newer versions are not silently downgraded. Unknown versions are reported as unknown. Each remote wait has a two-minute deadline; a timeout does not cancel the host job. If the outcome remains unknown, check the native plugin manager before retrying. Closing the card stops stale UI updates and does not automatically enable a still-installing bundle.
41
45
 
42
46
  ## Cabinet member settings
43
47
 
@@ -258,7 +262,7 @@ On failure, show the exact error. For $.format must be 1, replace the webpage so
258
262
  Use this only when the market is unavailable or for local development. Fully quit desktop DSH first to release the profile lock, then install the release bundle:
259
263
 
260
264
  ```sh
261
- dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.5.4/dsh-cabinet-mode-0.5.4.tgz
265
+ dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.6.1/dsh-cabinet-mode-0.6.1.tgz
262
266
  dsh plugin --profile desktop list
263
267
  ```
264
268
 
@@ -273,7 +277,7 @@ the same install command with the new version URL (or pick the new `.tgz` in the
273
277
  plugin page), then fully quit and restart DeepSeek Harness:
274
278
 
275
279
  ```sh
276
- dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.5.4/dsh-cabinet-mode-0.5.4.tgz
280
+ dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.6.1/dsh-cabinet-mode-0.6.1.tgz
277
281
  ```
278
282
 
279
283
  `dsh plugin --profile desktop list` should report the new version. Upgrades were
@@ -283,6 +287,25 @@ on DSH 0.2.1-rc.5.
283
287
 
284
288
  ---
285
289
 
290
+ ## Recommended companion: persistent memory
291
+
292
+ Cabinet Mode runs long, multi-member sessions. Decisions, dead ends and file
293
+ locations from one session are not carried into the next by default. A DSH
294
+ memory plugin recalls those facts automatically at the start of a relevant turn,
295
+ so the cabinet does not re-derive the same context.
296
+
297
+ Pick **one** of these companion plugins. Both inject memory rules and perform
298
+ pre-step recall; enabling both stacks two sets of rules and recall, which is
299
+ usually unnecessary.
300
+
301
+ | Plugin | Best for | How it works | Links |
302
+ |---|---|---|---|
303
+ | **respire-dsh** (`@rsrsai/dsh`) | You already use `rsrs`, or need encrypted storage, account sync and one library across hosts. | Calls the `rsrs` CLI and a running host runtime; Respire owns storage, deduplication, encryption, model inference, accounts and sync. Requires Node.js 24+, a configured `rsrs`, and a running runtime; the README baseline is DSH 0.2.1-rc.5. | [GitHub](https://github.com/risense-ai/respire-dsh) · [npm](https://www.npmjs.com/package/@rsrsai/dsh) |
304
+ | **dsh-memlite** (`@rsrsai/dsh-memlite`) | You want a zero-service local start, or a library you can read and edit as JSONL. | Runs `@rsrsai/memlite` in-process: BM25 by default, local JSONL causal tree, Obsidian import/export and git sync. Requires Node.js 18+ and no `rsrs`. | [GitHub](https://github.com/risense-ai/dsh-memlite) · [website](https://risense-ai.github.io/dsh-memlite/) |
305
+
306
+ Follow each repository's README for the current install command and supported
307
+ DSH version; both require a restart to take effect.
308
+
286
309
  ## What you get
287
310
 
288
311
  | | |
@@ -543,3 +566,7 @@ and the Windows-tested vs Linux/macOS-inferred split. Sections:
543
566
  ## License
544
567
 
545
568
  [MIT](LICENSE)
569
+
570
+ ### Optional Respire local source
571
+
572
+ The memory-plugin card accepts a path on the DSH host for **first installation only**. Dependencies may still need network access; this is not a guaranteed offline installer. Installed bundles reject local-source updates: clear the field for the pinned registry action, or manage local packages through the native plugin manager. Browser storage is best-effort; the current field value is used even when persistence fails. Only inspection failure before installation may fall back once to the registry. Installation, enablement, unknown outcomes, and unmount never trigger a second automatic mutation.
package/README.zh.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 内阁模式(Cabinet Mode)· DeepSeek Harness 插件
2
2
 
3
- **版本兼容(0.5.4):** 面向 DSH **0.2.2-rc.1**,修正依赖连线方向,支持点击任务名和成员卡打开会话,并保留在宿主固定每步模型前完成官职模型选择的修复;0.5.1/0.5.2 仅修复了预设加载和显示元数据。已使用官方宿主组件与隔离 profile 验证,未调用真实模型;测试范围见下文。旧 rc.3/rc.5 的界面及安装记录仅适用于当时的包。DSH 0.2.1-rc.3/rc.5 用户应保留原先已验证版本(包括 0.5.0),当前预设已移除 rc.5 所需的独立 list_agents 入口;请在商店选择匹配版本。
3
+ **版本兼容(0.6.1):** 面向 DSH **0.2.2-rc.1**,修正依赖连线方向,支持点击任务名和成员卡打开会话,并保留在宿主固定每步模型前完成官职模型选择的修复;0.5.1/0.5.2 仅修复了预设加载和显示元数据。已使用官方宿主组件与隔离 profile 验证,未调用真实模型;测试范围见下文。旧 rc.3/rc.5 的界面及安装记录仅适用于当时的包。DSH 0.2.1-rc.3/rc.5 用户应保留原先已验证版本(包括 0.5.0),当前预设已移除 rc.5 所需的独立 list_agents 入口;请在商店选择匹配版本。
4
4
 
5
5
  [English](README.md) | 中文
6
6
 
@@ -21,7 +21,11 @@
21
21
 
22
22
  它声明**两行**——`preset-cabinet`(一条 `@deepseek-ai/dsh-agent-preset` 声明)与 `cabinet-ui`(载入本包 JavaScript 的 Loader 行)——并复用 DSH **标准模式**(Standard Mode)出厂的 22 行插件清单,因此工具与标准模式一致;与出厂模式的差异是 persona,并另加右栏「内阁」面板。团队工具(`spawn_teammate`、`team_task_*` 等)由 profile 层的 `@deepseek-ai/dsh-experimental-agent-team-profile` 提供,**本 preset 未内置**。
23
23
 
24
- 本包声明 **无 DSH 版本硬限制**:没有 `engines.dsh`、没有 DSH `peerDependencies`、安装时不做版本检查。旧包曾在 DSH **0.2.1-rc.3** 实测;0.5.4 请遵循上方版本兼容说明(见 [DSH 侧限制与说明](#dsh-侧限制与说明))。
24
+ 本包声明 **无 DSH 版本硬限制**:没有 `engines.dsh`、没有 DSH `peerDependencies`、安装时不做版本检查。旧包曾在 DSH **0.2.1-rc.3** 实测;0.6.1 请遵循上方版本兼容说明(见 [DSH 侧限制与说明](#dsh-侧限制与说明))。
25
+
26
+ ## 可选记忆插件
27
+
28
+ 插件页签安装公开固定版本 `@rsrsai/dsh@0.1.13`。安装与启用分别确认;出现重启提示时需重启。不会静默降级已安装的新版本,未知版本如实显示未知。每次远程等待上限为两分钟,超时不会取消宿主作业;结果仍未知时,请先在原生插件管理页核实再重试。关闭卡片后不写回旧界面状态,也不会自动启用尚在安装的包。
25
29
 
26
30
  ## 内阁成员配置
27
31
 
@@ -189,7 +193,7 @@ https://raw.githubusercontent.com/luodaoyi/dsh-cabinet-mode/market-index/marketp
189
193
  仅在商店不可用或本地开发时使用。先完全退出桌面 DSH,释放 profile 锁,再执行:
190
194
 
191
195
  ```sh
192
- dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.5.4/dsh-cabinet-mode-0.5.4.tgz
196
+ dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.6.1/dsh-cabinet-mode-0.6.1.tgz
193
197
  dsh plugin --profile desktop list
194
198
  ```
195
199
 
@@ -200,7 +204,7 @@ dsh plugin --profile desktop list
200
204
  若通过插件市场安装:刷新市场,先在**已安装**页卸载旧版本,再从**插件市场**安装新版本,然后重启——没有 tgz URL 要换,也没有一键更新。否则用同一条安装命令换新版本 URL(或在插件页选新 `.tgz`),然后完全退出并重启 DeepSeek Harness:
201
205
 
202
206
  ```sh
203
- dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.5.4/dsh-cabinet-mode-0.5.4.tgz
207
+ dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.6.1/dsh-cabinet-mode-0.6.1.tgz
204
208
  ```
205
209
 
206
210
  `dsh plugin --profile desktop list` 应显示新版本。升级已在 Windows 实测:
@@ -209,6 +213,20 @@ v0.1.2 → v0.1.3 走内嵌 pnpm(DSH 0.2.1-rc.5)。
209
213
 
210
214
  ---
211
215
 
216
+ ## 推荐搭配:持久记忆插件
217
+
218
+ 内阁模式常跑多成员、长跨度的任务。上一轮的决策、死路和文件位置默认不会带进新会话;
219
+ 记忆插件会在相关回合开头自动召回,省去重复推导。
220
+
221
+ 以下两个同源方案**二选一**。两者都会注入记忆规则并在每轮前置召回,同时启用会让两套规则与召回叠加,通常没有必要。
222
+
223
+ | 插件 | 适合 | 机制 | 链接 |
224
+ |---|---|---|---|
225
+ | **respire-dsh**(`@rsrsai/dsh`) | 已在用 `rsrs`,或需要加密库、账号同步、跨宿主共用一份记忆。 | 调用 `rsrs` CLI 与运行中的宿主 runtime;存储、去重、加密、模型推理、账号与同步由 Respire 负责。要求 Node.js 24+、已配置 `rsrs` 与运行中的 runtime;README 的兼容基线为 DSH 0.2.1-rc.5。 | [GitHub](https://github.com/risense-ai/respire-dsh) · [npm](https://www.npmjs.com/package/@rsrsai/dsh) |
226
+ | **dsh-memlite**(`@rsrsai/dsh-memlite`) | 想零外部服务起步,或需要可直接读写 JSONL 的记忆库。 | 进程内运行 `@rsrsai/memlite`:默认 BM25、本地 JSONL 因果树、Obsidian 导入导出与 git 同步。要求 Node.js 18+,不需要 `rsrs`。 | [GitHub](https://github.com/risense-ai/dsh-memlite) · [介绍页](https://risense-ai.github.io/dsh-memlite/) |
227
+
228
+ 安装命令与当前支持的 DSH 版本以各自仓库 README 为准;两者装完都需要重启 DSH。
229
+
212
230
  ## 你会得到什么
213
231
 
214
232
  | | |
@@ -365,3 +383,7 @@ npmjs.com 侧的一次性配置(维护者在网页上完成,无法从本仓
365
383
  ## 许可证
366
384
 
367
385
  [MIT](LICENSE)
386
+
387
+ ### 可选的 Respire 本地源
388
+
389
+ 记忆插件卡可填写 DSH 宿主上的路径,**仅用于首次安装**。依赖可能仍需网络,不保证完全离线。已安装插件拒绝本地源更新:清空输入后使用固定 registry 版本操作,或通过原生插件管理器管理本地包。浏览器存储仅尽力保存;保存失败仍使用当前输入值。只有安装前检查源失败才可能向 registry 回退一次;安装、启用、未知结果或卸载之后不自动执行第二次修改。
package/client.js CHANGED
@@ -2531,6 +2531,7 @@ window.__ModuleLoader__.load({
2531
2531
  八、责任到人:缺陷点名到人到行号,不许用「我们」糊过去。
2532
2532
  九、反制糊弄:报「已完成」必追问证据三件(命令输出、路径行号、未验证清单);报「卡住」必追问三件(已做什么、卡在哪、需要什么);两次含糊即降级处理(换人、拆小)。
2533
2533
  十、收束:闭环才许说「这一版可以交差」,不许提前许诺功劳。
2534
+ 十一、监控纠偏:分派时约定回报节点、产物清单和单一交付范围;按实际可用的团队状态与消息工具检查进展,必要时要求回报做了什么、卡在哪里、需要什么。工具未提供时间字段时不得臆造耗时;文件时间戳仅作辅助,须读回产物并结合执行状态。finished、not found 或暂时沉默均不是成功或安全接管的证据。同一命令反复无进展、任务范围过大时先核实原因,再请求中断;中断返回不代表在途工具或写入已结束。必须确认原执行者及其写入停止后才能重派同一工作,无法确认则报告阻塞,不并发增加第二写入者。收窄任务后可重派或换人;超出当前上下文的回访使用宿主明确支持的调度机制,没有该机制不得承诺定时自动唤醒。
2534
2535
  红线(压过全部话术):只对 AI 阁臣施压,对用户只有敬;不许逼造假、删证据、凑绿;不许人身侮辱辱骂;不许以施压换取违规操作(越权改 live、泄密钥、跳验收);施压必须落在可核验的时间/交付物/判据上,空口威胁无效。`;
2535
2536
  /**
2536
2537
  * Factory duty prompt for each non-Lead member — the office duties the
@@ -3875,9 +3876,250 @@ window.__ModuleLoader__.load({
3875
3876
  };
3876
3877
  }
3877
3878
 
3879
+ // ---------- memory plugin install card (one-click, 方案A) --------------
3880
+ // Optional install channel: set by the ctx.inject guard in apply() and
3881
+ // cleared on dispose. Without the host's plugin-manager remote the card
3882
+ // renders an explicit unavailable line instead of a dead button — the
3883
+ // same degradation as memberRemote and cabinetOpenSession.
3884
+ let cabinetPluginManager = null;
3885
+ const memoryPluginListeners = new Set();
3886
+ const notifyMemoryPlugin = () => { for (const listener of memoryPluginListeners) listener(); };
3887
+ /** Package this card manages. */
3888
+ const MEMORY_PLUGIN_NAME = '@rsrsai/dsh';
3889
+ /** Public pinned package; inspect and install use the same spec. */
3890
+ const MEMORY_PLUGIN_SPEC = '@rsrsai/dsh@0.1.13';
3891
+ /** Browser key holding the optional local-source override (empty = none).
3892
+ * Machines whose registry is unreachable store a path in the card's
3893
+ * local-source box; no machine path may be hardcoded here, and every
3894
+ * failure echoes the spec(s) it actually tried. */
3895
+ const MEMORY_PLUGIN_SPEC_STORAGE_KEY = 'cabinet.memoryPluginSpec';
3896
+ const MEMORY_PLUGIN_SOURCE_VERSION = '';
3897
+ const memoryPluginJobs = new WeakMap();
3898
+ const memoryPluginRestart = new WeakSet();
3899
+ function pluginDeadline(operation, ms = 120000) {
3900
+ let timer;
3901
+ return Promise.race([operation, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Plugin operation timed out; outcome may still be pending. Check the native plugin manager before retrying.')), ms); })]).finally(() => clearTimeout(timer));
3902
+ }
3903
+ /** The five settings tabs, in display order. */
3904
+ const SETTINGS_TABS = ['members', 'avatars', 'models', 'prompts', 'plugin'];
3905
+ /** Derive the card's installed state from a listBundles() reply. */
3906
+ function memoryPluginInstalledOf(bundles) {
3907
+ if (!Array.isArray(bundles)) return null;
3908
+ const hit = bundles.find((entry) => entry && entry.name === MEMORY_PLUGIN_NAME && entry.installed === true);
3909
+ return hit === undefined ? null : { name: MEMORY_PLUGIN_NAME, version: typeof hit.version === 'string' ? hit.version : '', enabled: hit.enabled === true };
3910
+ }
3911
+ /** Read/write the optional local-source override. Both are best-effort:
3912
+ * private modes and test harnesses may expose no storage at all, and an
3913
+ * empty value is removed rather than persisted as a junk string. */
3914
+ function memoryPluginSpecRead() {
3915
+ try {
3916
+ const value = globalThis.localStorage?.getItem(MEMORY_PLUGIN_SPEC_STORAGE_KEY);
3917
+ return typeof value === 'string' ? value.trim() : '';
3918
+ } catch { return ''; }
3919
+ }
3920
+ function memoryPluginSpecWrite(value) {
3921
+ try {
3922
+ const store = globalThis.localStorage;
3923
+ if (!store) return;
3924
+ const text = typeof value === 'string' ? value.trim() : '';
3925
+ if (text === '') store.removeItem(MEMORY_PLUGIN_SPEC_STORAGE_KEY);
3926
+ else store.setItem(MEMORY_PLUGIN_SPEC_STORAGE_KEY, text);
3927
+ } catch { /* no storage available: the override simply does not persist */ }
3928
+ }
3929
+ function MemoryPluginCard(props) {
3930
+ const [, refreshChannel] = React.useState(0);
3931
+ React.useEffect(() => { const listener = () => refreshChannel(n => n + 1); memoryPluginListeners.add(listener); return () => memoryPluginListeners.delete(listener); }, []);
3932
+ const t = typeof props?.t === 'function' ? props.t : memberT;
3933
+ // Explicit props win so a host-driven render (and the tests) can pin the
3934
+ // channel; omitting them reads the injected module state.
3935
+ const manager = props !== undefined && props !== null && Object.hasOwn(props, 'manager') ? props.manager : cabinetPluginManager;
3936
+ const lifetime = React.useRef(null);
3937
+ if (!lifetime.current || lifetime.current.manager !== manager) {
3938
+ if (lifetime.current) lifetime.current.active = false;
3939
+ lifetime.current = {manager, active:true, epoch:0};
3940
+ }
3941
+ const token = lifetime.current;
3942
+ React.useEffect(() => { token.active = true; return () => { token.active = false; }; }, [token]);
3943
+ const [installed, writeInstalled] = React.useState(props?.initialInstalled ?? null);
3944
+ const [working, writeWorking] = React.useState(false);
3945
+ const [progress, writeProgress] = React.useState('');
3946
+ const [failure, writeFailure] = React.useState('');
3947
+ const [restart, writeRestart] = React.useState(manager ? memoryPluginRestart.has(manager) : false);
3948
+ // Optional local-source override, read eagerly so the card face shows
3949
+ // the stored value on first paint.
3950
+ const [specText, writeSpecText] = React.useState(memoryPluginSpecRead());
3951
+ const setInstalled = value => { if (token.active) writeInstalled(value); };
3952
+ const setWorking = value => { if (token.active) writeWorking(value); };
3953
+ const setProgress = value => { if (token.active) writeProgress(value); };
3954
+ const setFailure = value => { if (token.active) writeFailure(value); };
3955
+ const setRestart = value => { if (token.active) writeRestart(value); };
3956
+ const setSpecText = value => { if (token.active) writeSpecText(value); };
3957
+ React.useEffect(() => {
3958
+ let alive = true;
3959
+ const generation = token.epoch;
3960
+ (async () => {
3961
+ if (!manager || typeof manager.listBundles !== 'function') return;
3962
+ try {
3963
+ const reply = await pluginDeadline(manager.listBundles());
3964
+ const found = reply?.ok === true ? memoryPluginInstalledOf(reply.value) : null;
3965
+ if (alive && generation === token.epoch && reply?.ok === true) setInstalled(found);
3966
+ } catch { /* keep the render-time state; the card still shows */ }
3967
+ })();
3968
+ return () => { alive = false; };
3969
+ }, [manager]);
3970
+ // Failures are echoed verbatim: the raw message is the evidence.
3971
+ const fail = (text) => { setWorking(false); setFailure(typeof text === 'string' && text !== '' ? text : String(text)); };
3972
+ const run = async () => {
3973
+ if (!manager || typeof manager.inspect !== 'function' || typeof manager.installBundle !== 'function' || typeof manager.listBundles !== 'function') { fail('pluginManager remote unavailable'); return; }
3974
+ if (memoryPluginJobs.get(manager)?.running) return;
3975
+ if (memoryPluginJobs.get(manager)?.settled === true) memoryPluginJobs.delete(manager);
3976
+ if (memoryPluginJobs.has(manager)) { fail('An operation is pending or its result is unknown. Check the native plugin manager; do not start another installation.'); return; }
3977
+ token.epoch++;
3978
+ const job = {settled:false,running:true}; memoryPluginJobs.set(manager, job);
3979
+ const observe = (operation, update = false) => Promise.resolve(operation).then(reply => {
3980
+ const outcome = update ? reply?.value?.result : reply?.value;
3981
+ job.settled = reply?.ok === true && ['applied','restart-required','failed','cancelled'].includes(outcome?.application);
3982
+ return reply;
3983
+ });
3984
+ let uncertain = false;
3985
+ setWorking(true); setFailure(''); setRestart(memoryPluginRestart.has(manager)); setProgress('');
3986
+ const valueOf = reply => {
3987
+ if (reply?.ok !== true) throw new Error(reply?.error?.message || 'Plugin manager returned no successful reply');
3988
+ return reply.value;
3989
+ };
3990
+ const outcomeOf = outcome => {
3991
+ if (!outcome || !['applied', 'restart-required'].includes(outcome.application)) throw new Error(outcome?.error?.message || outcome?.error?.diagnostic || outcome?.packageResult?.stderr || outcome?.application || 'Unknown plugin application result');
3992
+ if (outcome.application === 'restart-required') { memoryPluginRestart.add(manager); setRestart(true); }
3993
+ return outcome;
3994
+ };
3995
+ /** One attempt against a concrete spec: the upstream 0.6.0 body
3996
+ * (inventory gate, pinned inspect, update/install, enable,
3997
+ * inventory confirm) verbatim, but it resolves {done}/{error}
3998
+ * instead of echoing so run() can annotate and fall back. */
3999
+ const attemptSpec = async (spec) => {
4000
+ let canFallback = false;
4001
+ try {
4002
+ const before = memoryPluginInstalledOf(valueOf(await pluginDeadline(manager.listBundles())));
4003
+ if (before && spec !== MEMORY_PLUGIN_SPEC) throw new Error('Local sources support first installation only. Clear the path for a registry update, or use the native plugin manager. No package was changed.');
4004
+ if (before && before.version !== '0.1.13') {
4005
+ // Only known, older stable versions are offered this pinned update.
4006
+ // The official host independently enforces semver.gt(target, installed).
4007
+ const parts = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.exec(before.version);
4008
+ const values = parts?.slice(1).map(Number);
4009
+ const older = values && values.every(Number.isSafeInteger) && values[0] === 0 && (values[1] === 0 || values[1] === 1 && values[2] < 13);
4010
+ if (!older) throw new Error('Installed version is newer than the pinned version or cannot be safely compared. Use the native plugin manager; no package was changed.');
4011
+ }
4012
+ const inspectionReply = await pluginDeadline(manager.inspect(spec, {}));
4013
+ canFallback = !before;
4014
+ const inspected = valueOf(inspectionReply);
4015
+ if (!inspected || inspected.status !== 'accepted' || inspected.name !== MEMORY_PLUGIN_NAME || inspected.bundle !== true) throw new Error(inspected?.reason || 'Plugin spec refused');
4016
+ canFallback = false;
4017
+ const requestId = globalThis.crypto?.randomUUID?.() || 'cabinet-' + Date.now() + '-' + Math.random().toString(16).slice(2);
4018
+ let outcome;
4019
+ if (before && before.version === '0.1.13') {
4020
+ outcome = { application: 'applied' };
4021
+ } else {
4022
+ if (before && typeof manager.updateBundle !== 'function') throw new Error('Use the native plugin manager to update this installed bundle');
4023
+ uncertain = true;
4024
+ const operation = before ? manager.updateBundle(MEMORY_PLUGIN_NAME, '0.1.13', {requestId}) : manager.installBundle(spec, {enabled:false,requestId});
4025
+ let reply = await pluginDeadline(observe(operation, !!before));
4026
+ if (reply?.ok !== true && !before && typeof manager.waitForInstall === 'function') reply = await pluginDeadline(observe(manager.waitForInstall(requestId)));
4027
+ const result = valueOf(reply);
4028
+ if (!result) throw new Error('Install outcome is unknown; check the native plugin manager before retrying');
4029
+ outcome = before ? result.result : result;
4030
+ if (!outcome || !['applied','restart-required','failed','cancelled'].includes(outcome.application)) throw new Error('Install outcome is unknown');
4031
+ uncertain = false;
4032
+ outcomeOf(outcome);
4033
+ }
4034
+ // Installation and enabling are separate operations; neither implies the other succeeded.
4035
+ setInstalled({name:MEMORY_PLUGIN_NAME,version:outcome.version || before?.version || '',enabled:false});
4036
+ if (!token.active) return { done: true };
4037
+ if (typeof manager.setBundleEnabled !== 'function') throw new Error('Installed, but enable is unavailable; enable it in the native plugin manager');
4038
+ uncertain = true; job.settled = false;
4039
+ const enabled = valueOf(await pluginDeadline(observe(manager.setBundleEnabled(MEMORY_PLUGIN_NAME,true))));
4040
+ if (!enabled || !['applied','restart-required','failed','cancelled'].includes(enabled.application)) throw new Error('Enable outcome is unknown');
4041
+ uncertain = false;
4042
+ outcomeOf(enabled);
4043
+ const found = memoryPluginInstalledOf(valueOf(await pluginDeadline(manager.listBundles())));
4044
+ if (!found) throw new Error('Installation cannot be confirmed from the plugin inventory');
4045
+ setInstalled(found);
4046
+ if (!found.enabled) throw new Error('Installed, but the plugin inventory reports disabled');
4047
+ setFailure('');
4048
+ return { done: true };
4049
+ } catch (error) {
4050
+ return { error: error?.message || String(error), canFallback };
4051
+ }
4052
+ };
4053
+ const specNote = (specs) => ' [spec' + (specs.length > 1 ? 's' : '') + ': ' + specs.join(' → ') + ']';
4054
+ try {
4055
+ // spec = stored local-source override, else the registry default.
4056
+ const overrideSpec = specText.trim();
4057
+ const primarySpec = overrideSpec !== '' ? overrideSpec : MEMORY_PLUGIN_SPEC;
4058
+ let first;
4059
+ try { first = await attemptSpec(primarySpec); } catch (error) { first = { error: error?.message || String(error) }; }
4060
+ if (first.done !== true) {
4061
+ // A definitive failure of the local source falls back to the
4062
+ // registry once; an uncertain outcome keeps the upstream
4063
+ // no-second-operation guard (its job stays registered).
4064
+ if (primarySpec !== MEMORY_PLUGIN_SPEC && first.canFallback === true && uncertain !== true && token.active) {
4065
+ let second;
4066
+ try { second = await attemptSpec(MEMORY_PLUGIN_SPEC); } catch (error) { second = { error: error?.message || String(error) }; }
4067
+ if (second.done !== true) fail(first.error + specNote([primarySpec, MEMORY_PLUGIN_SPEC]) + (second.error && second.error !== first.error ? ' · ' + second.error : ''));
4068
+ } else {
4069
+ fail(first.error + specNote([primarySpec]));
4070
+ }
4071
+ }
4072
+ } catch (error) {
4073
+ fail(error !== null && error !== undefined && typeof error.message === 'string' ? error.message : String(error));
4074
+ } finally {
4075
+ job.running = false;
4076
+ if (!uncertain && memoryPluginJobs.get(manager) === job) memoryPluginJobs.delete(manager);
4077
+ setWorking(false);
4078
+ }
4079
+ };
4080
+ // Version shown on the card: the installed bundle's own version, with
4081
+ // the local source package.json version as display-only fallback.
4082
+ const hasInstalledVersion = installed !== null && typeof installed.version === 'string' && installed.version !== '';
4083
+ const shownVersion = hasInstalledVersion ? installed.version : MEMORY_PLUGIN_SOURCE_VERSION;
4084
+ const line = { fontSize: 11, color: INK3, marginTop: 4 };
4085
+ const border = '1px solid var(--dsw-alias-border-l3, rgba(127,127,127,.28))';
4086
+ return h('div', { 'data-cabinet-plugin-card': 'memory', style: { border, borderRadius: 8, padding: '10px 12px', marginBottom: 10 } }, [
4087
+ h('div', { key: 'head', style: { display: 'flex', alignItems: 'center', gap: 8 } }, [
4088
+ h('span', { key: 'gap', style: { flex: 1 } }),
4089
+ installed !== null ? h('span', { key: 'badge', 'data-cabinet-plugin-state': 'installed', style: { fontSize: 11, color: '#3fb950' } }, t('settings.plugin.installed')) : null
4090
+ ]),
4091
+ // Highlight lines replace the old one-line description; install
4092
+ // specs stay off the card face — the local-source box below is
4093
+ // where a path belongs, and only when the user opts in.
4094
+ h('div', { key: 'hints', style: line }, [1, 2, 3, 4, 5].map((n) => h('div', { key: 'hint' + n, 'data-cabinet-plugin-hint': String(n), style: { ...line, marginTop: 3 } }, t('settings.plugin.hint' + n)))),
4095
+ h('div', { key: 'specRow', style: { ...line, marginTop: 8, display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' } }, [
4096
+ h('label', { key: 'specLabel', style: { fontSize: 11, color: INK2 } }, t('settings.plugin.specLabel')),
4097
+ h('input', { key: 'specInput', 'data-cabinet-plugin-spec-input': '1', type: 'text', value: specText, placeholder: t('settings.plugin.specPlaceholder'), style: { flex: 1, minWidth: 160, fontSize: 11 }, onChange: (event) => { const next = event !== null && event !== undefined && typeof event.target?.value === 'string' ? event.target.value : ''; setSpecText(next); memoryPluginSpecWrite(next); } }),
4098
+ h('button', { key: 'specClear', 'data-cabinet-plugin-spec-clear': '1', type: 'button', disabled: specText === '', style: { fontSize: 11, cursor: 'pointer' }, onClick: () => { setSpecText(''); memoryPluginSpecWrite(''); } }, t('settings.plugin.specClear'))
4099
+ ]),
4100
+ installed !== null
4101
+ ? h('div', { key: 'where', style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginTop: 8 } }, [
4102
+ h('span', { key: 'version', 'data-cabinet-plugin-version': shownVersion, style: { fontSize: 11, color: INK2 } }, shownVersion + (hasInstalledVersion ? '' : ' · ' + t('settings.plugin.versionFallback'))),
4103
+ h('span', { key: 'gap2', style: { flex: 1 } }),
4104
+ h('button', { key: 'update', 'data-cabinet-plugin-action': 'update', type: 'button', disabled: !manager || working, style: { fontSize: 11, cursor: 'pointer' }, onClick: () => { void run(); } }, working ? t('settings.plugin.installing') : t('settings.plugin.update'))
4105
+ ])
4106
+ : h('div', { key: 'row', style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginTop: 8 } }, [
4107
+ h('button', { key: 'install', 'data-cabinet-plugin-action': 'install', type: 'button', disabled: !manager || working, style: { fontSize: 11, cursor: 'pointer' }, onClick: () => { void run(); } }, working ? t('settings.plugin.installing') : t('settings.plugin.install'))
4108
+ ]),
4109
+ !manager ? h('div', { key: 'unavailable', 'data-cabinet-plugin-state': 'unavailable', style: line }, t('settings.plugin.unavailable')) : null,
4110
+ progress !== '' ? h('div', { key: 'progress', 'data-cabinet-plugin-progress': '1', style: line }, progress) : null,
4111
+ restart ? h('div', { key: 'restart', 'data-cabinet-plugin-state': 'restart', style: { ...line, color: '#d29922' } }, t('settings.plugin.restartRequired')) : null,
4112
+ failure !== '' ? h('div', { key: 'failure', 'data-cabinet-plugin-state': 'error', style: { ...line, color: '#f25a5a' } }, failure) : null
4113
+ ]);
4114
+ }
4115
+
3878
4116
  function CabinetMemberSettings(props) {
3879
4117
  const t = typeof props?.t === 'function' ? props.t : memberT;
3880
4118
  const [, redraw] = React.useState(0);
4119
+ // Active settings tab: session-local state (approved plan A). It is a
4120
+ // navigation preference, not user data; the only persisted settings
4121
+ // value is the plugin card's local-source override.
4122
+ const [activeTab, setActiveTab] = React.useState('members');
3881
4123
  const editorRef = React.useRef(null);
3882
4124
  if (!editorRef.current) editorRef.current = createMemberEditor(memberWriter, () => redraw(n => n + 1));
3883
4125
  const editor = editorRef.current;
@@ -3928,7 +4170,7 @@ window.__ModuleLoader__.load({
3928
4170
  onClick: () => resetMember(key)
3929
4171
  }, t('member.reset'))
3930
4172
  ]),
3931
- h('div', { key: 'builtin', style: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', marginBottom: 6 } }, [
4173
+ activeTab === 'avatars' ? h('div', { key: 'builtin', style: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', marginBottom: 6 } }, [
3932
4174
  h('span', { key: 'l', style: { fontSize: 11, color: INK3 } }, t('member.builtin')),
3933
4175
  ...(function () {
3934
4176
  const out = [];
@@ -3956,59 +4198,65 @@ window.__ModuleLoader__.load({
3956
4198
  t('member.upload')
3957
4199
  ]),
3958
4200
  avatars[key] ? h('button', { key: 'clear', type: 'button', style: { fontSize: 11, cursor: 'pointer' }, onClick: () => writeAvatar(key, '') }, t('member.avatar.clear')) : null
3959
- ]),
4201
+ ]) : null,
3960
4202
  errors[key] ? h('div', { key: 'e', style: { fontSize: 11, color: '#f25a5a', marginBottom: 4 } }, errors[key] === 'member.error.model' ? t(errors[key]) : errors[key]) : null,
3961
- h('label', { key: 'name', style: { display: 'block', fontSize: 11, color: INK2, marginBottom: 2 } }, t('member.name')),
3962
- h('input', {
3963
- key: 'ni',
3964
- type: 'text',
3965
- value: draft[key].name,
3966
- maxLength: MEMBER_NAME_LIMIT,
3967
- placeholder: t('member.name.placeholder'),
3968
- style: inputStyle,
3969
- onChange: (event) => update(key, { name: event?.target?.value ?? '' })
3970
- }),
3971
- h('label', { key: 'ml', style: { display: 'block', fontSize: 11, color: INK2, margin: '8px 0 2px' } }, t('member.model')),
3972
- modelOptions.length > 0
3973
- ? (function () {
3974
- const value = draft[key].model || '';
3975
- const opts = [h('option', { key: '', value: '' }, t(key === 'lead' ? 'member.model.defaultLead' : 'member.model.default'))];
3976
- if (value !== '' && !modelOptions.some((option) => option.value === value)) opts.push(h('option', { key: 'current', value }, value));
3977
- for (const option of modelOptions) opts.push(h('option', { key: option.value, value: option.value }, option.label));
3978
- return h('select', {
4203
+ activeTab === 'members' ? [
4204
+ h('label', { key: 'name', style: { display: 'block', fontSize: 11, color: INK2, marginBottom: 2 } }, t('member.name')),
4205
+ h('input', {
4206
+ key: 'ni',
4207
+ type: 'text',
4208
+ value: draft[key].name,
4209
+ maxLength: MEMBER_NAME_LIMIT,
4210
+ placeholder: t('member.name.placeholder'),
4211
+ style: inputStyle,
4212
+ onChange: (event) => update(key, { name: event?.target?.value ?? '' })
4213
+ })
4214
+ ] : null,
4215
+ activeTab === 'models' ? [
4216
+ h('label', { key: 'ml', style: { display: 'block', fontSize: 11, color: INK2, margin: '8px 0 2px' } }, t('member.model')),
4217
+ modelOptions.length > 0
4218
+ ? (function () {
4219
+ const value = draft[key].model || '';
4220
+ const opts = [h('option', { key: '', value: '' }, t(key === 'lead' ? 'member.model.defaultLead' : 'member.model.default'))];
4221
+ if (value !== '' && !modelOptions.some((option) => option.value === value)) opts.push(h('option', { key: 'current', value }, value));
4222
+ for (const option of modelOptions) opts.push(h('option', { key: option.value, value: option.value }, option.label));
4223
+ return h('select', {
4224
+ key: 'mi',
4225
+ value,
4226
+ style: inputStyle,
4227
+ onChange: (event) => update(key, { model: event?.target?.value ?? '' })
4228
+ }, opts);
4229
+ }())
4230
+ : h('input', {
3979
4231
  key: 'mi',
3980
- value,
4232
+ type: 'text',
4233
+ disabled: modelCatalog === undefined,
4234
+ value: draft[key].model,
4235
+ maxLength: 200,
4236
+ placeholder: 'provider/id',
3981
4237
  style: inputStyle,
3982
4238
  onChange: (event) => update(key, { model: event?.target?.value ?? '' })
3983
- }, opts);
3984
- }())
3985
- : h('input', {
3986
- key: 'mi',
3987
- type: 'text',
3988
- disabled: modelCatalog === undefined,
3989
- value: draft[key].model,
3990
- maxLength: 200,
3991
- placeholder: 'provider/id',
3992
- style: inputStyle,
3993
- onChange: (event) => update(key, { model: event?.target?.value ?? '' })
4239
+ }),
4240
+ modelCatalog !== undefined && modelOptions.length === 0 ? h('div', { key: 'mh', style: { fontSize: 11, color: INK3, marginTop: 4 } }, t('member.model.unavailable')) : null,
4241
+ h('div', { key: 'mhint', style: { fontSize: 11, color: INK3, marginTop: 4 } }, t('member.model.hint'))
4242
+ ] : null,
4243
+ activeTab === 'prompts' ? [
4244
+ h('label', { key: 'prompt', style: { display: 'block', fontSize: 11, color: INK2, margin: '8px 0 2px' } }, t('member.prompt')),
4245
+ h('textarea', {
4246
+ key: 'pi',
4247
+ value: promptOf(key),
4248
+ maxLength: MEMBER_PROMPT_LIMIT,
4249
+ rows: key === 'lead' ? 8 : 3,
4250
+ placeholder: t('member.prompt.placeholder'),
4251
+ style: { ...inputStyle, resize: 'vertical', fontFamily: 'inherit' },
4252
+ onChange: (event) => {
4253
+ const value = event?.target?.value ?? '';
4254
+ const mode = value.trim() === '' ? 'off' : 'custom';
4255
+ update(key, { prompt: value, mode }, false);
4256
+ }
3994
4257
  }),
3995
- modelCatalog !== undefined && modelOptions.length === 0 ? h('div', { key: 'mh', style: { fontSize: 11, color: INK3, marginTop: 4 } }, t('member.model.unavailable')) : null,
3996
- h('div', { key: 'mhint', style: { fontSize: 11, color: INK3, marginTop: 4 } }, t('member.model.hint')),
3997
- h('label', { key: 'prompt', style: { display: 'block', fontSize: 11, color: INK2, margin: '8px 0 2px' } }, t('member.prompt')),
3998
- h('textarea', {
3999
- key: 'pi',
4000
- value: promptOf(key),
4001
- maxLength: MEMBER_PROMPT_LIMIT,
4002
- rows: key === 'lead' ? 8 : 3,
4003
- placeholder: t('member.prompt.placeholder'),
4004
- style: { ...inputStyle, resize: 'vertical', fontFamily: 'inherit' },
4005
- onChange: (event) => {
4006
- const value = event?.target?.value ?? '';
4007
- const mode = value.trim() === '' ? 'off' : 'custom';
4008
- update(key, { prompt: value, mode }, false);
4009
- }
4010
- }),
4011
- key === 'lead' ? h('div', { key: 'hint', style: { fontSize: 11, color: INK3, marginTop: 4 } }, t('member.lead.hint')) : null
4258
+ key === 'lead' ? h('div', { key: 'hint', style: { fontSize: 11, color: INK3, marginTop: 4 } }, t('member.lead.hint')) : null
4259
+ ] : null
4012
4260
  ]);
4013
4261
  });
4014
4262
  return h('div', { style: { padding: '4px 2px 20px' } }, [
@@ -4021,9 +4269,27 @@ window.__ModuleLoader__.load({
4021
4269
  !ready ? h('div', { key: 'unavailable', role: 'status' }, t('member.status.unavailable')) : null,
4022
4270
  status ? h('div', { key: 'status', style: { fontSize: 11, color: INK2, marginBottom: 8 } }, t(status)) : null,
4023
4271
  conflict ? h('div', { key: 'conflict', role: 'alert' }, t('member.status.conflict')) : null,
4024
- h('button', { key: 'catalog', type: 'button', onClick: () => refreshCatalog(value => value + 1) }, t('member.model.refresh')),
4025
- modelCatalog?.failures?.length ? h('div', { key: 'catalog-errors', role: 'status' }, t('member.model.partial')) : null,
4026
- h('fieldset', { key: 'fields', disabled: !ready || busy, style: { border: 0, padding: 0, margin: 0 } }, cards),
4272
+ // Tab bar: session-local active tab, one button per field group.
4273
+ // The catalog refresh only serves the model picker, so it lives
4274
+ // with the models tab instead of the global chrome.
4275
+ h('div', { key: 'tabs', role: 'tablist', style: { display: 'flex', gap: 6, marginBottom: 8, flexWrap: 'wrap' } }, SETTINGS_TABS.map((id) => h('button', {
4276
+ key: id,
4277
+ type: 'button',
4278
+ role: 'tab',
4279
+ 'aria-selected': activeTab === id,
4280
+ 'data-cabinet-settings-tab': id,
4281
+ 'data-cabinet-settings-active': activeTab === id ? '1' : '0',
4282
+ style: { fontSize: 11, cursor: 'pointer', padding: '3px 8px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l3, rgba(127,127,127,.4))', background: activeTab === id ? 'rgba(79,140,255,.16)' : 'transparent', color: activeTab === id ? INK : INK2 },
4283
+ onClick: () => setActiveTab(id)
4284
+ }, t('settings.tab.' + id)))),
4285
+ activeTab === 'models' ? h('div', { key: 'catalog-row', style: { marginBottom: 8 } }, [
4286
+ h('button', { key: 'catalog', type: 'button', 'data-cabinet-settings-refresh': '1', onClick: () => refreshCatalog(value => value + 1) }, t('member.model.refresh')),
4287
+ modelCatalog?.failures?.length ? h('div', { key: 'catalog-errors', role: 'status' }, t('member.model.partial')) : null
4288
+ ]) : null,
4289
+ activeTab === 'plugin' ? null : h('fieldset', { key: 'fields', disabled: !ready || busy, style: { border: 0, padding: 0, margin: 0 } }, cards),
4290
+ // Memory plugin card: the plugin tab's own content — hidden on every
4291
+ // other tab, so the default view's save/cancel are never preceded by it.
4292
+ activeTab === 'plugin' ? h(MemoryPluginCard, { key: 'memory-plugin', t }) : null,
4027
4293
  h('button', { key: 'save', type: 'button', disabled: !ready || busy || !dirty || conflict, onClick: () => editor.save() }, t('member.save')),
4028
4294
  h('button', { key: 'cancel', type: 'button', disabled: busy, onClick: () => editor.cancel() }, t('member.cancel'))
4029
4295
  ]);
@@ -4086,6 +4352,26 @@ window.__ModuleLoader__.load({
4086
4352
  'member.model.default': '使用首辅配置;未配置时使用 DSH 默认模型',
4087
4353
  'member.model.defaultLead': '使用 DSH 默认模型',
4088
4354
  'member.model.refresh': '刷新模型目录',
4355
+ 'settings.tab.members': '成员',
4356
+ 'settings.tab.avatars': '头像',
4357
+ 'settings.tab.models': '模型',
4358
+ 'settings.tab.prompts': '提示词',
4359
+ 'settings.tab.plugin': '记忆插件',
4360
+ 'settings.plugin.install': '一键安装',
4361
+ 'settings.plugin.installing': '安装中…',
4362
+ 'settings.plugin.installed': '已安装',
4363
+ 'settings.plugin.update': '更新',
4364
+ 'settings.plugin.versionFallback': '已安装版本未知',
4365
+ 'settings.plugin.restartRequired': '已安装,需重启 DSH 生效',
4366
+ 'settings.plugin.unavailable': '安装通道不可用:宿主未提供 remote.pluginManager。可在宿主会话执行 dsh plugin --profile web add <本地路径> 安装。',
4367
+ 'settings.plugin.specLabel': '宿主本地源(仅首次安装;依赖可能需要网络)',
4368
+ 'settings.plugin.specPlaceholder': '可选:本地源路径;留空则用官方 registry',
4369
+ 'settings.plugin.specClear': '清空',
4370
+ 'settings.plugin.hint1': 'respire/dsh:原生 TypeScript 记忆插件,存储、去重与加密由 rsrs 负责',
4371
+ 'settings.plugin.hint2': '自动召回:新会话自动想起早前结论,不用重复交代背景',
4372
+ 'settings.plugin.hint3': '本地优先:记忆存本机,引擎故障只提示、主任务照跑',
4373
+ 'settings.plugin.hint4': '教训入库:报错与教训沉淀成条,同一坑不踩第二次',
4374
+ 'settings.plugin.hint5': '结构化记忆:正文分段、判重合并,分类树可挂父子',
4089
4375
  'member.model.partial': '部分提供方加载失败;现有选择保留。可刷新重试。',
4090
4376
  'member.error.model': '模型必须为 provider/id,最长 200 字符,不能含控制字符。',
4091
4377
  'member.model.unavailable': '模型列表暂不可用:请手动输入 provider/id。',
@@ -4151,6 +4437,26 @@ window.__ModuleLoader__.load({
4151
4437
  'member.model.default': 'Use Lead configuration, otherwise DSH default',
4152
4438
  'member.model.defaultLead': 'Use DSH default model',
4153
4439
  'member.model.refresh': 'Refresh model catalog',
4440
+ 'settings.tab.members': 'Members',
4441
+ 'settings.tab.avatars': 'Avatars',
4442
+ 'settings.tab.models': 'Models',
4443
+ 'settings.tab.prompts': 'Prompts',
4444
+ 'settings.tab.plugin': 'Memory Plugin',
4445
+ 'settings.plugin.install': 'Install',
4446
+ 'settings.plugin.installing': 'Installing…',
4447
+ 'settings.plugin.installed': 'Installed',
4448
+ 'settings.plugin.update': 'Update',
4449
+ 'settings.plugin.versionFallback': 'Installed version unavailable',
4450
+ 'settings.plugin.restartRequired': 'Installed; restart DSH to take effect',
4451
+ 'settings.plugin.unavailable': 'Install channel unavailable: the host did not expose remote.pluginManager. Run dsh plugin --profile web add <local path> in a host session instead.',
4452
+ 'settings.plugin.specLabel': 'Host-local source (first install only; dependencies may need network)',
4453
+ 'settings.plugin.specPlaceholder': 'Optional local source path; empty uses the official registry',
4454
+ 'settings.plugin.specClear': 'Clear',
4455
+ 'settings.plugin.hint1': 'respire/dsh: native TypeScript memory plugin; rsrs owns storage, dedup and encryption',
4456
+ 'settings.plugin.hint2': 'Auto-recall: a new session resurfaces earlier conclusions without re-briefing',
4457
+ 'settings.plugin.hint3': 'Local first: memories stay on this machine; an engine outage only notices, work continues',
4458
+ 'settings.plugin.hint4': 'Lessons recorded: errors and pitfalls are stored, to help avoid repeating earlier mistakes',
4459
+ 'settings.plugin.hint5': 'Structured memory: sectioned bodies, dedup and merges, a taxonomy tree with parents',
4154
4460
  'member.model.partial': 'Some providers failed to load; saved choices are retained. Refresh to retry.',
4155
4461
  'member.error.model': 'Use provider/id, at most 200 characters, without control characters.',
4156
4462
  'member.model.unavailable': 'Model list unavailable: type provider/id manually.',
@@ -4217,6 +4523,19 @@ window.__ModuleLoader__.load({
4217
4523
  return () => { if (cabinetOpenSession === opener) cabinetOpenSession = null; };
4218
4524
  }, 'cabinet-ui: open teammate session');
4219
4525
  });
4526
+ // Optional install channel for the memory-plugin card: its own guard, so
4527
+ // a host without the plugin manager leaves the model-catalog remote and
4528
+ // every other channel exactly as it was.
4529
+ ctx.inject(['remote', 'remote.pluginManager'], (scope) => {
4530
+ const remote = scope.remote;
4531
+ const manager = remote !== undefined && remote !== null ? remote.pluginManager : undefined;
4532
+ if (!manager || typeof manager.inspect !== 'function' || typeof manager.installBundle !== 'function') return;
4533
+ scope.effect(() => {
4534
+ cabinetPluginManager = manager;
4535
+ notifyMemoryPlugin();
4536
+ return () => { if (cabinetPluginManager === manager) { cabinetPluginManager = null; notifyMemoryPlugin(); } };
4537
+ }, 'cabinet-ui: memory plugin manager');
4538
+ });
4220
4539
  // Stage one: declare the page type. No patterns => a page type, opened by kind.
4221
4540
  ctx.effect(() => ctx.sidebarRightTabs.register({
4222
4541
  id: TAB_ID,
package/index.js CHANGED
@@ -149,6 +149,7 @@ const DEFAULT_LEAD_PROMPT = `【御下术·仅首辅适用】
149
149
  八、责任到人:缺陷点名到人到行号,不许用「我们」糊过去。
150
150
  九、反制糊弄:报「已完成」必追问证据三件(命令输出、路径行号、未验证清单);报「卡住」必追问三件(已做什么、卡在哪、需要什么);两次含糊即降级处理(换人、拆小)。
151
151
  十、收束:闭环才许说「这一版可以交差」,不许提前许诺功劳。
152
+ 十一、监控纠偏:分派时约定回报节点、产物清单和单一交付范围;按实际可用的团队状态与消息工具检查进展,必要时要求回报做了什么、卡在哪里、需要什么。工具未提供时间字段时不得臆造耗时;文件时间戳仅作辅助,须读回产物并结合执行状态。finished、not found 或暂时沉默均不是成功或安全接管的证据。同一命令反复无进展、任务范围过大时先核实原因,再请求中断;中断返回不代表在途工具或写入已结束。必须确认原执行者及其写入停止后才能重派同一工作,无法确认则报告阻塞,不并发增加第二写入者。收窄任务后可重派或换人;超出当前上下文的回访使用宿主明确支持的调度机制,没有该机制不得承诺定时自动唤醒。
152
153
  红线(压过全部话术):只对 AI 阁臣施压,对用户只有敬;不许逼造假、删证据、凑绿;不许人身侮辱辱骂;不许以施压换取违规操作(越权改 live、泄密钥、跳验收);施压必须落在可核验的时间/交付物/判据上,空口威胁无效。`;
153
154
 
154
155
  /** Declarative wire schema: no transform callbacks requiring browser eval.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cabinet-mode",
3
- "version": "0.5.4",
3
+ "version": "0.6.1",
4
4
  "description": "Cabinet Mode (内阁模式) for DeepSeek Harness: a declarative DSH bundle that adds a dual-identity Lead/teammate agent preset for the Great Ming Research Bureau cabinet team.",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.svg",
@@ -6,6 +6,16 @@ let client;
6
6
  const source = readFileSync(new URL('../client.js', import.meta.url), 'utf8');
7
7
  const exportPoint = 'return { inject, apply };';
8
8
  assert.equal(source.split(exportPoint).length, 2);
9
+ // PR#22 coderabbit Major: client.js must not hardcode a machine home path.
10
+ assert.ok(!source.includes('/home/fslong'), 'client.js source carries no hardcoded home path');
11
+ // The card persists its optional local-source override in localStorage; both
12
+ // VM realms below get a minimal store so the save/clear paths are observable.
13
+ const pluginSpecStore = new Map();
14
+ const pluginSpecStorage = {
15
+ getItem: (key) => (pluginSpecStore.has(key) ? pluginSpecStore.get(key) : null),
16
+ setItem: (key, value) => { pluginSpecStore.set(key, String(value)); },
17
+ removeItem: (key) => { pluginSpecStore.delete(key); },
18
+ };
9
19
  const React = {
10
20
  useId: () => 'test-mask',
11
21
  createElement: (type, props, ...children) => ({ type, props, children }),
@@ -14,9 +24,9 @@ const React = {
14
24
  useCallback: (callback) => callback,
15
25
  useLayoutEffect: () => {}, useEffect: () => {},
16
26
  };
17
- runInNewContext(source.replace(exportPoint,
18
- 'return { inject, apply, avatarFor, displayName, CabinetPanel, MemberCard, TaskLine, TaskEdgeLayer, buildTaskEdges, taskEdgesEqual, zh, en, BUREAUX, AVATARS, setMemberConfig, memberLabel, configuredAvatar, configuredPrompt, factoryPromptFor, DEFAULT_MEMBER_PROMPTS, DEFAULT_LEAD_PROMPT };'), {
19
- window: { __ModuleLoader__: { load: ({ factory }) => {
27
+ const exportList = 'return { inject, apply, avatarFor, displayName, CabinetPanel, MemberCard, TaskLine, TaskEdgeLayer, buildTaskEdges, taskEdgesEqual, zh, en, BUREAUX, AVATARS, setMemberConfig, memberLabel, configuredAvatar, configuredPrompt, factoryPromptFor, DEFAULT_MEMBER_PROMPTS, DEFAULT_LEAD_PROMPT, CabinetMemberSettings, MemoryPluginCard, memoryPluginInstalledOf, SETTINGS_TABS };';
28
+ runInNewContext(source.replace(exportPoint, exportList), {
29
+ setTimeout: (fn, ms) => setTimeout(fn, ms === 120000 ? 20 : ms), clearTimeout, localStorage: pluginSpecStorage, window: { __ModuleLoader__: { load: ({ factory }) => {
20
30
  client = factory((name) => { assert.equal(name, 'react'); return React; });
21
31
  } } },
22
32
  });
@@ -89,6 +99,9 @@ for (const key of ['hanlin', 'works', 'dali', 'yushi']) {
89
99
  assert.ok(client.factoryPromptFor(key).length <= 400, `${key} factory prompt must stay under 400 chars`);
90
100
  }
91
101
  assert.ok(client.DEFAULT_LEAD_PROMPT.includes('御下术'));
102
+ for (const clause of ['监控纠偏', '中断返回不代表', '写入停止后', '不并发增加第二写入者', '没有该机制不得承诺定时自动唤醒']) {
103
+ assert.ok(client.DEFAULT_LEAD_PROMPT.includes(clause), `lead prompt carries the monitoring/correction clause: ${clause}`);
104
+ }
92
105
  client.setMemberConfig({ members: [{ key: 'hanlin', name: '张翰林', prompt: '', mode: '' }] });
93
106
  assert.equal(client.memberLabel('hanlin'), '张翰林 · hanlin');
94
107
  assert.equal(client.configuredPrompt('hanlin'), client.factoryPromptFor('hanlin'), 'unconfigured mode keeps the factory prompt');
@@ -388,3 +401,350 @@ assert.equal(adjacent.length,1);assert.notEqual(adjacent[0].s[1],adjacent[0].e[1
388
401
  assert.ok(adjacent[0].c1[0]>adjacent[0].s[0]);
389
402
  console.log('PASS: adjacent same-column rows retain a nonzero gutter curve');
390
403
  console.log('PASS: edge direction blocker → blocked (start on blocker row, dot on blocked row) and click-to-open binding rules (lead/unassigned/inert never bind)');
404
+
405
+ // --- settings page: four tabs + the memory-plugin card ----------------------
406
+ // The shared React double above keeps useState inert; this second instance gives
407
+ // the settings page a stateful double so a tab click can be observed by
408
+ // re-rendering the same component with the updated state store.
409
+ let settingsClient;
410
+ const settingsState = [];
411
+ let settingsCursor = 0;
412
+ const SettingsReact = {
413
+ ...React,
414
+ useState: (initial) => {
415
+ const index = settingsCursor++;
416
+ if (!(index in settingsState)) settingsState[index] = initial;
417
+ return [settingsState[index], (next) => { settingsState[index] = typeof next === 'function' ? next(settingsState[index]) : next; }];
418
+ },
419
+ };
420
+ runInNewContext(source.replace(exportPoint, exportList), {
421
+ setTimeout: (fn, ms) => setTimeout(fn, ms === 120000 ? 20 : ms), clearTimeout, localStorage: pluginSpecStorage, window: { __ModuleLoader__: { load: ({ factory }) => { settingsClient = factory((name) => { assert.equal(name, 'react'); return SettingsReact; }); } } },
422
+ });
423
+ const mountSettings = (props) => {
424
+ settingsState.length = 0;
425
+ settingsCursor = 0;
426
+ return () => { settingsCursor = 0; return elements(settingsClient.CabinetMemberSettings(props)); };
427
+ };
428
+ const tabButton = (nodes, id) => nodes.find((node) => node.props?.['data-cabinet-settings-tab'] === id);
429
+
430
+ const renderSettings = mountSettings({ t: (key) => key });
431
+ let nodes = renderSettings();
432
+ assert.deepEqual(['members', 'avatars', 'models', 'prompts', 'plugin'].map((id) => tabButton(nodes, id)?.props['data-cabinet-settings-tab']),
433
+ ['members', 'avatars', 'models', 'prompts', 'plugin'], 'the settings page exposes five tabs in order');
434
+ assert.equal(tabButton(nodes, 'members').props['data-cabinet-settings-active'], '1', 'the members tab starts active');
435
+ assert.ok(nodes.some((node) => node.props?.key === 'name'), 'members tab shows the name field');
436
+ assert.ok(!nodes.some((node) => node.props?.key === 'pi'), 'prompt textarea is not on the members tab');
437
+ assert.ok(!nodes.some((node) => node.props?.key === 'builtin'), 'avatar row is not on the members tab');
438
+ assert.ok(nodes.some((node) => node.props?.key === 'head'), 'row head stays visible so members remain identifiable');
439
+ // The card lives inside the plugin tab now: absent by default, shown while the
440
+ // tab is active, and it is still the content directly above save/cancel there.
441
+ assert.equal(nodes.findIndex((node) => node.props?.['data-cabinet-plugin-card']), -1, 'the memory-plugin card is not on the default members tab');
442
+ tabButton(nodes, 'plugin').props.onClick();
443
+ nodes = renderSettings();
444
+ const cardAt = nodes.findIndex((node) => node.props?.['data-cabinet-plugin-card']);
445
+ const saveAt = nodes.findIndex((node) => node.props?.key === 'save');
446
+ assert.ok(cardAt >= 0, 'clicking the plugin tab shows the memory-plugin card');
447
+ assert.ok(saveAt > cardAt, 'the card sits directly above the save/cancel row while its tab is active');
448
+ assert.ok(!nodes.some((node) => node.props?.key === 'fields'), 'the plugin tab renders no members fieldset: its own content is the plugin card, and member shells without their sections would only be empty head rows');
449
+ tabButton(nodes, 'members').props.onClick();
450
+ nodes = renderSettings();
451
+ assert.ok(!nodes.some((node) => node.props?.['data-cabinet-plugin-card']), 'leaving the plugin tab hides the card again');
452
+ assert.ok(nodes.some((node) => node.props?.key === 'cancel'), 'cancel survives the restructure');
453
+
454
+ tabButton(nodes, 'models').props.onClick();
455
+ nodes = renderSettings();
456
+ assert.equal(tabButton(nodes, 'models').props['data-cabinet-settings-active'], '1', 'clicking a tab activates it');
457
+ assert.ok(nodes.some((node) => node.props?.['data-cabinet-settings-refresh'] === '1'), 'the catalog refresh moved into the models tab');
458
+ assert.ok(nodes.some((node) => node.props?.key === 'ml'), 'models tab shows the model field');
459
+ assert.ok(!nodes.some((node) => node.props?.key === 'name'), 'name field is not on the models tab');
460
+
461
+ tabButton(nodes, 'prompts').props.onClick();
462
+ nodes = renderSettings();
463
+ assert.ok(nodes.some((node) => node.props?.key === 'pi'), 'prompts tab shows the prompt textarea');
464
+ assert.ok(!nodes.some((node) => node.props?.key === 'ml'), 'model field is not on the prompts tab');
465
+
466
+ tabButton(nodes, 'avatars').props.onClick();
467
+ nodes = renderSettings();
468
+ assert.ok(nodes.some((node) => node.props?.key === 'builtin'), 'avatars tab shows the portrait row');
469
+ assert.ok(!nodes.some((node) => node.props?.key === 'pi'), 'prompt textarea is not on the avatars tab');
470
+ assert.ok(nodes.some((node) => node.props?.key === 'head'), 'row head stays visible on every member tab');
471
+
472
+ // Memory-plugin card: no channel degrades loudly, the installed state offers
473
+ // update (never one-click install), specs stay off the card face, the version
474
+ // falls back to the local source package.json, and failures echo verbatim.
475
+ settingsState.length = 0; settingsCursor = 0;
476
+ let cardNodes = elements(settingsClient.MemoryPluginCard({ t: (key) => key }));
477
+ assert.ok(cardNodes.some((node) => node.props?.['data-cabinet-plugin-state'] === 'unavailable'), 'a missing channel is stated, not silent');
478
+ const deadButton = cardNodes.find((node) => node.props?.['data-cabinet-plugin-action'] === 'install');
479
+ assert.ok(deadButton && deadButton.props.disabled === true, 'the install button stays disabled without a channel');
480
+ const faceTextOf = (rendered) => JSON.stringify(rendered.map((node) => node.props));
481
+ assert.ok(!faceTextOf(cardNodes).includes('file:'), 'the local file: spec is never rendered on the card');
482
+ assert.ok(!faceTextOf(cardNodes).includes('@rsrsai/dsh@'), 'the registry spec is never rendered on the card');
483
+ assert.ok(cardNodes.some((node) => node.props?.['data-cabinet-plugin-hint'] !== undefined), 'the highlight list renders on the card face');
484
+
485
+ settingsState.length = 0; settingsCursor = 0;
486
+ cardNodes = elements(settingsClient.MemoryPluginCard({ t: (key) => key, initialInstalled: { name: '@rsrsai/dsh', version: '0.1.13', enabled: true } }));
487
+ assert.ok(cardNodes.some((node) => node.props?.['data-cabinet-plugin-state'] === 'installed'), 'the installed state is announced');
488
+ assert.ok(!cardNodes.some((node) => node.props?.['data-cabinet-plugin-action'] === 'install'), 'the installed state shows no one-click install button');
489
+ const updateButton = cardNodes.find((node) => node.props?.['data-cabinet-plugin-action'] === 'update');
490
+ assert.ok(updateButton && updateButton.props.disabled === true, 'the installed state offers an update button, disabled without a channel');
491
+ const versionNode = cardNodes.find((node) => node.props?.['data-cabinet-plugin-version'] !== undefined);
492
+ assert.ok(versionNode && String(versionNode.children.flat().join('')).includes('0.1.13'), 'the installed version is visible on the card');
493
+ assert.ok(!faceTextOf(cardNodes).includes('file:'), 'the file: spec stays hidden in the installed state');
494
+ assert.ok(!faceTextOf(cardNodes).includes('@rsrsai/dsh@'), 'the registry spec stays hidden in the installed state');
495
+
496
+ settingsState.length = 0; settingsCursor = 0;
497
+ cardNodes = elements(settingsClient.MemoryPluginCard({ t: (key) => key, initialInstalled: { name: '@rsrsai/dsh', version: '', enabled: true } }));
498
+ const fallbackVersionNode = cardNodes.find((node) => node.props?.['data-cabinet-plugin-version'] !== undefined);
499
+ assert.ok(fallbackVersionNode && !String(fallbackVersionNode.children.flat().join('')).includes('0.1.13'), 'unknown installed version must not claim the source version');
500
+ assert.ok(fallbackVersionNode && String(fallbackVersionNode.children.flat().join('')).includes('settings.plugin.versionFallback'), 'the version fallback is marked on the card');
501
+
502
+ const mappedInstalled = settingsClient.memoryPluginInstalledOf([{ name: '@rsrsai/dsh', installed: true, version: '0.1.13', enabled: true }]);
503
+ // Field-by-field: the module lives in its own realm, so deepStrictEqual would
504
+ // compare a foreign Object.prototype and fail on identical fields.
505
+ assert.equal(mappedInstalled && mappedInstalled.name, '@rsrsai/dsh', 'listBundles shape maps to the card state');
506
+ assert.equal(mappedInstalled && mappedInstalled.version, '0.1.13', 'the installed version is carried through');
507
+ assert.equal(mappedInstalled && mappedInstalled.enabled, true, 'the enabled flag is carried through');
508
+ assert.equal(settingsClient.memoryPluginInstalledOf([{ name: 'other', installed: true }]), null, 'other bundles never count as ours');
509
+ assert.equal(settingsClient.memoryPluginInstalledOf('junk'), null, 'malformed replies never throw');
510
+
511
+ settingsState.length = 0; settingsCursor = 0;
512
+ const failingManager = {
513
+ inspect: async () => ({ ok: false, error: { message: 'boom: registry unreachable' } }),
514
+ installBundle: async () => ({ ok: false, error: { message: 'unreachable' } }),
515
+ listBundles: async () => ({ok:true,value:[]}),
516
+ };
517
+ cardNodes = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: failingManager }));
518
+ const installButton = cardNodes.find((node) => node.props?.['data-cabinet-plugin-action'] === 'install');
519
+ assert.ok(installButton && installButton.props.disabled === false, 'a live channel offers the install button');
520
+ installButton.props.onClick();
521
+ await new Promise((resolve) => setTimeout(resolve, 0));
522
+ settingsCursor = 0;
523
+ cardNodes = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: failingManager }));
524
+ const errorNode = cardNodes.find((node) => node.props?.['data-cabinet-plugin-state'] === 'error');
525
+ assert.ok(errorNode, 'a failed install is visible');
526
+ assert.ok(String(errorNode.children.flat().join('')).includes('boom: registry unreachable'), 'the raw error text is echoed verbatim');
527
+
528
+ settingsState.length = 0; settingsCursor = 0;
529
+ const updateInstalled = { name: '@rsrsai/dsh', version: '0.1.13', enabled: true };
530
+ cardNodes = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: failingManager, initialInstalled: updateInstalled }));
531
+ const updateClick = cardNodes.find((node) => node.props?.['data-cabinet-plugin-action'] === 'update');
532
+ assert.ok(updateClick, 'the installed state wires the update action');
533
+ assert.ok(updateClick && updateClick.props.disabled === false, 'a live channel enables the update action');
534
+ updateClick.props.onClick();
535
+ await new Promise((resolve) => setTimeout(resolve, 0));
536
+ settingsCursor = 0;
537
+ cardNodes = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: failingManager, initialInstalled: updateInstalled }));
538
+ const updateError = cardNodes.find((node) => node.props?.['data-cabinet-plugin-state'] === 'error');
539
+ assert.ok(updateError && String(updateError.children.flat().join('')).includes('boom: registry unreachable'), 'the update button reuses the install chain and echoes its failure verbatim');
540
+
541
+ // PR#22 coderabbit Major follow-up: no hardcoded machine path — the card reads
542
+ // its optional local-source override from localStorage (cabinet.memoryPluginSpec),
543
+ // tries it before the registry default, falls back once, and notes the specs.
544
+ pluginSpecStore.clear();
545
+ settingsState.length = 0; settingsCursor = 0;
546
+ let specCard = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: failingManager }));
547
+ const specInput = specCard.find((node) => node.props?.['data-cabinet-plugin-spec-input']);
548
+ assert.ok(specInput, 'the card renders the optional local-source input');
549
+ assert.equal(specInput.props.value, '', 'the input starts empty with no stored override');
550
+ specInput.props.onChange({ target: { value: '/tmp/local-source' } });
551
+ assert.equal(pluginSpecStore.get('cabinet.memoryPluginSpec'), '/tmp/local-source', 'typing saves the override to localStorage');
552
+ settingsState.length = 0; settingsCursor = 0;
553
+ specCard = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: failingManager }));
554
+ assert.equal(specCard.find((node) => node.props?.['data-cabinet-plugin-spec-input']).props.value, '/tmp/local-source', 'a stored override is shown on the card');
555
+ const specClear = specCard.find((node) => node.props?.['data-cabinet-plugin-spec-clear']);
556
+ assert.ok(specClear && specClear.props.disabled === false, 'the clear button is offered once a value is stored');
557
+ specClear.props.onClick();
558
+ assert.equal(pluginSpecStore.has('cabinet.memoryPluginSpec'), false, 'clearing removes the key instead of persisting an empty string');
559
+
560
+ // Spec selection: no override goes straight to the registry default; a stored
561
+ // override is tried first and the registry default is the single fallback.
562
+ const specCalls = [];
563
+ const specRefusingManager = {
564
+ inspect: async (spec) => { specCalls.push(spec); return { ok: false, error: { message: 'refused: ' + spec } }; },
565
+ installBundle: async (spec) => { specCalls.push(spec); return { ok: false, error: { message: 'unreachable' } }; },
566
+ listBundles: async () => ({ ok: true, value: [] }),
567
+ };
568
+ settingsState.length = 0; settingsCursor = 0;
569
+ specCard = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: specRefusingManager }));
570
+ specCard.find((node) => node.props?.['data-cabinet-plugin-action'] === 'install').props.onClick();
571
+ await new Promise((resolve) => setTimeout(resolve, 0));
572
+ assert.deepEqual(specCalls.slice(), ['@rsrsai/dsh@0.1.13'], 'without an override the run chain goes straight to the registry default');
573
+ settingsCursor = 0;
574
+ specCard = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: specRefusingManager }));
575
+ const defaultError = specCard.find((node) => node.props?.['data-cabinet-plugin-state'] === 'error');
576
+ const defaultErrorText = String(defaultError.children.flat().join(''));
577
+ assert.ok(defaultErrorText.includes('refused: @rsrsai/dsh@0.1.13'), 'the single-spec failure is echoed verbatim');
578
+ assert.ok(defaultErrorText.includes('[spec: @rsrsai/dsh@0.1.13]'), 'the failure notes the spec it tried');
579
+
580
+ pluginSpecStore.set('cabinet.memoryPluginSpec', '/tmp/local-source');
581
+ specCalls.length = 0;
582
+ settingsState.length = 0; settingsCursor = 0;
583
+ specCard = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: specRefusingManager }));
584
+ specCard.find((node) => node.props?.['data-cabinet-plugin-action'] === 'install').props.onClick();
585
+ await new Promise((resolve) => setTimeout(resolve, 0));
586
+ assert.deepEqual(specCalls.slice(), ['/tmp/local-source', '@rsrsai/dsh@0.1.13'], 'a failing override falls back to the registry default exactly once, in order');
587
+ settingsCursor = 0;
588
+ specCard = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: specRefusingManager }));
589
+ const fallbackError = specCard.find((node) => node.props?.['data-cabinet-plugin-state'] === 'error');
590
+ const fallbackErrorText = String(fallbackError.children.flat().join(''));
591
+ assert.ok(fallbackErrorText.includes('refused: /tmp/local-source'), 'the override error is echoed verbatim');
592
+ assert.ok(fallbackErrorText.includes('/tmp/local-source') && fallbackErrorText.includes('@rsrsai/dsh@0.1.13'), 'both tried specs are noted when both attempts fail');
593
+
594
+ // A successful override must not trigger the fallback at all.
595
+ pluginSpecStore.set('cabinet.memoryPluginSpec', '/tmp/ok-source');
596
+ const okSpecCalls = [];
597
+ let localInstalled = false;
598
+ const okSpecManager = {
599
+ inspect: async (spec) => { okSpecCalls.push(spec); return { ok: true, value: { status: 'accepted', name: '@rsrsai/dsh', bundle: true } }; },
600
+ installBundle: async (spec) => { localInstalled = true; okSpecCalls.push(spec); return { ok: true, value: { application: 'applied', bundle: '@rsrsai/dsh', version: '0.1.13' } }; },
601
+ setBundleEnabled: async () => ({ ok: true, value: { application: 'applied' } }),
602
+ listBundles: async () => ({ ok: true, value: localInstalled ? [{ name: '@rsrsai/dsh', installed: true, version: '0.1.13', enabled: true }] : [] }),
603
+ };
604
+ settingsState.length = 0; settingsCursor = 0;
605
+ specCard = elements(settingsClient.MemoryPluginCard({ t: (key) => key, manager: okSpecManager }));
606
+ specCard.find((node) => node.props?.['data-cabinet-plugin-action'] === 'install').props.onClick();
607
+ await new Promise((resolve) => setTimeout(resolve, 0));
608
+ assert.equal(okSpecCalls.length, 2, 'inspect and actual install both run');
609
+ assert.ok(localInstalled, 'installation changes inventory');
610
+ assert.ok(okSpecCalls.length > 0 && okSpecCalls.every((spec) => spec === '/tmp/ok-source'), 'a successful override never touches the registry fallback');
611
+
612
+ // A displayed override remains authoritative even when storage rejects writes.
613
+ for (const scenario of ['storage', 'installed', 'enable-failed']) {
614
+ pluginSpecStore.clear(); settingsState.length = 0; settingsCursor = 0;
615
+ let added = false; const calls = [];
616
+ const manager = {
617
+ listBundles: async () => ({ok:true,value: (added || scenario === 'installed') ? [{name:'@rsrsai/dsh',installed:true,version:'0.1.13',enabled:false}] : []}),
618
+ inspect: async spec => { calls.push(['inspect',spec]); return {ok:true,value:{status:'accepted',name:'@rsrsai/dsh',bundle:true}}; },
619
+ installBundle: async spec => { calls.push(['install',spec]); added=true;return {ok:true,value:{application:'applied',version:'0.1.13'}}; },
620
+ setBundleEnabled: async () => { calls.push(['enable']); return {ok:true,value:{application:'failed',error:{message:'enable refused'}}}; }
621
+ };
622
+ let nodes=elements(settingsClient.MemoryPluginCard({manager,t:k=>k}));
623
+ const write=pluginSpecStorage.setItem; pluginSpecStorage.setItem=()=>{throw Error('storage denied')};
624
+ nodes.find(n=>n.props?.['data-cabinet-plugin-spec-input']).props.onChange({target:{value:'/tmp/session-only'}});
625
+ pluginSpecStorage.setItem=write; settingsCursor=0;
626
+ nodes=elements(settingsClient.MemoryPluginCard({manager,t:k=>k}));
627
+ nodes.find(n=>n.props?.['data-cabinet-plugin-action']).props.onClick();
628
+ await new Promise(r=>setTimeout(r,0));
629
+ if(scenario==='installed') assert.deepEqual(calls,[], 'local update refuses before any inspection/mutation');
630
+ else assert.deepEqual(calls,[['inspect','/tmp/session-only'],['install','/tmp/session-only'],['enable']], 'current input survives failed persistence; enable failure never retries');
631
+ }
632
+
633
+ // Pending or rejected inspection promises must never start a fallback mutation.
634
+ for (const outcome of ['late-accepted', 'late-refused', 'rejected']) {
635
+ pluginSpecStore.set('cabinet.memoryPluginSpec', '/tmp/pending-source');
636
+ settingsState.length=0;settingsCursor=0;
637
+ const calls=[];let resolveInspection;
638
+ const manager={
639
+ listBundles:async()=>({ok:true,value:[]}),
640
+ inspect:spec=>{calls.push(['inspect',spec]);return outcome==='rejected'?Promise.reject(Error('transport failed')):new Promise(resolve=>{resolveInspection=resolve});},
641
+ installBundle:async()=>{calls.push(['install']);throw Error('must not install');},
642
+ setBundleEnabled:async()=>{calls.push(['enable']);throw Error('must not enable');}
643
+ };
644
+ let nodes=elements(settingsClient.MemoryPluginCard({manager,t:k=>k}));
645
+ nodes.find(n=>n.props?.['data-cabinet-plugin-action']).props.onClick();
646
+ await new Promise(r=>setTimeout(r,50));
647
+ assert.deepEqual(calls,[['inspect','/tmp/pending-source']],outcome+' causes no registry fallback');
648
+ settingsCursor=0;nodes=elements(settingsClient.MemoryPluginCard({manager,t:k=>k}));
649
+ assert.ok(nodes.some(n=>n.props?.['data-cabinet-plugin-state']==='error'), 'failure is visible');
650
+ resolveInspection?.({ok:true,value:{status:outcome==='late-accepted'?'accepted':'refused',name:'@rsrsai/dsh',bundle:true}});
651
+ await new Promise(r=>setTimeout(r,0));
652
+ assert.deepEqual(calls,[['inspect','/tmp/pending-source']], 'late response cannot resume installation');
653
+ }
654
+ console.log('PASS: inspection timeout, late acceptance/refusal and transport rejection cause no fallback mutation');
655
+
656
+ pluginSpecStore.delete('cabinet.memoryPluginSpec');
657
+
658
+ // Both dictionaries carry the same settings.* keys (nothing may exist in one
659
+ // language only) and every tab id is translatable.
660
+ const zhSettingsKeys = Object.keys(client.zh).filter((key) => key.startsWith('settings.'));
661
+ const enSettingsKeys = Object.keys(client.en).filter((key) => key.startsWith('settings.'));
662
+ assert.ok(zhSettingsKeys.length >= 17, 'settings copy exists in zh, got ' + zhSettingsKeys.length);
663
+ assert.deepEqual(zhSettingsKeys.slice().sort(), enSettingsKeys.slice().sort(), 'zh and en settings keys must match exactly');
664
+ for (const id of ['members', 'avatars', 'models', 'prompts', 'plugin']) {
665
+ assert.ok(zhSettingsKeys.includes('settings.tab.' + id), 'tab label present in zh: ' + id);
666
+ }
667
+ for (const key of ['settings.plugin.install', 'settings.plugin.installing', 'settings.plugin.installed', 'settings.plugin.update', 'settings.plugin.versionFallback', 'settings.plugin.restartRequired', 'settings.plugin.unavailable']) {
668
+ assert.ok(zhSettingsKeys.includes(key), 'plugin card copy present: ' + key);
669
+ }
670
+ for (const n of [1, 2, 3, 4, 5]) {
671
+ const key = 'settings.plugin.hint' + n;
672
+ assert.ok(zhSettingsKeys.includes(key), 'highlight line copy present: ' + key);
673
+ assert.ok(enSettingsKeys.includes(key), 'highlight line copy present in en: ' + key);
674
+ }
675
+ for (const key of ['settings.plugin.specLabel', 'settings.plugin.specPlaceholder', 'settings.plugin.specClear']) {
676
+ assert.ok(zhSettingsKeys.includes(key), 'local-source copy present: ' + key);
677
+ assert.ok(enSettingsKeys.includes(key), 'local-source copy present in en: ' + key);
678
+ }
679
+ console.log('PASS: five settings tabs switch by section; the plugin card keeps specs off its face, renders highlight lines and the local-source override box, offers update with a visible version, falls back from a failing override to the registry default, and echoes failures verbatim with the tried specs; bilingual settings keys match');
680
+
681
+ // Installation state machine uses the real remote Result envelope.
682
+ for (const scenario of ['success','install-failed','enable-failed','missing-wait','timeout','restart','update','missing-enable','wait-null','wait-failed']) {
683
+ settingsState.length=0;settingsCursor=0;
684
+ let installs=0,enabled=false,installed=scenario==='update', version=scenario==='update'?'0.1.12':'0.1.13';
685
+ const ok=value=>({ok:true,value});
686
+ const manager={
687
+ listBundles:async()=>ok(installed?[{name:'@rsrsai/dsh',installed:true,version,enabled}]:[]),
688
+ inspect:async(spec)=>{assert.equal(spec,'@rsrsai/dsh@0.1.13');return ok({status:'accepted',name:'@rsrsai/dsh',bundle:true});},
689
+ installBundle:async(spec)=>{installs++;assert.equal(spec,'@rsrsai/dsh@0.1.13');
690
+ if(scenario==='timeout')return new Promise(()=>{});
691
+ if(['missing-wait','wait-null','wait-failed'].includes(scenario))return {ok:false,error:{message:'lost reply'}};
692
+ if(scenario==='install-failed')return ok({application:'failed',error:{message:'install failed'}});
693
+ installed=true;return ok({application:'applied',version:'0.1.13'});
694
+ },
695
+ updateBundle:async(name,target)=>{assert.equal(name,'@rsrsai/dsh');assert.equal(target,'0.1.13');version=target;return ok({result:{application:'restart-required',version:target}});},
696
+ setBundleEnabled:async()=>{if(scenario==='enable-failed')return {ok:false,error:{message:'enable failed'}};enabled=true;return ok({application:scenario==='restart'?'restart-required':'applied'});}
697
+ };
698
+ if(scenario==='missing-enable')delete manager.setBundleEnabled;
699
+ if(scenario==='wait-null')manager.waitForInstall=async()=>ok(null);
700
+ if(scenario==='wait-failed')manager.waitForInstall=async()=>ok({application:'failed'});
701
+ const render=()=>{settingsCursor=0;return elements(settingsClient.MemoryPluginCard({manager,t:key=>key}));};
702
+ const initial=render();initial.find(n=>n.props?.['data-cabinet-plugin-action']==='install').props.onClick();
703
+ await new Promise(r=>setTimeout(r,45));
704
+ const result=render();const error=result.find(n=>n.props?.['data-cabinet-plugin-state']==='error');
705
+ assert.equal(!!error,!['success','restart','update'].includes(scenario),scenario);
706
+ assert.equal(enabled,['success','restart','update'].includes(scenario),scenario);
707
+ assert.equal(!!result.find(n=>n.props?.['data-cabinet-plugin-state']==='restart'),['restart','update'].includes(scenario));
708
+ if(['timeout','missing-wait'].includes(scenario)) {result.find(n=>n.props?.['data-cabinet-plugin-action']==='install').props.onClick();await new Promise(r=>setTimeout(r,0));assert.equal(installs,1,'unknown operation cannot be duplicated');}
709
+ }
710
+ console.log('PASS: install/enable success, failure, missing wait, deadline, unknown-result duplicate guard and restart state (mock remote)');
711
+ // Lifecycle double executes effects and preserves refs; unlike the tab-only
712
+ // renderer above, this detects broken first inventory reads. Browser evidence
713
+ // remains separate and uses real React.
714
+ function memoryCardHarness() {
715
+ let hooks=[],cursor=0,effects=[],api,tree;
716
+ const react={...React,
717
+ useState(initial){const i=cursor++;if(!(i in hooks))hooks[i]={value:typeof initial==='function'?initial():initial};return [hooks[i].value,v=>{hooks[i].value=typeof v==='function'?v(hooks[i].value):v;}];},
718
+ useRef(initial){const i=cursor++;return hooks[i]??(hooks[i]={current:initial});},
719
+ useEffect(fn,deps){const i=cursor++,old=hooks[i];if(!old||deps.some((v,n)=>v!==old.deps[n])){hooks[i]={deps,cleanup:old?.cleanup};effects.push(()=>{hooks[i].cleanup?.();hooks[i].cleanup=fn();});}}
720
+ };
721
+ runInNewContext(source.replace(exportPoint,exportList),{setTimeout,clearTimeout,window:{__ModuleLoader__:{load:({factory})=>{api=factory(()=>react);}}}});
722
+ return {render(manager){cursor=0;effects=[];tree=elements(api.MemoryPluginCard({manager,t:k=>k}));for(const effect of effects)effect();return tree;},unmount(){for(const hook of hooks)hook.cleanup?.();hooks=[];},};
723
+ }
724
+ const inventory=version=>({ok:true,value:[{name:'@rsrsai/dsh',installed:true,enabled:true,version}]});
725
+ const tick=()=>new Promise(r=>setTimeout(r,0));
726
+ const versionOf=nodes=>nodes.find(n=>n.props?.['data-cabinet-plugin-version']!==undefined)?.props['data-cabinet-plugin-version'];
727
+ {
728
+ const h=memoryCardHarness();const manager={listBundles:async()=>inventory('0.1.13')};
729
+ h.render(manager);await tick();assert.equal(versionOf(h.render(manager)),'0.1.13','first mount reads actual remote inventory');
730
+ h.unmount();h.render(manager);await tick();assert.equal(versionOf(h.render(manager)),'0.1.13','remount reads inventory without initialInstalled');h.unmount();
731
+ }
732
+ {
733
+ const h=memoryCardHarness();let resolve;
734
+ const old={listBundles:()=>new Promise(r=>resolve=r)},current={listBundles:async()=>inventory('0.1.14')};
735
+ h.render(old);h.render(current);await tick();resolve(inventory('0.1.12'));await tick();assert.equal(versionOf(h.render(current)),'0.1.14','old channel cannot overwrite the new inventory');h.unmount();
736
+ }
737
+ for(const version of ['0.1.14','0.2.0','1.0.0','','broken','0.1.13-rc.1','9007199254740993.0.0']) {
738
+ const h=memoryCardHarness();let mutations=0;
739
+ const manager={listBundles:async()=>inventory(version),inspect:async()=>{throw Error('must reject before inspect')},installBundle:async()=>{mutations++},updateBundle:async()=>{mutations++},setBundleEnabled:async()=>{mutations++}};
740
+ h.render(manager);await tick();h.render(manager).find(n=>n.props?.['data-cabinet-plugin-action']==='update').props.onClick();await tick();
741
+ assert.equal(mutations,0,version);assert.ok(h.render(manager).some(n=>n.props?.['data-cabinet-plugin-state']==='error'),version);h.unmount();
742
+ }
743
+ console.log('PASS: effectful inventory first mount/remount/channel replacement and seven conservative non-downgrade cases; hook double, not browser E2E');
744
+ // An initial inventory read that finishes after a clicked operation is stale.
745
+ {
746
+ const h=memoryCardHarness();let resolve,reads=0;
747
+ const manager={listBundles:async()=>++reads===1?new Promise(r=>resolve=r):inventory('0.1.13'),inspect:async()=>({ok:true,value:{status:'accepted',name:'@rsrsai/dsh',bundle:true}}),installBundle:async()=>{throw Error('already installed')},setBundleEnabled:async()=>({ok:true,value:{application:'applied'}})};
748
+ h.render(manager).find(n=>n.props?.['data-cabinet-plugin-action']==='install').props.onClick();await tick();resolve({ok:true,value:[]});await tick();assert.equal(versionOf(h.render(manager)),'0.1.13','epoch rejects pre-operation inventory response');h.unmount();
749
+ }
750
+ console.log('PASS: late initial inventory cannot overwrite a completed operation');
@@ -21,7 +21,12 @@ const render=()=>{cursor=0;return client.CabinetMemberSettings({t:key=>client[lo
21
21
  const settle=async()=>{let tree;for(let i=0;i<4;i++){tree=render();const jobs=effects;effects=[];for(const job of jobs)job();await new Promise(r=>setImmediate(r));}return tree;};
22
22
  const nodes=tree=>{const all=[];function walk(n){if(!n||typeof n!=='object')return;if(Array.isArray(n)){n.forEach(walk);return;}all.push(n);n.children?.forEach(walk);}walk(tree);return all;};
23
23
  const pickers=tree=>nodes(tree).filter(n=>n.props.key==='mi');
24
- let tree=render();assert.ok(pickers(tree).every(n=>n.type==='input'&&n.props.disabled));
24
+ let tree=render();
25
+ // Setup only: the model fields now live on the models tab, so this click puts
26
+ // the UI in the state every assertion below assumes. No assertion body changes.
27
+ nodes(tree).find(n=>n.props['data-cabinet-settings-tab']==='models').props.onClick();
28
+ tree=render();
29
+ assert.ok(pickers(tree).every(n=>n.type==='input'&&n.props.disabled));
25
30
  assert.equal(nodes(tree).filter(n=>n.props.key==='mh').length,0,'loading is not unavailable');
26
31
  tree=await settle();assert.equal(pickers(tree).length,5);assert.ok(pickers(tree).every(n=>n.type==='input'&&!n.props.disabled));assert.equal(pickers(tree)[0].props.value,'old/kept');
27
32
  assert.equal(nodes(tree).filter(n=>n.props.key==='mh').length,5,'completed empty catalog shows fallback hint');