dsh-cabinet-mode 0.5.2 → 0.5.4

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,43 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [0.5.4] - 2026-11-07
6
+
7
+ ### Fixed
8
+
9
+ - Draw task dependencies from the blocker to the blocked task; keep the endpoint
10
+ dot on the blocked task and animate active edges in that direction.
11
+ - Open teammate sessions from task titles and member cards through the optional
12
+ native workspace service. Current, failed and provisioning members stay inert;
13
+ lead-owned and unassigned task titles remain plain text.
14
+
15
+ ### Verification
16
+
17
+ - Passed the existing client regressions and all 43 package/composition checks
18
+ with the local DSH 0.2.2-rc.1 runtime on Windows.
19
+ - Exercised the installed plugin in an isolated DSH web profile with browser-only
20
+ team projection fixtures and real empty sessions: measured edge endpoints and
21
+ animation, then confirmed task-title and member-card clicks selected the target
22
+ session. No model calls or full agent-team task execution were exercised.
23
+
24
+ ## [0.5.3] - 2026-11-07
25
+
26
+ ### Fixed
27
+
28
+ - Select Cabinet member models through the public rc.1 AgentModel API before
29
+ step preparation, preserving one frozen selection for tools, prompts and requests.
30
+ - Observe entry-scoped volatile saves without remounting; use real empty-inbox
31
+ regressions and refuse stale owned routes after mode changes.
32
+ - Persist minimal ownership with host-loaded Session plugin records and an
33
+ incremental projection; recover interrupted writes and preserve later native
34
+ choices when clearing, exiting Cabinet or unloading. Standard mode restores
35
+ the original reasoning effort even when its route matches the last override.
36
+ - Keep the legacy rc.5 model path; the shipped preset still targets rc.1.
37
+ Existing unmarked overrides require a one-time native selection on migration.
38
+ - Update bilingual compatibility guidance, website versions and download links;
39
+ retain 0.5.2 locale/icon exports. Add official-component regressions without
40
+ model calls; these do not claim full browser/team end-to-end coverage.
41
+
5
42
  ## [0.5.2] - 2026-11-07
6
43
 
7
44
  ### Fixed
package/README.md CHANGED
@@ -1,5 +1,7 @@
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.
4
+
3
5
  [中文](README.zh.md) | English
4
6
 
5
7
  **Install:** [Use the plugin market (recommended)](#install-from-the-plugin-market-recommended).
@@ -35,9 +37,7 @@ and the rest) come from the profile-level
35
37
  ship them**.
36
38
 
37
39
  This bundle declares **no hard DSH version gate**: no `engines.dsh`, no DSH
