dsh-cabinet-mode 0.6.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +40 -4
- package/README.zh.md +40 -4
- package/client.js +348 -23
- package/docs/member-usage-validation.md +15 -0
- package/package.json +2 -1
- package/scripts/test-client.mjs +252 -3
- package/scripts/test-panel-browser.mjs +56 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [0.7.0] - 2026-11-09
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Open teammate sessions from member cards, task rows and Owner labels, with native keyboard buttons and single-navigation event propagation.
|
|
10
|
+
- Show member token totals, elapsed time and approximate context composition from host projections. Missing data remains unknown; cached snapshots are not guaranteed final usage.
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Keep usage hooks stable when team data arrives or disappears; handle initial idle reads, running/stopped transitions, optional service arrival and timer cleanup.
|
|
15
|
+
- Validate isolated real React lifecycle and keyboard navigation without restarting existing DSH or calling models.
|
|
16
|
+
|
|
17
|
+
## [0.6.4] - 2026-11-09
|
|
18
|
+
|
|
19
|
+
### Documentation
|
|
20
|
+
|
|
21
|
+
- Add bilingual update notes and clarify network requirements for local installation, the limited absolute-path checks, and role-dependent prompt size changes.
|
|
22
|
+
- Describe task budgets and retry limits as prompt-level guidance, not runtime enforcement. No fixed per-turn character or token savings are promised.
|
|
23
|
+
- Runtime behavior is unchanged from 0.6.3.
|
|
24
|
+
|
|
5
25
|
## [0.6.3] - 2026-11-08
|
|
6
26
|
|
|
7
27
|
### Changed
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Cabinet Mode (内阁模式) for DeepSeek Harness
|
|
2
2
|
|
|
3
|
-
**Version compatibility (0.
|
|
3
|
+
**Version compatibility (0.7.0):** Targets DSH **0.2.2-rc.1**. This release adds keyboard-accessible session navigation and member usage snapshots; it preserves the shorter default prompts while retaining budget, authorization and final-state verification requirements, 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,43 @@ 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.
|
|
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.7.0 (see [DSH-side constraints](#dsh-side-constraints)).
|
|
41
|
+
|
|
42
|
+
## Member usage snapshots
|
|
43
|
+
|
|
44
|
+
Cards show host-reported token totals, elapsed time and approximate context composition. Missing values show a dash. The public projection read may return a cached snapshot; these figures are not guaranteed final usage or billing totals. Tests use real React with simulated services, not live-team E2E. See [validation scope](docs/member-usage-validation.md).
|
|
45
|
+
|
|
46
|
+
## Update notes
|
|
47
|
+
|
|
48
|
+
0.6.3
|
|
49
|
+
|
|
50
|
+
- Default prompts are shorter than in 0.6.2; the reduction varies by role and custom settings. No fixed per-turn or token saving is claimed.
|
|
51
|
+
- Removed repeated instructions and examples.
|
|
52
|
+
- Prompt-level task budgets (not runtime-enforced counters): up to 30 tool calls for a single-file task.
|
|
53
|
+
- The prompt budget for a multi-file task is up to 100 tool calls.
|
|
54
|
+
- The prompt limits retries for the same failure to 2 and requires the task brief to state its budget and stop conditions; this is not a runtime guarantee. These budget limits predate 0.6.3.
|
|
55
|
+
|
|
56
|
+
0.6.2
|
|
57
|
+
|
|
58
|
+
- Explains when falling back to the public source.
|
|
59
|
+
- Shows the source of installed plugins; unknown when unreadable.
|
|
60
|
+
- Keeps state separate per connection.
|
|
61
|
+
|
|
62
|
+
0.6.1
|
|
63
|
+
|
|
64
|
+
- Memory plugin can install from a local path.
|
|
65
|
+
- The default registry source needs network access. A local source is for first installation only; dependencies may still need the network, so offline success is not guaranteed.
|
|
66
|
+
- Updates from local paths are rejected.
|
|
67
|
+
- Fallback to the registry is limited to a completed source inspection failure before installation; timeouts or thrown errors do not trigger fallback.
|
|
68
|
+
- Tests reject the literal `/home/fslong` in `client.js`; a separate check rejects selected absolute-path patterns in `cordis.patch.yml`. These checks do not detect every hardcoded home path.
|
|
69
|
+
|
|
70
|
+
0.6.0
|
|
71
|
+
|
|
72
|
+
- Member config page now has five tabs.
|
|
73
|
+
- Plugin page adds a memory plugin install card.
|
|
74
|
+
- Task assignment spells out reporting points and deliverable scope.
|
|
75
|
+
- Reassign only after the active writer stops.
|
|
76
|
+
- Remote install reads the official response structure.
|
|
41
77
|
|
|
42
78
|
## Optional memory plugin
|
|
43
79
|
|
|
@@ -262,7 +298,7 @@ On failure, show the exact error. For $.format must be 1, replace the webpage so
|
|
|
262
298
|
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:
|
|
263
299
|
|
|
264
300
|
```sh
|
|
265
|
-
dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.
|
|
301
|
+
dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.7.0/dsh-cabinet-mode-0.7.0.tgz
|
|
266
302
|
dsh plugin --profile desktop list
|
|
267
303
|
```
|
|
268
304
|
|
|
@@ -277,7 +313,7 @@ the same install command with the new version URL (or pick the new `.tgz` in the
|
|
|
277
313
|
plugin page), then fully quit and restart DeepSeek Harness:
|
|
278
314
|
|
|
279
315
|
```sh
|
|
280
|
-
dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.
|
|
316
|
+
dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.7.0/dsh-cabinet-mode-0.7.0.tgz
|
|
281
317
|
```
|
|
282
318
|
|
|
283
319
|
`dsh plugin --profile desktop list` should report the new version. Upgrades were
|
package/README.zh.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 内阁模式(Cabinet Mode)· DeepSeek Harness 插件
|
|
2
2
|
|
|
3
|
-
**版本兼容(0.
|
|
3
|
+
**版本兼容(0.7.0):** 面向 DSH **0.2.2-rc.1**,本版新增键盘会话导航和成员用量快照;保留较短的默认提示,保留预算、授权与最终状态验收要求,不承诺 Token 节省;依赖连线与成员会话入口属于 0.5.4 的更新。保留在宿主固定每步模型前完成官职模型选择的修复;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,43 @@
|
|
|
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.
|
|
24
|
+
本包声明 **无 DSH 版本硬限制**:没有 `engines.dsh`、没有 DSH `peerDependencies`、安装时不做版本检查。旧包曾在 DSH **0.2.1-rc.3** 实测;0.7.0 请遵循上方版本兼容说明(见 [DSH 侧限制与说明](#dsh-侧限制与说明))。
|
|
25
|
+
|
|
26
|
+
## 成员用量快照
|
|
27
|
+
|
|
28
|
+
卡片显示宿主投影中的 token 合计、耗时和近似上下文构成,缺失值显示破折号。公开投影读取可能返回缓存,不保证最终用量或计费精度。验证使用真实 React 与模拟服务,不是运行中团队的端到端测试。详见[验证范围](docs/member-usage-validation.md)。
|
|
29
|
+
|
|
30
|
+
## 更新日志
|
|
31
|
+
|
|
32
|
+
0.6.3
|
|
33
|
+
|
|
34
|
+
- 默认提示词比 0.6.2 更短;缩减量随角色和自定义设置而异,不承诺固定的每轮字数或 Token 节省。
|
|
35
|
+
- 删掉重复交代和举例。
|
|
36
|
+
- 提示词约定单文件任务最多 30 次工具调用,并非运行时计数器强制执行。
|
|
37
|
+
- 提示词约定多文件任务最多 100 次工具调用。
|
|
38
|
+
- 提示词约定同一失败最多重试 2 次,任务书须写明预算与停止条件;这不是运行时保证,预算限制也不是 0.6.3 首次引入。
|
|
39
|
+
|
|
40
|
+
0.6.2
|
|
41
|
+
|
|
42
|
+
- 回退到公共源时会说明。
|
|
43
|
+
- 显示已装插件的来源,读不到显示未知。
|
|
44
|
+
- 不同连接的状态分开存放。
|
|
45
|
+
|
|
46
|
+
0.6.1
|
|
47
|
+
|
|
48
|
+
- 记忆插件支持从本机路径安装。
|
|
49
|
+
- 默认 registry 来源需要联网。本地源仅用于首次安装,依赖仍可能需要网络,不保证离线成功。
|
|
50
|
+
- 本机路径的更新会被拒绝。
|
|
51
|
+
- 只有安装前已返回的源检查失败才允许回退到 registry;检查超时或抛出异常不回退。
|
|
52
|
+
- 测试检查 `client.js` 中的字面量 `/home/fslong`;另有检查针对 `cordis.patch.yml` 中部分绝对路径模式,并不覆盖所有写死的家目录路径。
|
|
53
|
+
|
|
54
|
+
0.6.0
|
|
55
|
+
|
|
56
|
+
- 成员配置页改成五个标签页。
|
|
57
|
+
- 插件页加了记忆插件安装卡。
|
|
58
|
+
- 派活时写清回报节点和产物范围。
|
|
59
|
+
- 确认在写的人停了才能重新派。
|
|
60
|
+
- 远程安装按官方返回结构读取。
|
|
25
61
|
|
|
26
62
|
## 可选记忆插件
|
|
27
63
|
|
|
@@ -193,7 +229,7 @@ https://raw.githubusercontent.com/luodaoyi/dsh-cabinet-mode/market-index/marketp
|
|
|
193
229
|
仅在商店不可用或本地开发时使用。先完全退出桌面 DSH,释放 profile 锁,再执行:
|
|
194
230
|
|
|
195
231
|
```sh
|
|
196
|
-
dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.
|
|
232
|
+
dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.7.0/dsh-cabinet-mode-0.7.0.tgz
|
|
197
233
|
dsh plugin --profile desktop list
|
|
198
234
|
```
|
|
199
235
|
|
|
@@ -204,7 +240,7 @@ dsh plugin --profile desktop list
|
|
|
204
240
|
若通过插件市场安装:刷新市场,先在**已安装**页卸载旧版本,再从**插件市场**安装新版本,然后重启——没有 tgz URL 要换,也没有一键更新。否则用同一条安装命令换新版本 URL(或在插件页选新 `.tgz`),然后完全退出并重启 DeepSeek Harness:
|
|
205
241
|
|
|
206
242
|
```sh
|
|
207
|
-
dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.
|
|
243
|
+
dsh plugin --profile desktop add https://github.com/luodaoyi/dsh-cabinet-mode/releases/download/v0.7.0/dsh-cabinet-mode-0.7.0.tgz
|
|
208
244
|
```
|
|
209
245
|
|
|
210
246
|
`dsh plugin --profile desktop list` 应显示新版本。升级已在 Windows 实测:
|
package/client.js
CHANGED
|
@@ -2399,6 +2399,17 @@ window.__ModuleLoader__.load({
|
|
|
2399
2399
|
// org-chart cards + first-class lead badge
|
|
2400
2400
|
'.cabinet-card{box-sizing:border-box;display:flex;flex-direction:column;gap:4px;min-width:0;padding:8px 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l3,light-dark(#0000001f,#ffffff29));background:var(--dsw-alias-bg-layer-1,light-dark(#ffffff,#232324))}',
|
|
2401
2401
|
'.cabinet-card-lead{border-color:rgba(245,197,24,.55);background-image:linear-gradient(rgba(245,197,24,.10),rgba(245,197,24,.10))}',
|
|
2402
|
+
// click-through affordance: the whole card, the whole task row and the
|
|
2403
|
+
// Owner tag are targets, so hover has to say so. An inset ring leaves
|
|
2404
|
+
// every inline background (tags, live rows) untouched.
|
|
2405
|
+
'.cabinet-card-clickable:hover{border-color:rgba(127,127,127,.60)}',
|
|
2406
|
+
'.cabinet-card button:focus-visible{outline:2px solid currentColor;outline-offset:2px}',
|
|
2407
|
+
'.cabinet-clickable:hover{box-shadow:inset 0 0 0 1px rgba(127,127,127,.55)}',
|
|
2408
|
+
// context-pressure bar: one 4px track, three state-coloured segments
|
|
2409
|
+
// (system / tools / message) sized by the projection's own breakdown
|
|
2410
|
+
'.cabinet-ctxbar{display:inline-flex;width:34px;height:4px;border-radius:2px;overflow:hidden;background:rgba(127,127,127,.25);flex:none}',
|
|
2411
|
+
'.cabinet-ctxbar i{display:block;height:100%}',
|
|
2412
|
+
'.cabinet-ctxbar-system{background:#8b5cf6}.cabinet-ctxbar-tools{background:#0ea5e9}.cabinet-ctxbar-message{background:#22c55e}',
|
|
2402
2413
|
'.cabinet-badge-lead{font-size:10px;line-height:14px;padding:0 6px;border-radius:4px;font-weight:600;background:rgba(245,197,24,.20);border:1px solid rgba(245,197,24,.45);color:#6b4a00}',
|
|
2403
2414
|
'body[data-ds-dark-theme] .cabinet-badge-lead{color:#ffd666}',
|
|
2404
2415
|
// status / task text: one colour per state per theme, so 11px copy clears
|
|
@@ -2567,6 +2578,39 @@ window.__ModuleLoader__.load({
|
|
|
2567
2578
|
* degrades to a silent no-op instead of throwing at the panel.
|
|
2568
2579
|
*/
|
|
2569
2580
|
let cabinetOpenSession = null;
|
|
2581
|
+
/**
|
|
2582
|
+
* Optional `sessions` service, captured by ctx.inject() inside apply(). It is
|
|
2583
|
+
* the only way to pull projections for member sessions the panel has not
|
|
2584
|
+
* subscribed to yet; when the service is missing every card still renders
|
|
2585
|
+
* and simply prints its em dash.
|
|
2586
|
+
*/
|
|
2587
|
+
let cabinetSessions = null;
|
|
2588
|
+
const cabinetSessionsListeners = new Set();
|
|
2589
|
+
/**
|
|
2590
|
+
* Retry cadence for public projection reads while a member is running.
|
|
2591
|
+
* Ready snapshots can be cached by the host; this is not forced polling.
|
|
2592
|
+
* The sessions service does not issue model requests.
|
|
2593
|
+
*/
|
|
2594
|
+
const PROJECTION_REFRESH_MS = 5000;
|
|
2595
|
+
/**
|
|
2596
|
+
* Ask the sessions service once for one member's projections (same call the
|
|
2597
|
+
* native roster makes). Never throws: a missing service, a refusing
|
|
2598
|
+
* deployment or a rejected promise all degrade to "no value yet", which the
|
|
2599
|
+
* cards render as an em dash.
|
|
2600
|
+
*/
|
|
2601
|
+
function refreshCabinetProjection(id) {
|
|
2602
|
+
if (typeof id !== 'string' || id === '') return null;
|
|
2603
|
+
const sessions = cabinetSessions;
|
|
2604
|
+
if (!sessions || typeof sessions.refreshProjections !== 'function') return null;
|
|
2605
|
+
try {
|
|
2606
|
+
const pending = sessions.refreshProjections(id);
|
|
2607
|
+
if (pending !== undefined && pending !== null && typeof pending.catch === 'function') pending.catch(() => {});
|
|
2608
|
+
return pending;
|
|
2609
|
+
} catch (error) {
|
|
2610
|
+
try { console.warn('[cabinet-ui] refresh projections failed:', error); } catch (ignored) { /* console may be unavailable */ }
|
|
2611
|
+
return null;
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2570
2614
|
/**
|
|
2571
2615
|
* Open a teammate's child session the way the native roster does
|
|
2572
2616
|
* (dsh-experimental-client-ui-agent-team openTeammate): the Lead session
|
|
@@ -3019,18 +3063,153 @@ window.__ModuleLoader__.load({
|
|
|
3019
3063
|
]);
|
|
3020
3064
|
}
|
|
3021
3065
|
|
|
3022
|
-
function Tag({ background, color, title, children }) {
|
|
3023
|
-
|
|
3066
|
+
function Tag({ background, color, title, children, onClick }) {
|
|
3067
|
+
// A tag that carries an opener is its own click target (the Owner tag);
|
|
3068
|
+
// the caller stops propagation so the enclosing card or task row does
|
|
3069
|
+
// not forward the same click a second time.
|
|
3070
|
+
const clickable = typeof onClick === 'function';
|
|
3071
|
+
return h(clickable ? 'button' : 'span', {
|
|
3072
|
+
type: clickable ? 'button' : undefined,
|
|
3024
3073
|
title,
|
|
3025
|
-
|
|
3074
|
+
onClick,
|
|
3075
|
+
className: clickable ? 'cabinet-clickable' : undefined,
|
|
3076
|
+
style: { font: 'inherit', border: 0, fontSize: 10, padding: '0 5px', borderRadius: 4, color, background, flex: 'none', cursor: clickable ? 'pointer' : undefined }
|
|
3026
3077
|
}, children);
|
|
3027
3078
|
}
|
|
3028
3079
|
|
|
3080
|
+
// One click opens one session. Nested targets (the who row inside a card,
|
|
3081
|
+
// the subject / Owner tag / blocker toggle inside a task row) stop the
|
|
3082
|
+
// click so the enclosing handler does not repeat the same navigation.
|
|
3083
|
+
function stopPropagation(event) {
|
|
3084
|
+
if (event && typeof event.stopPropagation === 'function') event.stopPropagation();
|
|
3085
|
+
}
|
|
3086
|
+
|
|
3087
|
+
// ---- member usage: token total, elapsed time, context pressure --------
|
|
3088
|
+
// Everything below reads DSH's own session projections (tokenUsage,
|
|
3089
|
+
// subagentTiming, contextPressure, contextBreakdown) and never invents a
|
|
3090
|
+
// field: a projection the host did not publish renders as an em dash.
|
|
3091
|
+
|
|
3092
|
+
/** Compact token count: 842 stays exact, 3.3M / 12.5K collapse like the stats strip. */
|
|
3093
|
+
function formatTokenCount(value) {
|
|
3094
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return undefined;
|
|
3095
|
+
const scaled = (next) => (next >= 100 ? String(Math.round(next)) : String(Math.round(next * 10) / 10));
|
|
3096
|
+
if (value < 1000) return String(Math.round(value));
|
|
3097
|
+
if (value < 1e6) return scaled(value / 1e3) + 'K';
|
|
3098
|
+
return scaled(value / 1e6) + 'M';
|
|
3099
|
+
}
|
|
3100
|
+
|
|
3101
|
+
/** Whole-second elapsed time: 12s, 3m12s, 1h05m, 2d03h. */
|
|
3102
|
+
function formatElapsed(ms) {
|
|
3103
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return undefined;
|
|
3104
|
+
const totalSeconds = Math.floor(ms / 1000);
|
|
3105
|
+
if (totalSeconds < 60) return totalSeconds + 's';
|
|
3106
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
3107
|
+
if (minutes < 60) return minutes + 'm' + String(totalSeconds % 60).padStart(2, '0') + 's';
|
|
3108
|
+
const hours = Math.floor(minutes / 60);
|
|
3109
|
+
if (hours < 24) return hours + 'h' + String(minutes % 60).padStart(2, '0') + 'm';
|
|
3110
|
+
return Math.floor(hours / 24) + 'd' + String(hours % 24).padStart(2, '0') + 'h';
|
|
3111
|
+
}
|
|
3112
|
+
|
|
3113
|
+
/** Sum the four disjoint provider-usage buckets; undefined when none exists. */
|
|
3114
|
+
function tokenTotalOf(usage) {
|
|
3115
|
+
if (usage === undefined || usage === null || typeof usage !== 'object') return undefined;
|
|
3116
|
+
const buckets = ['uncachedInputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens']
|
|
3117
|
+
.map((key) => usage[key])
|
|
3118
|
+
.filter((value) => typeof value === 'number' && Number.isFinite(value) && value >= 0);
|
|
3119
|
+
if (buckets.length === 0) return undefined;
|
|
3120
|
+
return buckets.reduce((sum, value) => sum + value, 0);
|
|
3121
|
+
}
|
|
3122
|
+
|
|
3123
|
+
/**
|
|
3124
|
+
* Turn one session's projection values into a display record. Every field is
|
|
3125
|
+
* optional: a missing projection yields undefined (the card prints its dash),
|
|
3126
|
+
* and a missing contextWindow keeps the token numbers but drops the ratio.
|
|
3127
|
+
*/
|
|
3128
|
+
function usageFor(values, now) {
|
|
3129
|
+
const source = values !== undefined && values !== null && typeof values === 'object' ? values : {};
|
|
3130
|
+
const tokens = tokenTotalOf(source.tokenUsage?.totals ?? source.tokenUsage);
|
|
3131
|
+
let elapsedMs;
|
|
3132
|
+
const timing = source.subagentTiming;
|
|
3133
|
+
if (timing !== undefined && timing !== null && typeof timing === 'object') {
|
|
3134
|
+
const settled = typeof timing.settledMs === 'number' && Number.isFinite(timing.settledMs) ? timing.settledMs : 0;
|
|
3135
|
+
const active = timing.active;
|
|
3136
|
+
if (active !== undefined && active !== null && typeof active.since === 'number' && Number.isFinite(active.since)) {
|
|
3137
|
+
const clock = typeof now === 'number' && Number.isFinite(now) ? now : active.since;
|
|
3138
|
+
elapsedMs = settled + Math.max(0, clock - active.since);
|
|
3139
|
+
} else if (typeof timing.settledMs === 'number' && Number.isFinite(timing.settledMs)) {
|
|
3140
|
+
elapsedMs = settled;
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
const pressure = source.contextPressure;
|
|
3144
|
+
const breakdown = source.contextBreakdown?.breakdown ?? source.contextBreakdown;
|
|
3145
|
+
const projected = pressure !== undefined && pressure !== null && typeof pressure.projectedTokens === 'number' && Number.isFinite(pressure.projectedTokens)
|
|
3146
|
+
&& pressure.projectedTokens >= 0 ? pressure.projectedTokens : undefined;
|
|
3147
|
+
const contextWindow = pressure !== undefined && pressure !== null && typeof pressure.contextWindow === 'number' && Number.isFinite(pressure.contextWindow) && pressure.contextWindow > 0
|
|
3148
|
+
? pressure.contextWindow : undefined;
|
|
3149
|
+
const parts = breakdown !== undefined && breakdown !== null && typeof breakdown === 'object'
|
|
3150
|
+
? [
|
|
3151
|
+
{ key: 'system', value: breakdown.systemTokens },
|
|
3152
|
+
{ key: 'tools', value: breakdown.toolsTokens },
|
|
3153
|
+
{ key: 'message', value: breakdown.messageTokens }
|
|
3154
|
+
].filter((part) => typeof part.value === 'number' && Number.isFinite(part.value) && part.value >= 0)
|
|
3155
|
+
: [];
|
|
3156
|
+
let context;
|
|
3157
|
+
if (projected !== undefined || contextWindow !== undefined || parts.length > 0) {
|
|
3158
|
+
const sum = parts.reduce((total, part) => total + part.value, 0);
|
|
3159
|
+
context = {
|
|
3160
|
+
projectedTokens: projected,
|
|
3161
|
+
contextWindow,
|
|
3162
|
+
percent: projected !== undefined && contextWindow !== undefined
|
|
3163
|
+
? Math.min(100, Math.round((projected / contextWindow) * 1000) / 10) : undefined,
|
|
3164
|
+
segments: sum > 0 ? parts.map((part) => ({ key: part.key, ratio: part.value / sum })) : []
|
|
3165
|
+
};
|
|
3166
|
+
}
|
|
3167
|
+
return { tokens, elapsedMs, context };
|
|
3168
|
+
}
|
|
3169
|
+
|
|
3170
|
+
/**
|
|
3171
|
+
* Which member sessions need another projection refresh now.
|
|
3172
|
+
*
|
|
3173
|
+
* Time-based, not once-per-mount: a running member's numbers have to keep
|
|
3174
|
+
* moving, so an id becomes eligible again once `throttleMs` has passed since
|
|
3175
|
+
* its last request. `lastRequestedAt` is the caller's Map<id, timestamp>; the
|
|
3176
|
+
* helper applies only a time threshold; lifecycle transitions are handled
|
|
3177
|
+
* separately by the panel, including initial and settled reads.
|
|
3178
|
+
*/
|
|
3179
|
+
function planProjectionRequests(ids, lastRequestedAt, now, throttleMs) {
|
|
3180
|
+
const planned = [];
|
|
3181
|
+
const clock = typeof now === 'number' && Number.isFinite(now) ? now : Date.now();
|
|
3182
|
+
const throttle = typeof throttleMs === 'number' && Number.isFinite(throttleMs) && throttleMs >= 0 ? throttleMs : PROJECTION_REFRESH_MS;
|
|
3183
|
+
// Duck-typed so a Map from another realm (tests, host bridge) still counts.
|
|
3184
|
+
const log = lastRequestedAt !== undefined && lastRequestedAt !== null && typeof lastRequestedAt.get === 'function'
|
|
3185
|
+
? lastRequestedAt : new Map();
|
|
3186
|
+
for (const id of Array.isArray(ids) ? ids : []) {
|
|
3187
|
+
if (typeof id !== 'string' || id === '' || planned.includes(id)) continue;
|
|
3188
|
+
const previous = log.get(id);
|
|
3189
|
+
if (typeof previous === 'number' && Number.isFinite(previous) && clock - previous < throttle) continue;
|
|
3190
|
+
planned.push(id);
|
|
3191
|
+
}
|
|
3192
|
+
return planned;
|
|
3193
|
+
}
|
|
3194
|
+
|
|
3195
|
+
/** Sum member usage records for the lead card's team line. */
|
|
3196
|
+
function teamUsageOf(entries) {
|
|
3197
|
+
const list = Array.isArray(entries) ? entries : [];
|
|
3198
|
+
let tokens;
|
|
3199
|
+
let elapsedMs;
|
|
3200
|
+
for (const entry of list) {
|
|
3201
|
+
if (entry === undefined || entry === null) continue;
|
|
3202
|
+
if (typeof entry.tokens === 'number' && Number.isFinite(entry.tokens)) tokens = (tokens ?? 0) + entry.tokens;
|
|
3203
|
+
if (typeof entry.elapsedMs === 'number' && Number.isFinite(entry.elapsedMs)) elapsedMs = (elapsedMs ?? 0) + entry.elapsedMs;
|
|
3204
|
+
}
|
|
3205
|
+
return { tokens, elapsedMs };
|
|
3206
|
+
}
|
|
3207
|
+
|
|
3029
3208
|
// One card of the org chart: avatar + name (+ lead badge / current tag) on
|
|
3030
3209
|
// line one; status dot + state text (+ live dots / model) on line two.
|
|
3031
3210
|
// State text carries a theme-aware class so 11px copy clears 3:1 in both
|
|
3032
3211
|
// themes; the badge keeps lead's formula with a light-theme dark amber.
|
|
3033
|
-
function MemberCard({ member, running, model, isCurrent, lead, statusLabel, t, size, onOpen, children }) {
|
|
3212
|
+
function MemberCard({ member, running, model, isCurrent, lead, statusLabel, t, size, onOpen, usage, teamUsage, children }) {
|
|
3034
3213
|
const tt = typeof t === 'function' ? t : (key) => key;
|
|
3035
3214
|
const status = member.phase === 'active' ? (running ? 'running' : 'inactive') : member.phase;
|
|
3036
3215
|
// Availability mirrors the native roster row (agent-team TeamMemberRow):
|
|
@@ -3042,11 +3221,22 @@ window.__ModuleLoader__.load({
|
|
|
3042
3221
|
&& member.phase !== 'failed'
|
|
3043
3222
|
&& member.phase !== 'provisioning'
|
|
3044
3223
|
&& typeof member.id === 'string' && member.id !== '';
|
|
3045
|
-
|
|
3046
|
-
|
|
3224
|
+
// The whole card is a click target now, not just the who row: one click
|
|
3225
|
+
// anywhere on a member card enters that member's child session. `canOpen`
|
|
3226
|
+
// keeps its exemptions untouched; the who row and the card's own task
|
|
3227
|
+
// lines stop propagation so a nested target opens only once.
|
|
3228
|
+
return h('div', {
|
|
3229
|
+
className: (lead ? 'cabinet-card cabinet-card-lead' : 'cabinet-card') + (canOpen ? ' cabinet-card-clickable' : ''),
|
|
3230
|
+
onClick: canOpen ? () => onOpen(member) : undefined,
|
|
3231
|
+
style: { position: 'relative', zIndex: 1, cursor: canOpen ? 'pointer' : undefined }
|
|
3232
|
+
}, [
|
|
3233
|
+
h(canOpen ? 'button' : 'div', {
|
|
3234
|
+
type: canOpen ? 'button' : undefined,
|
|
3047
3235
|
key: 'who',
|
|
3048
|
-
|
|
3049
|
-
|
|
3236
|
+
// Same opener as the card, so the who row stops the click instead
|
|
3237
|
+
// of letting the card forward it a second time.
|
|
3238
|
+
onClick: canOpen ? (event) => { stopPropagation(event); return onOpen(member); } : undefined,
|
|
3239
|
+
style: { font: 'inherit', textAlign: 'left', padding: 0, border: 0, background: 'transparent', display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minWidth: 0, cursor: canOpen ? 'pointer' : undefined }
|
|
3050
3240
|
}, [
|
|
3051
3241
|
h(Avatar, { key: 'avatar', name: member.name, size: size || 22, live: status === 'running' }),
|
|
3052
3242
|
h('span', {
|
|
@@ -3078,6 +3268,40 @@ window.__ModuleLoader__.load({
|
|
|
3078
3268
|
style: { fontSize: 11, color: '#f25a5a', width: '100%', wordBreak: 'break-all' }
|
|
3079
3269
|
}, member.error) : null
|
|
3080
3270
|
]),
|
|
3271
|
+
// Usage line: token total, elapsed time and the context-pressure bar,
|
|
3272
|
+
// all from DSH session projections. A missing projection prints the em
|
|
3273
|
+
// dash instead of collapsing the card, and the lead card adds the team
|
|
3274
|
+
// total summed over its members.
|
|
3275
|
+
usage ? h('div', {
|
|
3276
|
+
key: 'usage',
|
|
3277
|
+
className: 'cabinet-usage',
|
|
3278
|
+
style: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minWidth: 0, fontSize: 10, color: INK2 }
|
|
3279
|
+
}, [
|
|
3280
|
+
h('span', { key: 'tok', style: { flex: 'none' }, title: tt('usage.tokens') },
|
|
3281
|
+
tt('usage.tokens') + ' ' + (formatTokenCount(usage.tokens) ?? tt('usage.none'))),
|
|
3282
|
+
h('span', { key: 'el', style: { flex: 'none' }, title: tt('usage.elapsed') },
|
|
3283
|
+
tt('usage.elapsed') + ' ' + (formatElapsed(usage.elapsedMs) ?? tt('usage.none'))),
|
|
3284
|
+
usage.context ? h('span', {
|
|
3285
|
+
key: 'ctx',
|
|
3286
|
+
title: usage.context.percent !== undefined ? tt('usage.context') + ' ' + usage.context.percent + '%' : tt('usage.context'),
|
|
3287
|
+
style: { display: 'inline-flex', alignItems: 'center', gap: 4, flex: 'none' }
|
|
3288
|
+
}, [
|
|
3289
|
+
usage.context.percent !== undefined ? h('span', {
|
|
3290
|
+
key: 'bar',
|
|
3291
|
+
className: 'cabinet-ctxbar',
|
|
3292
|
+
'aria-hidden': 'true'
|
|
3293
|
+
}, usage.context.segments.map((segment) => h('i', {
|
|
3294
|
+
key: segment.key,
|
|
3295
|
+
className: 'cabinet-ctxbar-' + segment.key,
|
|
3296
|
+
style: { width: Math.max(0, Math.min(100, segment.ratio * 100)) + '%' }
|
|
3297
|
+
}))) : null,
|
|
3298
|
+
h('span', { key: 'pct' }, usage.context.percent !== undefined
|
|
3299
|
+
? usage.context.percent + '%'
|
|
3300
|
+
: (formatTokenCount(usage.context.projectedTokens) ?? tt('usage.none')))
|
|
3301
|
+
]) : null,
|
|
3302
|
+
teamUsage ? h('span', { key: 'team', style: { flex: 'none' }, title: tt('usage.team') },
|
|
3303
|
+
tt('usage.team') + ' ' + (formatTokenCount(teamUsage.tokens) ?? tt('usage.none'))) : null
|
|
3304
|
+
]) : null,
|
|
3081
3305
|
// the member's own task list hangs inside the card (品字形 layout)
|
|
3082
3306
|
children
|
|
3083
3307
|
]);
|
|
@@ -3088,11 +3312,12 @@ window.__ModuleLoader__.load({
|
|
|
3088
3312
|
const status = TASK_COLOR[task.status] ? task.status : 'pending';
|
|
3089
3313
|
const color = TASK_COLOR[status];
|
|
3090
3314
|
const blockers = Array.isArray(task.blockedBy) ? [...new Set(task.blockedBy.filter((id) => typeof id === 'string' && id !== task.id))] : [];
|
|
3091
|
-
// The subject
|
|
3092
|
-
// us a resolved opener: lead-owned,
|
|
3093
|
-
// inert-owner tasks arrive with
|
|
3094
|
-
// look (no onClick, no pointer
|
|
3315
|
+
// The subject, the whole row and the Owner tag are all affordances, but
|
|
3316
|
+
// only when the panel handed us a resolved opener: lead-owned,
|
|
3317
|
+
// unassigned, foreign-owner and inert-owner tasks arrive with
|
|
3318
|
+
// onOpenOwner === null and keep the plain look (no onClick, no pointer).
|
|
3095
3319
|
const openTask = typeof onOpenOwner === 'function';
|
|
3320
|
+
const openOnce = openTask ? (event) => { stopPropagation(event); return onOpenOwner(task); } : undefined;
|
|
3096
3321
|
const parts = [
|
|
3097
3322
|
h('span', {
|
|
3098
3323
|
key: 'dot',
|
|
@@ -3100,17 +3325,26 @@ window.__ModuleLoader__.load({
|
|
|
3100
3325
|
style: { width: 8, height: 8, flex: 'none', borderRadius: '50%', background: color }
|
|
3101
3326
|
}),
|
|
3102
3327
|
h('span', { key: 'st', className: 'cabinet-task-' + status, style: { fontSize: 11, flex: 'none' } }, taskLabel(status)),
|
|
3103
|
-
h('span', {
|
|
3328
|
+
h(openTask ? 'button' : 'span', {
|
|
3329
|
+
type: openTask ? 'button' : undefined,
|
|
3104
3330
|
key: 'subj',
|
|
3105
|
-
style: { fontSize: 12.5, color: INK, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: openTask ? 'pointer' : undefined },
|
|
3331
|
+
style: { font: 'inherit', textAlign: 'left', padding: 0, border: 0, background: 'transparent', fontSize: 12.5, color: INK, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: openTask ? 'pointer' : undefined },
|
|
3106
3332
|
title: task.subject,
|
|
3107
|
-
onClick:
|
|
3333
|
+
onClick: openOnce
|
|
3108
3334
|
}, task.subject)
|
|
3109
3335
|
];
|
|
3110
3336
|
if (!task.ownerName) {
|
|
3111
3337
|
parts.push(h(Tag, { key: 'own', background: 'rgba(127,127,127,.18)', color: INK2 }, t('task.unassigned')));
|
|
3112
3338
|
} else {
|
|
3113
|
-
|
|
3339
|
+
// The Owner tag opens the same owner session and stops the click, so
|
|
3340
|
+
// the enclosing row does not forward the same navigation again.
|
|
3341
|
+
parts.push(h(Tag, {
|
|
3342
|
+
key: 'owner',
|
|
3343
|
+
title: memberLabel(task.ownerName),
|
|
3344
|
+
background: 'rgba(127,127,127,.16)',
|
|
3345
|
+
color: INK2,
|
|
3346
|
+
onClick: openOnce
|
|
3347
|
+
}, 'Owner: ' + memberLabel(task.ownerName)));
|
|
3114
3348
|
}
|
|
3115
3349
|
parts.push(h('span', {
|
|
3116
3350
|
key: 'id',
|
|
@@ -3128,7 +3362,9 @@ window.__ModuleLoader__.load({
|
|
|
3128
3362
|
h('button', {
|
|
3129
3363
|
key: 'lb',
|
|
3130
3364
|
type: 'button',
|
|
3131
|
-
|
|
3365
|
+
// Toggling the blocker list is not navigation: stop the click so
|
|
3366
|
+
// the row's opener does not fire on the same event.
|
|
3367
|
+
onClick: (event) => { stopPropagation(event); setOpenBlockers((value) => !value); },
|
|
3132
3368
|
style: { fontSize: 10, lineHeight: '14px', height: 16, padding: '0 6px', borderRadius: 999, cursor: 'pointer', color: INK2, background: 'transparent', border: '1px solid ' + CARD_BORDER, fontFamily: 'inherit' }
|
|
3133
3369
|
}, (openBlockers ? '▾ ' : '▸ ') + t('task.waits') + ' ' + blockers.length),
|
|
3134
3370
|
...(openBlockers ? blockers.map((id) => {
|
|
@@ -3143,10 +3379,18 @@ window.__ModuleLoader__.load({
|
|
|
3143
3379
|
}
|
|
3144
3380
|
// in_progress tasks pulse only while their owner is actually running.
|
|
3145
3381
|
// data-cabinet-task anchors this row for the dependency-edge overlay.
|
|
3382
|
+
// The whole row is a click target when an opener resolved; its onClick
|
|
3383
|
+
// also stops the click so the member card that contains this row does
|
|
3384
|
+
// not open the member session as well.
|
|
3146
3385
|
return h(Row, {
|
|
3147
3386
|
tickTop: 12,
|
|
3148
3387
|
'data-cabinet-task': task.id,
|
|
3149
|
-
|
|
3388
|
+
onClick: openOnce,
|
|
3389
|
+
className: [
|
|
3390
|
+
ownerRunning && status === 'in_progress' ? 'cabinet-task-live' : '',
|
|
3391
|
+
openTask ? 'cabinet-clickable' : ''
|
|
3392
|
+
].filter(Boolean).join(' ') || undefined,
|
|
3393
|
+
style: { cursor: openTask ? 'pointer' : undefined }
|
|
3150
3394
|
}, children);
|
|
3151
3395
|
}
|
|
3152
3396
|
|
|
@@ -3513,7 +3757,7 @@ window.__ModuleLoader__.load({
|
|
|
3513
3757
|
// row subtree, so that height change is caught by the MutationObserver
|
|
3514
3758
|
// below instead of this effect.
|
|
3515
3759
|
React.useLayoutEffect(() => { measureLinks(); });
|
|
3516
|
-
const hasTeam = team
|
|
3760
|
+
const hasTeam = Boolean(team);
|
|
3517
3761
|
React.useEffect(() => {
|
|
3518
3762
|
const tree = treeRef.current;
|
|
3519
3763
|
if (!tree || typeof window === 'undefined') return undefined;
|
|
@@ -3617,6 +3861,64 @@ window.__ModuleLoader__.load({
|
|
|
3617
3861
|
h('span', { key: 'c' }, tt('task.completed') + ' ' + counts.completed)
|
|
3618
3862
|
]));
|
|
3619
3863
|
|
|
3864
|
+
const lead = members.find((member) => member.role === 'lead');
|
|
3865
|
+
const leadShown = lead ?? { id: sessionId, name: 'lead', role: 'lead', phase: 'active' };
|
|
3866
|
+
const mates = members.filter((member) => member.role !== 'lead');
|
|
3867
|
+
// Usage hooks stay above the empty-team return. Ensure initial/settled
|
|
3868
|
+
// projections, retry live sessions at a bounded cadence, and consume
|
|
3869
|
+
// host updates via useSessions. Ready host snapshots may remain cached.
|
|
3870
|
+
const [usageTick, setUsageTick] = React.useState(0);
|
|
3871
|
+
const usageNow = Date.now();
|
|
3872
|
+
const usageOfMember = (member) => (member !== undefined && member !== null && typeof member.id === 'string' && member.id !== '')
|
|
3873
|
+
? usageFor(projections !== undefined && projections !== null ? projections[member.id]?.values : undefined, usageNow)
|
|
3874
|
+
: null;
|
|
3875
|
+
const leadUsage = usageOfMember(leadShown);
|
|
3876
|
+
const mateUsages = mates.map((member) => usageOfMember(member));
|
|
3877
|
+
const runningUsageIds = (team ? [leadShown, ...mates] : [])
|
|
3878
|
+
.map((member) => (member !== undefined && member !== null && typeof member.id === 'string' && member.id !== '' && runningOf(member.id)) ? member.id : undefined)
|
|
3879
|
+
.filter((id) => typeof id === 'string' && id !== '');
|
|
3880
|
+
const runningUsageKey = JSON.stringify(runningUsageIds);
|
|
3881
|
+
const allUsageIds = team ? [leadShown, ...mates].map(m => m.id).filter(id => typeof id === 'string' && id) : [];
|
|
3882
|
+
const allUsageKey = JSON.stringify(allUsageIds);
|
|
3883
|
+
const usageRequestState = React.useRef(new Map());
|
|
3884
|
+
const [usageService, setUsageService] = React.useState(cabinetSessions);
|
|
3885
|
+
React.useEffect(() => {
|
|
3886
|
+
const notify = () => setUsageService(cabinetSessions);
|
|
3887
|
+
cabinetSessionsListeners.add(notify); notify();
|
|
3888
|
+
return () => cabinetSessionsListeners.delete(notify);
|
|
3889
|
+
}, []);
|
|
3890
|
+
React.useEffect(() => {
|
|
3891
|
+
const state = new Map();
|
|
3892
|
+
usageRequestState.current = state;
|
|
3893
|
+
return () => { state.disposed = true; };
|
|
3894
|
+
}, [usageService, leadSessionId, hasTeam]);
|
|
3895
|
+
React.useEffect(() => {
|
|
3896
|
+
if (!usageService || typeof usageService.refreshProjections !== 'function') return;
|
|
3897
|
+
const states = usageRequestState.current;
|
|
3898
|
+
const running = new Set(runningUsageIds);
|
|
3899
|
+
for (const id of states.keys()) if (!allUsageIds.includes(id)) states.delete(id);
|
|
3900
|
+
for (const id of allUsageIds) {
|
|
3901
|
+
const live = running.has(id), previous = states.get(id);
|
|
3902
|
+
const changed = previous && previous.live !== live;
|
|
3903
|
+
const due = !previous || changed || (live && Date.now() - previous.at >= PROJECTION_REFRESH_MS);
|
|
3904
|
+
if (previous?.pending) { if (changed) previous.retry = true; continue; }
|
|
3905
|
+
if (!due) continue;
|
|
3906
|
+
const record = {live, at: Date.now(), pending: true};
|
|
3907
|
+
states.set(id, record);
|
|
3908
|
+
// Public refresh is ensure/retry: ready snapshots may be cached by
|
|
3909
|
+
// the host. Live updates arrive through useSessions, not forced RPCs.
|
|
3910
|
+
try { Promise.resolve(usageService.refreshProjections(id)).catch(() => {}).finally(() => { record.pending = false; if (record.retry && !states.disposed) { states.delete(id); setUsageTick(tick => tick + 1); } }); }
|
|
3911
|
+
catch (_) { record.pending = false; }
|
|
3912
|
+
}
|
|
3913
|
+
}, [usageService, leadSessionId, hasTeam, allUsageKey, runningUsageKey, usageTick]);
|
|
3914
|
+
// While anybody runs, re-render on the same cadence so the elapsed time and
|
|
3915
|
+
// the fresh projections reach the card. Nothing running → no timer at all.
|
|
3916
|
+
React.useEffect(() => {
|
|
3917
|
+
if (!usageService || runningUsageIds.length === 0) return undefined;
|
|
3918
|
+
const timer = setInterval(() => setUsageTick((tick) => tick + 1), PROJECTION_REFRESH_MS);
|
|
3919
|
+
return () => { clearInterval(timer); };
|
|
3920
|
+
}, [usageService, runningUsageKey]);
|
|
3921
|
+
|
|
3620
3922
|
if (!team) {
|
|
3621
3923
|
body.push(h('div', {
|
|
3622
3924
|
key: 'empty',
|
|
@@ -3631,9 +3933,6 @@ window.__ModuleLoader__.load({
|
|
|
3631
3933
|
return h('div', { ref: panelRef, style: PANEL }, body);
|
|
3632
3934
|
}
|
|
3633
3935
|
|
|
3634
|
-
const lead = members.find((member) => member.role === 'lead');
|
|
3635
|
-
const leadShown = lead ?? { id: sessionId, name: 'lead', role: 'lead', phase: 'active' };
|
|
3636
|
-
const mates = members.filter((member) => member.role !== 'lead');
|
|
3637
3936
|
const isLeadTask = (task) => task.ownerName === 'lead' || (lead !== undefined && task.ownerName === lead.name);
|
|
3638
3937
|
const unassigned = tasks.filter((task) => !task.ownerName);
|
|
3639
3938
|
const leadOwn = tasks.filter((task) => task.ownerName !== undefined && isLeadTask(task));
|
|
@@ -3679,7 +3978,9 @@ window.__ModuleLoader__.load({
|
|
|
3679
3978
|
size: 26,
|
|
3680
3979
|
statusLabel,
|
|
3681
3980
|
t: tt,
|
|
3682
|
-
onOpen: openMemberSession
|
|
3981
|
+
onOpen: openMemberSession,
|
|
3982
|
+
usage: leadUsage,
|
|
3983
|
+
teamUsage: teamUsageOf(mateUsages)
|
|
3683
3984
|
});
|
|
3684
3985
|
|
|
3685
3986
|
// Cells: every minister first, then 未分派 / 首辅自办 / 不在册 as
|
|
@@ -3738,6 +4039,7 @@ window.__ModuleLoader__.load({
|
|
|
3738
4039
|
statusLabel,
|
|
3739
4040
|
t: tt,
|
|
3740
4041
|
onOpen: openMemberSession,
|
|
4042
|
+
usage: usageOfMember(member),
|
|
3741
4043
|
// tasks live inside the card, elbow-connected by RailList
|
|
3742
4044
|
children: own.length > 0
|
|
3743
4045
|
? h(RailList, { key: 'tasks', style: { marginTop: 4 } }, own.map((task) => h(TaskLine, {
|
|
@@ -4336,6 +4638,11 @@ window.__ModuleLoader__.load({
|
|
|
4336
4638
|
'task.completed': '已完成',
|
|
4337
4639
|
'task.deleted': '已删除',
|
|
4338
4640
|
'task.unassigned': '未分派',
|
|
4641
|
+
'usage.tokens': 'token',
|
|
4642
|
+
'usage.elapsed': '耗时',
|
|
4643
|
+
'usage.context': '上下文',
|
|
4644
|
+
'usage.team': '团队',
|
|
4645
|
+
'usage.none': '—',
|
|
4339
4646
|
'task.leadOwn': '首辅自办',
|
|
4340
4647
|
'task.waits': '等待',
|
|
4341
4648
|
'task.none': '暂无任务',
|
|
@@ -4424,6 +4731,11 @@ window.__ModuleLoader__.load({
|
|
|
4424
4731
|
'task.completed': 'done',
|
|
4425
4732
|
'task.deleted': 'deleted',
|
|
4426
4733
|
'task.unassigned': 'unassigned',
|
|
4734
|
+
'usage.tokens': 'tokens',
|
|
4735
|
+
'usage.elapsed': 'elapsed',
|
|
4736
|
+
'usage.context': 'context',
|
|
4737
|
+
'usage.team': 'team',
|
|
4738
|
+
'usage.none': '—',
|
|
4427
4739
|
'task.leadOwn': 'lead-owned',
|
|
4428
4740
|
'task.waits': 'blocked by',
|
|
4429
4741
|
'task.none': 'no tasks',
|
|
@@ -4545,6 +4857,19 @@ window.__ModuleLoader__.load({
|
|
|
4545
4857
|
return () => { if (cabinetOpenSession === opener) cabinetOpenSession = null; };
|
|
4546
4858
|
}, 'cabinet-ui: open teammate session');
|
|
4547
4859
|
});
|
|
4860
|
+
// Optional usage channel: the panel shows each member's token total, time
|
|
4861
|
+
// and context pressure from the DSH session projections. Its own guard,
|
|
4862
|
+
// so a host without the sessions service leaves every other channel and
|
|
4863
|
+
// every card exactly as it was (cards then print their em dash).
|
|
4864
|
+
ctx.inject(['sessions'], (scope) => {
|
|
4865
|
+
const sessions = scope.sessions;
|
|
4866
|
+
if (!sessions || typeof sessions.refreshProjections !== 'function') return;
|
|
4867
|
+
scope.effect(() => {
|
|
4868
|
+
cabinetSessions = sessions;
|
|
4869
|
+
for (const notify of cabinetSessionsListeners) notify();
|
|
4870
|
+
return () => { if (cabinetSessions === sessions) { cabinetSessions = null; for (const notify of cabinetSessionsListeners) notify(); } };
|
|
4871
|
+
}, 'cabinet-ui: session projections');
|
|
4872
|
+
});
|
|
4548
4873
|
// Optional install channel for the memory-plugin card: its own guard, so
|
|
4549
4874
|
// a host without the plugin manager leaves the model-catalog remote and
|
|
4550
4875
|
// every other channel exactly as it was.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Member usage validation
|
|
2
|
+
|
|
3
|
+
The panel displays host projection snapshots. It does not run a model or calculate prices.
|
|
4
|
+
|
|
5
|
+
The inspected official DSH 0.2.2-rc.1 package exposes flat `tokenUsage` counters and flat `contextBreakdown` fields in `dsh-token-meter/lib/types/projection.d.ts`; the reader also accepts wrapped `totals` / `breakdown` records. Four provider token buckets are disjoint; reasoning is already included in output. Breakdown segments are heuristic composition, not provider usage. Context pressure and capacity are last-known observations and need not describe the same request.
|
|
6
|
+
|
|
7
|
+
`ISessions.refreshProjections` is a public ensure/retry operation. In the inspected `dsh-api-session-controller/lib/types/client/sessions/manager.js`, a ready projection load returns immediately. Calling it is not a forced new RPC and cannot guarantee fresh final numbers. The panel ensures every member initially, attempts another read on running/stopped transitions, retries while running at five-second intervals, and consumes projection changes from `useSessions`. No timer remains while all members are stopped or the service is absent. Missing fields display a dash; values remain snapshots, not guaranteed billing totals.
|
|
8
|
+
|
|
9
|
+
## Isolated browser fixture
|
|
10
|
+
|
|
11
|
+
`scripts/test-panel-browser.mjs` bundles production code with real React DOM. Set `DSH_BROWSER_TEST_ROOT` to an isolated npm installation containing `react`, `react-dom` and `esbuild`; open the printed loopback URL and run lifecycle checks. It uses synthetic team/projection/service records and never connects to a running DSH process or user profile.
|
|
12
|
+
|
|
13
|
+
Chrome validation on 2026-11-09 passed 11 lifecycle assertions: empty team, team arrival, late service plus idle initial reads, running transition, stopped read/timer cleanup, team disappearance, no nested buttons, one subject navigation, one row navigation, blocker toggle without navigation, and unmount cleanup. Native Enter on the task subject and Space on the member button each opened once; Owner Enter opened once and blocker Space did not navigate. At a 340px panel width, scrollWidth equalled clientWidth. This is real React/browser validation with service fixtures, not a real-team or model end-to-end test.
|
|
14
|
+
|
|
15
|
+
No user DSH process was restarted. Only the fixture's own temporary server was stopped after testing.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-cabinet-mode",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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",
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
"LICENSE",
|
|
51
51
|
"CHANGELOG.md",
|
|
52
52
|
"docs/cross-platform.md",
|
|
53
|
+
"docs/member-usage-validation.md",
|
|
53
54
|
"docs/images",
|
|
54
55
|
"scripts",
|
|
55
56
|
"src"
|
package/scripts/test-client.mjs
CHANGED
|
@@ -22,11 +22,37 @@ const React = {
|
|
|
22
22
|
useRef: () => ({ current: null }),
|
|
23
23
|
useState: (initial) => [initial, () => {}],
|
|
24
24
|
useCallback: (callback) => callback,
|
|
25
|
-
useLayoutEffect: () => {}, useEffect: () => {},
|
|
25
|
+
useLayoutEffect: () => {}, useEffect: (fn) => { recordedEffects.push(fn); },
|
|
26
26
|
};
|
|
27
|
-
|
|
27
|
+
// The panel decides whether to mount its usage ticker; the spy observes the real
|
|
28
|
+
// setInterval/clearInterval call the component makes (not a proxy assertion).
|
|
29
|
+
const recordedEffects = [];
|
|
30
|
+
const intervalSpy = { mounted: 0, cleared: 0, delays: [], lastTimer: null };
|
|
31
|
+
// A controllable clock: the 5s projection throttle is time-based, so the chain
|
|
32
|
+
// test advances this instead of sleeping.
|
|
33
|
+
const clockState = { now: 1000000 };
|
|
34
|
+
class RealmDate extends Date {
|
|
35
|
+
constructor(...args) { super(...(args.length ? args : [clockState.now])); }
|
|
36
|
+
static now() { return clockState.now; }
|
|
37
|
+
}
|
|
38
|
+
// A simulated re-render needs React's real useRef semantics (same ref across
|
|
39
|
+
// renders of one component). Opt-in only: while `persistentRefs` is null every
|
|
40
|
+
// render keeps the fresh-ref default, so no other harness changes behaviour.
|
|
41
|
+
let persistentRefs = null;
|
|
42
|
+
const resetHookCursor = () => { if (persistentRefs !== null) persistentRefs.cursor = 0; };
|
|
43
|
+
React.useRef = (initial) => {
|
|
44
|
+
if (persistentRefs === null) return { current: initial };
|
|
45
|
+
const index = persistentRefs.cursor++;
|
|
46
|
+
if (!(index in persistentRefs.slots)) persistentRefs.slots[index] = { current: initial };
|
|
47
|
+
return persistentRefs.slots[index];
|
|
48
|
+
};
|
|
49
|
+
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, formatTokenCount, formatElapsed, tokenTotalOf, usageFor, planProjectionRequests, teamUsageOf };';
|
|
28
50
|
runInNewContext(source.replace(exportPoint, exportList), {
|
|
29
|
-
setTimeout: (fn, ms) => setTimeout(fn, ms === 120000 ? 20 : ms), clearTimeout,
|
|
51
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms === 120000 ? 20 : ms), clearTimeout,
|
|
52
|
+
Date: RealmDate,
|
|
53
|
+
setInterval: (fn, ms) => { intervalSpy.mounted += 1; intervalSpy.delays.push(ms); intervalSpy.lastTimer = { fn, ms }; return intervalSpy.lastTimer; },
|
|
54
|
+
clearInterval: () => { intervalSpy.cleared += 1; },
|
|
55
|
+
localStorage: pluginSpecStorage, window: { __ModuleLoader__: { load: ({ factory }) => {
|
|
30
56
|
client = factory((name) => { assert.equal(name, 'react'); return React; });
|
|
31
57
|
} } },
|
|
32
58
|
});
|
|
@@ -379,7 +405,226 @@ assert.equal(whoNodes.length, clickTeam.members.length, 'one who-row per member'
|
|
|
379
405
|
assert.deepEqual(whoNodes.map((node) => typeof node.props.onClick), ['undefined', 'function', 'undefined', 'undefined'],
|
|
380
406
|
'lead(self)/failed/provisioning cards stay inert, the active mate binds');
|
|
381
407
|
|
|
408
|
+
// --- click-through: whole card, whole task row and Owner tag are targets ---
|
|
409
|
+
// One click must open exactly one session. Every nested target stops the event,
|
|
410
|
+
// so the enclosing handler (row inside card, subject/Owner inside row) cannot
|
|
411
|
+
// forward the same click a second time.
|
|
412
|
+
const eventLog = [];
|
|
413
|
+
const fakeEvent = () => ({ stopped: false, stopPropagation() { this.stopped = true; eventLog.push('stopped'); } });
|
|
414
|
+
const cardOf = (member, extra) => elements(client.MemberCard({
|
|
415
|
+
member, statusLabel: (status) => status, ...extra,
|
|
416
|
+
})).find((node) => typeof node.props?.className === 'string' && node.props.className.split(' ').includes('cabinet-card'));
|
|
417
|
+
const opens = [];
|
|
418
|
+
const openRecorder = (target) => { opens.push(target); return true; };
|
|
419
|
+
|
|
420
|
+
// 1) the task row itself binds, shows the pointer, and stops the click
|
|
421
|
+
const rowLine = client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: openRecorder });
|
|
422
|
+
const rowNode = elements(rowLine).find((node) => node.props?.['data-cabinet-task'] === tasks[0].id);
|
|
423
|
+
assert.equal(typeof rowNode.props.onClick, 'function', 'the whole task row binds a resolved opener');
|
|
424
|
+
assert.equal(rowNode.props.style.cursor, 'pointer', 'the whole task row shows the pointer cursor');
|
|
425
|
+
assert.ok(rowNode.props.className.split(' ').includes('cabinet-clickable'), 'the clickable row carries the hover class');
|
|
426
|
+
const rowEvent = fakeEvent();
|
|
427
|
+
assert.equal(rowNode.props.onClick(rowEvent), true, 'the row forwards to the opener');
|
|
428
|
+
assert.deepEqual(opens, [tasks[0]], 'one click on the row opens once');
|
|
429
|
+
assert.equal(rowEvent.stopped, true, 'the row stops the click so the enclosing card cannot also open');
|
|
430
|
+
|
|
431
|
+
// 2) the Owner tag binds and stops the click instead of double-opening
|
|
432
|
+
// Tag drops the element key when it renders its span, so locate the Owner tag by
|
|
433
|
+
// its label text (same probe the identity test above uses).
|
|
434
|
+
const ownerTag = (line) => elements(line).find((node) => ['span', 'button'].includes(node.type)
|
|
435
|
+
&& node.children.flat().some((text) => typeof text === 'string' && text.startsWith('Owner: ')));
|
|
436
|
+
const boundOwner = ownerTag(client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: openRecorder }));
|
|
437
|
+
assert.equal(boundOwner.type, 'button', 'Owner is a native keyboard button');
|
|
438
|
+
assert.equal(boundOwner.props.type, 'button');
|
|
439
|
+
assert.equal(typeof boundOwner.props.onClick, 'function', 'the Owner tag binds a resolved opener');
|
|
440
|
+
assert.equal(boundOwner.props.style.cursor, 'pointer', 'the Owner tag shows the pointer cursor');
|
|
441
|
+
opens.length = 0;
|
|
442
|
+
const ownerEvent = fakeEvent();
|
|
443
|
+
assert.equal(boundOwner.props.onClick(ownerEvent), true, 'the Owner tag forwards to the opener');
|
|
444
|
+
assert.deepEqual(opens, [tasks[0]], 'one click on the Owner tag opens once');
|
|
445
|
+
assert.equal(ownerEvent.stopped, true, 'the Owner tag stops the click so the row cannot also open');
|
|
446
|
+
|
|
447
|
+
// 3) the subject keeps working and also stops the click
|
|
448
|
+
const subjectNode = elements(client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: openRecorder }))
|
|
449
|
+
.find((node) => node.props?.key === 'subj');
|
|
450
|
+
opens.length = 0;
|
|
451
|
+
assert.equal(subjectNode.type, 'button', 'Subject is a native keyboard button');
|
|
452
|
+
const subjectEvent = fakeEvent();
|
|
453
|
+
subjectNode.props.onClick(subjectEvent);
|
|
454
|
+
assert.deepEqual(opens, [tasks[0]], 'the subject still opens once with an event argument');
|
|
455
|
+
assert.equal(subjectEvent.stopped, true, 'the subject stops the click so the row cannot also open');
|
|
456
|
+
|
|
457
|
+
// 4) a task row inside a member card: card binds, row stops, card handler is not
|
|
458
|
+
// reachable from the row click (React propagation ends at stopPropagation)
|
|
459
|
+
const hybridCard = cardOf({ id: 'm-works', name: 'works', phase: 'active' },
|
|
460
|
+
{ isCurrent: false, onOpen: openRecorder, children: [client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: openRecorder })] });
|
|
461
|
+
assert.equal(typeof hybridCard.props.onClick, 'function', 'the card around a task row still binds');
|
|
462
|
+
const hybridRow = elements(hybridCard).find((node) => node.props?.['data-cabinet-task'] === tasks[0].id);
|
|
463
|
+
assert.equal(typeof hybridRow.props.onClick, 'function', 'the nested task row binds independently');
|
|
464
|
+
opens.length = 0;
|
|
465
|
+
const nestedEvent = fakeEvent();
|
|
466
|
+
hybridRow.props.onClick(nestedEvent);
|
|
467
|
+
assert.equal(nestedEvent.stopped, true, 'the nested row stops before the card handler can run');
|
|
468
|
+
assert.deepEqual(opens, [tasks[0]], 'clicking a task inside a card opens the task target once, never the member');
|
|
469
|
+
|
|
470
|
+
// Nested member identity is a native button and prevents its card from firing.
|
|
471
|
+
const who = elements(hybridCard).find(node => node.props?.key === 'who');
|
|
472
|
+
assert.equal(who.type, 'button');
|
|
473
|
+
opens.length = 0;
|
|
474
|
+
const whoEvent = fakeEvent();
|
|
475
|
+
who.props.onClick(whoEvent);
|
|
476
|
+
if (!whoEvent.stopped) hybridCard.props.onClick(whoEvent);
|
|
477
|
+
assert.equal(opens.length, 1);
|
|
478
|
+
|
|
479
|
+
// 5) inert members stay inert on the CARD too (self / failed / provisioning / no id / no channel)
|
|
480
|
+
for (const [label, member, extra] of [
|
|
481
|
+
['self', { id: 'lead-session', name: 'lead', phase: 'active' }, { isCurrent: true, onOpen: openRecorder }],
|
|
482
|
+
['failed', { id: 'm-dali', name: 'dali', phase: 'failed' }, { isCurrent: false, onOpen: openRecorder }],
|
|
483
|
+
['provisioning', { id: 'm-yushi', name: 'yushi', phase: 'provisioning' }, { isCurrent: false, onOpen: openRecorder }],
|
|
484
|
+
['no id', { name: 'works', phase: 'active' }, { isCurrent: false, onOpen: openRecorder }],
|
|
485
|
+
['no channel', { id: 'm-works', name: 'works', phase: 'active' }, { isCurrent: false }],
|
|
486
|
+
]) {
|
|
487
|
+
const card = cardOf(member, extra);
|
|
488
|
+
assert.equal(card.props.onClick, undefined, `${label}: the whole card stays unbound`);
|
|
489
|
+
assert.equal(card.props.style.cursor, undefined, `${label}: the whole card keeps the plain cursor`);
|
|
490
|
+
assert.ok(!card.props.className.includes('cabinet-card-clickable'), `${label}: no hover affordance on an inert card`);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// 6) tasks without a resolved opener stay plain on the row and the Owner tag
|
|
494
|
+
for (const task of [
|
|
495
|
+
{ id: 'k-lead', subject: 'lead work', ownerName: 'lead', status: 'pending' },
|
|
496
|
+
{ id: 'k-none', subject: 'nobody', status: 'pending' },
|
|
497
|
+
]) {
|
|
498
|
+
const line = client.TaskLine({ task, t: (key) => key, taskLabel: (status) => status, onOpenOwner: null });
|
|
499
|
+
const row = elements(line).find((node) => node.props?.['data-cabinet-task'] === task.id);
|
|
500
|
+
assert.equal(row.props.onClick, undefined, `${task.id}: no row click binding without an opener`);
|
|
501
|
+
assert.equal(row.props.style.cursor, undefined, `${task.id}: no pointer cursor on the row`);
|
|
502
|
+
assert.ok(!String(row.props.className || '').includes('cabinet-clickable'), `${task.id}: no hover affordance without an opener`);
|
|
503
|
+
if (task.ownerName) {
|
|
504
|
+
const owner = ownerTag(line);
|
|
505
|
+
assert.equal(owner.props.onClick, undefined, `${task.id}: no Owner-tag click binding without an opener`);
|
|
506
|
+
assert.equal(owner.props.style.cursor, undefined, `${task.id}: no pointer cursor on the Owner tag`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// 7) panel level: the whole card of the one openable member is bound, the rest inert
|
|
511
|
+
const memberCardNodes = clickEls.filter((node) => typeof node.props?.className === 'string' && node.props.className.split(' ').includes('cabinet-card'));
|
|
512
|
+
// The panel also paints bucket cards (unassigned / foreign owner) next to the
|
|
513
|
+
// member cards, so count clickable cards instead of assuming one per member.
|
|
514
|
+
const boundCardNodes = memberCardNodes.filter((node) => typeof node.props.onClick === 'function');
|
|
515
|
+
assert.equal(boundCardNodes.length, 1, 'exactly one card in the panel is clickable: the single openable member');
|
|
516
|
+
assert.ok(boundCardNodes[0].props.className.includes('cabinet-card-clickable'), 'the clickable card carries the hover affordance');
|
|
517
|
+
assert.deepEqual(memberCardNodes.filter((node) => node !== boundCardNodes[0]).map((node) => node.props.onClick), memberCardNodes.filter((node) => node !== boundCardNodes[0]).map(() => undefined),
|
|
518
|
+
'every other card — inert member and bucket alike — stays unbound');
|
|
519
|
+
|
|
382
520
|
console.log('PASS: avatars, stale-team warnings, and distinct member/owner/group identities; mocked React, not browser E2E');
|
|
521
|
+
console.log('PASS: click-through targets — whole card, whole task row and Owner tag bind only with a resolved opener, nested clicks stop propagation so one click opens one session, inert members stay inert');
|
|
522
|
+
|
|
523
|
+
// --- member usage: token total, elapsed time, context pressure (projections) ---
|
|
524
|
+
// Projection field names come from the DSH session schema; nothing here invents
|
|
525
|
+
// one. A missing projection must render the em dash, never throw.
|
|
526
|
+
assert.equal(client.formatTokenCount(842), '842', 'sub-thousand tokens stay exact');
|
|
527
|
+
assert.equal(client.formatTokenCount(1500), '1.5K', 'thousands collapse to one decimal');
|
|
528
|
+
assert.equal(client.formatTokenCount(3300000), '3.3M', 'millions collapse to one decimal');
|
|
529
|
+
assert.equal(client.formatTokenCount(undefined), undefined, 'missing total has no string');
|
|
530
|
+
assert.equal(client.formatTokenCount(Number.NaN), undefined, 'non-finite total has no string');
|
|
531
|
+
assert.equal(client.formatElapsed(12000), '12s');
|
|
532
|
+
assert.equal(client.formatElapsed(192000), '3m12s');
|
|
533
|
+
assert.equal(client.formatElapsed(3900000), '1h05m');
|
|
534
|
+
assert.equal(client.formatElapsed(undefined), undefined, 'missing timing has no string');
|
|
535
|
+
|
|
536
|
+
const fullValues = {
|
|
537
|
+
tokenUsage: { uncachedInputTokens: 1000, outputTokens: 2000, cacheReadTokens: 3000000, cacheWriteTokens: 4000 },
|
|
538
|
+
subagentTiming: { settledMs: 5000, active: { since: 100000, through: 180000 } },
|
|
539
|
+
contextPressure: { projectedTokens: 120000, contextWindow: 400000 },
|
|
540
|
+
contextBreakdown: { systemTokens: 2000, toolsTokens: 6000, messageTokens: 2000 },
|
|
541
|
+
};
|
|
542
|
+
const full = client.usageFor(fullValues, 112000);
|
|
543
|
+
assert.equal(full.tokens, 3007000, 'token total sums the four durable buckets');
|
|
544
|
+
assert.equal(full.elapsedMs, 17000, 'a running member adds now − active.since to settledMs');
|
|
545
|
+
assert.equal(full.context.percent, 30, 'context percent is projectedTokens / contextWindow');
|
|
546
|
+
assert.deepEqual(Array.from(full.context.segments, (segment) => segment.key), ['system', 'tools', 'message'], 'segments follow the projection breakdown order');
|
|
547
|
+
assert.deepEqual(Array.from(full.context.segments, (segment) => Math.round(segment.ratio * 100)), [20, 60, 20], 'segments follow the projection breakdown');
|
|
548
|
+
const settledOnly = client.usageFor({ ...fullValues, subagentTiming: { settledMs: 42000 } }, 112000);
|
|
549
|
+
assert.equal(settledOnly.elapsedMs, 42000, 'an inactive member shows settledMs');
|
|
550
|
+
const noWindow = client.usageFor({ contextPressure: { projectedTokens: 120000 }, contextBreakdown: { systemTokens: 1 } }, 0);
|
|
551
|
+
assert.equal(noWindow.context.percent, undefined, 'no contextWindow → no ratio, numbers only');
|
|
552
|
+
assert.deepEqual(noWindow.context.segments.length, 1, 'breakdown still renders without a window');
|
|
553
|
+
const empty = client.usageFor(undefined, 112000);
|
|
554
|
+
assert.equal(empty.tokens, undefined);
|
|
555
|
+
assert.equal(empty.elapsedMs, undefined);
|
|
556
|
+
assert.equal(empty.context, undefined, 'a missing projection yields no context, and no throw');
|
|
557
|
+
assert.equal(client.formatTokenCount(empty.tokens) ?? '—', '—', 'the card prints the em dash for a missing total');
|
|
558
|
+
assert.equal(client.formatElapsed(empty.elapsedMs) ?? '—', '—', 'the card prints the em dash for a missing time');
|
|
559
|
+
|
|
560
|
+
// Throttle is TIME based, not once-per-mount: a running card must keep moving.
|
|
561
|
+
// A live id is skipped inside the 5s window and eligible again once it passes;
|
|
562
|
+
// a member that stopped is simply never passed in (panel filters on running).
|
|
563
|
+
const REQUEST_LOG = new Map([['m-works', 1000], ['m-dali', 2500]]);
|
|
564
|
+
assert.deepEqual(Array.from(client.planProjectionRequests(['m-works', 'm-dali', 'm-yushi', 'm-yushi', '', null], REQUEST_LOG, 3000, 5000)),
|
|
565
|
+
['m-yushi'], 'inside the 5s window a requested id is skipped; unknown ids and duplicates collapse');
|
|
566
|
+
assert.deepEqual(Array.from(client.planProjectionRequests(['m-works', 'm-dali'], REQUEST_LOG, 5999, 5000)), [],
|
|
567
|
+
'just under the window nothing is re-requested — the number is not double-fetched');
|
|
568
|
+
assert.deepEqual(Array.from(client.planProjectionRequests(['m-works', 'm-dali'], REQUEST_LOG, 7500, 5000)), ['m-works', 'm-dali'],
|
|
569
|
+
'past the window both ids are eligible again — a running card refreshes');
|
|
570
|
+
assert.deepEqual(Array.from(client.planProjectionRequests(['m-works'], undefined, 9000, 5000)), ['m-works'],
|
|
571
|
+
'a missing request log still plans the id, never throws');
|
|
572
|
+
|
|
573
|
+
// Team total on the lead card = the sum of its members.
|
|
574
|
+
const teamSum = client.teamUsageOf([{ tokens: 1000, elapsedMs: 60000 }, { tokens: 2000, elapsedMs: 5000 }, undefined, {}]);
|
|
575
|
+
assert.equal(teamSum.tokens, 3000, 'team tokens sum the members');
|
|
576
|
+
assert.equal(teamSum.elapsedMs, 65000, 'team time sums the members');
|
|
577
|
+
const emptyTeam = client.teamUsageOf(undefined);
|
|
578
|
+
assert.equal(emptyTeam.tokens, undefined, 'no members → no team tokens');
|
|
579
|
+
assert.equal(emptyTeam.elapsedMs, undefined, 'no members → no team time');
|
|
580
|
+
|
|
581
|
+
// Card render: a projection paints the usage line, a missing one paints dashes.
|
|
582
|
+
const zhT = (key) => client.zh[key] || key;
|
|
583
|
+
const usageCard = elements(client.MemberCard({
|
|
584
|
+
member: { id: 'm-works', name: 'works', phase: 'active' },
|
|
585
|
+
statusLabel: (status) => status,
|
|
586
|
+
t: zhT,
|
|
587
|
+
usage: full,
|
|
588
|
+
teamUsage: teamSum,
|
|
589
|
+
})).find((node) => node.props?.key === 'usage');
|
|
590
|
+
assert.ok(usageCard, 'the card renders a usage line');
|
|
591
|
+
const usageText = JSON.stringify(usageCard);
|
|
592
|
+
assert.ok(usageText.includes(client.zh['usage.tokens'] + ' 3M'), 'token total is rendered compactly: ' + usageText.slice(0, 160));
|
|
593
|
+
assert.ok(usageText.includes(client.zh['usage.elapsed'] + ' 17s'), 'elapsed time is rendered');
|
|
594
|
+
assert.ok(usageText.includes('30%'), 'context percent is rendered');
|
|
595
|
+
assert.ok(usageText.includes(client.zh['usage.team'] + ' 3K'), 'the lead card shows the team total');
|
|
596
|
+
const bars = elements(usageCard).filter((node) => node.props?.className === 'cabinet-ctxbar-system');
|
|
597
|
+
assert.equal(bars.length, 1, 'the context bar carries one segment per breakdown part');
|
|
598
|
+
const dashCard = elements(client.MemberCard({
|
|
599
|
+
member: { id: 'm-dali', name: 'dali', phase: 'active' },
|
|
600
|
+
statusLabel: (status) => status,
|
|
601
|
+
t: zhT,
|
|
602
|
+
usage: empty,
|
|
603
|
+
})).find((node) => node.props?.key === 'usage');
|
|
604
|
+
const dashText = JSON.stringify(dashCard);
|
|
605
|
+
assert.ok(dashText.includes(client.zh['usage.tokens'] + ' ' + client.zh['usage.none']), 'a missing token projection renders the em dash');
|
|
606
|
+
assert.ok(dashText.includes(client.zh['usage.elapsed'] + ' ' + client.zh['usage.none']), 'a missing timing projection renders the em dash');
|
|
607
|
+
assert.ok(!dashText.includes('cabinet-ctxbar'), 'no context bar without a pressure projection');
|
|
608
|
+
const noUsageCard = elements(client.MemberCard({ member: { name: 'works', phase: 'active' }, statusLabel: (status) => status, t: (key) => key }))
|
|
609
|
+
.filter((node) => node.props?.key === 'usage');
|
|
610
|
+
assert.equal(noUsageCard.length, 0, 'a member without a session id renders no usage line at all');
|
|
611
|
+
|
|
612
|
+
// Panel wiring: the usage line appears for a member whose projection exists.
|
|
613
|
+
const usagePanel = elements(client.CabinetPanel({
|
|
614
|
+
sessionId: 'lead-session',
|
|
615
|
+
useSession: (select) => select({}),
|
|
616
|
+
useSessions: (select) => select({ projectionsBySession: {
|
|
617
|
+
'lead-session': { values: { agentTeam: { members: [{ id: 'm-works', name: 'works', role: 'mate', phase: 'active' }], tasks: [] } } },
|
|
618
|
+
'm-works': { values: { tokenUsage: { outputTokens: 2000 }, subagentTiming: { settledMs: 42000 } } },
|
|
619
|
+
} }),
|
|
620
|
+
useSessionStatus: (select) => select(new Map()),
|
|
621
|
+
t: (key) => client.zh[key] || key,
|
|
622
|
+
}));
|
|
623
|
+
assert.ok(elements(usagePanel).some((node) => node.props?.key === 'usage'), 'the panel hands projections to the member cards');
|
|
624
|
+
|
|
625
|
+
// Stateful lifecycle, initial/settled loads and timer cleanup are exercised
|
|
626
|
+
// with real React DOM by scripts/test-panel-browser.mjs, not this hook double.
|
|
627
|
+
console.log('PASS: member usage formatting, missing data and pure throttle helpers; lifecycle is tested separately with real React DOM');
|
|
383
628
|
console.log('PASS: task dependency edges — data attributes, three states, missing-blocker tolerance, reduced-motion CSS, geometry refresh gate');
|
|
384
629
|
|
|
385
630
|
// IDs are opaque; delimiter-bearing pairs must not collide or inject markup.
|
|
@@ -804,3 +1049,7 @@ console.log('PASS: late initial inventory cannot overwrite a completed operation
|
|
|
804
1049
|
finish({ok:true,value:{application:'applied',version:'0.1.13'}});await tick();
|
|
805
1050
|
const nodes=h.render(b);assert.equal(action(nodes).props.disabled,false);assert.equal(versionOf(nodes),undefined);assert.equal(enabled,0,'old installation completion must not enable after switching');h.unmount();
|
|
806
1051
|
}
|
|
1052
|
+
|
|
1053
|
+
// Both public projection encodings are accepted; malformed counters remain unknown.
|
|
1054
|
+
assert.equal(client.usageFor({tokenUsage:{totals:{outputTokens:42}},contextBreakdown:{breakdown:{systemTokens:1,toolsTokens:2,messageTokens:3}}},0).tokens,42);
|
|
1055
|
+
assert.equal(client.usageFor({tokenUsage:{outputTokens:-1},contextPressure:{contextWindow:Infinity,projectedTokens:-1}},0).tokens,undefined);
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Isolated real-React browser fixture; no DSH process, profile or model access.
|
|
2
|
+
// DSH_BROWSER_TEST_ROOT must contain react, react-dom and esbuild from npm.
|
|
3
|
+
// Run with node, open the printed loopback URL, then Run lifecycle checks.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import {createRequire} from 'node:module';
|
|
6
|
+
import {createServer} from 'node:http';
|
|
7
|
+
const root = process.env.DSH_BROWSER_TEST_ROOT;
|
|
8
|
+
if (!root) throw Error('Set DSH_BROWSER_TEST_ROOT to isolated npm test dependencies');
|
|
9
|
+
const require = createRequire(root + '/package.json');
|
|
10
|
+
const source = fs.readFileSync(new URL('../client.js', import.meta.url), 'utf8')
|
|
11
|
+
.replace('return { inject, apply };', 'return { inject, apply, CabinetPanel, STYLE_CSS, en, setOpener: fn => cabinetOpenSession = fn, setSessions: s => { cabinetSessions = s; for (const fn of cabinetSessionsListeners) fn(); } };');
|
|
12
|
+
const fixture = `
|
|
13
|
+
import React from 'react'; import {createRoot} from 'react-dom/client';
|
|
14
|
+
window.__ModuleLoader__={load:({factory})=>window.cabinet=factory(()=>React)};
|
|
15
|
+
${source}
|
|
16
|
+
const style=document.createElement('style');style.textContent=cabinet.STYLE_CSS;document.head.append(style);
|
|
17
|
+
const errors=[];window.addEventListener('error',e=>errors.push(e.message));
|
|
18
|
+
let opens=[],calls=[],team,live=false,mounted=true;
|
|
19
|
+
const timers=new Set(),originalSet=window.setInterval,originalClear=window.clearInterval;
|
|
20
|
+
window.setInterval=(fn,ms)=>{const id=originalSet(fn,ms);timers.add(id);return id};
|
|
21
|
+
window.clearInterval=id=>{timers.delete(id);originalClear(id)};
|
|
22
|
+
const members=[{id:'lead',name:'lead',role:'lead',phase:'active'},{id:'mate',name:'works',role:'teammate',phase:'active'}];
|
|
23
|
+
const tasks=[{id:'task',ownerName:'works',subject:'Open task session',status:'pending',blockedBy:['other']},{id:'other',ownerName:'works',subject:'Blocker task',status:'pending'}];
|
|
24
|
+
const root=createRoot(document.getElementById('panel'));
|
|
25
|
+
const stats=()=>document.getElementById('stats').textContent=JSON.stringify({opens,calls,timers:timers.size,errors});
|
|
26
|
+
cabinet.setOpener((...args)=>{opens.push(args);stats()});
|
|
27
|
+
const service={refreshProjections:async id=>{calls.push(id);stats()}};
|
|
28
|
+
function render(){root.render(mounted?React.createElement(cabinet.CabinetPanel,{sessionId:'lead',useSession:fn=>fn({}),useSessions:fn=>fn({projectionsBySession:{lead:{values:{agentTeam:team}},mate:{values:{tokenUsage:{outputTokens:1234},contextPressure:{projectedTokens:25,contextWindow:100},contextBreakdown:{systemTokens:1,toolsTokens:2,messageTokens:3}}}}}),useSessionStatus:fn=>fn(new Map([['mate',{running:live}]])),t:k=>cabinet.en[k]||k}):null)}
|
|
29
|
+
const wait=()=>new Promise(r=>setTimeout(r,80));
|
|
30
|
+
const assert=(condition,message)=>{if(!condition)throw Error(message)};
|
|
31
|
+
document.getElementById('show').onclick=()=>{team={members,tasks};cabinet.setSessions(service);render()};
|
|
32
|
+
document.getElementById('clear').onclick=()=>{opens=[];calls=[];stats()};
|
|
33
|
+
document.getElementById('width').onclick=()=>{const p=document.getElementById('panel');p.style.width=p.clientWidth>500?'340px':'900px'};
|
|
34
|
+
document.getElementById('run').onclick=async()=>{const passed=[];try{
|
|
35
|
+
mounted=true;team=undefined;live=false;calls=[];cabinet.setSessions(null);render();await wait();
|
|
36
|
+
assert(!errors.length,'empty render');passed.push('empty team');
|
|
37
|
+
team={members,tasks};render();await wait();assert(document.querySelectorAll('.cabinet-card').length>=2,'team appears');assert(!calls.length,'no service');passed.push('team arrives without hook mismatch');
|
|
38
|
+
cabinet.setSessions(service);await wait();assert(calls.includes('mate')&&calls.includes('lead'),'idle initial reads');passed.push('late service and idle initial reads');
|
|
39
|
+
calls=[];live=true;render();await wait();assert(calls.includes('mate')&&timers.size===1,'running starts');passed.push('running transition');
|
|
40
|
+
calls=[];live=false;render();await wait();assert(calls.includes('mate')&&timers.size===0,'settled read and cleanup');passed.push('stopped read and timer cleanup');
|
|
41
|
+
team=undefined;render();await wait();assert(!errors.length,'team disappears');passed.push('team disappears');
|
|
42
|
+
team={members,tasks};render();await wait();
|
|
43
|
+
assert(!document.querySelector('button button'),'no nested buttons');passed.push('no nested buttons');
|
|
44
|
+
const button=Array.from(document.querySelectorAll('#panel button')).find(e=>e.textContent==='Open task session');
|
|
45
|
+
opens=[];button.click();assert(opens.length===1,'subject bubbles once');passed.push('subject click opens once');
|
|
46
|
+
opens=[];document.querySelector('[data-cabinet-task="task"]').click();assert(opens.length===1,'row click');passed.push('row click opens once');
|
|
47
|
+
opens=[];const toggle=Array.from(document.querySelectorAll('#panel button')).find(e=>e.textContent.includes('blocked by'));toggle.click();assert(opens.length===0,'blocker toggle inert');passed.push('blocker toggle does not navigate');
|
|
48
|
+
live=true;render();await wait();mounted=false;render();await wait();assert(timers.size===0,'unmount cleanup');assert(!errors.length,'no React errors');passed.push('unmount cleanup');
|
|
49
|
+
mounted=true;live=false;render();await wait();document.getElementById('result').textContent='PASS '+passed.length+' '+passed.join('; ');stats();
|
|
50
|
+
}catch(e){document.getElementById('result').textContent='FAIL '+e.stack;stats()}};
|
|
51
|
+
render();stats();
|
|
52
|
+
`;
|
|
53
|
+
const bundle=require('esbuild').buildSync({stdin:{contents:fixture,resolveDir:root},bundle:true,format:'iife',write:false}).outputFiles[0].contents;
|
|
54
|
+
const html='<!doctype html><meta charset="utf-8"><title>Cabinet isolated React regression</title><style>body{font:14px system-ui;margin:20px}#panel{width:900px;max-width:100%;height:650px;overflow:auto}#stats,#result{white-space:pre-wrap;overflow-wrap:anywhere}button{margin:2px}</style><button id="run">Run lifecycle checks</button><button id="show">Show team</button><button id="clear">Clear counters</button><button id="width">Narrow / wide</button><pre id="result"></pre><pre id="stats"></pre><div id="panel"></div><script src="/fixture.js"></script>';
|
|
55
|
+
const server=createServer((req,res)=>{res.setHeader('Content-Type',req.url==='/fixture.js'?'text/javascript':'text/html');res.end(req.url==='/fixture.js'?bundle:html)});
|
|
56
|
+
server.listen(0,'127.0.0.1',()=>console.log('http://127.0.0.1:'+server.address().port));
|