dsh-context-compression-improved 0.2.4 → 0.2.5

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.
Files changed (127) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +8 -8
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +212 -16
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +1 -19
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +75 -54
  22. package/packages/selector/README.md +7 -12
  23. package/packages/selector/README.zh.md +6 -13
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +16 -16
  27. package/packages/selector/lib/client.d.ts +97 -5
  28. package/packages/selector/lib/client.js +1884 -92
  29. package/packages/selector/lib/config.js +863 -6
  30. package/packages/selector/lib/index.d.ts +29 -21
  31. package/packages/selector/lib/index.js +424 -18
  32. package/packages/selector/lib/invariant.js +4 -4
  33. package/packages/selector/lib/pruner.d.ts +179 -4
  34. package/packages/selector/lib/pruner.js +1406 -371
  35. package/packages/selector/lib/style.css +42 -0
  36. package/packages/selector/lib/tail-trim.js +13 -4
  37. package/packages/selector/package.json +18 -27
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +200 -62
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/profiles.ts +431 -342
  61. package/packages/selector/src/pruner/state.ts +57 -43
  62. package/packages/selector/src/pruner.ts +2736 -2154
  63. package/packages/selector/src/runtime/audit.ts +303 -231
  64. package/packages/selector/src/runtime/config.ts +756 -642
  65. package/packages/selector/src/runtime/measurement.ts +436 -432
  66. package/packages/selector/src/runtime/monitor.ts +235 -0
  67. package/packages/selector/src/runtime/retrieve.ts +479 -457
  68. package/packages/selector/src/runtime/savings.ts +337 -0
  69. package/packages/selector/src/runtime/session-events.ts +30 -17
  70. package/packages/selector/src/runtime/summary-command.ts +127 -0
  71. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  72. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  73. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  74. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  75. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  76. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  77. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  78. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  79. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  80. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  81. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -275
  82. package/packages/selector/src/runtime/types.ts +365 -325
  83. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  84. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  85. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  86. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  87. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  88. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  89. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  90. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  91. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  92. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  93. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  94. package/packages/selector/tests/preset-overlay.host.spec.ts +8 -18
  95. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  96. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  97. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  98. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  99. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  100. package/packages/selector/tests/runtime/audit.spec.ts +275 -172
  101. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  102. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  103. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  104. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  105. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2702
  106. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  107. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  108. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  109. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  110. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  111. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  112. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  113. package/packages/selector/tests/standing-generation.host.spec.ts +142 -87
  114. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  115. package/pnpm-workspace.yaml +66 -19
  116. package/scripts/capture-profile-baseline.mjs +42 -0
  117. package/scripts/generate-tokenizer-fixtures.py +81 -81
  118. package/scripts/generate-vision-fixtures.py +208 -208
  119. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  120. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  121. package/scripts/toolclass-corpus-replay.mjs +281 -273
  122. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  123. package/tests/TEST_INVENTORY.md +41 -42
  124. package/scripts/capture-profile-baseline.ts +0 -80
  125. package/tsconfig.scripts.json +0 -13
  126. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  127. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -0,0 +1,336 @@