38
- `peerDependencies`, no install-time version check. It was tested on DSH
39
- **0.2.1-rc.3**; other DSH versions that provide the declarative preset mechanism
40
- may work, but are **not verified** (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.5.4 (see [DSH-side constraints](#dsh-side-constraints)).
41
41
 
42
42
  ## Cabinet member settings
43
43
 
@@ -59,23 +59,38 @@ failures do not erase them. If the catalog is unavailable, a manual
59
59
  `provider/id` field is offered. IDs may contain +, @, spaces and further slashes;
60
60
  only the first slash separates the provider. Invalid input blocks Save.
61
61
 
62
- In **Cabinet mode**, the profile policy takes precedence over the native
63
- session picker: an explicit member model wins; an empty teammate selection
64
- uses the configured Lead model, otherwise the current **DSH deployment default**.
65
- An empty Lead selection uses that deployment default. This is not inheritance
66
- of a different session's last request. Clearing actively restores this default,
67
- even when the previous request header recorded an overridden model.
68
-
69
- Routes are snapshotted at prompt assembly and paired with the same AgentLoop
70
- turn signal for requests. Save affects the next assembly, including already-live
71
- members; in-flight requests keep their snapshot. Actual team roles and the live
72
- Cabinet preset gate the policy; a teammate named lead cannot gain Lead policy.
73
- Different models use their adapter's reasoning default; matching routes retain
74
- native effort. Mode changes during a step abort that step rather than route a
75
- mismatched prompt. On a live mode exit, a retained plugin override is restored
76
- to the route recorded before Cabinet took over. Unloading cancels any active routed turn while retaining queued input, then
77
- removes its listeners; it does not rewrite persisted session history. The default model
78
- must be available; missing defaults fail explicitly instead of keeping a stale override.
62
+ In **Cabinet mode**, an explicit member model takes precedence; an empty teammate
63
+ selection follows the configured Lead model. On rc.1, a session with no configured
64
+ Cabinet override keeps its native selection. Clearing a previously owned override
65
+ restores the current **DSH deployment default** (not another session's last model).
66
+ A newer native manual selection is preserved when clearing or unloading the policy.
67
+
68
+ On rc.1, the plugin calls the public AgentModel.select() before step preparation;
69
+ the host's frozen selection supplies tools, prompt variables and the request together.
70
+ Saving uses the owning entry's committed loader/volatile-update notification, so
71
+ it applies to the next step even with an empty inbox and no remount; an already
72
+ prepared step keeps its selection. Unsignaled in-memory config mutations are only
73
+ sampled at attachment, a real status change or a claimed inbox message. Deployment
74
+ defaults are sampled when clearing an owned override; later default edits do not
75
+ silently rewrite a native selection. Actual team roles and the current preset gate the policy: a
76
+ teammate named lead cannot gain Lead policy. Different routes use the new adapter's
77
+ reasoning default; matching routes retain native effort. Exiting Cabinet restores
78
+ the pre-policy native selection, including its effort. Unloading cancels the active
79
+ managed turn and retains queued input, then restores a still-owned selection.
80
+
81
+ A host-only Session projection tracks minimal route ownership through public plugin
82
+ records. An intent is recorded before selection; restoration happens before ownership
83
+ is cleared. Interrupted writes can be recovered on reopening, without overwriting a
84
+ later native choice. No credentials or complete configuration are recorded. Missing
85
+ host record APIs reject configured overrides before a model request. Historical
86
+ versions did not record ownership: if an old override is already persisted, select
87
+ the desired native model once before enabling the new policy; its origin cannot be
88
+ inferred safely from a request header.
89
+
90
+ Regression scope: 120 rc.1 cases use official Cordis, Session, AgentModel, projections,
91
+ SystemPrompt and the unchanged preStep/prepareRequest implementations. The inbox and volatile Loader updates are real; team identity and model adapters are fixtures; there are no paid/real model calls and this
92
+ is not a full team/browser end-to-end test. The 41 legacy rc.5 model cases remain
93
+ covered, but do not certify the current rc.1 preset for older hosts.
79
94
 
80
95
  Upload PNG/JPEG/WebP up to 2 MB; the browser crops it to a 96×96 PNG (at most
81
96
  48 KB data URL). Saved portraits apply to Cabinet cards and native team avatars.
@@ -243,7 +258,7 @@ On failure, show the exact error. For $.format must be 1, replace the webpage so
243
258
  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:
244
259
 
245
260
  ```sh
246
- dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.5.2/dsh-cabinet-mode-0.5.2.tgz
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
247
262
  dsh plugin --profile desktop list
248
263
  ```
249
264
 
@@ -258,7 +273,7 @@ the same install command with the new version URL (or pick the new `.tgz` in the
258
273
  plugin page), then fully quit and restart DeepSeek Harness:
259
274
 
260
275
  ```sh
261
- dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.5.2/dsh-cabinet-mode-0.5.2.tgz
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
262
277
  ```
263
278
 
264
279
  `dsh plugin --profile desktop list` should report the new version. Upgrades were
package/README.zh.md CHANGED
@@ -1,5 +1,7 @@
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 入口;请在商店选择匹配版本。
4
+
3
5
  [English](README.md) | 中文
4
6
 
5
7
  **安装入口:** [优先从插件市场安装](#从插件市场安装索引源推荐)。
@@ -19,7 +21,7 @@
19
21
 
20
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 未内置**。
21
23
 
22
- 本包声明 **无 DSH 版本硬限制**:没有 `engines.dsh`、没有 DSH `peerDependencies`、安装时不做版本检查。本机在 DSH **0.2.1-rc.3** 实测;其他提供声明式 preset 机制的 DSH 版本可尝试安装,但**未经验证**(见 [DSH 侧限制与说明](#dsh-侧限制与说明))。
24
+ 本包声明 **无 DSH 版本硬限制**:没有 `engines.dsh`、没有 DSH `peerDependencies`、安装时不做版本检查。旧包曾在 DSH **0.2.1-rc.3** 实测;0.5.4 请遵循上方版本兼容说明(见 [DSH 侧限制与说明](#dsh-侧限制与说明))。
23
25
 
24
26
  ## 内阁成员配置
25
27
 
@@ -37,18 +39,29 @@
37
39
  目录不可用时提供手动 `provider/id` 输入。模型 ID 支持 +、@、空格及额外斜杠,
38
40
  仅第一个斜杠分隔提供方;格式错误会阻止保存。
39
41
 
40
- 仅在 **内阁模式** 中,profile 策略优先于原生会话模型选择:成员显式模型优先;
41
- 阁臣留空时使用已配置的首辅模型,首辅未配置时使用当前 **DSH 部署默认模型**。
42
- 首辅留空也使用部署默认模型,并非继承另一个会话最后使用的模型。清空会主动恢复
43
- 该默认路由,即使历史请求头仍记录上次覆盖模型也不会继续沿用它。
44
-
45
- 路由在提示词装配时快照,并通过同一 AgentLoop turn signal 关联请求。保存影响
46
- 下一次装配,已存活成员同样生效;正在进行的请求保持原快照。实时 cabinet preset
47
- 和真实团队角色共同限定范围,名为 lead 的阁臣不会获得首辅策略。换模型时使用
48
- 新模型适配器的 reasoning 默认值,同路由保留原生 effort。步骤中途切换模式会
49
- 中止该步骤,避免提示词与路由错配;运行期间切出内阁时,将残留插件覆盖恢复到
50
- 接管前记录的路由。卸载会中止仍在运行的受管轮次、保留排队输入并移除监听器,但不会改写会话历史。默认模型不可用时明确
51
- 报错,不会静默保留旧覆盖。
42
+ 仅在 **内阁模式** 中,成员显式模型优先,阁臣留空时跟随已配置的首辅模型。
43
+ rc.1 中从未配置内阁覆盖的会话保留原生选择;清空原先受管的覆盖时恢复当前
44
+ **DSH 部署默认模型**,不继承其他会话最后使用的模型。清空或卸载时保留后来
45
+ 由用户手动设置的原生选择。
46
+
47
+ rc.1 路径在步骤准备前调用公开 AgentModel.select(),工具、提示变量和请求均使用
48
+ 宿主固定的同一模型。保存通过仅属于本插件的 loader/volatile-update 通知同步模型,即使 inbox 为空且
49
+ 没有重挂载也影响下一步;已经准备的步骤保持原选择。没有发送通知的内存配置修改
50
+ 仅在挂载、真实状态变化或领取 inbox 消息时重新读取。部署默认模型在清空受管覆盖
51
+ 时读取,后续修改部署默认不会静默改写已有原生选择。实时 preset 和真实团队角色限定范围,名为 lead 的阁臣不会获得首辅策略。
52
+ 换路由使用新适配器的 reasoning 默认值,同路由保留原生 effort。退出内阁恢复
53
+ 接管前的原生模型及 effort;卸载中止受管轮次、保留排队输入并恢复仍归插件所有的选择。
54
+
55
+ 公开 Session 插件记录和宿主 projection 仅记录路由归属,不记录凭据或完整配置。
56
+ 先记录覆盖意图再选择模型;先恢复原生选择再清除归属。两次写入之间中断后可在
57
+ 重开时恢复,且不覆盖后来的原生手动选择。缺失宿主记录 API 时,显式覆盖会在模型
58
+ 请求前报错。旧版本没有归属记录,不能仅凭历史请求头安全推断来源;若旧覆盖已
59
+ 持久化,请先用原生模型选择器选回所需模型,再启用新策略。
60
+
61
+ 回归范围:120 项 rc.1 测试使用官方 Cordis、Session、AgentModel、projection、
62
+ SystemPrompt 及未改动的 preStep/prepareRequest 实现;inbox 和 Loader volatile 更新使用真实实现,身份和模型适配器为
63
+ 测试替身,未调用真实模型,也不是完整团队或浏览器端到端测试。保留旧 rc.5 的
64
+ 41 项模型组合回归,但这不代表当前 rc.1 预设已通过旧宿主验收。
52
65
 
53
66
  可上传不超过 2 MB 的 PNG/JPEG/WebP;浏览器居中裁成 96×96 PNG,data URL 不超过
54
67
  48 KB。保存后头像同时用于内阁面板和原生团队列表。**恢复默认** 将该官职组的
@@ -176,7 +189,7 @@ https://raw.githubusercontent.com/luodaoyi/dsh-cabinet-mode/market-index/marketp
176
189
  仅在商店不可用或本地开发时使用。先完全退出桌面 DSH,释放 profile 锁,再执行:
177
190
 
178
191
  ```sh
179
- dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.5.2/dsh-cabinet-mode-0.5.2.tgz
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
180
193
  dsh plugin --profile desktop list
181
194
  ```
182
195
 
@@ -187,7 +200,7 @@ dsh plugin --profile desktop list
187
200
  若通过插件市场安装:刷新市场,先在**已安装**页卸载旧版本,再从**插件市场**安装新版本,然后重启——没有 tgz URL 要换,也没有一键更新。否则用同一条安装命令换新版本 URL(或在插件页选新 `.tgz`),然后完全退出并重启 DeepSeek Harness:
188
201
 
189
202
  ```sh
190
- dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.5.2/dsh-cabinet-mode-0.5.2.tgz
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
191
204
  ```
192
205
 
193
206
  `dsh plugin --profile desktop list` 应显示新版本。升级已在 Windows 实测:
package/client.js CHANGED
@@ -2407,8 +2407,13 @@ window.__ModuleLoader__.load({
2407
2407
  'body[data-ds-dark-theme] .cabinet-status-running{color:#4ade80}body[data-ds-dark-theme] .cabinet-status-inactive{color:#adb2b8}body[data-ds-dark-theme] .cabinet-status-provisioning{color:#f7ad31}body[data-ds-dark-theme] .cabinet-status-failed{color:#f25a5a}',
2408
2408
  '.cabinet-task-pending{color:#61666b}.cabinet-task-in_progress{color:#2563eb}.cabinet-task-completed{color:#15803d}',
2409
2409
  'body[data-ds-dark-theme] .cabinet-task-pending{color:#adb2b8}body[data-ds-dark-theme] .cabinet-task-in_progress{color:#60a5fa}body[data-ds-dark-theme] .cabinet-task-completed{color:#4ed17e}',
2410
- // task dependency edges (blocked → blocker): one class per blocker state,
2410
+ // task dependency edges (blocker → blocked): one class per blocker state,
2411
2411
  // same palette as TASK_COLOR (done #22c55e / active #3b82f6 / pending #9aa0a6)
2412
+ // Flow direction: the path now runs blocker → blocked, and a dash pattern
2413
+ // starts at path distance ≡ -offset, so animating offset 0 → -24 slides
2414
+ // the dashes toward the path END — with the arrow, toward the blocked
2415
+ // task. No sign flip was needed after reversing the path; this is a desk
2416
+ // derivation from the SVG dash rule, not a browser observation (未验证).
2412
2417
  '@keyframes cabinetEdgeFlow{to{stroke-dashoffset:-24}}',
2413
2418
  '.cabinet-edge{fill:none;stroke-width:1.5;stroke-linecap:round}',
2414
2419
  '.cabinet-edge-done{stroke:light-dark(#15803d,#4ade80)}',
@@ -2554,6 +2559,34 @@ window.__ModuleLoader__.load({
2554
2559
  let memberWriter = null;
2555
2560
  /** Host remote handle for the model catalog; null degrades the picker to text. */
2556
2561
  let memberRemote = null;
2562
+ /**
2563
+ * Optional uiWorkspace opener, captured by ctx.inject() inside apply()
2564
+ * (same pattern as memberRemote/memberWriter). It stays null on a
2565
+ * deployment without the workspace service, and every panel click then
2566
+ * degrades to a silent no-op instead of throwing at the panel.
2567
+ */
2568
+ let cabinetOpenSession = null;
2569
+ /**
2570
+ * Open a teammate's child session the way the native roster does
2571
+ * (dsh-experimental-client-ui-agent-team openTeammate): the Lead session
2572
+ * is the parent, the member id the child, mode "continuable"; when the
2573
+ * target IS the parent the native code takes the plain-string branch, so
2574
+ * mirror that too. Returns false when the channel or the id is missing —
2575
+ * callers simply do nothing, no exception reaches the panel.
2576
+ */
2577
+ function openCabinetSession(childSessionId, parentSessionId) {
2578
+ const open = cabinetOpenSession;
2579
+ if (typeof open !== 'function') return false;
2580
+ if (typeof childSessionId !== 'string' || childSessionId === '') return false;
2581
+ try {
2582
+ if (parentSessionId && childSessionId === parentSessionId) open(parentSessionId);
2583
+ else open({ parentSessionId: parentSessionId ?? childSessionId, childSessionId, mode: 'continuable' });
2584
+ return true;
2585
+ } catch (error) {
2586
+ try { console.warn('[cabinet-ui] open session failed:', error); } catch (ignored) { /* console may be unavailable */ }
2587
+ return false;
2588
+ }
2589
+ }
2557
2590
  const MEMBER_LISTENERS = new Set();
2558
2591
  let memberT = (key) => key;
2559
2592
  function clampMemberText(value, limit) {
@@ -2996,13 +3029,23 @@ window.__ModuleLoader__.load({
2996
3029
  // line one; status dot + state text (+ live dots / model) on line two.
2997
3030
  // State text carries a theme-aware class so 11px copy clears 3:1 in both
2998
3031
  // themes; the badge keeps lead's formula with a light-theme dark amber.
2999
- function MemberCard({ member, running, model, isCurrent, lead, statusLabel, t, size, children }) {
3032
+ function MemberCard({ member, running, model, isCurrent, lead, statusLabel, t, size, onOpen, children }) {
3000
3033
  const tt = typeof t === 'function' ? t : (key) => key;
3001
3034
  const status = member.phase === 'active' ? (running ? 'running' : 'inactive') : member.phase;
3035
+ // Availability mirrors the native roster row (agent-team TeamMemberRow):
3036
+ // the session you are already viewing, and failed/provisioning members,
3037
+ // are inert — no click, no pointer cursor. Opening also needs a real
3038
+ // session id, which is what member.id is (sessionIdSchema).
3039
+ const canOpen = typeof onOpen === 'function'
3040
+ && isCurrent !== true
3041
+ && member.phase !== 'failed'
3042
+ && member.phase !== 'provisioning'
3043
+ && typeof member.id === 'string' && member.id !== '';
3002
3044
  return h('div', { className: lead ? 'cabinet-card cabinet-card-lead' : 'cabinet-card', style: { position: 'relative', zIndex: 1 } }, [
3003
3045
  h('div', {
3004
3046
  key: 'who',
3005
- style: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minWidth: 0 }
3047
+ onClick: canOpen ? () => onOpen(member) : undefined,
3048
+ style: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minWidth: 0, cursor: canOpen ? 'pointer' : undefined }
3006
3049
  }, [
3007
3050
  h(Avatar, { key: 'avatar', name: member.name, size: size || 22, live: status === 'running' }),
3008
3051
  h('span', {
@@ -3039,11 +3082,16 @@ window.__ModuleLoader__.load({
3039
3082
  ]);
3040
3083
  }
3041
3084
 
3042
- function TaskLine({ task, blockerOf, t, taskLabel, ownerRunning }) {
3085
+ function TaskLine({ task, blockerOf, t, taskLabel, ownerRunning, onOpenOwner }) {
3043
3086
  const [openBlockers, setOpenBlockers] = React.useState(true);
3044
3087
  const status = TASK_COLOR[task.status] ? task.status : 'pending';
3045
3088
  const color = TASK_COLOR[status];
3046
3089
  const blockers = Array.isArray(task.blockedBy) ? [...new Set(task.blockedBy.filter((id) => typeof id === 'string' && id !== task.id))] : [];
3090
+ // The subject itself is the affordance, but only when the panel handed
3091
+ // us a resolved opener: lead-owned, unassigned, foreign-owner and
3092
+ // inert-owner tasks arrive with onOpenOwner === null and keep the plain
3093
+ // look (no onClick, no pointer cursor).
3094
+ const openTask = typeof onOpenOwner === 'function';
3047
3095
  const parts = [
3048
3096
  h('span', {
3049
3097
  key: 'dot',
@@ -3053,8 +3101,9 @@ window.__ModuleLoader__.load({
3053
3101
  h('span', { key: 'st', className: 'cabinet-task-' + status, style: { fontSize: 11, flex: 'none' } }, taskLabel(status)),
3054
3102
  h('span', {
3055
3103
  key: 'subj',
3056
- style: { fontSize: 12.5, color: INK, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
3057
- title: task.subject
3104
+ style: { fontSize: 12.5, color: INK, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: openTask ? 'pointer' : undefined },
3105
+ title: task.subject,
3106
+ onClick: openTask ? () => onOpenOwner(task) : undefined
3058
3107
  }, task.subject)
3059
3108
  ];
3060
3109
  if (!task.ownerName) {
@@ -3100,11 +3149,13 @@ window.__ModuleLoader__.load({
3100
3149
  }, children);
3101
3150
  }
3102
3151
 
3103
- // Dependency-edge overlay: one cubic path + one blocker-side dot per edge,
3104
- // paths are masked behind card interiors; endpoint dots remain visible. The
3105
- // layer is pointer-transparent, so rows stay
3106
- // clickable. `data-cabinet-edge="<blocked>-><blocker>"` plus a
3107
- // cabinet-edge-pending/active/done class makes every edge assertable.
3152
+ // Dependency-edge overlay: one cubic path + one blocked-side dot per edge
3153
+ // (the line leaves the blocker's row and lands on the blocked task's row),
3154
+ // masked behind card interiors while endpoint dots remain visible. The
3155
+ // layer is pointer-transparent, so rows stay clickable.
3156
+ // `data-cabinet-edge="<blocked>-><blocker>"` — key format is unchanged by
3157
+ // the geometry flip — plus a cabinet-edge-pending/active/done class makes
3158
+ // every edge assertable.
3108
3159
  function TaskEdgeLayer({ edges, cards = [] }) {
3109
3160
  const maskId = React.useId();
3110
3161
  if (!Array.isArray(edges) || edges.length === 0) return null;
@@ -3240,16 +3291,19 @@ window.__ModuleLoader__.load({
3240
3291
  }
3241
3292
  return paths;
3242
3293
  }
3243
- // One cubic per dependency: from the blocked task's row to its blocker's
3244
- // row, both endpoints taken from task-row DOM rects relative to the
3245
- // overlay container. State mirrors the BLOCKER's status — completed →
3246
- // solid green, in_progress → flowing dashes (travelling toward the
3247
- // blocker, "the dependency is progressing"), pending → static grey
3248
- // dashes; a missing or deleted blocker, or an unmeasured row, draws
3249
- // nothing (tolerant, never throws). Edges sharing a source row or a
3250
- // target row fan their control points apart so parallel lines never sit
3251
- // exactly on top of each other. Returns null while the panel is hidden
3252
- // (zero-size base) so a collapsed pane keeps the last drawing.
3294
+ // One cubic per dependency: from the BLOCKER's row to the blocked task's
3295
+ // row (首辅 → 阁臣 reading on a normal board), both endpoints taken from
3296
+ // task-row DOM rects relative to the overlay container. The edge key stays
3297
+ // `<blocked>-><blocker>` — only the geometry flipped, so data-cabinet-edge
3298
+ // and the CSS class names keep their old form. State mirrors the BLOCKER's
3299
+ // status — completed → solid green, in_progress → flowing dashes
3300
+ // (travelling with the arrow, toward the blocked task, "the dependency is
3301
+ // progressing"), pending → static grey dashes; a missing or deleted
3302
+ // blocker, or an unmeasured row, draws nothing (tolerant, never throws).
3303
+ // Edges sharing a source row or a target row fan their control points
3304
+ // apart so parallel lines never sit exactly on top of each other. Returns
3305
+ // null while the panel is hidden (zero-size base) so a collapsed pane
3306
+ // keeps the last drawing.
3253
3307
  function buildTaskEdges(base, tasks, rectOf, isLive) {
3254
3308
  if (!base || base.width === 0 || base.height === 0) return null;
3255
3309
  const list = Array.isArray(tasks) ? tasks : [];
@@ -3275,8 +3329,13 @@ window.__ModuleLoader__.load({
3275
3329
  seen.add(key);
3276
3330
  const blocker = byId.get(blockerId);
3277
3331
  if (!blocker || blocker.status === 'deleted') continue; // missing/removed task: skip, don't crash
3278
- const from = rectOf(task.id);
3279
- const to = rectOf(blockerId);
3332
+ // Geometry reversed: the path starts on the blocker's row and
3333
+ // ends on the blocked task's row (the key above still reads
3334
+ // blocked->blocker). from/to drive the anchors, fromId/toId the
3335
+ // parallel-edge fan, and the endpoint dot lands on edge.e — i.e.
3336
+ // on the blocked task.
3337
+ const from = rectOf(blockerId);
3338
+ const to = rectOf(task.id);
3280
3339
  if (!from || !to || from.width === 0 || from.height === 0 || to.width === 0 || to.height === 0) continue;
3281
3340
  const state = blocker.status === 'completed' ? 'done'
3282
3341
  : blocker.status === 'in_progress' ? 'active'
@@ -3285,8 +3344,8 @@ window.__ModuleLoader__.load({
3285
3344
  key,
3286
3345
  state,
3287
3346
  live: state === 'active' && typeof isLive === 'function' && isLive(blockerId) === true,
3288
- fromId: task.id,
3289
- toId: blockerId,
3347
+ fromId: blockerId,
3348
+ toId: task.id,
3290
3349
  from: rel(from),
3291
3350
  to: rel(to)
3292
3351
  });
@@ -3325,9 +3384,10 @@ window.__ModuleLoader__.load({
3325
3384
  edge.c2 = [c2x, c2y];
3326
3385
  edge.e = [ex, ey];
3327
3386
  }
3328
- // Parallel-edge offset: edges from the same row (or into the same
3329
- // blocker row) share an anchor, so shift their control points apart
3330
- // perpendicular to the travel axis (7px pitch, centred on the group).
3387
+ // Parallel-edge offset: edges leaving the same blocker row (or arriving
3388
+ // at the same blocked row) share an anchor, so shift their control
3389
+ // points apart perpendicular to the travel axis (7px pitch, centred on
3390
+ // the group). fromId is the blocker, toId the blocked task.
3331
3391
  const fan = (pointField, idField, prefix) => {
3332
3392
  const groups = new Map();
3333
3393
  for (const edge of edges) {
@@ -3576,6 +3636,24 @@ window.__ModuleLoader__.load({
3576
3636
  const isLeadTask = (task) => task.ownerName === 'lead' || (lead !== undefined && task.ownerName === lead.name);
3577
3637
  const unassigned = tasks.filter((task) => !task.ownerName);
3578
3638
  const leadOwn = tasks.filter((task) => task.ownerName !== undefined && isLeadTask(task));
3639
+
3640
+ // ---- click-to-open a member's child session (optional channel) ----
3641
+ // cabinetOpenSession is filled by ctx.inject(['uiWorkspace']) in apply()
3642
+ // and stays null when the service is missing — the helpers below then
3643
+ // return false and the click does nothing. Availability follows the
3644
+ // native roster's inert rule (agent-team: self / failed / provisioning
3645
+ // never open); lead-owned and unassigned tasks resolve to no member at
3646
+ // all, so the panel hands TaskLine null and nothing is bound.
3647
+ const openableMember = (member) => Boolean(member)
3648
+ && typeof member.id === 'string' && member.id !== ''
3649
+ && member.id !== sessionId
3650
+ && member.phase !== 'failed'
3651
+ && member.phase !== 'provisioning';
3652
+ const openMemberSession = (member) => openableMember(member) && openCabinetSession(member.id, leadSessionId);
3653
+ const ownerMemberOf = (task) => (task && task.ownerName && !isLeadTask(task) ? memberByName.get(task.ownerName) : undefined);
3654
+ const openOwnerSession = (task) => openMemberSession(ownerMemberOf(task));
3655
+ // Per-task opener handed to TaskLine: null means "do not bind".
3656
+ const ownerOpener = (task) => (openableMember(ownerMemberOf(task)) ? openOwnerSession : null);
3579
3657
  const rosterNames = new Set(mates.map((member) => member.name));
3580
3658
  const foreignOwners = [];
3581
3659
  for (const task of tasks) {
@@ -3599,7 +3677,8 @@ window.__ModuleLoader__.load({
3599
3677
  lead: true,
3600
3678
  size: 26,
3601
3679
  statusLabel,
3602
- t: tt
3680
+ t: tt,
3681
+ onOpen: openMemberSession
3603
3682
  });
3604
3683
 
3605
3684
  // Cells: every minister first, then 未分派 / 首辅自办 / 不在册 as
@@ -3657,6 +3736,7 @@ window.__ModuleLoader__.load({
3657
3736
  isCurrent: member.id === sessionId,
3658
3737
  statusLabel,
3659
3738
  t: tt,
3739
+ onOpen: openMemberSession,
3660
3740
  // tasks live inside the card, elbow-connected by RailList
3661
3741
  children: own.length > 0
3662
3742
  ? h(RailList, { key: 'tasks', style: { marginTop: 4 } }, own.map((task) => h(TaskLine, {
@@ -3665,7 +3745,8 @@ window.__ModuleLoader__.load({
3665
3745
  blockerOf,
3666
3746
  t: tt,
3667
3747
  taskLabel,
3668
- ownerRunning: memberRunning
3748
+ ownerRunning: memberRunning,
3749
+ onOpenOwner: ownerOpener(task)
3669
3750
  })))
3670
3751
  : h('div', { key: 'tasks', style: { fontSize: 11, color: INK3, padding: '2px 0' } }, tt('task.none'))
3671
3752
  });
@@ -3681,7 +3762,8 @@ window.__ModuleLoader__.load({
3681
3762
  blockerOf,
3682
3763
  t: tt,
3683
3764
  taskLabel,
3684
- ownerRunning: false
3765
+ ownerRunning: false,
3766
+ onOpenOwner: ownerOpener(task)
3685
3767
  })))
3686
3768
  ]);
3687
3769
  }
@@ -4122,6 +4204,19 @@ window.__ModuleLoader__.load({
4122
4204
  return () => { if (memberRemote === remote) memberRemote = null; };
4123
4205
  }, 'cabinet-ui: model catalog remote');
4124
4206
  });
4207
+ // Optional navigation channel for the panel's click-to-open rows. The
4208
+ // manifest inject list above stays untouched: without the workspace
4209
+ // service this callback never runs, cabinetOpenSession stays null and
4210
+ // every click no-ops — the same degradation as the remote channel.
4211
+ ctx.inject(['uiWorkspace'], (scope) => {
4212
+ const workspace = scope.uiWorkspace;
4213
+ if (!workspace || typeof workspace.openSession !== 'function') return;
4214
+ scope.effect(() => {
4215
+ const opener = (target) => workspace.openSession(target);
4216
+ cabinetOpenSession = opener;
4217
+ return () => { if (cabinetOpenSession === opener) cabinetOpenSession = null; };
4218
+ }, 'cabinet-ui: open teammate session');
4219
+ });
4125
4220
  // Stage one: declare the page type. No patterns => a page type, opened by kind.
4126
4221
  ctx.effect(() => ctx.sidebarRightTabs.register({
4127
4222
  id: TAB_ID,
package/index.js CHANGED
@@ -285,9 +285,12 @@ function memberKeyOf(ctx, agent) {
285
285
  }
286
286
 
287
287
  /** Couple one live Cabinet route to one AgentLoop turn signal. */
288
- function attachMemberModel(ctx, config, agent, attached, routeMemory = new Map()) {
288
+ function attachMemberModel(ctx, config, agent, attached, routeMemory = new Map(), sessionApi) {
289
289
  if (!agent || typeof agent.ctx?.on !== 'function') return undefined;
290
290
  if (agent.id !== undefined && attached.has(agent.id)) return undefined;
291
+ if (typeof agent.model?.current === 'function' && typeof agent.model?.select === 'function') {
292
+ return attachPreparedMemberModel(ctx, config, agent, attached, routeMemory, sessionApi);
293
+ }
291
294
  let active = true;
292
295
  let controlledSignal;
293
296
  const turns = new WeakMap();
@@ -382,13 +385,153 @@ function attachMemberModel(ctx, config, agent, attached, routeMemory = new Map()
382
385
  return dispose;
383
386
  }
384
387
 
388
+ // Use the host's module instance and incremental projection contract. Records
389
+ // contain only selection provenance, never provider credentials or user config.
390
+ async function prepareModelSessionApi(ctx) {
391
+ const loader = ctx.get('loader'), registry = ctx.get('sessionProjections');
392
+ if (!loader?.import || !registry?.register) return undefined;
393
+ const api = await loader.import('@deepseek-ai/dsh-session');
394
+ const { z } = await loader.import('zod');
395
+ const route = z.object({ provider: z.string().min(1), model: z.string().min(1), reasoningEffort: z.string().optional() });
396
+ const record = z.object({ agentId: z.string(), baseline: route, override: route, from: route, settled: z.boolean().default(false) });
397
+ const equal = (a, b) => a?.provider === b?.provider && a?.model === b?.model && a?.reasoningEffort === b?.reasoningEffort;
398
+ const ownership = await registry.register({
399
+ key: 'cabinetModelOwnership', stateVersion: 1,
400
+ stateSchema: z.object({ inheritedCount: z.number(), record: record.nullable() }),
401
+ init: (_, inheritedCount = 0) => ({ inheritedCount, record: null }),
402
+ apply: (state, event) => {
403
+ if (event.seq < state.inheritedCount) return state;
404
+ const item = api.pluginRecordOf(event);
405
+ if (item?.type === 'plugin:dsh-cabinet-mode/model-policy') {
406
+ const parsed = record.safeParse(item.data);
407
+ return { ...state, record: parsed.success ? parsed.data : null };
408
+ }
409
+ if (event.type === 'model/selection' && state.record) return {
410
+ ...state, record: equal(event.data, state.record.override) ? { ...state.record, settled: true } : null
411
+ };
412
+ return state;
413
+ }
414
+ });
415
+ return { ...api, ownership };
416
+ }
417
+
418
+ /** Host plugin entry. */
419
+ function attachPreparedMemberModel(ctx, config, agent, attached, routeMemory, sessionApi) {
420
+ let active = true;
421
+ let synchronizedKey;
422
+ const sameRoute = (a, b) => !!a && !!b && a.provider === b.provider && a.model === b.model;
423
+ const sameSelection = (a, b) => sameRoute(a, b) && a.reasoningEffort === b.reasoningEffort;
424
+ const recordType = 'plugin:dsh-cabinet-mode/model-policy';
425
+ const validRoute = value => value && typeof value.provider === 'string' && value.provider.length > 0 && typeof value.model === 'string' && value.model.length > 0 && (value.reasoningEffort === undefined || typeof value.reasoningEffort === 'string');
426
+ const canRecord = typeof sessionApi?.appendPluginRecord === 'function' && typeof sessionApi?.pluginRecordOf === 'function' && typeof sessionApi?.Session === 'function' && agent.session instanceof sessionApi.Session && !!sessionApi.ownership;
427
+ const refreshOwnership = () => {
428
+ const record = canRecord ? sessionApi.ownership.stateOf(agent.session).record : undefined;
429
+ const current = agent.model.current();
430
+ if (record?.agentId === agent.id && (sameSelection(current, record.override) || (!record.settled && sameSelection(current, record.from) && !sameSelection(record.from, record.baseline)))) {
431
+ routeMemory.set(agent.id, { baseline: record.baseline, override: current });
432
+ } else routeMemory.delete(agent.id);
433
+ };
434
+ const remember = value => {
435
+ if (!canRecord) throw new Error('Cabinet: host Session plugin-record API unavailable; model override refused');
436
+ sessionApi.appendPluginRecord(agent.session, recordType, value ? { agentId: agent.id, ...value, from: agent.model.current() } : { agentId: agent.id });
437
+ if (value) routeMemory.set(agent.id, value); else routeMemory.delete(agent.id);
438
+ };
439
+ const keyFor = () => { try { return memberKeyOf(ctx, agent); } catch { return undefined; } };
440
+ const syncSelection = () => {
441
+ if (!active) return;
442
+ refreshOwnership();
443
+ const key = keyFor();
444
+ synchronizedKey = key;
445
+ const current = agent.model.current();
446
+ const previous = routeMemory.get(agent.id);
447
+ const override = key === undefined ? undefined : memberModel(config, key) ?? (key === 'lead' ? undefined : memberModel(config, 'lead'));
448
+ if (!override && !previous) return; // Never alter an unconfigured/native agent.
449
+ if (!override && previous && !sameSelection(current, previous.override)) {
450
+ remember(undefined); return; // Respect a newer native selection.
451
+ }
452
+ const defaults = ctx.get('agentDefaultModel')?.currentSelection?.() ?? agent.options;
453
+ const desired = override ?? (key === undefined ? previous?.baseline : defaults);
454
+ if (!desired?.provider || !desired?.model) throw new Error('Cabinet: no model available to restore native selection');
455
+ const selection = (override || key !== undefined) && sameRoute(desired, current) ? current : {
456
+ provider: desired.provider, model: desired.model,
457
+ ...(desired.reasoningEffort === undefined ? {} : { reasoningEffort: desired.reasoningEffort })
458
+ };
459
+ if (override) {
460
+ const value = { baseline: previous && sameSelection(current, previous.override) ? previous.baseline : current, override: selection };
461
+ if (!validRoute(value.baseline)) throw new Error('Cabinet: no native selection available to restore');
462
+ if (JSON.stringify(value) !== JSON.stringify(previous)) remember(value);
463
+ }
464
+ agent.model.select(selection);
465
+ // Clear ownership only after restoration is durable. Reopening between
466
+ // these writes sees the native selection and retires the stale marker.
467
+ if (!override) remember(undefined);
468
+ };
469
+ // Both notifications precede preStep's model.current(): status starts the
470
+ // turn, and inbox claim resolves members registered after agent creation.
471
+ let syncError;
472
+ const sync = () => {
473
+ try { syncSelection(); syncError = undefined; }
474
+ catch (error) { syncError = error; }
475
+ };
476
+ const offStatus = agent.ctx.on('agent/status', sync);
477
+ const offClaim = agent.ctx.on('agent/inbox/claimed', sync);
478
+ // Loader dispatches committed volatile paths only to the owning plugin fiber.
479
+ // Register on this entry's context, not the unrelated Agent scope.
480
+ const offConfig = ctx.on('loader/volatile-update', paths => {
481
+ if (paths.some(path => path[0] === 'members')) sync();
482
+ });
483
+ // Defer errors to preparation too: a failed capability check must never
484
+ // silently send a configured override to the native model.
485
+ sync();
486
+ const turns = new WeakMap();
487
+ let controlledSignal;
488
+ const offAssembly = agent.ctx.on('system-prompt/assemble', async (_, context, next) => {
489
+ if (syncError) throw syncError;
490
+ const key = keyFor();
491
+ // An empty inbox emits no notification. Refuse a stale owned selection
492
+ // after a mode/role change even before the next status boundary can restore it.
493
+ refreshOwnership();
494
+ const configured = key === undefined ? undefined : memberModel(config, key) ?? (key === 'lead' ? undefined : memberModel(config, 'lead'));
495
+ if ((routeMemory.has(agent.id) || configured) && key !== synchronizedKey) throw new Error('Cabinet: model policy changed before step preparation; start a new turn');
496
+ const controlled = key !== undefined && routeMemory.has(agent.id);
497
+ const state = { key, controlled };
498
+ if (context.signal) {
499
+ turns.set(context.signal, state);
500
+ if (controlled) controlledSignal = context.signal;
501
+ }
502
+ const result = await next();
503
+ if (controlled && (!active || context.signal?.aborted || keyFor() !== key)) throw new Error('Cabinet: model policy changed during step preparation');
504
+ return result; // The official frozen modelSelection owns all variables.
505
+ }, { prepend: true });
506
+ const offRequest = agent.ctx.on('agent/request', async (payload, next) => {
507
+ const state = turns.get(payload.signal);
508
+ const result = await next();
509
+ if (state?.controlled && (!active || payload.signal.aborted || keyFor() !== state.key)) throw new Error('Cabinet: model policy changed before request');
510
+ return result; // Never change the prepared route or effort.
511
+ }, { prepend: true });
512
+ const dispose = () => {
513
+ active = false;
514
+ if (controlledSignal && !controlledSignal.aborted) agent.cancel?.({ kind: 'hook', reason: 'Cabinet model policy unloaded' }, { keepInbox: true });
515
+ offStatus(); offClaim(); offConfig(); offAssembly(); offRequest();
516
+ refreshOwnership();
517
+ const previous = routeMemory.get(agent.id);
518
+ if (previous?.baseline && sameSelection(agent.model.current(), previous.override)) agent.model.select(previous.baseline);
519
+ if (previous && canRecord) remember(undefined);
520
+ };
521
+ if (agent.id !== undefined) attached.set(agent.id, dispose);
522
+ return dispose;
523
+ }
524
+
385
525
  /** Host plugin entry. */
386
526
  const name = 'cabinet-ui';
387
- /** Services read by this entry; `agentTeams` is resolved lazily in apply(). */
388
- const inject = ['systemPrompt'];
527
+ /** Host services needed for prompt sections and durable model ownership. */
528
+ const inject = ['systemPrompt', 'loader', 'sessionProjections'];
389
529
 
390
530
  /** Register the runtime member block as a prompt section. */
391
- function apply(ctx, config) {
531
+ async function apply(ctx, config) {
532
+ let sessionApi;
533
+ try { sessionApi = await prepareModelSessionApi(ctx); }
534
+ catch { /* Legacy hosts need no records; rc.1 overrides fail closed below. */ }
392
535
  ctx.effect(() => ctx.systemPrompt.section({
393
536
  name: MEMBER_SECTION,
394
537
  order: ctx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') + 1,
@@ -407,7 +550,7 @@ function apply(ctx, config) {
407
550
  const routeMemory = new Map();
408
551
  const attach = (agent) => {
409
552
  try {
410
- attachMemberModel(ctx, config, agent, attached, routeMemory);
553
+ attachMemberModel(ctx, config, agent, attached, routeMemory, sessionApi);
411
554
  } catch (error) {
412
555
  try { ctx.logger?.warn?.(`cabinet-ui: model selection attach failed: ${String(error)}`); } catch { /* logger unavailable */ }
413
556
  }
@@ -433,4 +576,4 @@ function apply(ctx, config) {
433
576
  }, 'cabinet-member: model selection');
434
577
  }
435
578
 
436
- export { bureauOf, sectionText, memberBlock, memberModel, modelRoute, clampModel, attachMemberModel, Config, DEFAULT_LEAD_PROMPT, DEFAULT_MEMBER_PROMPTS, MEMBER_KEYS, MEMBER_LABELS, MEMBER_SECTION, MAX_AVATAR_LENGTH, MAX_MODEL_LENGTH, MAX_NAME_LENGTH, MAX_PROMPT_LENGTH, apply, inject, name };
579
+ export { prepareModelSessionApi, bureauOf, sectionText, memberBlock, memberModel, modelRoute, clampModel, attachMemberModel, Config, DEFAULT_LEAD_PROMPT, DEFAULT_MEMBER_PROMPTS, MEMBER_KEYS, MEMBER_LABELS, MEMBER_SECTION, MAX_AVATAR_LENGTH, MAX_MODEL_LENGTH, MAX_NAME_LENGTH, MAX_PROMPT_LENGTH, apply, inject, name };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cabinet-mode",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
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",
@@ -234,7 +234,7 @@ assert.ok(classByKey['t-audit->t-build'].includes('cabinet-edge-active'), classB
234
234
  assert.ok(classByKey['t-audit->t-build'].includes('cabinet-edge-live'), 'running-owner flow edge is distinguishable');
235
235
  assert.ok(classByKey['t-extra->t-audit'].includes('cabinet-edge-pending'), classByKey['t-extra->t-audit']);
236
236
  const edgeDots = layerEls.filter((node) => node.type === 'circle');
237
- assert.equal(edgeDots.length, 5, 'every edge ends in a dot on the blocker side');
237
+ assert.equal(edgeDots.length, 5, 'every edge ends in a dot on the blocked side');
238
238
  assert.ok(edgeDots.every((dot) => dot.props['data-cabinet-edge-dot'].includes('->')));
239
239
  assert.equal(client.TaskEdgeLayer({ edges: [] }), null, 'no edges → no overlay layer');
240
240
  // panel render: cross-member tasks all expose measurement anchors, no premature edges
@@ -270,6 +270,102 @@ assert.ok(reducedMedia.includes('.cabinet-edge-active') && reducedMedia.includes
270
270
  assert.ok(source.includes('.cabinet-edge-done{stroke:light-dark(#15803d,#4ade80)}'), 'done edge has theme-specific green contrast');
271
271
  assert.ok(source.includes('.cabinet-edge-pending{stroke:light-dark(#6b7280,#9ca3af)'), 'pending edge is static grey');
272
272
  assert.ok(source.includes('cabinetEdgeFlow'), 'active edge gets the dash-offset flow');
273
+ // --- direction: the path LEAVES the blocker's row and LANDS on the blocked
274
+ // task's row, dot included; the key still reads <blocked>-><blocker> because
275
+ // only the geometry flipped (首辅 → 阁臣) ---
276
+ const rectBoundary = (point, id) => {
277
+ const rect = edgeRects.get(id);
278
+ if (!rect) return false;
279
+ const [x, y] = point;
280
+ return ((x === rect.left || x === rect.right) && y >= rect.top && y <= rect.bottom)
281
+ || ((y === rect.top || y === rect.bottom) && x >= rect.left && x <= rect.right);
282
+ };
283
+ const dPoints = (d) => d.split(/[MC]/).slice(1).map((part) => part.trim().split(/\s+/).map(Number));
284
+ const near = (a, b) => Math.abs(a - b) < 0.05;
285
+ for (const edge of built) {
286
+ const [blockedId, blockerId] = edge.key.split('->');
287
+ const [start, curve] = dPoints(edge.d);
288
+ const end = curve.slice(-2);
289
+ assert.ok(near(start[0], edge.s[0]) && near(start[1], edge.s[1]), `${edge.key}: M must sit on the start anchor`);
290
+ assert.ok(near(end[0], edge.e[0]) && near(end[1], edge.e[1]), `${edge.key}: path end must sit on the end anchor`);
291
+ assert.equal(edge.ex, edge.e[0], `${edge.key}: dot x is the path end`);
292
+ assert.equal(edge.ey, edge.e[1], `${edge.key}: dot y is the path end`);
293
+ assert.ok(rectBoundary(start, blockerId), `${edge.key}: start anchor lies on the BLOCKER row ${blockerId}`);
294
+ assert.ok(rectBoundary(end, blockedId), `${edge.key}: end anchor lies on the BLOCKED row ${blockedId}`);
295
+ assert.ok(!rectBoundary(start, blockedId), `${edge.key}: start is not on the blocked row — direction is blocker → blocked`);
296
+ assert.ok(!rectBoundary(end, blockerId), `${edge.key}: end is not on the blocker row`);
297
+ }
298
+ // --- click-to-open: only a resolvable, non-inert target binds a handler ---
299
+ const openLog = [];
300
+ const recordOpen = (target) => { openLog.push(target); return true; };
301
+ const subjectOf = (line) => elements(line).find((node) => node.props?.key === 'subj');
302
+ const boundLine = subjectOf(client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: recordOpen }));
303
+ assert.equal(typeof boundLine.props.onClick, 'function', 'a resolved owner binds the subject span');
304
+ assert.equal(boundLine.props.style.cursor, 'pointer', 'a bound subject shows the pointer cursor');
305
+ boundLine.props.onClick();
306
+ assert.deepEqual(openLog, [tasks[0]], 'clicking the subject invokes the opener once with the task');
307
+ for (const task of [
308
+ { id: 'k-lead', subject: 'lead work', ownerName: 'lead', status: 'pending' },
309
+ { id: 'k-none', subject: 'nobody', status: 'pending' },
310
+ ]) {
311
+ const subject = subjectOf(client.TaskLine({ task, t: (key) => key, taskLabel: (status) => status, onOpenOwner: null }));
312
+ assert.equal(subject.props.onClick, undefined, `${task.id}: no click binding without an opener`);
313
+ assert.equal(subject.props.style.cursor, undefined, `${task.id}: no pointer cursor without an opener`);
314
+ }
315
+ // panel level: the resolver decides who gets an opener
316
+ const clickTeam = {
317
+ members: [
318
+ { id: 'lead-session', name: 'lead', role: 'lead', phase: 'active' },
319
+ { id: 'm-works', name: 'works', role: 'mate', phase: 'active' },
320
+ { id: 'm-dali', name: 'dali', role: 'mate', phase: 'failed' },
321
+ { id: 'm-yushi', name: 'yushi', role: 'mate', phase: 'provisioning' },
322
+ ],
323
+ tasks: [
324
+ { id: 'k-lead', subject: 'lead owns this', ownerName: 'lead', status: 'pending' },
325
+ { id: 'k-none', subject: 'no owner', status: 'pending' },
326
+ { id: 'k-works', subject: 'works owns this', ownerName: 'works', status: 'pending' },
327
+ { id: 'k-dali', subject: 'dali owns this', ownerName: 'dali', status: 'pending' },
328
+ { id: 'k-yushi', subject: 'yushi owns this', ownerName: 'yushi', status: 'pending' },
329
+ ],
330
+ };
331
+ const clickEls = elements(render(clickTeam, client.zh));
332
+ const subjectByTitle = new Map();
333
+ for (const node of clickEls) if (node.props?.key === 'subj') subjectByTitle.set(node.props.title, node);
334
+ assert.equal(subjectByTitle.size, clickTeam.tasks.length, 'every task subject rendered');
335
+ assert.equal(subjectByTitle.get('lead owns this').props.onClick, undefined, 'lead task: panel hands no opener');
336
+ assert.equal(subjectByTitle.get('no owner').props.onClick, undefined, 'unassigned task: panel hands no opener');
337
+ assert.equal(typeof subjectByTitle.get('works owns this').props.onClick, 'function', 'teammate task binds');
338
+ assert.equal(subjectByTitle.get('dali owns this').props.onClick, undefined, 'failed-owner task: no opener');
339
+ assert.equal(subjectByTitle.get('yushi owns this').props.onClick, undefined, 'provisioning-owner task: no opener');
340
+ assert.equal(subjectByTitle.get('works owns this').props.style.cursor, 'pointer', 'clickable subject shows the pointer');
341
+ assert.equal(subjectByTitle.get('lead owns this').props.style.cursor, undefined, 'lead task keeps the plain cursor');
342
+ // a bound click with no uiWorkspace channel must degrade silently, never throw
343
+ assert.equal(subjectByTitle.get('works owns this').props.onClick(), false, 'missing channel → silent false, no throw');
344
+ // member cards: same inert rule as the native roster row (self / failed / provisioning)
345
+ const cardWho = (member, extra) => elements(client.MemberCard({
346
+ member, statusLabel: (status) => status, ...extra,
347
+ })).find((node) => node.props?.key === 'who');
348
+ const activeWho = cardWho({ id: 'm-works', name: 'works', phase: 'active' }, { isCurrent: false, onOpen: recordOpen });
349
+ assert.equal(typeof activeWho.props.onClick, 'function', 'active non-current member binds');
350
+ assert.equal(activeWho.props.style.cursor, 'pointer', 'clickable member card shows the pointer');
351
+ assert.equal(activeWho.props.onClick(), true, 'click forwards to the opener');
352
+ for (const [label, member, extra] of [
353
+ ['self', { id: 'lead-session', name: 'lead', phase: 'active' }, { isCurrent: true, onOpen: recordOpen }],
354
+ ['failed', { id: 'm-dali', name: 'dali', phase: 'failed' }, { isCurrent: false, onOpen: recordOpen }],
355
+ ['provisioning', { id: 'm-yushi', name: 'yushi', phase: 'provisioning' }, { isCurrent: false, onOpen: recordOpen }],
356
+ ['no id', { name: 'works', phase: 'active' }, { isCurrent: false, onOpen: recordOpen }],
357
+ ['no channel', { id: 'm-works', name: 'works', phase: 'active' }, { isCurrent: false }],
358
+ ]) {
359
+ const who = cardWho(member, extra);
360
+ assert.equal(who.props.onClick, undefined, `${label}: no click binding`);
361
+ assert.equal(who.props.style.cursor, undefined, `${label}: no pointer cursor`);
362
+ }
363
+ // panel level: exactly the one openable member card is bound
364
+ const whoNodes = clickEls.filter((node) => node.props?.key === 'who');
365
+ assert.equal(whoNodes.length, clickTeam.members.length, 'one who-row per member');
366
+ assert.deepEqual(whoNodes.map((node) => typeof node.props.onClick), ['undefined', 'function', 'undefined', 'undefined'],
367
+ 'lead(self)/failed/provisioning cards stay inert, the active mate binds');
368
+
273
369
  console.log('PASS: avatars, stale-team warnings, and distinct member/owner/group identities; mocked React, not browser E2E');
274
370
  console.log('PASS: task dependency edges — data attributes, three states, missing-blocker tolerance, reduced-motion CSS, geometry refresh gate');
275
371
 
@@ -291,3 +387,4 @@ const adjacent=client.buildTaskEdges(edgeBase,[{id:'top'},{id:'bottom',blockedBy
291
387
  assert.equal(adjacent.length,1);assert.notEqual(adjacent[0].s[1],adjacent[0].e[1]);
292
388
  assert.ok(adjacent[0].c1[0]>adjacent[0].s[0]);
293
389
  console.log('PASS: adjacent same-column rows retain a nonzero gutter curve');
390
+ 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)');
@@ -0,0 +1,173 @@
1
+ import assert from 'node:assert/strict';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {pathToFileURL} from 'node:url';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {attachMemberModel,prepareModelSessionApi,apply,inject} from '../index.js';
7
+ const base=path.join(process.env.DSH_MODULE_ROOT,'@deepseek-ai');
8
+ const load=name=>import(pathToFileURL(path.join(base,name,'lib/index.js')));
9
+ const {Context}=await load('cordis'),{SystemPrompt}=await load('dsh-system-prompt');
10
+ const {createScope}=await load('dsh-scope');
11
+ const {AgentModel,agentEvents,installModelSelection,modelSelectionProjectionDefinition}=await load('dsh-agent');
12
+ const {Loader}=await load('cordis-plugin-loader');
13
+ const loaderCtx=new Context();loaderCtx.baseUrl=pathToFileURL(path.join(process.env.DSH_MODULE_ROOT,'../cordis.yml')).href;new Loader(loaderCtx);
14
+ const {SessionProjectionRegistry}=await load('dsh-session-projection');new SessionProjectionRegistry(loaderCtx);
15
+ const sessionApi=await prepareModelSessionApi(loaderCtx);
16
+ assert.equal(sessionApi.Session,(await load('dsh-session')).Session);
17
+ // Expose the official implementation without changing any method or guard.
18
+ // This additional module lives only in the isolated test runtime and is removed.
19
+ const loopPath=path.join(base,'dsh-agent-loop/lib/index.js');
20
+ const exposed=path.join(path.dirname(loopPath),'cabinet-test-'+randomUUID()+'.mjs');
21
+ fs.writeFileSync(exposed,fs.readFileSync(loopPath,'utf8')+'\nexport { ReactLoopAgent, ReactLoopInbox, inboxProjectionDefinition };\n');
22
+ let Loop,Inbox,inboxProjection;try{const official=await import(pathToFileURL(exposed));Loop=official.ReactLoopAgent;Inbox=official.ReactLoopInbox;inboxProjection=official.inboxProjectionDefinition;}finally{fs.unlinkSync(exposed);}
23
+ // Mount the exported declaration through real Cordis; direct apply() tests cannot
24
+ // detect an invalid injection schema that silently leaves the entry pending.
25
+ new SystemPrompt(loaderCtx,{});let mounted=false;
26
+ const entry=loaderCtx.plugin({name:'cabinet-test-entry',inject,apply:async(ctx,cfg)=>{await apply(ctx,cfg);mounted=true;}},{members:[]});
27
+ await entry;assert.ok(mounted,'Cabinet entry activates through actual Cordis inject');
28
+ let passed=1;
29
+ for(const role of ['lead','teammate']){
30
+ const ctx=new Context();new SystemPrompt(ctx,{});
31
+ // The two variable providers registered by the official AgentLoop constructor.
32
+ ctx.systemPrompt.variable('provider',context=>context.modelSelection?.provider ?? context.agent?.options.provider);
33
+ ctx.systemPrompt.variable('model',context=>context.modelSelection?.model ?? context.agent?.options.model);
34
+ let preset='cabinet',member={role,name:role==='lead'?'lead':'hanlin'},defaults={provider:'default',model:'model'};
35
+ ctx.provide('agentPresets',{composedPreset:()=>preset});ctx.provide('agentTeams',{tryMembership:()=>member});ctx.provide('agentDefaultModel',{currentSelection:()=>defaults});
36
+ let header={config:{provider:'native',model:'initial',reasoningEffort:'high'}},calls=0,toolSelection;
37
+ const agent={id:role,options:{...header.config},requestHeaderLogged:true,phase:{kind:'idle'}};
38
+ Object.defineProperty(agent,'status',Object.getOwnPropertyDescriptor(Loop.prototype,'status'));
39
+ const scope=createScope(ctx,agent);agent.ctx=scope.ctx;agent.dispatch=agentEvents(ctx,agent);
40
+ function reopen(seed){agent.session=sessionApi.Session.create(role,seed);if(!seed)agent.session.append('request/header',{header,reason:'initial'});agent.model=new AgentModel(()=>agent.session.snapshotEvents().reduce(modelSelectionProjectionDefinition.apply,modelSelectionProjectionDefinition.init()),agent.session,agent.options);agent.inbox=new Inbox(()=>agent.session.snapshotEvents().reduce(inboxProjection.apply,inboxProjection.init()),agent.session,agent.dispatch);}
41
+ reopen();assert.ok(agent.session instanceof sessionApi.Session);
42
+ agent.loopCtx={systemPrompt:ctx.systemPrompt,tools:{resolve:async({modelSelection})=>{toolSelection=modelSelection;return{dispose(){},tools:[]}}},llm:{prepareCall:async(config)=>{calls++;return{config}}}};
43
+ agent.runtimeContext={project:()=>undefined};
44
+ const cfg={members:[{key:role==='lead'?'lead':'hanlin',model:'p/override'}]};
45
+ installModelSelection(agent.ctx);
46
+ const memory=new Map(),off=attachMemberModel(ctx,cfg,agent,new Map(),memory,sessionApi);
47
+ const cancellations=[];agent.cancel=(cause,options)=>{cancellations.push({cause,options});agent.phase?.abort.abort(cause)};
48
+ async function step(expected,newTurn=true){if(newTurn){Loop.prototype.setPhase.call(agent,{kind:'idle'});Loop.prototype.setPhase.call(agent,{kind:'running',abort:new AbortController()});}const d=await Loop.prototype.preStep.call(agent,'next-turn',{turn:1,step:1});assert.equal(d.kind,'enter');const request=await Loop.prototype.prepareRequest.call(agent,1,1,d.selection,agent.phase.abort.signal);assert.deepEqual(request.config,expected);assert.deepEqual(toolSelection,d.selection);assert.equal(d.assembly.variables.provider,expected.provider);assert.equal(d.assembly.variables.model,expected.model);passed++;return d;}
49
+ await step({provider:'p',model:'override'});
50
+ cfg.members=[];await step(defaults);
51
+ cfg.members=[{key:role==='lead'?'lead':'hanlin',model:'native/initial'}];await step({provider:'native',model:'initial'});
52
+ agent.model.select({...agent.model.current(),reasoningEffort:'high'});await step({provider:'native',model:'initial',reasoningEffort:'high'});
53
+ cfg.members=[{key:'lead',model:'p/lead'}];await step({provider:'p',model:'lead'});
54
+ preset='standard';await step(header.config);
55
+ if(role==='teammate'){preset='cabinet';member={role:'teammate',name:'lead'};await step(header.config);member={role:'teammate',name:'hanlin'};}
56
+ preset='cabinet';await step({provider:'p',model:'lead'});
57
+ // A real prepared step retains its own route across later configuration changes.
58
+ agent.phase={kind:'running',abort:new AbortController()};
59
+ const a=await Loop.prototype.preStep.call(agent,'next-turn',{turn:2,step:1});
60
+ const aSignal=agent.phase.abort.signal;
61
+ cfg.members=[{key:'lead',model:'p/next'}];agent.dispatch.emit('agent/status',{status:'running'});
62
+ const b=await Loop.prototype.preStep.call(agent,'next-turn',{turn:2,step:2});
63
+ assert.equal((await Loop.prototype.prepareRequest.call(agent,2,1,a.selection,aSignal)).config.model,'lead');
64
+ assert.equal((await Loop.prototype.prepareRequest.call(agent,2,2,b.selection,aSignal)).config.model,'next');passed++;
65
+ // Signal-free preview cannot change either prepared selection or unload tracking.
66
+ await ctx.systemPrompt.assemble({agent,scope:agent});
67
+ assert.equal(agent.model.current().model,'next');passed++;
68
+ preset='standard';await assert.rejects(Loop.prototype.prepareRequest.call(agent,2,2,b.selection,aSignal),/policy changed/);passed++;
69
+ preset='cabinet';
70
+ off();assert.deepEqual(agent.model.current(),header.config);passed++;
71
+ assert.equal(cancellations.length,1);assert.equal(cancellations[0].options.keepInbox,true);assert.ok(aSignal.aborted);passed++;
72
+ // Native mode with configured Cabinet overrides remains entirely untouched.
73
+ preset='standard';reopen();
74
+ const offNative=attachMemberModel(ctx,cfg,agent,new Map(),new Map(),sessionApi);
75
+ await step(header.config);offNative();passed++;
76
+ // Actual teammate role, not a lead-like name, controls access to Lead policy.
77
+ preset='cabinet';member={role:'teammate',name:'lead'};reopen();
78
+ const offImpostor=attachMemberModel(ctx,cfg,agent,new Map(),new Map(),sessionApi);await step(header.config);offImpostor();passed++;
79
+ // Created before membership: the first running notification selects before preStep.
80
+ member=undefined;const offLate=attachMemberModel(ctx,cfg,agent,new Map(),new Map(),sessionApi);
81
+ member={role:'lead',name:'lead'};agent.dispatch.emit('agent/status',{status:'running'});await step({provider:'p',model:'next'});passed++;
82
+ const disk=path.join(path.dirname(exposed),'cabinet-session-'+randomUUID()+'.json');
83
+ fs.writeFileSync(disk,JSON.stringify(agent.session.snapshotEvents()));offLate();
84
+ const crashLog=JSON.parse(fs.readFileSync(disk,'utf8'));fs.unlinkSync(disk);reopen(crashLog);cfg.members=[];
85
+ const offRestored=attachMemberModel(ctx,cfg,agent,new Map(),new Map(),sessionApi);await step(defaults);offRestored();passed++;
86
+
87
+ // Recover real Session logs across each side of the two-write transaction.
88
+ const native={...header.config};member={role:'lead',name:'lead'};preset='cabinet';
89
+ const persist=()=>{const file=path.join(path.dirname(exposed),'cabinet-crash-'+randomUUID()+'.json');fs.writeFileSync(file,JSON.stringify(agent.session.snapshotEvents()));const result=JSON.parse(fs.readFileSync(file,'utf8'));fs.unlinkSync(file);return result;};
90
+ const attach=(api=sessionApi)=>attachMemberModel(ctx,cfg,agent,new Map(),new Map(),api);
91
+ const notify=()=>agent.dispatch.emit('agent/status',{status:'running'});
92
+ // Initial intent durable, selection failed: a never-applied policy must not claim native state.
93
+ reopen();cfg.members=[{key:'lead',model:'p/first'}];
94
+ let select=agent.model.select.bind(agent.model);agent.model.select=()=>{throw Error('injected select failure')};
95
+ let cleanup=attach();await assert.rejects(step({}),/injected select failure/);passed++;
96
+ let seed=persist();agent.model.select=select;cleanup();reopen(seed);cfg.members=[];cleanup=attach();await step(native);cleanup();
97
+ // Changing an owned override: failure after new intent must retain the old override's provenance.
98
+ reopen();cfg.members=[{key:'lead',model:'p/first'}];cleanup=attach();await step({provider:'p',model:'first'});
99
+ select=agent.model.select.bind(agent.model);agent.model.select=()=>{throw Error('between intent and select')};
100
+ cfg.members=[{key:'lead',model:'p/second'}];notify();await assert.rejects(step({}),/between intent and select/);passed++;
101
+ seed=persist();agent.model.select=select;cleanup();reopen(seed);cfg.members=[];cleanup=attach();await step(defaults);cleanup();
102
+ // Restoration succeeds, clearing ownership fails: replay must keep the restored native choice.
103
+ reopen();cfg.members=[{key:'lead',model:'p/first'}];let failClear=false;
104
+ const interruptedApi={...sessionApi,appendPluginRecord:(session,type,data)=>{if(failClear&&!data.baseline)throw Error('between restore and clear');return sessionApi.appendPluginRecord(session,type,data);}};
105
+ cleanup=attach(interruptedApi);await step({provider:'p',model:'first'});cfg.members=[];failClear=true;notify();
106
+ assert.deepEqual(agent.model.current(),defaults);await assert.rejects(ctx.systemPrompt.assemble({agent,scope:agent}),/between restore and clear/);passed++;
107
+ seed=persist();failClear=false;cleanup();reopen(seed);cleanup=attach();await step(defaults);cleanup();
108
+ // A manual native change, even away and back to the same override, revokes ownership.
109
+ for(const action of ['clear','unload','restart','standard']){
110
+ reopen();cfg.members=[{key:'lead',model:'p/first'}];cleanup=attach();await step({provider:'p',model:'first'});
111
+ agent.model.select({provider:'manual',model:'other',reasoningEffort:'low'});agent.model.select({provider:'p',model:'first'});
112
+ if(action==='restart'){seed=persist();cleanup();reopen(seed);cfg.members=[];cleanup=attach();}
113
+ else if(action==='unload'){cleanup();cleanup=()=>{};}
114
+ else if(action==='standard')preset='standard';else cfg.members=[];
115
+ assert.deepEqual(agent.model.current(),{provider:'p',model:'first'});
116
+ if(action!=='unload')await step({provider:'p',model:'first'});else passed++;
117
+ cleanup();preset='cabinet';
118
+ }
119
+ // Restoring Standard reinstates baseline effort even if its route equals the latest override.
120
+ reopen();cfg.members=[{key:'lead',model:'p/first'}];cleanup=attach();await step({provider:'p',model:'first'});
121
+ cfg.members=[{key:'lead',model:'native/initial'}];await step({provider:'native',model:'initial'});
122
+ preset='standard';await step(native);cleanup();preset='cabinet';
123
+ // Empty real inbox: neither claim nor running-to-running publishes a new boundary.
124
+ reopen();cfg.members=[{key:'lead',model:'p/first'}];cleanup=attach();await step({provider:'p',model:'first'});
125
+ cfg.members=[{key:'lead',model:'p/second'}];Loop.prototype.setPhase.call(agent,{...agent.phase});
126
+ await step({provider:'p',model:'first'},false);
127
+ // A real claimed message, unlike an empty queue, synchronizes before selection freezes.
128
+ agent.inbox.append('next-step',{id:'fixture-'+role,role:'user',content:[{type:'text',text:'fixture'}]});
129
+ await step({provider:'p',model:'second'},false);
130
+ cfg.members=[];defaults={provider:'changed-default',model:'new'};
131
+ await step({provider:'p',model:'second'},false);await step(defaults);cleanup();
132
+ defaults={provider:'default',model:'model'};
133
+ // Changing preset with no phase/inbox notification cannot send the old owned route.
134
+ reopen();cfg.members=[{key:'lead',model:'p/first'}];cleanup=attach();await step({provider:'p',model:'first'});
135
+ preset='standard';const beforeMode=calls;await assert.rejects(step({},false),/policy changed before step/);assert.equal(calls,beforeMode);passed++;
136
+ await step(native);cleanup();preset='cabinet';
137
+ // Membership arriving after a running transition must not silently use native fallback.
138
+ reopen();member=undefined;cfg.members=[{key:'lead',model:'p/late'}];cleanup=attach();await step(native);
139
+ member={role:'lead',name:'lead'};const beforeLate=calls;await assert.rejects(step({},false),/policy changed before step/);assert.equal(calls,beforeLate);passed++;
140
+ await step({provider:'p',model:'late'});cleanup();
141
+ // Corrupt records do not acquire ownership, and missing host APIs fail before any adapter call.
142
+ reopen();cfg.members=[];sessionApi.appendPluginRecord(agent.session,'plugin:dsh-cabinet-mode/model-policy',{agentId:agent.id,baseline:'bad',override:native});
143
+ cleanup=attach();await step(native);cleanup();
144
+ reopen();cfg.members=[{key:'lead',model:'p/first'}];const before=calls;cleanup=attach({});await assert.rejects(step({}),/API unavailable/);assert.equal(calls,before);passed++;
145
+ cfg.members=[];notify();await step(native);cleanup();
146
+
147
+ // Exercise real Loader volatile reconciliation, not a synthetic save notification.
148
+ reopen();member={role:'lead',name:'lead'};preset='cabinet';
149
+ ctx.baseUrl=loaderCtx.baseUrl;await ctx.plugin(Loader);new SessionProjectionRegistry(ctx);
150
+ ctx.provide('agents',{list:()=>[agent]});const loader=ctx.get('loader');
151
+ const entryId=await loader.create({name:new URL('../index.js',import.meta.url).href,config:{members:[{key:'lead',model:'p/saved-a'}]}});
152
+ await loader.await();const loaded=loader.resolve(entryId);assert.equal(loaded.fiber.state,2);const originalFiber=loaded.fiber;
153
+ await step({provider:'p',model:'saved-a'});
154
+ const oldPrepared=await Loop.prototype.preStep.call(agent,'next-step',{turn:3,step:1});const oldSignal=agent.phase.abort.signal;
155
+ await loader.update(entryId,{config:{members:[{key:'lead',model:'p/saved-b'}]}});await loader.await();
156
+ assert.equal(loaded.fiber,originalFiber,'volatile save does not remount');
157
+ assert.equal((await Loop.prototype.prepareRequest.call(agent,3,1,oldPrepared.selection,oldSignal)).config.model,'saved-a');passed++;
158
+ await step({provider:'p',model:'saved-b'},false);
159
+ // Another entry changing a field also called members cannot synchronize this policy.
160
+ const otherFile=path.join(path.dirname(exposed),'cabinet-unrelated-'+randomUUID()+'.mjs');
161
+ fs.writeFileSync(otherFile,'export {Config} from '+JSON.stringify(new URL('../index.js',import.meta.url).href)+'; export function apply(){}');
162
+ let otherId;try{otherId=await loader.create({name:pathToFileURL(otherFile).href,config:{members:[]}});await loader.await();
163
+ agent.model.select({provider:'manual',model:'keep'});
164
+ await loader.update(otherId,{config:{members:[{key:'lead',model:'p/unrelated'}]}});await loader.await();
165
+ assert.deepEqual(agent.model.current(),{provider:'manual',model:'keep'});passed++;
166
+ }finally{if(otherId)loader.remove(otherId);await loader.await();fs.unlinkSync(otherFile);}
167
+ // Restore a controlled route via a real save, then clear it with an empty inbox.
168
+ await loader.update(entryId,{config:{members:[{key:'lead',model:'p/saved-c'}]}});await loader.await();await step({provider:'p',model:'saved-c'},false);
169
+ await loader.update(entryId,{config:{members:[]}});await loader.await();await step(defaults,false);
170
+ loader.remove(entryId);await loader.await();
171
+ assert.ok(calls>=7);
172
+ }
173
+ console.log(`PASS ${passed} official rc.1 preStep -> prepareRequest cases; real AgentModel/Cordis/SystemPrompt; real inbox; identity and adapter fixtures; no model calls`);
@@ -14,7 +14,7 @@ preset='cabinet';config.members=[];assert.deepEqual((await route()).r,defaults);
14
14
  services.agentPresets=undefined;assert.equal((await route()).r.model,'seed');
15
15
  off();assert.equal(Object.keys(callbacks).length,0);
16
16
  const effects=[],events={};services.agents={list:()=>[agent]};
17
- apply({get:key=>services[key],effect:fn=>effects.push(fn()),on:(name,fn)=>{events[name]=fn;return()=>delete events[name];},systemPrompt:{getSectionOrder:()=>0,section:()=>()=>{}}},config);
17
+ await apply({get:key=>services[key],effect:fn=>effects.push(fn()),on:(name,fn)=>{events[name]=fn;return()=>delete events[name];},systemPrompt:{getSectionOrder:()=>0,section:()=>()=>{}}},config);
18
18
  assert.equal(typeof callbacks['agent/request'],'function','backfill existing agents');
19
19
  events['agent/disposed']({agent});assert.equal(Object.keys(callbacks).length,0);
20
20
  events['agent/created']({agent});assert.equal(typeof callbacks['agent/request'],'function','attach before membership is available');