dsh-cabinet-mode 0.6.4 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +8 -4
- package/README.zh.md +8 -4
- package/client.js +379 -25
- package/docs/member-usage-validation.md +15 -0
- package/package.json +2 -1
- package/scripts/test-client.mjs +421 -4
- package/scripts/test-panel-browser.mjs +56 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [0.7.1] - 2026-11-09
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- Count elapsed time for stopped members through the recorded active window end instead of letting an unclosed window grow.
|
|
10
|
+
- Keep blocker chips informational by stopping click propagation before task-row navigation.
|
|
11
|
+
- Include the lead in the team usage total and label the aggregation clearly.
|
|
12
|
+
- Verify that a ready projection load short-circuits on retry and that host-pushed frames update usage without another read.
|
|
13
|
+
|
|
14
|
+
## [0.7.0] - 2026-11-09
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- Open teammate sessions from member cards, task rows and Owner labels, with native keyboard buttons and single-navigation event propagation.
|
|
19
|
+
- Show member token totals, elapsed time and approximate context composition from host projections. Missing data remains unknown; cached snapshots are not guaranteed final usage.
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- Keep usage hooks stable when team data arrives or disappears; handle initial idle reads, running/stopped transitions, optional service arrival and timer cleanup.
|
|
24
|
+
- Validate isolated real React lifecycle and keyboard navigation without restarting existing DSH or calling models.
|
|
25
|
+
|
|
5
26
|
## [0.6.4] - 2026-11-09
|
|
6
27
|
|
|
7
28
|
### Documentation
|
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,11 @@ and the rest) come from the profile-level
|
|
|
37
37
|
ship them**.
|
|
38
38
|
|
|
39
39
|
This bundle declares **no hard DSH version gate**: no `engines.dsh`, no DSH
|
|
40
|
-
`peerDependencies`, no install-time version check. Earlier package releases were tested on DSH **0.2.1-rc.3**; use the compatibility guidance above for 0.
|
|
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).
|
|
41
45
|
|
|
42
46
|
## Update notes
|
|
43
47
|
|
|
@@ -294,7 +298,7 @@ On failure, show the exact error. For $.format must be 1, replace the webpage so
|
|
|
294
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:
|
|
295
299
|
|
|
296
300
|
```sh
|
|
297
|
-
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.1/dsh-cabinet-mode-0.7.1.tgz
|
|
298
302
|
dsh plugin --profile desktop list
|
|
299
303
|
```
|
|
300
304
|
|
|
@@ -309,7 +313,7 @@ the same install command with the new version URL (or pick the new `.tgz` in the
|
|
|
309
313
|
plugin page), then fully quit and restart DeepSeek Harness:
|
|
310
314
|
|
|
311
315
|
```sh
|
|
312
|
-
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.1/dsh-cabinet-mode-0.7.1.tgz
|
|
313
317
|
```
|
|
314
318
|
|
|
315
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,11 @@
|
|
|
21
21
|
|
|
22
22
|
它声明**两行**——`preset-cabinet`(一条 `@deepseek-ai/dsh-agent-preset` 声明)与 `cabinet-ui`(载入本包 JavaScript 的 Loader 行)——并复用 DSH **标准模式**(Standard Mode)出厂的 22 行插件清单,因此工具与标准模式一致;与出厂模式的差异是 persona,并另加右栏「内阁」面板。团队工具(`spawn_teammate`、`team_task_*` 等)由 profile 层的 `@deepseek-ai/dsh-experimental-agent-team-profile` 提供,**本 preset 未内置**。
|
|
23
23
|
|
|
24
|
-
本包声明 **无 DSH 版本硬限制**:没有 `engines.dsh`、没有 DSH `peerDependencies`、安装时不做版本检查。旧包曾在 DSH **0.2.1-rc.3** 实测;0.
|
|
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)。
|
|
25
29
|
|
|
26
30
|
## 更新日志
|
|
27
31
|
|
|
@@ -225,7 +229,7 @@ https://raw.githubusercontent.com/luodaoyi/dsh-cabinet-mode/market-index/marketp
|
|
|
225
229
|
仅在商店不可用或本地开发时使用。先完全退出桌面 DSH,释放 profile 锁,再执行:
|
|
226
230
|
|
|
227
231
|
```sh
|
|
228
|
-
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.1/dsh-cabinet-mode-0.7.1.tgz
|
|
229
233
|
dsh plugin --profile desktop list
|
|
230
234
|
```
|
|
231
235
|
|
|
@@ -236,7 +240,7 @@ dsh plugin --profile desktop list
|
|
|
236
240
|
若通过插件市场安装:刷新市场,先在**已安装**页卸载旧版本,再从**插件市场**安装新版本,然后重启——没有 tgz URL 要换,也没有一键更新。否则用同一条安装命令换新版本 URL(或在插件页选新 `.tgz`),然后完全退出并重启 DeepSeek Harness:
|
|
237
241
|
|
|
238
242
|
```sh
|
|
239
|
-
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.1/dsh-cabinet-mode-0.7.1.tgz
|
|
240
244
|
```
|
|
241
245
|
|
|
242
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,47 @@ 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
|
+
* Bounded retry/re-render cadence for member usage while somebody runs.
|
|
2591
|
+
*
|
|
2592
|
+
* `refreshProjections` is NOT a polling read: the client manager returns the
|
|
2593
|
+
* in-flight promise while a load runs and resolves immediately once that
|
|
2594
|
+
* session's projections are `ready`
|
|
2595
|
+
* (dsh-api-session-controller/lib/types/client/sessions/manager.js:268-272),
|
|
2596
|
+
* so one connection really reads a session once. Later changes arrive as
|
|
2597
|
+
* Host frames — `ctx.sessionProjections.onChanged` → control stream
|
|
2598
|
+
* (lib/types/control.js:9-19) — and land in the projection store the panel
|
|
2599
|
+
* already subscribes to. The 5s tick therefore only re-renders the elapsed
|
|
2600
|
+
* clock; it neither re-reads the store nor spends any model token.
|
|
2601
|
+
*/
|
|
2602
|
+
const PROJECTION_REFRESH_MS = 5000;
|
|
2603
|
+
/**
|
|
2604
|
+
* Ask the sessions service once for one member's projections (same call the
|
|
2605
|
+
* native roster makes). Never throws: a missing service, a refusing
|
|
2606
|
+
* deployment or a rejected promise all degrade to "no value yet", which the
|
|
2607
|
+
* cards render as an em dash.
|
|
2608
|
+
*/
|
|
2609
|
+
function refreshCabinetProjection(id) {
|
|
2610
|
+
if (typeof id !== 'string' || id === '') return null;
|
|
2611
|
+
const sessions = cabinetSessions;
|
|
2612
|
+
if (!sessions || typeof sessions.refreshProjections !== 'function') return null;
|
|
2613
|
+
try {
|
|
2614
|
+
const pending = sessions.refreshProjections(id);
|
|
2615
|
+
if (pending !== undefined && pending !== null && typeof pending.catch === 'function') pending.catch(() => {});
|
|
2616
|
+
return pending;
|
|
2617
|
+
} catch (error) {
|
|
2618
|
+
try { console.warn('[cabinet-ui] refresh projections failed:', error); } catch (ignored) { /* console may be unavailable */ }
|
|
2619
|
+
return null;
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2570
2622
|
/**
|
|
2571
2623
|
* Open a teammate's child session the way the native roster does
|
|
2572
2624
|
* (dsh-experimental-client-ui-agent-team openTeammate): the Lead session
|
|
@@ -2933,9 +2985,10 @@ window.__ModuleLoader__.load({
|
|
|
2933
2985
|
});
|
|
2934
2986
|
}
|
|
2935
2987
|
|
|
2936
|
-
function Chip({ color, children, title }) {
|
|
2988
|
+
function Chip({ color, children, title, onClick }) {
|
|
2937
2989
|
return h('span', {
|
|
2938
2990
|
title,
|
|
2991
|
+
onClick,
|
|
2939
2992
|
style: {
|
|
2940
2993
|
display: 'inline-flex',
|
|
2941
2994
|
alignItems: 'center',
|
|
@@ -3019,18 +3072,159 @@ window.__ModuleLoader__.load({
|
|
|
3019
3072
|
]);
|
|
3020
3073
|
}
|
|
3021
3074
|
|
|
3022
|
-
function Tag({ background, color, title, children }) {
|
|
3023
|
-
|
|
3075
|
+
function Tag({ background, color, title, children, onClick }) {
|
|
3076
|
+
// A tag that carries an opener is its own click target (the Owner tag);
|
|
3077
|
+
// the caller stops propagation so the enclosing card or task row does
|
|
3078
|
+
// not forward the same click a second time.
|
|
3079
|
+
const clickable = typeof onClick === 'function';
|
|
3080
|
+
return h(clickable ? 'button' : 'span', {
|
|
3081
|
+
type: clickable ? 'button' : undefined,
|
|
3024
3082
|
title,
|
|
3025
|
-
|
|
3083
|
+
onClick,
|
|
3084
|
+
className: clickable ? 'cabinet-clickable' : undefined,
|
|
3085
|
+
style: { font: 'inherit', border: 0, fontSize: 10, padding: '0 5px', borderRadius: 4, color, background, flex: 'none', cursor: clickable ? 'pointer' : undefined }
|
|
3026
3086
|
}, children);
|
|
3027
3087
|
}
|
|
3028
3088
|
|
|
3089
|
+
// One click opens one session. Nested targets (the who row inside a card,
|
|
3090
|
+
// the subject / Owner tag / blocker toggle inside a task row) stop the
|
|
3091
|
+
// click so the enclosing handler does not repeat the same navigation.
|
|
3092
|
+
function stopPropagation(event) {
|
|
3093
|
+
if (event && typeof event.stopPropagation === 'function') event.stopPropagation();
|
|
3094
|
+
}
|
|
3095
|
+
|
|
3096
|
+
// ---- member usage: token total, elapsed time, context pressure --------
|
|
3097
|
+
// Everything below reads DSH's own session projections (tokenUsage,
|
|
3098
|
+
// subagentTiming, contextPressure, contextBreakdown) and never invents a
|
|
3099
|
+
// field: a projection the host did not publish renders as an em dash.
|
|
3100
|
+
|
|
3101
|
+
/** Compact token count: 842 stays exact, 3.3M / 12.5K collapse like the stats strip. */
|
|
3102
|
+
function formatTokenCount(value) {
|
|
3103
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return undefined;
|
|
3104
|
+
const scaled = (next) => (next >= 100 ? String(Math.round(next)) : String(Math.round(next * 10) / 10));
|
|
3105
|
+
if (value < 1000) return String(Math.round(value));
|
|
3106
|
+
if (value < 1e6) return scaled(value / 1e3) + 'K';
|
|
3107
|
+
return scaled(value / 1e6) + 'M';
|
|
3108
|
+
}
|
|
3109
|
+
|
|
3110
|
+
/** Whole-second elapsed time: 12s, 3m12s, 1h05m, 2d03h. */
|
|
3111
|
+
function formatElapsed(ms) {
|
|
3112
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return undefined;
|
|
3113
|
+
const totalSeconds = Math.floor(ms / 1000);
|
|
3114
|
+
if (totalSeconds < 60) return totalSeconds + 's';
|
|
3115
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
3116
|
+
if (minutes < 60) return minutes + 'm' + String(totalSeconds % 60).padStart(2, '0') + 's';
|
|
3117
|
+
const hours = Math.floor(minutes / 60);
|
|
3118
|
+
if (hours < 24) return hours + 'h' + String(minutes % 60).padStart(2, '0') + 'm';
|
|
3119
|
+
return Math.floor(hours / 24) + 'd' + String(hours % 24).padStart(2, '0') + 'h';
|
|
3120
|
+
}
|
|
3121
|
+
|
|
3122
|
+
/** Sum the four disjoint provider-usage buckets; undefined when none exists. */
|
|
3123
|
+
function tokenTotalOf(usage) {
|
|
3124
|
+
if (usage === undefined || usage === null || typeof usage !== 'object') return undefined;
|
|
3125
|
+
const buckets = ['uncachedInputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens']
|
|
3126
|
+
.map((key) => usage[key])
|
|
3127
|
+
.filter((value) => typeof value === 'number' && Number.isFinite(value) && value >= 0);
|
|
3128
|
+
if (buckets.length === 0) return undefined;
|
|
3129
|
+
return buckets.reduce((sum, value) => sum + value, 0);
|
|
3130
|
+
}
|
|
3131
|
+
|
|
3132
|
+
/**
|
|
3133
|
+
* Turn one session's projection values into a display record. Every field is
|
|
3134
|
+
* optional: a missing projection yields undefined (the card prints its dash),
|
|
3135
|
+
* and a missing contextWindow keeps the token numbers but drops the ratio.
|
|
3136
|
+
*/
|
|
3137
|
+
function usageFor(values, now, running) {
|
|
3138
|
+
const source = values !== undefined && values !== null && typeof values === 'object' ? values : {};
|
|
3139
|
+
const tokens = tokenTotalOf(source.tokenUsage?.totals ?? source.tokenUsage);
|
|
3140
|
+
let elapsedMs;
|
|
3141
|
+
const timing = source.subagentTiming;
|
|
3142
|
+
if (timing !== undefined && timing !== null && typeof timing === 'object') {
|
|
3143
|
+
const settled = typeof timing.settledMs === 'number' && Number.isFinite(timing.settledMs) ? timing.settledMs : 0;
|
|
3144
|
+
const active = timing.active;
|
|
3145
|
+
if (active !== undefined && active !== null && typeof active.since === 'number' && Number.isFinite(active.since)) {
|
|
3146
|
+
// Native parity (subagent catalog): a running turn ends at "now", an
|
|
3147
|
+
// inactive one at `active.through` — otherwise an unclosed active
|
|
3148
|
+
// window keeps growing while nobody is working.
|
|
3149
|
+
const clock = typeof now === 'number' && Number.isFinite(now) ? now : active.since;
|
|
3150
|
+
const end = running !== false
|
|
3151
|
+
? clock
|
|
3152
|
+
: (typeof active.through === 'number' && Number.isFinite(active.through) ? active.through : active.since);
|
|
3153
|
+
elapsedMs = settled + Math.max(0, end - active.since);
|
|
3154
|
+
} else if (typeof timing.settledMs === 'number' && Number.isFinite(timing.settledMs)) {
|
|
3155
|
+
elapsedMs = settled;
|
|
3156
|
+
}
|
|
3157
|
+
}
|
|
3158
|
+
const pressure = source.contextPressure;
|
|
3159
|
+
const breakdown = source.contextBreakdown?.breakdown ?? source.contextBreakdown;
|
|
3160
|
+
const projected = pressure !== undefined && pressure !== null && typeof pressure.projectedTokens === 'number' && Number.isFinite(pressure.projectedTokens)
|
|
3161
|
+
&& pressure.projectedTokens >= 0 ? pressure.projectedTokens : undefined;
|
|
3162
|
+
const contextWindow = pressure !== undefined && pressure !== null && typeof pressure.contextWindow === 'number' && Number.isFinite(pressure.contextWindow) && pressure.contextWindow > 0
|
|
3163
|
+
? pressure.contextWindow : undefined;
|
|
3164
|
+
const parts = breakdown !== undefined && breakdown !== null && typeof breakdown === 'object'
|
|
3165
|
+
? [
|
|
3166
|
+
{ key: 'system', value: breakdown.systemTokens },
|
|
3167
|
+
{ key: 'tools', value: breakdown.toolsTokens },
|
|
3168
|
+
{ key: 'message', value: breakdown.messageTokens }
|
|
3169
|
+
].filter((part) => typeof part.value === 'number' && Number.isFinite(part.value) && part.value >= 0)
|
|
3170
|
+
: [];
|
|
3171
|
+
let context;
|
|
3172
|
+
if (projected !== undefined || contextWindow !== undefined || parts.length > 0) {
|
|
3173
|
+
const sum = parts.reduce((total, part) => total + part.value, 0);
|
|
3174
|
+
context = {
|
|
3175
|
+
projectedTokens: projected,
|
|
3176
|
+
contextWindow,
|
|
3177
|
+
percent: projected !== undefined && contextWindow !== undefined
|
|
3178
|
+
? Math.min(100, Math.round((projected / contextWindow) * 1000) / 10) : undefined,
|
|
3179
|
+
segments: sum > 0 ? parts.map((part) => ({ key: part.key, ratio: part.value / sum })) : []
|
|
3180
|
+
};
|
|
3181
|
+
}
|
|
3182
|
+
return { tokens, elapsedMs, context };
|
|
3183
|
+
}
|
|
3184
|
+
|
|
3185
|
+
/**
|
|
3186
|
+
* Which member sessions need another projection refresh now.
|
|
3187
|
+
*
|
|
3188
|
+
* Time-based, not once-per-mount: a running member's numbers have to keep
|
|
3189
|
+
* moving, so an id becomes eligible again once `throttleMs` has passed since
|
|
3190
|
+
* its last request. `lastRequestedAt` is the caller's Map<id, timestamp>; the
|
|
3191
|
+
* helper applies only a time threshold; lifecycle transitions are handled
|
|
3192
|
+
* separately by the panel, including initial and settled reads.
|
|
3193
|
+
*/
|
|
3194
|
+
function planProjectionRequests(ids, lastRequestedAt, now, throttleMs) {
|
|
3195
|
+
const planned = [];
|
|
3196
|
+
const clock = typeof now === 'number' && Number.isFinite(now) ? now : Date.now();
|
|
3197
|
+
const throttle = typeof throttleMs === 'number' && Number.isFinite(throttleMs) && throttleMs >= 0 ? throttleMs : PROJECTION_REFRESH_MS;
|
|
3198
|
+
// Duck-typed so a Map from another realm (tests, host bridge) still counts.
|
|
3199
|
+
const log = lastRequestedAt !== undefined && lastRequestedAt !== null && typeof lastRequestedAt.get === 'function'
|
|
3200
|
+
? lastRequestedAt : new Map();
|
|
3201
|
+
for (const id of Array.isArray(ids) ? ids : []) {
|
|
3202
|
+
if (typeof id !== 'string' || id === '' || planned.includes(id)) continue;
|
|
3203
|
+
const previous = log.get(id);
|
|
3204
|
+
if (typeof previous === 'number' && Number.isFinite(previous) && clock - previous < throttle) continue;
|
|
3205
|
+
planned.push(id);
|
|
3206
|
+
}
|
|
3207
|
+
return planned;
|
|
3208
|
+
}
|
|
3209
|
+
|
|
3210
|
+
/** Sum member usage records for the lead card's team line. */
|
|
3211
|
+
function teamUsageOf(entries) {
|
|
3212
|
+
const list = Array.isArray(entries) ? entries : [];
|
|
3213
|
+
let tokens;
|
|
3214
|
+
let elapsedMs;
|
|
3215
|
+
for (const entry of list) {
|
|
3216
|
+
if (entry === undefined || entry === null) continue;
|
|
3217
|
+
if (typeof entry.tokens === 'number' && Number.isFinite(entry.tokens)) tokens = (tokens ?? 0) + entry.tokens;
|
|
3218
|
+
if (typeof entry.elapsedMs === 'number' && Number.isFinite(entry.elapsedMs)) elapsedMs = (elapsedMs ?? 0) + entry.elapsedMs;
|
|
3219
|
+
}
|
|
3220
|
+
return { tokens, elapsedMs };
|
|
3221
|
+
}
|
|
3222
|
+
|
|
3029
3223
|
// One card of the org chart: avatar + name (+ lead badge / current tag) on
|
|
3030
3224
|
// line one; status dot + state text (+ live dots / model) on line two.
|
|
3031
3225
|
// State text carries a theme-aware class so 11px copy clears 3:1 in both
|
|
3032
3226
|
// 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 }) {
|
|
3227
|
+
function MemberCard({ member, running, model, isCurrent, lead, statusLabel, t, size, onOpen, usage, teamUsage, children }) {
|
|
3034
3228
|
const tt = typeof t === 'function' ? t : (key) => key;
|
|
3035
3229
|
const status = member.phase === 'active' ? (running ? 'running' : 'inactive') : member.phase;
|
|
3036
3230
|
// Availability mirrors the native roster row (agent-team TeamMemberRow):
|
|
@@ -3042,11 +3236,22 @@ window.__ModuleLoader__.load({
|
|
|
3042
3236
|
&& member.phase !== 'failed'
|
|
3043
3237
|
&& member.phase !== 'provisioning'
|
|
3044
3238
|
&& typeof member.id === 'string' && member.id !== '';
|
|
3045
|
-
|
|
3046
|
-
|
|
3239
|
+
// The whole card is a click target now, not just the who row: one click
|
|
3240
|
+
// anywhere on a member card enters that member's child session. `canOpen`
|
|
3241
|
+
// keeps its exemptions untouched; the who row and the card's own task
|
|
3242
|
+
// lines stop propagation so a nested target opens only once.
|
|
3243
|
+
return h('div', {
|
|
3244
|
+
className: (lead ? 'cabinet-card cabinet-card-lead' : 'cabinet-card') + (canOpen ? ' cabinet-card-clickable' : ''),
|
|
3245
|
+
onClick: canOpen ? () => onOpen(member) : undefined,
|
|
3246
|
+
style: { position: 'relative', zIndex: 1, cursor: canOpen ? 'pointer' : undefined }
|
|
3247
|
+
}, [
|
|
3248
|
+
h(canOpen ? 'button' : 'div', {
|
|
3249
|
+
type: canOpen ? 'button' : undefined,
|
|
3047
3250
|
key: 'who',
|
|
3048
|
-
|
|
3049
|
-
|
|
3251
|
+
// Same opener as the card, so the who row stops the click instead
|
|
3252
|
+
// of letting the card forward it a second time.
|
|
3253
|
+
onClick: canOpen ? (event) => { stopPropagation(event); return onOpen(member); } : undefined,
|
|
3254
|
+
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
3255
|
}, [
|
|
3051
3256
|
h(Avatar, { key: 'avatar', name: member.name, size: size || 22, live: status === 'running' }),
|
|
3052
3257
|
h('span', {
|
|
@@ -3078,6 +3283,40 @@ window.__ModuleLoader__.load({
|
|
|
3078
3283
|
style: { fontSize: 11, color: '#f25a5a', width: '100%', wordBreak: 'break-all' }
|
|
3079
3284
|
}, member.error) : null
|
|
3080
3285
|
]),
|
|
3286
|
+
// Usage line: token total, elapsed time and the context-pressure bar,
|
|
3287
|
+
// all from DSH session projections. A missing projection prints the em
|
|
3288
|
+
// dash instead of collapsing the card, and the lead card adds the team
|
|
3289
|
+
// total summed over its members.
|
|
3290
|
+
usage ? h('div', {
|
|
3291
|
+
key: 'usage',
|
|
3292
|
+
className: 'cabinet-usage',
|
|
3293
|
+
style: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minWidth: 0, fontSize: 10, color: INK2 }
|
|
3294
|
+
}, [
|
|
3295
|
+
h('span', { key: 'tok', style: { flex: 'none' }, title: tt('usage.tokens') },
|
|
3296
|
+
tt('usage.tokens') + ' ' + (formatTokenCount(usage.tokens) ?? tt('usage.none'))),
|
|
3297
|
+
h('span', { key: 'el', style: { flex: 'none' }, title: tt('usage.elapsed') },
|
|
3298
|
+
tt('usage.elapsed') + ' ' + (formatElapsed(usage.elapsedMs) ?? tt('usage.none'))),
|
|
3299
|
+
usage.context ? h('span', {
|
|
3300
|
+
key: 'ctx',
|
|
3301
|
+
title: usage.context.percent !== undefined ? tt('usage.context') + ' ' + usage.context.percent + '%' : tt('usage.context'),
|
|
3302
|
+
style: { display: 'inline-flex', alignItems: 'center', gap: 4, flex: 'none' }
|
|
3303
|
+
}, [
|
|
3304
|
+
usage.context.percent !== undefined ? h('span', {
|
|
3305
|
+
key: 'bar',
|
|
3306
|
+
className: 'cabinet-ctxbar',
|
|
3307
|
+
'aria-hidden': 'true'
|
|
3308
|
+
}, usage.context.segments.map((segment) => h('i', {
|
|
3309
|
+
key: segment.key,
|
|
3310
|
+
className: 'cabinet-ctxbar-' + segment.key,
|
|
3311
|
+
style: { width: Math.max(0, Math.min(100, segment.ratio * 100)) + '%' }
|
|
3312
|
+
}))) : null,
|
|
3313
|
+
h('span', { key: 'pct' }, usage.context.percent !== undefined
|
|
3314
|
+
? usage.context.percent + '%'
|
|
3315
|
+
: (formatTokenCount(usage.context.projectedTokens) ?? tt('usage.none')))
|
|
3316
|
+
]) : null,
|
|
3317
|
+
teamUsage ? h('span', { key: 'team', style: { flex: 'none' }, title: tt('usage.team') },
|
|
3318
|
+
tt('usage.team') + ' ' + (formatTokenCount(teamUsage.tokens) ?? tt('usage.none'))) : null
|
|
3319
|
+
]) : null,
|
|
3081
3320
|
// the member's own task list hangs inside the card (品字形 layout)
|
|
3082
3321
|
children
|
|
3083
3322
|
]);
|
|
@@ -3088,11 +3327,12 @@ window.__ModuleLoader__.load({
|
|
|
3088
3327
|
const status = TASK_COLOR[task.status] ? task.status : 'pending';
|
|
3089
3328
|
const color = TASK_COLOR[status];
|
|
3090
3329
|
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
|
|
3330
|
+
// The subject, the whole row and the Owner tag are all affordances, but
|
|
3331
|
+
// only when the panel handed us a resolved opener: lead-owned,
|
|
3332
|
+
// unassigned, foreign-owner and inert-owner tasks arrive with
|
|
3333
|
+
// onOpenOwner === null and keep the plain look (no onClick, no pointer).
|
|
3095
3334
|
const openTask = typeof onOpenOwner === 'function';
|
|
3335
|
+
const openOnce = openTask ? (event) => { stopPropagation(event); return onOpenOwner(task); } : undefined;
|
|
3096
3336
|
const parts = [
|
|
3097
3337
|
h('span', {
|
|
3098
3338
|
key: 'dot',
|
|
@@ -3100,17 +3340,26 @@ window.__ModuleLoader__.load({
|
|
|
3100
3340
|
style: { width: 8, height: 8, flex: 'none', borderRadius: '50%', background: color }
|
|
3101
3341
|
}),
|
|
3102
3342
|
h('span', { key: 'st', className: 'cabinet-task-' + status, style: { fontSize: 11, flex: 'none' } }, taskLabel(status)),
|
|
3103
|
-
h('span', {
|
|
3343
|
+
h(openTask ? 'button' : 'span', {
|
|
3344
|
+
type: openTask ? 'button' : undefined,
|
|
3104
3345
|
key: 'subj',
|
|
3105
|
-
style: { fontSize: 12.5, color: INK, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: openTask ? 'pointer' : undefined },
|
|
3346
|
+
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
3347
|
title: task.subject,
|
|
3107
|
-
onClick:
|
|
3348
|
+
onClick: openOnce
|
|
3108
3349
|
}, task.subject)
|
|
3109
3350
|
];
|
|
3110
3351
|
if (!task.ownerName) {
|
|
3111
3352
|
parts.push(h(Tag, { key: 'own', background: 'rgba(127,127,127,.18)', color: INK2 }, t('task.unassigned')));
|
|
3112
3353
|
} else {
|
|
3113
|
-
|
|
3354
|
+
// The Owner tag opens the same owner session and stops the click, so
|
|
3355
|
+
// the enclosing row does not forward the same navigation again.
|
|
3356
|
+
parts.push(h(Tag, {
|
|
3357
|
+
key: 'owner',
|
|
3358
|
+
title: memberLabel(task.ownerName),
|
|
3359
|
+
background: 'rgba(127,127,127,.16)',
|
|
3360
|
+
color: INK2,
|
|
3361
|
+
onClick: openOnce
|
|
3362
|
+
}, 'Owner: ' + memberLabel(task.ownerName)));
|
|
3114
3363
|
}
|
|
3115
3364
|
parts.push(h('span', {
|
|
3116
3365
|
key: 'id',
|
|
@@ -3128,13 +3377,17 @@ window.__ModuleLoader__.load({
|
|
|
3128
3377
|
h('button', {
|
|
3129
3378
|
key: 'lb',
|
|
3130
3379
|
type: 'button',
|
|
3131
|
-
|
|
3380
|
+
// Toggling the blocker list is not navigation: stop the click so
|
|
3381
|
+
// the row's opener does not fire on the same event.
|
|
3382
|
+
onClick: (event) => { stopPropagation(event); setOpenBlockers((value) => !value); },
|
|
3132
3383
|
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
3384
|
}, (openBlockers ? '▾ ' : '▸ ') + t('task.waits') + ' ' + blockers.length),
|
|
3134
3385
|
...(openBlockers ? blockers.map((id) => {
|
|
3135
3386
|
const blocker = blockerOf(id);
|
|
3136
3387
|
const c = blocker ? (TASK_COLOR[blocker.status] || TASK_COLOR.pending) : 'rgba(127,127,127,.5)';
|
|
3137
|
-
|
|
3388
|
+
// A blocker chip is information, not navigation: stop the click so
|
|
3389
|
+
// the task row's opener does not fire when a chip is clicked.
|
|
3390
|
+
return h(Chip, { key: id, color: c, title: blocker ? blocker.subject : id, onClick: (event) => stopPropagation(event) }, [
|
|
3138
3391
|
h('span', { key: 'd', style: { width: 6, height: 6, borderRadius: '50%', background: c, flex: 'none' } }),
|
|
3139
3392
|
h('span', { key: 't', style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, id)
|
|
3140
3393
|
]);
|
|
@@ -3143,10 +3396,18 @@ window.__ModuleLoader__.load({
|
|
|
3143
3396
|
}
|
|
3144
3397
|
// in_progress tasks pulse only while their owner is actually running.
|
|
3145
3398
|
// data-cabinet-task anchors this row for the dependency-edge overlay.
|
|
3399
|
+
// The whole row is a click target when an opener resolved; its onClick
|
|
3400
|
+
// also stops the click so the member card that contains this row does
|
|
3401
|
+
// not open the member session as well.
|
|
3146
3402
|
return h(Row, {
|
|
3147
3403
|
tickTop: 12,
|
|
3148
3404
|
'data-cabinet-task': task.id,
|
|
3149
|
-
|
|
3405
|
+
onClick: openOnce,
|
|
3406
|
+
className: [
|
|
3407
|
+
ownerRunning && status === 'in_progress' ? 'cabinet-task-live' : '',
|
|
3408
|
+
openTask ? 'cabinet-clickable' : ''
|
|
3409
|
+
].filter(Boolean).join(' ') || undefined,
|
|
3410
|
+
style: { cursor: openTask ? 'pointer' : undefined }
|
|
3150
3411
|
}, children);
|
|
3151
3412
|
}
|
|
3152
3413
|
|
|
@@ -3513,7 +3774,7 @@ window.__ModuleLoader__.load({
|
|
|
3513
3774
|
// row subtree, so that height change is caught by the MutationObserver
|
|
3514
3775
|
// below instead of this effect.
|
|
3515
3776
|
React.useLayoutEffect(() => { measureLinks(); });
|
|
3516
|
-
const hasTeam = team
|
|
3777
|
+
const hasTeam = Boolean(team);
|
|
3517
3778
|
React.useEffect(() => {
|
|
3518
3779
|
const tree = treeRef.current;
|
|
3519
3780
|
if (!tree || typeof window === 'undefined') return undefined;
|
|
@@ -3617,6 +3878,76 @@ window.__ModuleLoader__.load({
|
|
|
3617
3878
|
h('span', { key: 'c' }, tt('task.completed') + ' ' + counts.completed)
|
|
3618
3879
|
]));
|
|
3619
3880
|
|
|
3881
|
+
const lead = members.find((member) => member.role === 'lead');
|
|
3882
|
+
const leadShown = lead ?? { id: sessionId, name: 'lead', role: 'lead', phase: 'active' };
|
|
3883
|
+
const mates = members.filter((member) => member.role !== 'lead');
|
|
3884
|
+
// Usage hooks stay above the empty-team return.
|
|
3885
|
+
//
|
|
3886
|
+
// The numbers move because the Host pushes projection frames
|
|
3887
|
+
// (`sessionProjections.onChanged` → control stream, control.js:9-19) into
|
|
3888
|
+
// the store read by useSessions — NOT because this panel re-reads them:
|
|
3889
|
+
// `refreshProjections` really reads a session once and resolves without
|
|
3890
|
+
// reading once that load is `ready` (manager.js:268-272). What is left for
|
|
3891
|
+
// this panel is (a) one ensure call per member the first time we see it,
|
|
3892
|
+
// (b) a bounded retry for a session that never loaded or just changed
|
|
3893
|
+
// state, and (c) a 5s re-render so the elapsed clock advances.
|
|
3894
|
+
const [usageTick, setUsageTick] = React.useState(0);
|
|
3895
|
+
const usageNow = Date.now();
|
|
3896
|
+
const usageOfMember = (member) => (member !== undefined && member !== null && typeof member.id === 'string' && member.id !== '')
|
|
3897
|
+
? usageFor(
|
|
3898
|
+
projections !== undefined && projections !== null ? projections[member.id]?.values : undefined,
|
|
3899
|
+
usageNow,
|
|
3900
|
+
runningOf(member.id)
|
|
3901
|
+
)
|
|
3902
|
+
: null;
|
|
3903
|
+
const leadUsage = usageOfMember(leadShown);
|
|
3904
|
+
const mateUsages = mates.map((member) => usageOfMember(member));
|
|
3905
|
+
const runningUsageIds = (team ? [leadShown, ...mates] : [])
|
|
3906
|
+
.map((member) => (member !== undefined && member !== null && typeof member.id === 'string' && member.id !== '' && runningOf(member.id)) ? member.id : undefined)
|
|
3907
|
+
.filter((id) => typeof id === 'string' && id !== '');
|
|
3908
|
+
const runningUsageKey = JSON.stringify(runningUsageIds);
|
|
3909
|
+
const allUsageIds = team ? [leadShown, ...mates].map(m => m.id).filter(id => typeof id === 'string' && id) : [];
|
|
3910
|
+
const allUsageKey = JSON.stringify(allUsageIds);
|
|
3911
|
+
const usageRequestState = React.useRef(new Map());
|
|
3912
|
+
const [usageService, setUsageService] = React.useState(cabinetSessions);
|
|
3913
|
+
React.useEffect(() => {
|
|
3914
|
+
const notify = () => setUsageService(cabinetSessions);
|
|
3915
|
+
cabinetSessionsListeners.add(notify); notify();
|
|
3916
|
+
return () => cabinetSessionsListeners.delete(notify);
|
|
3917
|
+
}, []);
|
|
3918
|
+
React.useEffect(() => {
|
|
3919
|
+
const state = new Map();
|
|
3920
|
+
usageRequestState.current = state;
|
|
3921
|
+
return () => { state.disposed = true; };
|
|
3922
|
+
}, [usageService, leadSessionId, hasTeam]);
|
|
3923
|
+
React.useEffect(() => {
|
|
3924
|
+
if (!usageService || typeof usageService.refreshProjections !== 'function') return;
|
|
3925
|
+
const states = usageRequestState.current;
|
|
3926
|
+
const running = new Set(runningUsageIds);
|
|
3927
|
+
for (const id of states.keys()) if (!allUsageIds.includes(id)) states.delete(id);
|
|
3928
|
+
for (const id of allUsageIds) {
|
|
3929
|
+
const live = running.has(id), previous = states.get(id);
|
|
3930
|
+
const changed = previous && previous.live !== live;
|
|
3931
|
+
const due = !previous || changed || (live && Date.now() - previous.at >= PROJECTION_REFRESH_MS);
|
|
3932
|
+
if (previous?.pending) { if (changed) previous.retry = true; continue; }
|
|
3933
|
+
if (!due) continue;
|
|
3934
|
+
const record = {live, at: Date.now(), pending: true};
|
|
3935
|
+
states.set(id, record);
|
|
3936
|
+
// Ensure/retry only: the first call per member really reads; a `ready`
|
|
3937
|
+
// session resolves without reading, so this is not a re-read loop.
|
|
3938
|
+
// Live updates arrive through useSessions (host push frames).
|
|
3939
|
+
try { Promise.resolve(usageService.refreshProjections(id)).catch(() => {}).finally(() => { record.pending = false; if (record.retry && !states.disposed) { states.delete(id); setUsageTick(tick => tick + 1); } }); }
|
|
3940
|
+
catch (_) { record.pending = false; }
|
|
3941
|
+
}
|
|
3942
|
+
}, [usageService, leadSessionId, hasTeam, allUsageKey, runningUsageKey, usageTick]);
|
|
3943
|
+
// While anybody runs, re-render on the same cadence so the elapsed time and
|
|
3944
|
+
// the fresh projections reach the card. Nothing running → no timer at all.
|
|
3945
|
+
React.useEffect(() => {
|
|
3946
|
+
if (!usageService || runningUsageIds.length === 0) return undefined;
|
|
3947
|
+
const timer = setInterval(() => setUsageTick((tick) => tick + 1), PROJECTION_REFRESH_MS);
|
|
3948
|
+
return () => { clearInterval(timer); };
|
|
3949
|
+
}, [usageService, runningUsageKey]);
|
|
3950
|
+
|
|
3620
3951
|
if (!team) {
|
|
3621
3952
|
body.push(h('div', {
|
|
3622
3953
|
key: 'empty',
|
|
@@ -3631,9 +3962,6 @@ window.__ModuleLoader__.load({
|
|
|
3631
3962
|
return h('div', { ref: panelRef, style: PANEL }, body);
|
|
3632
3963
|
}
|
|
3633
3964
|
|
|
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
3965
|
const isLeadTask = (task) => task.ownerName === 'lead' || (lead !== undefined && task.ownerName === lead.name);
|
|
3638
3966
|
const unassigned = tasks.filter((task) => !task.ownerName);
|
|
3639
3967
|
const leadOwn = tasks.filter((task) => task.ownerName !== undefined && isLeadTask(task));
|
|
@@ -3679,7 +4007,9 @@ window.__ModuleLoader__.load({
|
|
|
3679
4007
|
size: 26,
|
|
3680
4008
|
statusLabel,
|
|
3681
4009
|
t: tt,
|
|
3682
|
-
onOpen: openMemberSession
|
|
4010
|
+
onOpen: openMemberSession,
|
|
4011
|
+
usage: leadUsage,
|
|
4012
|
+
teamUsage: teamUsageOf([leadUsage, ...mateUsages])
|
|
3683
4013
|
});
|
|
3684
4014
|
|
|
3685
4015
|
// Cells: every minister first, then 未分派 / 首辅自办 / 不在册 as
|
|
@@ -3738,6 +4068,7 @@ window.__ModuleLoader__.load({
|
|
|
3738
4068
|
statusLabel,
|
|
3739
4069
|
t: tt,
|
|
3740
4070
|
onOpen: openMemberSession,
|
|
4071
|
+
usage: usageOfMember(member),
|
|
3741
4072
|
// tasks live inside the card, elbow-connected by RailList
|
|
3742
4073
|
children: own.length > 0
|
|
3743
4074
|
? h(RailList, { key: 'tasks', style: { marginTop: 4 } }, own.map((task) => h(TaskLine, {
|
|
@@ -4336,6 +4667,11 @@ window.__ModuleLoader__.load({
|
|
|
4336
4667
|
'task.completed': '已完成',
|
|
4337
4668
|
'task.deleted': '已删除',
|
|
4338
4669
|
'task.unassigned': '未分派',
|
|
4670
|
+
'usage.tokens': 'token',
|
|
4671
|
+
'usage.elapsed': '耗时',
|
|
4672
|
+
'usage.context': '上下文',
|
|
4673
|
+
'usage.team': '团队合计(含首辅)',
|
|
4674
|
+
'usage.none': '—',
|
|
4339
4675
|
'task.leadOwn': '首辅自办',
|
|
4340
4676
|
'task.waits': '等待',
|
|
4341
4677
|
'task.none': '暂无任务',
|
|
@@ -4424,6 +4760,11 @@ window.__ModuleLoader__.load({
|
|
|
4424
4760
|
'task.completed': 'done',
|
|
4425
4761
|
'task.deleted': 'deleted',
|
|
4426
4762
|
'task.unassigned': 'unassigned',
|
|
4763
|
+
'usage.tokens': 'tokens',
|
|
4764
|
+
'usage.elapsed': 'elapsed',
|
|
4765
|
+
'usage.context': 'context',
|
|
4766
|
+
'usage.team': 'team total (incl. lead)',
|
|
4767
|
+
'usage.none': '—',
|
|
4427
4768
|
'task.leadOwn': 'lead-owned',
|
|
4428
4769
|
'task.waits': 'blocked by',
|
|
4429
4770
|
'task.none': 'no tasks',
|
|
@@ -4545,6 +4886,19 @@ window.__ModuleLoader__.load({
|
|
|
4545
4886
|
return () => { if (cabinetOpenSession === opener) cabinetOpenSession = null; };
|
|
4546
4887
|
}, 'cabinet-ui: open teammate session');
|
|
4547
4888
|
});
|
|
4889
|
+
// Optional usage channel: the panel shows each member's token total, time
|
|
4890
|
+
// and context pressure from the DSH session projections. Its own guard,
|
|
4891
|
+
// so a host without the sessions service leaves every other channel and
|
|
4892
|
+
// every card exactly as it was (cards then print their em dash).
|
|
4893
|
+
ctx.inject(['sessions'], (scope) => {
|
|
4894
|
+
const sessions = scope.sessions;
|
|
4895
|
+
if (!sessions || typeof sessions.refreshProjections !== 'function') return;
|
|
4896
|
+
scope.effect(() => {
|
|
4897
|
+
cabinetSessions = sessions;
|
|
4898
|
+
for (const notify of cabinetSessionsListeners) notify();
|
|
4899
|
+
return () => { if (cabinetSessions === sessions) { cabinetSessions = null; for (const notify of cabinetSessionsListeners) notify(); } };
|
|
4900
|
+
}, 'cabinet-ui: session projections');
|
|
4901
|
+
});
|
|
4548
4902
|
// Optional install channel for the memory-plugin card: its own guard, so
|
|
4549
4903
|
// a host without the plugin manager leaves the model-catalog remote and
|
|
4550
4904
|
// 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.1",
|
|
4
4
|
"description": "Cabinet Mode (内阁模式) for DeepSeek Harness: a declarative DSH bundle that adds a dual-identity Lead/teammate agent preset for the Great Ming Research Bureau cabinet team.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"icon": "./icon.svg",
|
|
@@ -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
|
@@ -20,13 +20,55 @@ const React = {
|
|
|
20
20
|
useId: () => 'test-mask',
|
|
21
21
|
createElement: (type, props, ...children) => ({ type, props, children }),
|
|
22
22
|
useRef: () => ({ current: null }),
|
|
23
|
-
|
|
23
|
+
// Persistent state is opt-in like useRef: only the re-render chain test needs
|
|
24
|
+
// a setter that really changes the value the next render reads.
|
|
25
|
+
useState: (initial) => {
|
|
26
|
+
const value = typeof initial === 'function' ? initial() : initial;
|
|
27
|
+
if (persistentRefs === null) return [value, () => {}];
|
|
28
|
+
const index = hookStates.cursor++;
|
|
29
|
+
if (!(index in hookStates.slots)) hookStates.slots[index] = value;
|
|
30
|
+
return [hookStates.slots[index], (next) => {
|
|
31
|
+
hookStates.slots[index] = typeof next === 'function' ? next(hookStates.slots[index]) : next;
|
|
32
|
+
}];
|
|
33
|
+
},
|
|
24
34
|
useCallback: (callback) => callback,
|
|
25
|
-
useLayoutEffect: () => {}, useEffect: () => {},
|
|
35
|
+
useLayoutEffect: () => {}, useEffect: (fn, deps) => { recordedEffects.push({ fn, deps }); },
|
|
36
|
+
};
|
|
37
|
+
// The panel decides whether to mount its usage ticker; the spy observes the real
|
|
38
|
+
// setInterval/clearInterval call the component makes (not a proxy assertion).
|
|
39
|
+
const recordedEffects = [];
|
|
40
|
+
const intervalSpy = { mounted: 0, cleared: 0, delays: [], lastTimer: null };
|
|
41
|
+
// A controllable clock: the 5s projection throttle is time-based, so the chain
|
|
42
|
+
// test advances this instead of sleeping.
|
|
43
|
+
const clockState = { now: 1000000 };
|
|
44
|
+
class RealmDate extends Date {
|
|
45
|
+
constructor(...args) { super(...(args.length ? args : [clockState.now])); }
|
|
46
|
+
static now() { return clockState.now; }
|
|
47
|
+
}
|
|
48
|
+
// A simulated re-render needs React's real useRef semantics (same ref across
|
|
49
|
+
// renders of one component). Opt-in only: while `persistentRefs` is null every
|
|
50
|
+
// render keeps the fresh-ref default, so no other harness changes behaviour.
|
|
51
|
+
let persistentRefs = null;
|
|
52
|
+
const hookStates = { cursor: 0, slots: [] };
|
|
53
|
+
const resetHookCursor = () => {
|
|
54
|
+
if (persistentRefs !== null) {
|
|
55
|
+
persistentRefs.cursor = 0;
|
|
56
|
+
hookStates.cursor = 0;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
React.useRef = (initial) => {
|
|
60
|
+
if (persistentRefs === null) return { current: initial };
|
|
61
|
+
const index = persistentRefs.cursor++;
|
|
62
|
+
if (!(index in persistentRefs.slots)) persistentRefs.slots[index] = { current: initial };
|
|
63
|
+
return persistentRefs.slots[index];
|
|
26
64
|
};
|
|
27
|
-
const exportList = 'return { inject, apply, avatarFor, displayName, CabinetPanel, MemberCard, TaskLine, TaskEdgeLayer, buildTaskEdges, taskEdgesEqual, zh, en, BUREAUX, AVATARS, setMemberConfig, memberLabel, configuredAvatar, configuredPrompt, factoryPromptFor, DEFAULT_MEMBER_PROMPTS, DEFAULT_LEAD_PROMPT, CabinetMemberSettings, MemoryPluginCard, memoryPluginInstalledOf, SETTINGS_TABS };';
|
|
65
|
+
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
66
|
runInNewContext(source.replace(exportPoint, exportList), {
|
|
29
|
-
setTimeout: (fn, ms) => setTimeout(fn, ms === 120000 ? 20 : ms), clearTimeout,
|
|
67
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms === 120000 ? 20 : ms), clearTimeout,
|
|
68
|
+
Date: RealmDate,
|
|
69
|
+
setInterval: (fn, ms) => { intervalSpy.mounted += 1; intervalSpy.delays.push(ms); intervalSpy.lastTimer = { fn, ms }; return intervalSpy.lastTimer; },
|
|
70
|
+
clearInterval: () => { intervalSpy.cleared += 1; },
|
|
71
|
+
localStorage: pluginSpecStorage, window: { __ModuleLoader__: { load: ({ factory }) => {
|
|
30
72
|
client = factory((name) => { assert.equal(name, 'react'); return React; });
|
|
31
73
|
} } },
|
|
32
74
|
});
|
|
@@ -379,7 +421,378 @@ assert.equal(whoNodes.length, clickTeam.members.length, 'one who-row per member'
|
|
|
379
421
|
assert.deepEqual(whoNodes.map((node) => typeof node.props.onClick), ['undefined', 'function', 'undefined', 'undefined'],
|
|
380
422
|
'lead(self)/failed/provisioning cards stay inert, the active mate binds');
|
|
381
423
|
|
|
424
|
+
// --- click-through: whole card, whole task row and Owner tag are targets ---
|
|
425
|
+
// One click must open exactly one session. Every nested target stops the event,
|
|
426
|
+
// so the enclosing handler (row inside card, subject/Owner inside row) cannot
|
|
427
|
+
// forward the same click a second time.
|
|
428
|
+
const eventLog = [];
|
|
429
|
+
const fakeEvent = () => ({ stopped: false, stopPropagation() { this.stopped = true; eventLog.push('stopped'); } });
|
|
430
|
+
const cardOf = (member, extra) => elements(client.MemberCard({
|
|
431
|
+
member, statusLabel: (status) => status, ...extra,
|
|
432
|
+
})).find((node) => typeof node.props?.className === 'string' && node.props.className.split(' ').includes('cabinet-card'));
|
|
433
|
+
const opens = [];
|
|
434
|
+
const openRecorder = (target) => { opens.push(target); return true; };
|
|
435
|
+
|
|
436
|
+
// 1) the task row itself binds, shows the pointer, and stops the click
|
|
437
|
+
const rowLine = client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: openRecorder });
|
|
438
|
+
const rowNode = elements(rowLine).find((node) => node.props?.['data-cabinet-task'] === tasks[0].id);
|
|
439
|
+
assert.equal(typeof rowNode.props.onClick, 'function', 'the whole task row binds a resolved opener');
|
|
440
|
+
assert.equal(rowNode.props.style.cursor, 'pointer', 'the whole task row shows the pointer cursor');
|
|
441
|
+
assert.ok(rowNode.props.className.split(' ').includes('cabinet-clickable'), 'the clickable row carries the hover class');
|
|
442
|
+
const rowEvent = fakeEvent();
|
|
443
|
+
assert.equal(rowNode.props.onClick(rowEvent), true, 'the row forwards to the opener');
|
|
444
|
+
assert.deepEqual(opens, [tasks[0]], 'one click on the row opens once');
|
|
445
|
+
assert.equal(rowEvent.stopped, true, 'the row stops the click so the enclosing card cannot also open');
|
|
446
|
+
|
|
447
|
+
// 2) the Owner tag binds and stops the click instead of double-opening
|
|
448
|
+
// Tag drops the element key when it renders its span, so locate the Owner tag by
|
|
449
|
+
// its label text (same probe the identity test above uses).
|
|
450
|
+
const ownerTag = (line) => elements(line).find((node) => ['span', 'button'].includes(node.type)
|
|
451
|
+
&& node.children.flat().some((text) => typeof text === 'string' && text.startsWith('Owner: ')));
|
|
452
|
+
const boundOwner = ownerTag(client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: openRecorder }));
|
|
453
|
+
assert.equal(boundOwner.type, 'button', 'Owner is a native keyboard button');
|
|
454
|
+
assert.equal(boundOwner.props.type, 'button');
|
|
455
|
+
assert.equal(typeof boundOwner.props.onClick, 'function', 'the Owner tag binds a resolved opener');
|
|
456
|
+
assert.equal(boundOwner.props.style.cursor, 'pointer', 'the Owner tag shows the pointer cursor');
|
|
457
|
+
opens.length = 0;
|
|
458
|
+
const ownerEvent = fakeEvent();
|
|
459
|
+
assert.equal(boundOwner.props.onClick(ownerEvent), true, 'the Owner tag forwards to the opener');
|
|
460
|
+
assert.deepEqual(opens, [tasks[0]], 'one click on the Owner tag opens once');
|
|
461
|
+
assert.equal(ownerEvent.stopped, true, 'the Owner tag stops the click so the row cannot also open');
|
|
462
|
+
|
|
463
|
+
// 3) the subject keeps working and also stops the click
|
|
464
|
+
const subjectNode = elements(client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: openRecorder }))
|
|
465
|
+
.find((node) => node.props?.key === 'subj');
|
|
466
|
+
opens.length = 0;
|
|
467
|
+
assert.equal(subjectNode.type, 'button', 'Subject is a native keyboard button');
|
|
468
|
+
const subjectEvent = fakeEvent();
|
|
469
|
+
subjectNode.props.onClick(subjectEvent);
|
|
470
|
+
assert.deepEqual(opens, [tasks[0]], 'the subject still opens once with an event argument');
|
|
471
|
+
assert.equal(subjectEvent.stopped, true, 'the subject stops the click so the row cannot also open');
|
|
472
|
+
|
|
473
|
+
// 4) a task row inside a member card: card binds, row stops, card handler is not
|
|
474
|
+
// reachable from the row click (React propagation ends at stopPropagation)
|
|
475
|
+
const hybridCard = cardOf({ id: 'm-works', name: 'works', phase: 'active' },
|
|
476
|
+
{ isCurrent: false, onOpen: openRecorder, children: [client.TaskLine({ task: tasks[0], t: (key) => key, taskLabel: (status) => status, onOpenOwner: openRecorder })] });
|
|
477
|
+
assert.equal(typeof hybridCard.props.onClick, 'function', 'the card around a task row still binds');
|
|
478
|
+
const hybridRow = elements(hybridCard).find((node) => node.props?.['data-cabinet-task'] === tasks[0].id);
|
|
479
|
+
assert.equal(typeof hybridRow.props.onClick, 'function', 'the nested task row binds independently');
|
|
480
|
+
opens.length = 0;
|
|
481
|
+
const nestedEvent = fakeEvent();
|
|
482
|
+
hybridRow.props.onClick(nestedEvent);
|
|
483
|
+
assert.equal(nestedEvent.stopped, true, 'the nested row stops before the card handler can run');
|
|
484
|
+
assert.deepEqual(opens, [tasks[0]], 'clicking a task inside a card opens the task target once, never the member');
|
|
485
|
+
|
|
486
|
+
// Nested member identity is a native button and prevents its card from firing.
|
|
487
|
+
const who = elements(hybridCard).find(node => node.props?.key === 'who');
|
|
488
|
+
assert.equal(who.type, 'button');
|
|
489
|
+
opens.length = 0;
|
|
490
|
+
const whoEvent = fakeEvent();
|
|
491
|
+
who.props.onClick(whoEvent);
|
|
492
|
+
if (!whoEvent.stopped) hybridCard.props.onClick(whoEvent);
|
|
493
|
+
assert.equal(opens.length, 1);
|
|
494
|
+
|
|
495
|
+
// 5) inert members stay inert on the CARD too (self / failed / provisioning / no id / no channel)
|
|
496
|
+
for (const [label, member, extra] of [
|
|
497
|
+
['self', { id: 'lead-session', name: 'lead', phase: 'active' }, { isCurrent: true, onOpen: openRecorder }],
|
|
498
|
+
['failed', { id: 'm-dali', name: 'dali', phase: 'failed' }, { isCurrent: false, onOpen: openRecorder }],
|
|
499
|
+
['provisioning', { id: 'm-yushi', name: 'yushi', phase: 'provisioning' }, { isCurrent: false, onOpen: openRecorder }],
|
|
500
|
+
['no id', { name: 'works', phase: 'active' }, { isCurrent: false, onOpen: openRecorder }],
|
|
501
|
+
['no channel', { id: 'm-works', name: 'works', phase: 'active' }, { isCurrent: false }],
|
|
502
|
+
]) {
|
|
503
|
+
const card = cardOf(member, extra);
|
|
504
|
+
assert.equal(card.props.onClick, undefined, `${label}: the whole card stays unbound`);
|
|
505
|
+
assert.equal(card.props.style.cursor, undefined, `${label}: the whole card keeps the plain cursor`);
|
|
506
|
+
assert.ok(!card.props.className.includes('cabinet-card-clickable'), `${label}: no hover affordance on an inert card`);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// 6) tasks without a resolved opener stay plain on the row and the Owner tag
|
|
510
|
+
for (const task of [
|
|
511
|
+
{ id: 'k-lead', subject: 'lead work', ownerName: 'lead', status: 'pending' },
|
|
512
|
+
{ id: 'k-none', subject: 'nobody', status: 'pending' },
|
|
513
|
+
]) {
|
|
514
|
+
const line = client.TaskLine({ task, t: (key) => key, taskLabel: (status) => status, onOpenOwner: null });
|
|
515
|
+
const row = elements(line).find((node) => node.props?.['data-cabinet-task'] === task.id);
|
|
516
|
+
assert.equal(row.props.onClick, undefined, `${task.id}: no row click binding without an opener`);
|
|
517
|
+
assert.equal(row.props.style.cursor, undefined, `${task.id}: no pointer cursor on the row`);
|
|
518
|
+
assert.ok(!String(row.props.className || '').includes('cabinet-clickable'), `${task.id}: no hover affordance without an opener`);
|
|
519
|
+
if (task.ownerName) {
|
|
520
|
+
const owner = ownerTag(line);
|
|
521
|
+
assert.equal(owner.props.onClick, undefined, `${task.id}: no Owner-tag click binding without an opener`);
|
|
522
|
+
assert.equal(owner.props.style.cursor, undefined, `${task.id}: no pointer cursor on the Owner tag`);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// 7) panel level: the whole card of the one openable member is bound, the rest inert
|
|
527
|
+
const memberCardNodes = clickEls.filter((node) => typeof node.props?.className === 'string' && node.props.className.split(' ').includes('cabinet-card'));
|
|
528
|
+
// The panel also paints bucket cards (unassigned / foreign owner) next to the
|
|
529
|
+
// member cards, so count clickable cards instead of assuming one per member.
|
|
530
|
+
const boundCardNodes = memberCardNodes.filter((node) => typeof node.props.onClick === 'function');
|
|
531
|
+
assert.equal(boundCardNodes.length, 1, 'exactly one card in the panel is clickable: the single openable member');
|
|
532
|
+
assert.ok(boundCardNodes[0].props.className.includes('cabinet-card-clickable'), 'the clickable card carries the hover affordance');
|
|
533
|
+
assert.deepEqual(memberCardNodes.filter((node) => node !== boundCardNodes[0]).map((node) => node.props.onClick), memberCardNodes.filter((node) => node !== boundCardNodes[0]).map(() => undefined),
|
|
534
|
+
'every other card — inert member and bucket alike — stays unbound');
|
|
535
|
+
|
|
382
536
|
console.log('PASS: avatars, stale-team warnings, and distinct member/owner/group identities; mocked React, not browser E2E');
|
|
537
|
+
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');
|
|
538
|
+
|
|
539
|
+
// --- member usage: token total, elapsed time, context pressure (projections) ---
|
|
540
|
+
// Projection field names come from the DSH session schema; nothing here invents
|
|
541
|
+
// one. A missing projection must render the em dash, never throw.
|
|
542
|
+
assert.equal(client.formatTokenCount(842), '842', 'sub-thousand tokens stay exact');
|
|
543
|
+
assert.equal(client.formatTokenCount(1500), '1.5K', 'thousands collapse to one decimal');
|
|
544
|
+
assert.equal(client.formatTokenCount(3300000), '3.3M', 'millions collapse to one decimal');
|
|
545
|
+
assert.equal(client.formatTokenCount(undefined), undefined, 'missing total has no string');
|
|
546
|
+
assert.equal(client.formatTokenCount(Number.NaN), undefined, 'non-finite total has no string');
|
|
547
|
+
assert.equal(client.formatElapsed(12000), '12s');
|
|
548
|
+
assert.equal(client.formatElapsed(192000), '3m12s');
|
|
549
|
+
assert.equal(client.formatElapsed(3900000), '1h05m');
|
|
550
|
+
assert.equal(client.formatElapsed(undefined), undefined, 'missing timing has no string');
|
|
551
|
+
|
|
552
|
+
const fullValues = {
|
|
553
|
+
tokenUsage: { uncachedInputTokens: 1000, outputTokens: 2000, cacheReadTokens: 3000000, cacheWriteTokens: 4000 },
|
|
554
|
+
subagentTiming: { settledMs: 5000, active: { since: 100000, through: 180000 } },
|
|
555
|
+
contextPressure: { projectedTokens: 120000, contextWindow: 400000 },
|
|
556
|
+
contextBreakdown: { systemTokens: 2000, toolsTokens: 6000, messageTokens: 2000 },
|
|
557
|
+
};
|
|
558
|
+
const full = client.usageFor(fullValues, 112000);
|
|
559
|
+
assert.equal(full.tokens, 3007000, 'token total sums the four durable buckets');
|
|
560
|
+
assert.equal(full.elapsedMs, 17000, 'a running member adds now − active.since to settledMs');
|
|
561
|
+
assert.equal(full.context.percent, 30, 'context percent is projectedTokens / contextWindow');
|
|
562
|
+
assert.deepEqual(Array.from(full.context.segments, (segment) => segment.key), ['system', 'tools', 'message'], 'segments follow the projection breakdown order');
|
|
563
|
+
assert.deepEqual(Array.from(full.context.segments, (segment) => Math.round(segment.ratio * 100)), [20, 60, 20], 'segments follow the projection breakdown');
|
|
564
|
+
const settledOnly = client.usageFor({ ...fullValues, subagentTiming: { settledMs: 42000 } }, 112000);
|
|
565
|
+
assert.equal(settledOnly.elapsedMs, 42000, 'an inactive member shows settledMs');
|
|
566
|
+
const closedActive = client.usageFor({ subagentTiming: { settledMs: 5000, active: { since: 100000, through: 180000 } } }, 112000, false);
|
|
567
|
+
assert.equal(closedActive.elapsedMs, 85000, 'an inactive member ends the active window at active.through, not at now (native parity)');
|
|
568
|
+
const openActive = client.usageFor({ subagentTiming: { settledMs: 5000, active: { since: 100000, through: 180000 } } }, 112000, true);
|
|
569
|
+
assert.equal(openActive.elapsedMs, 17000, 'a running member keeps counting to now');
|
|
570
|
+
const noWindow = client.usageFor({ contextPressure: { projectedTokens: 120000 }, contextBreakdown: { systemTokens: 1 } }, 0);
|
|
571
|
+
assert.equal(noWindow.context.percent, undefined, 'no contextWindow → no ratio, numbers only');
|
|
572
|
+
assert.deepEqual(noWindow.context.segments.length, 1, 'breakdown still renders without a window');
|
|
573
|
+
const empty = client.usageFor(undefined, 112000);
|
|
574
|
+
assert.equal(empty.tokens, undefined);
|
|
575
|
+
assert.equal(empty.elapsedMs, undefined);
|
|
576
|
+
assert.equal(empty.context, undefined, 'a missing projection yields no context, and no throw');
|
|
577
|
+
assert.equal(client.formatTokenCount(empty.tokens) ?? '—', '—', 'the card prints the em dash for a missing total');
|
|
578
|
+
assert.equal(client.formatElapsed(empty.elapsedMs) ?? '—', '—', 'the card prints the em dash for a missing time');
|
|
579
|
+
|
|
580
|
+
// Throttle is TIME based, not once-per-mount: a running card must keep moving.
|
|
581
|
+
// A live id is skipped inside the 5s window and eligible again once it passes;
|
|
582
|
+
// a member that stopped is simply never passed in (panel filters on running).
|
|
583
|
+
const REQUEST_LOG = new Map([['m-works', 1000], ['m-dali', 2500]]);
|
|
584
|
+
assert.deepEqual(Array.from(client.planProjectionRequests(['m-works', 'm-dali', 'm-yushi', 'm-yushi', '', null], REQUEST_LOG, 3000, 5000)),
|
|
585
|
+
['m-yushi'], 'inside the 5s window a requested id is skipped; unknown ids and duplicates collapse');
|
|
586
|
+
assert.deepEqual(Array.from(client.planProjectionRequests(['m-works', 'm-dali'], REQUEST_LOG, 5999, 5000)), [],
|
|
587
|
+
'just under the window nothing is re-requested — the number is not double-fetched');
|
|
588
|
+
assert.deepEqual(Array.from(client.planProjectionRequests(['m-works', 'm-dali'], REQUEST_LOG, 7500, 5000)), ['m-works', 'm-dali'],
|
|
589
|
+
'past the window both ids are eligible again — a running card refreshes');
|
|
590
|
+
assert.deepEqual(Array.from(client.planProjectionRequests(['m-works'], undefined, 9000, 5000)), ['m-works'],
|
|
591
|
+
'a missing request log still plans the id, never throws');
|
|
592
|
+
|
|
593
|
+
// Team total on the lead card = the sum of its members.
|
|
594
|
+
const teamSum = client.teamUsageOf([{ tokens: 1000, elapsedMs: 60000 }, { tokens: 2000, elapsedMs: 5000 }, undefined, {}]);
|
|
595
|
+
assert.equal(teamSum.tokens, 3000, 'team tokens sum the members');
|
|
596
|
+
assert.equal(teamSum.elapsedMs, 65000, 'team time sums the members');
|
|
597
|
+
const emptyTeam = client.teamUsageOf(undefined);
|
|
598
|
+
assert.equal(emptyTeam.tokens, undefined, 'no members → no team tokens');
|
|
599
|
+
assert.equal(emptyTeam.elapsedMs, undefined, 'no members → no team time');
|
|
600
|
+
|
|
601
|
+
// Card render: a projection paints the usage line, a missing one paints dashes.
|
|
602
|
+
const zhT = (key) => client.zh[key] || key;
|
|
603
|
+
const usageCard = elements(client.MemberCard({
|
|
604
|
+
member: { id: 'm-works', name: 'works', phase: 'active' },
|
|
605
|
+
statusLabel: (status) => status,
|
|
606
|
+
t: zhT,
|
|
607
|
+
usage: full,
|
|
608
|
+
teamUsage: teamSum,
|
|
609
|
+
})).find((node) => node.props?.key === 'usage');
|
|
610
|
+
assert.ok(usageCard, 'the card renders a usage line');
|
|
611
|
+
const usageText = JSON.stringify(usageCard);
|
|
612
|
+
assert.ok(usageText.includes(client.zh['usage.tokens'] + ' 3M'), 'token total is rendered compactly: ' + usageText.slice(0, 160));
|
|
613
|
+
assert.ok(usageText.includes(client.zh['usage.elapsed'] + ' 17s'), 'elapsed time is rendered');
|
|
614
|
+
assert.ok(usageText.includes('30%'), 'context percent is rendered');
|
|
615
|
+
assert.ok(usageText.includes(client.zh['usage.team'] + ' 3K'), 'the lead card shows the team total');
|
|
616
|
+
const bars = elements(usageCard).filter((node) => node.props?.className === 'cabinet-ctxbar-system');
|
|
617
|
+
assert.equal(bars.length, 1, 'the context bar carries one segment per breakdown part');
|
|
618
|
+
const dashCard = elements(client.MemberCard({
|
|
619
|
+
member: { id: 'm-dali', name: 'dali', phase: 'active' },
|
|
620
|
+
statusLabel: (status) => status,
|
|
621
|
+
t: zhT,
|
|
622
|
+
usage: empty,
|
|
623
|
+
})).find((node) => node.props?.key === 'usage');
|
|
624
|
+
const dashText = JSON.stringify(dashCard);
|
|
625
|
+
assert.ok(dashText.includes(client.zh['usage.tokens'] + ' ' + client.zh['usage.none']), 'a missing token projection renders the em dash');
|
|
626
|
+
assert.ok(dashText.includes(client.zh['usage.elapsed'] + ' ' + client.zh['usage.none']), 'a missing timing projection renders the em dash');
|
|
627
|
+
assert.ok(!dashText.includes('cabinet-ctxbar'), 'no context bar without a pressure projection');
|
|
628
|
+
const noUsageCard = elements(client.MemberCard({ member: { name: 'works', phase: 'active' }, statusLabel: (status) => status, t: (key) => key }))
|
|
629
|
+
.filter((node) => node.props?.key === 'usage');
|
|
630
|
+
assert.equal(noUsageCard.length, 0, 'a member without a session id renders no usage line at all');
|
|
631
|
+
|
|
632
|
+
// Panel wiring: the usage line appears for a member whose projection exists.
|
|
633
|
+
const usagePanel = elements(client.CabinetPanel({
|
|
634
|
+
sessionId: 'lead-session',
|
|
635
|
+
useSession: (select) => select({}),
|
|
636
|
+
useSessions: (select) => select({ projectionsBySession: {
|
|
637
|
+
'lead-session': { values: { tokenUsage: { outputTokens: 1000 }, agentTeam: { members: [{ id: 'm-works', name: 'works', role: 'mate', phase: 'active' }], tasks: [] } } },
|
|
638
|
+
'm-works': { values: { tokenUsage: { outputTokens: 2000 }, subagentTiming: { settledMs: 42000 } } },
|
|
639
|
+
} }),
|
|
640
|
+
useSessionStatus: (select) => select(new Map()),
|
|
641
|
+
t: (key) => client.zh[key] || key,
|
|
642
|
+
}));
|
|
643
|
+
assert.ok(elements(usagePanel).some((node) => node.props?.key === 'usage'), 'the panel hands projections to the member cards');
|
|
644
|
+
const panelTeam = elements(usagePanel)
|
|
645
|
+
.filter((node) => node.props?.key === 'usage')
|
|
646
|
+
.map((node) => JSON.stringify(node))
|
|
647
|
+
.find((text) => text.includes(client.zh['usage.team']));
|
|
648
|
+
assert.ok(panelTeam, 'the lead card renders a team total');
|
|
649
|
+
assert.ok(panelTeam.includes(client.zh['usage.team'] + ' 3K'), 'the team total includes the lead itself (1K lead + 2K mate)');
|
|
650
|
+
|
|
651
|
+
// A blocker chip is information, not navigation: it must stop the click before
|
|
652
|
+
// the task row's opener runs.
|
|
653
|
+
const chipOpenLog = [];
|
|
654
|
+
const chipLine = client.TaskLine({
|
|
655
|
+
task: { id: 't-chip', subject: 'rows', ownerName: 'works', status: 'pending', blockedBy: ['t-blocker'] },
|
|
656
|
+
blockerOf: (id) => (id === 't-blocker' ? { subject: 'upstream work', status: 'pending' } : undefined),
|
|
657
|
+
t: (key) => key,
|
|
658
|
+
taskLabel: (status) => status,
|
|
659
|
+
onOpenOwner: (task) => { chipOpenLog.push(task); return true; },
|
|
660
|
+
});
|
|
661
|
+
const chipNode = elements(chipLine).find((node) => node.props?.title === 'upstream work');
|
|
662
|
+
assert.ok(chipNode, 'the blocker chip renders');
|
|
663
|
+
assert.equal(typeof chipNode.props.onClick, 'function', 'a blocker chip is its own click target');
|
|
664
|
+
const chipEvent = { stopped: false, stopPropagation() { this.stopped = true; } };
|
|
665
|
+
chipNode.props.onClick(chipEvent);
|
|
666
|
+
assert.equal(chipEvent.stopped, true, 'the chip stops the click so the task row does not navigate');
|
|
667
|
+
assert.deepEqual(chipOpenLog, [], 'clicking a blocker chip never opens the owner session');
|
|
668
|
+
|
|
669
|
+
// Facts: refreshProjections reads a session once and resolves without reading
|
|
670
|
+
// once that load is `ready` (manager.js:268-272); later changes come from Host
|
|
671
|
+
// pushed frames (control.js:9-19) into the store the panel renders from.
|
|
672
|
+
// React semantics for the double: an effect whose deps array is shallow-equal
|
|
673
|
+
// to the previous render's deps does not run again (the panel's request-state
|
|
674
|
+
// reset effect must not wipe its Map on every unrelated re-render).
|
|
675
|
+
const depSlots = [];
|
|
676
|
+
const sameDeps = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((value, index) => Object.is(value, b[index]));
|
|
677
|
+
const factsRunEffects = () => {
|
|
678
|
+
const queued = recordedEffects.splice(0, recordedEffects.length);
|
|
679
|
+
const cleanups = [];
|
|
680
|
+
let index = 0;
|
|
681
|
+
for (const entry of queued) {
|
|
682
|
+
const previous = depSlots[index];
|
|
683
|
+
if (previous !== undefined && sameDeps(previous.deps, entry.deps)) {
|
|
684
|
+
if (typeof previous.cleanup === 'function') cleanups.push(previous.cleanup);
|
|
685
|
+
index += 1;
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
const cleanup = entry.fn();
|
|
689
|
+
depSlots[index] = { deps: entry.deps, cleanup };
|
|
690
|
+
if (typeof cleanup === 'function') cleanups.push(cleanup);
|
|
691
|
+
index += 1;
|
|
692
|
+
}
|
|
693
|
+
depSlots.length = index;
|
|
694
|
+
return () => { for (const cleanup of cleanups) cleanup(); };
|
|
695
|
+
};
|
|
696
|
+
const factsCalls = [];
|
|
697
|
+
const factsReads = [];
|
|
698
|
+
const factsReady = new Set();
|
|
699
|
+
const factsSessions = {
|
|
700
|
+
refreshProjections: (id) => {
|
|
701
|
+
factsCalls.push(id);
|
|
702
|
+
if (factsReady.has(id)) return Promise.resolve(); // ready → short circuit, no read
|
|
703
|
+
factsReady.add(id);
|
|
704
|
+
factsReads.push(id);
|
|
705
|
+
return Promise.resolve();
|
|
706
|
+
},
|
|
707
|
+
};
|
|
708
|
+
client.apply({
|
|
709
|
+
locale: { register: () => {}, bind: () => (key) => key },
|
|
710
|
+
effect: (fn) => { try { return fn(); } catch (error) { return undefined; } },
|
|
711
|
+
inject: (names, callback) => {
|
|
712
|
+
if (Array.isArray(names) && names.includes('sessions')) callback({ sessions: factsSessions, effect: (fn) => { try { return fn(); } catch (error) { return undefined; } } });
|
|
713
|
+
},
|
|
714
|
+
});
|
|
715
|
+
const factsPanel = (mateTokens, extra) => elements(client.CabinetPanel({
|
|
716
|
+
sessionId: 'lead-session',
|
|
717
|
+
useSession: (select) => select({}),
|
|
718
|
+
useSessions: (select) => select({ projectionsBySession: {
|
|
719
|
+
'lead-session': { values: { tokenUsage: { outputTokens: 1000 }, agentTeam: { members: [
|
|
720
|
+
{ id: 'm-works', name: 'works', role: 'mate', phase: 'active' },
|
|
721
|
+
...((extra && extra.members) || []),
|
|
722
|
+
], tasks: [] } } },
|
|
723
|
+
'm-works': { values: { tokenUsage: { outputTokens: mateTokens } } },
|
|
724
|
+
} }),
|
|
725
|
+
useSessionStatus: (select) => select(new Map((extra && extra.status) || [['m-works', { running: true }]])),
|
|
726
|
+
t: (key) => client.zh[key] || key,
|
|
727
|
+
}));
|
|
728
|
+
const factsUsageText = (nodes) => nodes
|
|
729
|
+
.filter((node) => node.props?.key === 'usage')
|
|
730
|
+
.map((node) => JSON.stringify(node))
|
|
731
|
+
.join('|');
|
|
732
|
+
|
|
733
|
+
clockState.now = 2000000;
|
|
734
|
+
recordedEffects.length = 0;
|
|
735
|
+
persistentRefs = { cursor: 0, slots: [] };
|
|
736
|
+
factsCalls.length = 0; factsReads.length = 0; factsReady.clear();
|
|
737
|
+
resetHookCursor();
|
|
738
|
+
const factsFirst = factsPanel(2000);
|
|
739
|
+
const factsStop = factsRunEffects();
|
|
740
|
+
assert.deepEqual(Array.from(factsReads).sort(), ['lead-session', 'm-works'], 'the first pass ensures every member once (an idle one included)');
|
|
741
|
+
assert.ok(factsUsageText(factsFirst).includes(' 2K'), 'the first read paints the member total');
|
|
742
|
+
const factsCallsAfterFirst = factsCalls.length;
|
|
743
|
+
const factsReadsAfterFirst = factsReads.length;
|
|
744
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
745
|
+
|
|
746
|
+
// One 5s tick: the bounded retry asks again, but the manager is `ready`, so
|
|
747
|
+
// nothing is read. This is the fact the old "every 5s re-read" story got wrong.
|
|
748
|
+
clockState.now += 5001;
|
|
749
|
+
intervalSpy.lastTimer.fn();
|
|
750
|
+
resetHookCursor();
|
|
751
|
+
factsPanel(2000);
|
|
752
|
+
factsRunEffects();
|
|
753
|
+
// The tick re-renders on the retry cadence; whatever it does, it must not read
|
|
754
|
+
// the session again — that is the ready short-circuit this suite used to miss.
|
|
755
|
+
assert.deepEqual(factsCalls.slice(factsCallsAfterFirst), ['m-works'], 'a tick retries only the running member');
|
|
756
|
+
assert.equal(factsReads.length, factsReadsAfterFirst, 'no re-read after a tick: the ready load short-circuits (manager.js:268-272)');
|
|
757
|
+
|
|
758
|
+
// A Host push frame changes the store the panel renders from: the number moves
|
|
759
|
+
// with no further read and no further ensure call.
|
|
760
|
+
clockState.now += 1000;
|
|
761
|
+
const factsCallsBeforePush = factsCalls.length;
|
|
762
|
+
resetHookCursor();
|
|
763
|
+
const factsPushed = factsPanel(5000);
|
|
764
|
+
factsRunEffects();
|
|
765
|
+
assert.ok(factsUsageText(factsPushed).includes(' 5K'), 'a Host-pushed projection frame updates the card to the new total');
|
|
766
|
+
assert.ok(!factsUsageText(factsPushed).includes(' 2K'), 'the card shows the pushed value, not the stale one');
|
|
767
|
+
assert.equal(factsReads.length, factsReadsAfterFirst, 'the update came from the push, not from re-reading the session');
|
|
768
|
+
assert.equal(factsCalls.length, factsCallsBeforePush, 'a push never re-reads or re-requests on its own');
|
|
769
|
+
factsStop();
|
|
770
|
+
|
|
771
|
+
// An idle member is ensured once when the panel first sees it (never-loaded
|
|
772
|
+
// stores get filled), then not re-requested inside the window.
|
|
773
|
+
factsCalls.length = 0; factsReads.length = 0; factsReady.clear();
|
|
774
|
+
clockState.now = 3000000;
|
|
775
|
+
recordedEffects.length = 0;
|
|
776
|
+
persistentRefs = { cursor: 0, slots: [] };
|
|
777
|
+
const idleFacts = () => factsPanel(2000, {
|
|
778
|
+
members: [{ id: 'm-dali', name: 'dali', role: 'mate', phase: 'active' }],
|
|
779
|
+
status: [['m-works', { running: true }]],
|
|
780
|
+
});
|
|
781
|
+
resetHookCursor();
|
|
782
|
+
idleFacts();
|
|
783
|
+
const idleStop = factsRunEffects();
|
|
784
|
+
assert.ok(factsCalls.includes('m-dali'), 'an idle, never-loaded member still gets one ensure call');
|
|
785
|
+
resetHookCursor();
|
|
786
|
+
clockState.now += 1000;
|
|
787
|
+
idleFacts();
|
|
788
|
+
factsRunEffects();
|
|
789
|
+
assert.equal(factsCalls.filter((id) => id === 'm-dali').length, 1, 'an idle member is not re-requested inside the window');
|
|
790
|
+
idleStop();
|
|
791
|
+
persistentRefs = null;
|
|
792
|
+
|
|
793
|
+
// Stateful lifecycle, initial/settled loads and timer cleanup are exercised
|
|
794
|
+
// with real React DOM by scripts/test-panel-browser.mjs, not this hook double.
|
|
795
|
+
console.log('PASS: member usage formatting, missing data, throttle helpers, active.through parity, blocker chips that do not navigate, team total including the lead, and the projection facts — a ready load short-circuits (the retry call reads nothing) while a Host push frame updates the card without another read; lifecycle is tested separately with real React DOM');
|
|
383
796
|
console.log('PASS: task dependency edges — data attributes, three states, missing-blocker tolerance, reduced-motion CSS, geometry refresh gate');
|
|
384
797
|
|
|
385
798
|
// IDs are opaque; delimiter-bearing pairs must not collide or inject markup.
|
|
@@ -804,3 +1217,7 @@ console.log('PASS: late initial inventory cannot overwrite a completed operation
|
|
|
804
1217
|
finish({ok:true,value:{application:'applied',version:'0.1.13'}});await tick();
|
|
805
1218
|
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
1219
|
}
|
|
1220
|
+
|
|
1221
|
+
// Both public projection encodings are accepted; malformed counters remain unknown.
|
|
1222
|
+
assert.equal(client.usageFor({tokenUsage:{totals:{outputTokens:42}},contextBreakdown:{breakdown:{systemTokens:1,toolsTokens:2,messageTokens:3}}},0).tokens,42);
|
|
1223
|
+
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));
|