1
+ /**
2
+ * 压缩监控浮动球 + 面板(task: cci-monitor-fab;骨架整编自 pm 撤下的
3
+ * `longtask-fab.ts` — d29bcb1^, VANILLA DOM overlay 模式: FAB + 面板
4
+ * appendChild 到 document.body, position:fixed + JS 内联定位, Pointer Events
5
+ * 拖拽 + localStorage 持久化 + 视口夹紧)。
6
+ *
7
+ * cci 客户端纪律:
8
+ * - body 级直挂 = 幂等单例,应用生命周期存续,不做 dispose(页面刷新自然回收);
9
+ * - 回声环过滤:自有节点带 `dsh-cci-parasite` 类,不参与宿主面板探测;
10
+ * - 数据面: `/api/.../monitor` 忙 2s / 闲 5s 自调度轮询(savings 卡同口径),
11
+ * fetch 失败静默降级 + 陈旧标记——监控面板永不打扰主流程;
12
+ * - 动作面: 仅会话覆盖(POST,复用 /ctx-summary 状态机),不做压缩执行。
13
+ *
14
+ * 显隐: `enabledOf()`(设置文档 monitorPanel.enabled)为总闸;总闸开才显示球;
15
+ * 净节省为负时「点亮」呼吸态(负节省警示)。v1 监控全会话聚合(savings 卡同
16
+ * 口径),覆盖作用于默认会话;会话级绑定待 cci 有输入栏座位后另行接线。
17
+ */
18
+
19
+ const FAB_ID = 'dsh-cci-monitor-fab';
20
+ const PANEL_ID = 'dsh-cci-monitor-panel';
21
+ const STYLE_ID = 'dsh-cci-monitor-style';
22
+ const PARASITE = 'dsh-cci-parasite';
23
+ const POS_KEY = 'dsh.cci.monitor.pos';
24
+
25
+ /** `/monitor` 快照的消费侧窄化(服务端契约在路由 spec 钉住;此处自断言)。 */
26
+ export interface MonitorSnapshotPayload {
27
+ ok?: unknown
28
+ startedAt?: unknown
29
+ gross?: { exact?: unknown; estimated?: unknown }
30
+ offsets?: { exact?: unknown; estimated?: unknown }
31
+ net?: { exact?: unknown; estimated?: unknown }
32
+ usage?: { requests?: unknown; cacheHitRate?: unknown }
33
+ pricing?: { currency?: unknown; actualCost?: unknown; estimatedSavedCost?: unknown }
34
+ intent?: {
35
+ override?: 'on' | 'off' | undefined
36
+ observedEnabled?: boolean | undefined
37
+ gate?: { floorFraction?: unknown; growthTokens?: unknown }
38
+ lastFold?: { turn?: unknown; startSeq?: unknown; endSeq?: unknown } | undefined
39
+ }
40
+ context?: { liveTokens?: unknown; contextWindow?: unknown; pct?: unknown }
41
+ suggestion?: { suggest?: unknown; thresholdPct?: unknown; occupancyPct?: unknown }
42
+ recentOffsets?: Array<{ component?: unknown; tokens?: unknown }>
43
+ sessionScope?: string | null
44
+ }
45
+
46
+ export type MonitorAction = 'on' | 'off' | 'clear'
47
+
48
+ export interface MonitorFabDeps {
49
+ /** bind(NS) 的活性翻译器:漏译回退键名,跟随宿主语言切换。 */
50
+ t: (key: string) => string
51
+ fetchSnapshot: (sessionId: string | undefined) => Promise<MonitorSnapshotPayload>
52
+ applyOverride: (sessionId: string | undefined, action: MonitorAction) => Promise<void>
53
+ sessionIdOf: () => string | undefined
54
+ enabledOf: () => boolean
55
+ /** 首轮轮询延迟(ms);测试注入 1ms 走真实时钟。 */
56
+ initialDelayMs?: number
57
+ }
58
+
59
+ const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
60
+
61
+ export function initMonitorFab(deps: MonitorFabDeps): void {
62
+ if (document.getElementById(FAB_ID) !== null) return;
63
+ const { t } = deps;
64
+
65
+ const style = document.createElement('style');
66
+ style.id = STYLE_ID;
67
+ style.textContent = `
68
+ #${FAB_ID} { position: fixed; z-index: 9999; width: 42px; height: 42px; border-radius: 50%;
69
+ background: rgba(30,30,32,.72); backdrop-filter: blur(22px) saturate(180%);
70
+ border: 1px solid rgba(255,255,255,.14); box-shadow: 0 8px 24px rgba(0,0,0,.4);
71
+ color: #f5f5f7; font-size: 18px; line-height: 40px; text-align: center; cursor: grab;
72
+ touch-action: none; user-select: none; display: none; transition: transform .18s; }
73
+ #${FAB_ID}:hover { transform: scale(1.08); }
74
+ #${FAB_ID}.lit { display: block; box-shadow: 0 0 0 5px rgba(255,159,10,.28), 0 8px 24px rgba(0,0,0,.4);
75
+ animation: dsh-cci-mon-breathe 2.4s ease-in-out infinite; }
76
+ @keyframes dsh-cci-mon-breathe { 0%,100% { box-shadow: 0 0 0 4px rgba(255,159,10,.18), 0 8px 24px rgba(0,0,0,.4); }
77
+ 50% { box-shadow: 0 0 0 8px rgba(255,159,10,.32), 0 8px 24px rgba(0,0,0,.4); } }
78
+ #${PANEL_ID} { position: fixed; z-index: 9998; width: 336px; border-radius: 14px;
79
+ background: rgba(28,28,30,.78); backdrop-filter: blur(26px) saturate(180%);
80
+ border: 1px solid rgba(255,255,255,.12); box-shadow: 0 14px 44px rgba(0,0,0,.55);
81
+ color: #f5f5f7; font-size: 12.5px; opacity: 0; pointer-events: none;
82
+ transform: translateY(10px) scale(.92); transform-origin: 88% 100%;
83
+ transition: opacity .22s cubic-bezier(.16,.8,.3,1.05), transform .22s cubic-bezier(.16,.8,.3,1.1); }
84
+ #${PANEL_ID}.open { opacity: 1; pointer-events: auto; transform: none; }
85
+ #${PANEL_ID} h4 { margin: 0; padding: 10px 14px 8px; font-size: 13px; cursor: grab;
86
+ touch-action: none; user-select: none; border-bottom: 1px solid rgba(255,255,255,.09); }
87
+ #${PANEL_ID} .row { display: flex; align-items: center; gap: 8px; padding: 6px 14px; }
88
+ #${PANEL_ID} .row.label { width: 108px; flex: none; color: rgba(245,245,247,.55); }
89
+ #${PANEL_ID} .muted { color: rgba(245,245,247,.55); }
90
+ #${PANEL_ID} .neg { color: #ff9f0a; }
91
+ #${PANEL_ID} button { font: inherit; border-radius: 8px; border: 1px solid rgba(255,255,255,.18);
92
+ background: rgba(10,132,255,.85); color: #fff; padding: 4px 10px; cursor: pointer; }
93
+ #${PANEL_ID} button.ghost { background: transparent; }
94
+ #${PANEL_ID} button:disabled { opacity: .45; cursor: default; }
95
+ #${PANEL_ID} .stale { padding: 4px 14px 8px; color: #ffd60a; display: none; }
96
+ #${PANEL_ID} .hint { margin: 0; padding: 8px 14px; color: #ffd60a; display: none;
97
+ border-bottom: 1px solid rgba(255,255,255,.09); }
98
+ #${PANEL_ID} .hint.show { display: block; }
99
+ #${PANEL_ID} .stale.show { display: block; }
100
+ #${PANEL_ID} .recent { max-height: 132px; overflow: auto; padding: 2px 14px 8px;
101
+ color: rgba(245,245,247,.8); white-space: pre-wrap; }
102
+ `;
103
+ document.head.appendChild(style);
104
+
105
+ const fab = document.createElement('div');
106
+ fab.id = FAB_ID;
107
+ fab.className = PARASITE;
108
+ fab.textContent = '📉';
109
+ fab.title = t('monitor.fab.title');
110
+ const panel = document.createElement('div');
111
+ panel.id = PANEL_ID;
112
+ panel.className = PARASITE;
113
+ panel.hidden = true;
114
+ panel.innerHTML = `
115
+ <h4>${t('monitor.panel.title')}</h4>
116
+ <div class="hint" data-hint></div>
117
+ <div class="row"><span class="label">${t('monitor.panel.net')}</span><span data-net>–</span></div>
118
+ <div class="row"><span class="label">${t('monitor.panel.gross')}</span><span data-gross class="muted">–</span></div>
119
+ <div class="row"><span class="label">${t('monitor.panel.offsets')}</span><span data-offsets class="muted">–</span></div>
120
+ <div class="row"><span class="label">${t('monitor.panel.context')}</span><div class="bar"><i data-ctxbar></i></div><span data-ctxpct class="muted">–</span></div>
121
+ <div class="row"><span class="label">${t('monitor.panel.cacheHit')}</span><span data-cache class="muted">–</span></div>
122
+ <div class="row"><span class="label">${t('monitor.panel.cost')}</span><span data-cost class="muted">–</span></div>
123
+ <div class="row"><span class="label">${t('monitor.panel.intent')}</span><span data-intent class="muted">–</span></div>
124
+ <div class="row"><span class="label">${t('monitor.panel.overrideHint')}</span>
125
+ <button data-overon>${t('monitor.panel.resume')}</button>
126
+ <button data-overoff class="ghost">${t('monitor.panel.disable')}</button></div>
127
+ <div class="row muted" data-fold style="display:none"></div>
128
+ <div class="stale" data-stale>${t('monitor.panel.stale')}</div>
129
+ <div class="recent" data-recent></div>
130
+ `;
131
+ document.body.append(fab, panel);
132
+
133
+ // 位置:localStorage 恢复 + 视口夹紧(pm 骨架原样)
134
+ let pos: { x: number; y: number };
135
+ try {
136
+ pos = JSON.parse(localStorage.getItem(POS_KEY) ?? 'null') ?? {
137
+ x: Math.max(8, window.innerWidth - 66),
138
+ y: Math.max(8, Math.round(window.innerHeight * 0.6)),
139
+ };
140
+ } catch {
141
+ pos = { x: Math.max(8, window.innerWidth - 66), y: Math.max(8, Math.round(window.innerHeight * 0.6)) };
142
+ }
143
+ const clamp = (p: { x: number; y: number }): { x: number; y: number } => ({
144
+ x: Math.max(8, Math.min(window.innerWidth - 50, p.x)),
145
+ y: Math.max(8, Math.min(window.innerHeight - 50, p.y)),
146
+ });
147
+ const place = (): void => {
148
+ pos = clamp(pos);
149
+ fab.style.left = `${pos.x}px`;
150
+ fab.style.top = `${pos.y}px`;
151
+ };
152
+ place();
153
+ window.addEventListener('resize', place);
154
+
155
+ const makeDrag = (el: HTMLElement, key: 'fab' | 'panel'): void => {
156
+ let active = false;
157
+ let moved = false;
158
+ let origin = { x: 0, y: 0 };
159
+ el.addEventListener('pointerdown', (e) => {
160
+ active = true;
161
+ moved = false;
162
+ origin = { x: e.clientX, y: e.clientY };
163
+ el.setPointerCapture(e.pointerId);
164
+ });
165
+ el.addEventListener('pointermove', (e) => {
166
+ if (!active) return;
167
+ const next = clamp({ x: pos.x + e.clientX - origin.x, y: pos.y + e.clientY - origin.y });
168
+ if (Math.abs(next.x - pos.x) > 2 || Math.abs(next.y - pos.y) > 2) moved = true;
169
+ pos = key === 'fab' ? next : pos;
170
+ if (key === 'fab') place();
171
+ });
172
+ el.addEventListener('pointerup', () => {
173
+ active = false;
174
+ if (moved && key === 'fab') {
175
+ try { localStorage.setItem(POS_KEY, JSON.stringify(pos)); } catch { /* 隐私模式:位置不持久化 */ }
176
+ }
177
+ });
178
+ el.addEventListener('pointercancel', () => {
179
+ active = false;
180
+ });
181
+ };
182
+ let suppressClick = false;
183
+ makeDrag(fab, 'fab');
184
+
185
+ let open = false;
186
+ fab.addEventListener('click', () => {
187
+ if (suppressClick) {
188
+ suppressClick = false;
189
+ return;
190
+ }
191
+ open = !open;
192
+ if (open) {
193
+ panel.hidden = false;
194
+ const px = Math.max(8, Math.min(window.innerWidth - 344, pos.x - 300));
195
+ const py = pos.y - 300 < 8 ? pos.y + 46 : Math.max(8, pos.y - 300);
196
+ panel.style.left = `${px}px`;
197
+ panel.style.top = `${py}px`;
198
+ void panel.offsetHeight;
199
+ panel.classList.add('open');
200
+ } else {
201
+ panel.classList.remove('open');
202
+ setTimeout(() => {
203
+ panel.hidden = true;
204
+ }, 240);
205
+ }
206
+ });
207
+ makeDrag(panel.querySelector('h4') as HTMLElement, 'panel');
208
+
209
+ // 状态与轮询
210
+ let last: MonitorSnapshotPayload | undefined;
211
+ let stale = false;
212
+ let busyAction = false;
213
+
214
+ const fmtTokens = (n: unknown): string => num(n).toLocaleString('en-US');
215
+
216
+ const render = (snap: MonitorSnapshotPayload): void => {
217
+ last = snap;
218
+ const net = num(snap.net?.exact) + num(snap.net?.estimated);
219
+ const netEl = panel.querySelector('[data-net]') as HTMLElement;
220
+ netEl.textContent = `${fmtTokens(snap.net?.exact)}${num(snap.net?.estimated) > 0 ? ` (+${fmtTokens(snap.net?.estimated)} est)` : ''}`;
221
+ netEl.classList.toggle('neg', net < 0);
222
+ const suggest = snap.suggestion?.suggest === true;
223
+ fab.classList.toggle('lit', suggest || net < 0);
224
+ const hint = panel.querySelector('[data-hint]') as HTMLElement;
225
+ if (suggest) {
226
+ const pct = typeof snap.suggestion?.occupancyPct === 'number'
227
+ ? Math.round(snap.suggestion.occupancyPct * 100)
228
+ : null;
229
+ hint.textContent = (t('monitor.panel.suggest') as string).replace('{pct}', String(pct ?? '–'));
230
+ hint.classList.add('show');
231
+ } else {
232
+ hint.classList.remove('show');
233
+ }
234
+ (panel.querySelector('[data-gross]') as HTMLElement).textContent = fmtTokens(snap.gross?.exact);
235
+ (panel.querySelector('[data-offsets]') as HTMLElement).textContent = `-${fmtTokens(snap.offsets?.exact)}`;
236
+ const ctxBar = panel.querySelector('[data-ctxbar]') as HTMLElement;
237
+ const ctxPct = panel.querySelector('[data-ctxpct]') as HTMLElement;
238
+ const ctxPctNum = typeof snap.context?.pct === 'number' ? snap.context.pct : null;
239
+ if (ctxPctNum === null) {
240
+ ctxBar.style.width = '0%';
241
+ ctxPct.textContent = '–';
242
+ } else {
243
+ ctxBar.style.width = `${Math.min(100, Math.round(ctxPctNum * 100))}%`;
244
+ ctxBar.parentElement?.classList.toggle('hot', ctxPctNum >= 0.7);
245
+ ctxPct.textContent = `${Math.round(ctxPctNum * 100)}%`;
246
+ }
247
+ const hit = snap.usage?.cacheHitRate;
248
+ (panel.querySelector('[data-cache]') as HTMLElement).textContent =
249
+ typeof hit === 'number' ? `${Math.round(hit * 100)}%` : '–';
250
+ const pricing = snap.pricing;
251
+ (panel.querySelector('[data-cost]') as HTMLElement).textContent =
252
+ pricing?.actualCost === undefined && pricing?.estimatedSavedCost === undefined
253
+ ? '–'
254
+ : `${pricing?.actualCost ?? '–'} / -${pricing?.estimatedSavedCost ?? '–'} ${String(pricing?.currency ?? '')}`.trim();
255
+ const intentEl = panel.querySelector('[data-intent]') as HTMLElement;
256
+ const override = snap.intent?.override;
257
+ const observed = snap.intent?.observedEnabled;
258
+ intentEl.textContent = override === 'on' || override === 'off'
259
+ ? `${t('monitor.panel.overridePrefix')} ${override === 'on' ? t('monitor.panel.stateOn') : t('monitor.panel.stateOff')}`
260
+ : observed === undefined
261
+ ? t('monitor.panel.gateUnknown')
262
+ : observed ? t('monitor.panel.stateOn') : t('monitor.panel.stateOff');
263
+ const fold = snap.intent?.lastFold;
264
+ const foldEl = panel.querySelector('[data-fold]') as HTMLElement;
265
+ if (fold !== undefined && fold !== null && typeof fold === 'object') {
266
+ foldEl.style.display = '';
267
+ foldEl.textContent = `${t('monitor.panel.lastFold')} turn ${String(fold.turn ?? '–')}, seq ${String(fold.startSeq ?? '–')}..${String(fold.endSeq ?? '–')}`;
268
+ } else {
269
+ foldEl.style.display = 'none';
270
+ }
271
+ const recent = Array.isArray(snap.recentOffsets) ? snap.recentOffsets.slice(0, 3) : [];
272
+ (panel.querySelector('[data-recent]') as HTMLElement).textContent = recent.length === 0
273
+ ? t('savings.empty')
274
+ : recent
275
+ .map((entry: { component?: unknown; tokens?: unknown }) => {
276
+ const e = entry as { component?: unknown; tokens?: unknown };
277
+ return `${String(e.component ?? '–')}: ${fmtTokens(e.tokens)}`;
278
+ })
279
+ .join('\n');
280
+ for (const [selector, action] of [
281
+ ['[data-overon]', 'on'],
282
+ ['[data-overoff]', 'off'],
283
+ ] as const) {
284
+ (panel.querySelector(selector) as HTMLButtonElement).disabled = busyAction || override === action;
285
+ }
286
+ };
287
+
288
+ const markStale = (isStale: boolean): void => {
289
+ stale = isStale;
290
+ (panel.querySelector('[data-stale]') as HTMLElement).classList.toggle('show', stale);
291
+ };
292
+
293
+ const tick = async (): Promise<void> => {
294
+ const enabled = deps.enabledOf();
295
+ fab.style.display = enabled ? 'block' : 'none';
296
+ if (!enabled) {
297
+ if (open) {
298
+ open = false;
299
+ panel.classList.remove('open');
300
+ panel.hidden = true;
301
+ }
302
+ setTimeout(tick, 5000);
303
+ return;
304
+ }
305
+ try {
306
+ const snap = await deps.fetchSnapshot(deps.sessionIdOf());
307
+ markStale(false);
308
+ render(snap);
309
+ } catch {
310
+ /* 快照不可达:静默 + 陈旧标记,不打扰主流程 */
311
+ markStale(true);
312
+ }
313
+ setTimeout(tick, open ? 2000 : 5000);
314
+ };
315
+ setTimeout(tick, deps.initialDelayMs ?? 1500);
316
+
317
+ const wireOverride = (selector: string, action: MonitorAction): void => {
318
+ panel.querySelector(selector)?.addEventListener('click', async () => {
319
+ if (busyAction) return;
320
+ busyAction = true;
321
+ try {
322
+ await deps.applyOverride(deps.sessionIdOf(), action);
323
+ const sid = deps.sessionIdOf();
324
+ const snap = await deps.fetchSnapshot(sid);
325
+ markStale(false);
326
+ render(snap);
327
+ } catch {
328
+ markStale(true);
329
+ } finally {
330
+ busyAction = false;
331
+ }
332
+ });
333
+ };
334
+ wireOverride('[data-overon]', 'on');
335
+ wireOverride('[data-overoff]', 'off');
336
+ }
@@ -1,70 +1,88 @@
1
- /**
2
- * Field-wise writes for the `presetOptions` section of the
3
- * context-compression settings namespace.
4
- *
5
- * `settingsScope.set(field, value)` replaces the value AT that field, so
6
- * writing the section root with a patch deleted every sibling: choosing a
7
- * provider after choosing a channel erased `estimatorMode` and silently turned
8
- * the estimator back off, and the stored document kept exactly the last field
9
- * the user touched. The client reads the complete section (this namespace
10
- * declares no secret fields), so a patch is applied over the current document
11
- * and the merged result is what gets written.
12
- *
13
- * A patch member set to `undefined` means "clear this field" (it then
14
- * re-inherits the preset default); absent members stay untouched.
15
- */
16
-
17
- import type { PresetOptionsSettings } from '../profiles.ts'
18
-
19
- /** Every field a patch may address, in the schema's own order. */
20
- const PRESET_OPTION_KEYS = [
21
- 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
22
- 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
23
- ] as const
24
-
25
- /** One partial edit of `presetOptions`; `undefined` clears the named field. */
26
- export type PresetOptionsPatch = {
27
- readonly [K in keyof PresetOptionsSettings]?: PresetOptionsSettings[K] | undefined
28
- }
29
-
30
- /**
31
- * Apply one patch over the stored section.
32
- *
33
- * @param current - the decoded `presetOptions` section, when one is stored.
34
- * @param patch - the fields to write or clear.
35
- * @returns the complete section to store.
36
- */
37
- export function mergePresetOptionsPatch(
38
- current: PresetOptionsSettings | undefined,
39
- patch: PresetOptionsPatch,
40
- ): PresetOptionsSettings {
41
- const source = current as Record<string, unknown> | undefined
42
- const merged: Record<string, unknown> = {}
43
- for (const key of PRESET_OPTION_KEYS) {
44
- const stored = source?.[key]
45
- if (stored !== undefined) merged[key] = stored
46
- }
47
- for (const key of Object.keys(patch)) {
48
- const value = (patch as Record<string, unknown>)[key]
49
- if (value === undefined) delete merged[key]
50
- else merged[key] = value
51
- }
52
- return merged as PresetOptionsSettings
53
- }
54
-
55
- /**
56
- * Compare two sections field by field, so an unchanged patch neither rewrites
57
- * the document nor reports a save the Host never committed.
58
- *
59
- * @param left - one section (or none).
60
- * @param right - the other section.
61
- * @returns whether every known field holds the same value.
62
- */
63
- export function presetOptionsEqual(
64
- left: PresetOptionsSettings | undefined,
65
- right: PresetOptionsSettings | undefined,
66
- ): boolean {
67
- const a = left as Record<string, unknown> | undefined
68
- const b = right as Record<string, unknown> | undefined
69
- return PRESET_OPTION_KEYS.every(key => a?.[key] === b?.[key])
70
- }
1
+ /**
2
+ * Path-addressed writes for the `presetOptions` section of the
3
+ * context-compression settings namespace.
4
+ *
5
+ * The settings Host applies a `set` op AT its path, so a field write must name
6
+ * only the field it changes. Writing the whole section — `scope.set(
7
+ * 'presetOptions', patch)` — replaces the section root with the patch, which
8
+ * deleted every sibling field: choosing a provider after choosing a channel
9
+ * erased `estimatorMode` and silently turned the estimator back off, and the
10
+ * saved document kept exactly the last field the user touched.
11
+ *
12
+ * A patch member set to `undefined` means "clear this field" (the section then
13
+ * re-inherits the preset default) rather than "leave it alone"; absent members
14
+ * are untouched by construction.
15
+ */
16
+
17
+ import type { SettingsPathOpView } from '@deepseek-ai/dsh-settings/types'
18
+ import type { PresetOptionsSettings } from '../profiles.ts'
19
+
20
+ /** The namespace key holding every tokenpilot-inspired sub-capability override. */
21
+ const PRESET_OPTIONS_KEY = 'presetOptions'
22
+
23
+ /** Every field a patch may address, in the schema's own order. The retired
24
+ * review-gate keys are deliberately absent: nothing writes them any more, and
25
+ * a stored document that still carries them is tolerated by the decoders. */
26
+ const PRESET_OPTION_KEYS = [
27
+ 'dedupeToolResults', 'summaryLocator', 'prefixStabilizer', 'readState', 'estimatorMode',
28
+ 'estimatorProvider', 'estimatorModel', 'estimatorBaseUrl', 'estimatorApiKey', 'estimatorTimeoutMs',
29
+ 'advisorMode', 'advisorTimeoutMs', 'advisorRefreshTurns', 'advisorScoreThreshold', 'advisorSampleLimit',
30
+ 'advisorMinTokens',
31
+ ] as const
32
+
33
+ /** One partial edit of `presetOptions`; `undefined` clears the named field. */
34
+ export type PresetOptionsPatch = {
35
+ readonly [K in keyof PresetOptionsSettings]?: PresetOptionsSettings[K] | undefined
36
+ }
37
+
38
+ /**
39
+ * Plan the path ops one patch needs against the section currently stored.
40
+ *
41
+ * Fields already at their requested value produce no op, so a re-selected
42
+ * value neither rewrites the document nor reports a save the Host never
43
+ * committed.
44
+ *
45
+ * @param current - the decoded `presetOptions` section, when one is stored.
46
+ * @param patch - the fields to write or clear.
47
+ * @returns the ordered ops, empty when the patch changes nothing.
48
+ */
49
+ export function planPresetOptionsOps(
50
+ current: PresetOptionsSettings | undefined,
51
+ patch: PresetOptionsPatch,
52
+ ): SettingsPathOpView[] {
53
+ const stored = current as Record<string, unknown> | undefined
54
+ const ops: SettingsPathOpView[] = []
55
+ for (const key of PRESET_OPTION_KEYS) {
56
+ if (!Object.hasOwn(patch, key)) continue
57
+ const value = patch[key]
58
+ const path = [PRESET_OPTIONS_KEY, key]
59
+ if (value === undefined) {
60
+ if (stored?.[key] !== undefined) ops.push({ op: 'unset', path })
61
+ continue
62
+ }
63
+ if (stored?.[key] === value) continue
64
+ ops.push({ op: 'set', path, value })
65
+ }
66
+ return ops
67
+ }
68
+
69
+ /**
70
+ * Test whether one resolved settings document already carries every planned op.
71
+ *
72
+ * @param settings - the resolved namespace section after a write.
73
+ * @param ops - the ops that write submitted.
74
+ * @returns whether every named field holds its requested state.
75
+ */
76
+ export function presetOptionsOpsAccepted(
77
+ presetOptions: PresetOptionsSettings | undefined,
78
+ ops: readonly SettingsPathOpView[],
79
+ ): boolean {
80
+ if (ops.length === 0) return true
81
+ if (presetOptions === undefined) return false
82
+ const stored = presetOptions as Record<string, unknown>
83
+ return ops.every((op) => {
84
+ const key = op.path[op.path.length - 1]
85
+ if (key === undefined) return false
86
+ return op.op === 'set' ? stored[key] === op.value : stored[key] === undefined
87
+ })
88
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * 节省统计卡片(设置分节内,只读):净/毛/抵消 + 分项条。
3
+ * 数据源 = `/api/.../savings` 只读快照路由(忙 2s / 闲 5s 自调度轮询,
4
+ * 失败静默——统计卡片永不打扰设置页主功能)。
5
+ *
6
+ * @module dsh-context-compression-improved/client/savings-card
7
+ */
8
+ import { useEffect, useRef, useState } from 'react'
9
+ import css from './CompressionProfileSelector.module.css'
10
+ import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
11
+
12
+ const SAVINGS_ROUTE = '/api/dsh-context-compression-improved/savings'
13
+
14
+ interface SavingsSnapshot {
15
+ ok?: boolean
16
+ startedAt: string
17
+ sessions: number
18
+ gross: { exact: number; estimated: number }
19
+ offsets: { exact: number; estimated: number }
20
+ net: { exact: number; estimated: number }
21
+ perComponent: Array<{ component: string; tokens: number; basis: string; kind: string }>
22
+ recentOffsets: Array<{ component: string; tokens: number; basis: string; at: string; note?: string }>
23
+ usage?: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; cacheHitRate: number | null }
24
+ perSession?: Array<{ sessionId: string; net: { exact: number; estimated: number }; requests: number; cacheHitRate: number | null }>
25
+ pricing?: { currency: string; actualCost?: string; estimatedSavedCost?: string }
26
+ }
27
+
28
+ export interface SavingsCardProps {
29
+ /** locale 文案函数(与设置分节同一 translator,键受字典类型约束)。 */
30
+ t: CompressionProfileSelectorProps['t']
31
+ }
32
+
33
+ function fmt(n: number): string {
34
+ return n.toLocaleString('en-US')
35
+ }
36
+
37
+ /** 节省统计卡片:口径分列(精确 tokenizer vs chars/4 估算),永不混算。 */
38
+ export function SavingsCard({ t }: SavingsCardProps) {
39
+ const [snap, setSnap] = useState<SavingsSnapshot | null>(null)
40
+ const stopped = useRef(false)
41
+ useEffect(() => {
42
+ stopped.current = false
43
+ const tick = async (): Promise<void> => {
44
+ try {
45
+ const response = await fetch(SAVINGS_ROUTE, { headers: { 'cache-control': 'no-cache' } })
46
+ if (response.ok) {
47
+ const data = (await response.json()) as SavingsSnapshot
48
+ if (data?.startedAt !== undefined && !stopped.current) setSnap(data)
49
+ }
50
+ } catch {
51
+ /* 路由未注册/网络不可用:静默 */
52
+ }
53
+ if (!stopped.current) setTimeout(tick, 5000)
54
+ }
55
+ void tick()
56
+ return () => {
57
+ stopped.current = true
58
+ }
59
+ }, [])
60
+
61
+ if (snap === null || (snap.gross.exact + snap.gross.estimated === 0)) {
62
+ return <div className={css.pricing}>{t('savings.empty')}</div>
63
+ }
64
+ const hasExact = snap.gross.exact > 0 || snap.offsets.exact > 0
65
+ const hasEstimated = snap.gross.estimated > 0 || snap.offsets.estimated > 0
66
+ const netTone = (snap.net.exact + snap.net.estimated) >= 0 ? css.savingsNetPositive : css.savingsNetNegative
67
+ return (
68
+ <div className={`${css.savingsCard}`} data-testid="savings-card">
69
+ <div className={css.savingsRow}>
70
+ <span>{t('savings.title')}</span>
71
+ </div>
72
+ {hasExact ? (
73
+ <div className={`${css.savingsRow} ${netTone}`}>
74
+ <span>{t('savings.netExact')}</span>
75
+ <strong>{fmt(snap.net.exact)}</strong>
76
+ </div>
77
+ ) : null}
78
+ {hasEstimated ? (
79
+ <div className={css.savingsRow}>
80
+ <span>{t('savings.netEstimated')}</span>
81
+ <strong>{fmt(snap.net.estimated)}</strong>
82
+ </div>
83
+ ) : null}
84
+ <div className={css.savingsRow}>
85
+ <span className={css.savingsMuted}>{t('savings.gross')}</span>
86
+ <span className={css.savingsMuted}>
87
+ {hasExact ? `✓ ${fmt(snap.gross.exact)}` : ''}{hasExact && hasEstimated ? ' · ' : ''}{hasEstimated ? `≈ ${fmt(snap.gross.estimated)}` : ''}
88
+ </span>
89
+ </div>
90
+ <div className={css.savingsRow}>
91
+ <span className={css.savingsMuted}>{t('savings.offsets')}</span>
92
+ <span className={css.savingsMuted}>
93
+ {hasExact ? `−${fmt(snap.offsets.exact)}` : ''}{hasExact && hasEstimated ? ' · ' : ''}{hasEstimated ? `−${fmt(snap.offsets.estimated)}` : ''}
94
+ </span>
95
+ </div>
96
+ {snap.usage !== undefined && snap.usage.requests > 0 ? (
97
+ <>
98
+ <div className={css.savingsRow}>
99
+ <span className={css.savingsMuted}>{t('savings.requests')}</span>
100
+ <span className={css.savingsMuted}>{fmt(snap.usage.requests)}</span>
101
+ </div>
102
+ <div className={css.savingsRow}>
103
+ <span className={css.savingsMuted}>{t('savings.cacheHit')}</span>
104
+ <span className={css.savingsMuted}>
105
+ {snap.usage.cacheHitRate === null ? '–' : `${Math.round(snap.usage.cacheHitRate * 100)}%`}
106
+ </span>
107
+ </div>
108
+ {snap.pricing?.actualCost !== undefined ? (
109
+ <div className={css.savingsRow}>
110
+ <span className={css.savingsMuted}>{t('savings.actualCost')}</span>
111
+ <span className={css.savingsMuted}>{snap.pricing.currency} {snap.pricing.actualCost}</span>
112
+ </div>
113
+ ) : null}
114
+ {snap.pricing?.estimatedSavedCost !== undefined ? (
115
+ <div className={css.savingsRow}>
116
+ <span className={css.savingsMuted}>{t('savings.savedMoney')}</span>
117
+ <span className={css.savingsMuted}>{snap.pricing.currency} {snap.pricing.estimatedSavedCost}</span>
118
+ </div>
119
+ ) : null}
120
+ </>
121
+ ) : null}
122
+ {snap.perSession !== undefined && snap.perSession.length > 1 ? (
123
+ <div className={css.savingsBreakdown}>
124
+ {snap.perSession.slice(0, 5).map(row => (
125
+ <div key={row.sessionId} className={css.savingsRow}>
126
+ <span className={css.savingsMuted}>
127
+ {t('savings.perSession')} · {row.sessionId.slice(0, 8)}…{row.requests > 0 ? ` · ${t('savings.cacheHit')} ${row.cacheHitRate === null ? '–' : `${Math.round(row.cacheHitRate * 100)}%`}` : ''}
128
+ </span>
129
+ <span className={css.savingsMuted}>{fmt(row.net.exact)}</span>
130
+ </div>
131
+ ))}
132
+ </div>
133
+ ) : null}
134
+ {snap.perComponent.length > 0 ? (
135
+ <div className={css.savingsBreakdown}>
136
+ {snap.perComponent.slice(0, 6).map((row) => (
137
+ <div key={`${row.kind}:${row.component}:${row.basis}`} className={css.savingsRow}>
138
+ <span className={css.savingsMuted}>
139
+ {row.kind === 'offset' ? '−' : '+'} {row.component}
140
+ <small> ({row.basis === 'exact-tokenizer' ? t('savings.basisExact') : t('savings.basisEstimated')})</small>
141
+ </span>
142
+ <span className={css.savingsMuted}>{fmt(row.tokens)}</span>
143
+ </div>
144
+ ))}
145
+ </div>
146
+ ) : null}
147
+ <div className={css.savingsNote}>{t('savings.basisNote')}</div>
148
+ </div>
149
+ )
150
+ }