dsh-context-compression-improved 0.8.0-beta.4 → 0.8.0-beta.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.
- package/CHANGELOG.md +13 -0
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +22 -0
- package/packages/selector/lib/client.js +528 -3
- package/packages/selector/lib/{intent-gate.js → config.js} +153 -136
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +215 -50
- package/packages/selector/lib/profiles.d.ts +6 -0
- package/packages/selector/lib/pruner.d.ts +6 -0
- package/packages/selector/lib/pruner.js +1 -1
- package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +1 -0
- package/packages/selector/src/client/decode.ts +5 -1
- package/packages/selector/src/client/index.ts +37 -0
- package/packages/selector/src/client/locales/de.ts +21 -0
- package/packages/selector/src/client/locales/es.ts +21 -0
- package/packages/selector/src/client/locales/fr.ts +21 -0
- package/packages/selector/src/client/locales/it.ts +21 -0
- package/packages/selector/src/client/locales/ja.ts +21 -0
- package/packages/selector/src/client/locales/ko.ts +21 -0
- package/packages/selector/src/client/locales/ru.ts +21 -0
- package/packages/selector/src/client/locales.ts +42 -0
- package/packages/selector/src/client/monitor-fab.ts +307 -0
- package/packages/selector/src/client/settings-section.tsx +9 -2
- package/packages/selector/src/index.ts +126 -60
- package/packages/selector/src/profiles.ts +17 -0
- package/packages/selector/src/runtime/config.ts +26 -1
- package/packages/selector/src/runtime/monitor.ts +149 -0
- package/packages/selector/src/runtime/types.ts +7 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +8 -6
- package/packages/selector/tests/monitor-fab.client.spec.ts +117 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +236 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +1 -1
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compression monitor surface for the floating panel (FAB, task: cci-monitor-fab).
|
|
3
|
+
*
|
|
4
|
+
* Three pieces, one module:
|
|
5
|
+
* - `buildMonitorSnapshot`: the savings snapshot (reused verbatim from the
|
|
6
|
+
* ledger — no second accounting) plus the turn-tail intent-summary block
|
|
7
|
+
* (override / observed flag / gate constants / last fold);
|
|
8
|
+
* - `applySessionOverride`: the `/ctx-summary` override state machine,
|
|
9
|
+
* addressed by session id — the panel buttons drive the same state the
|
|
10
|
+
* command drives, never a second one;
|
|
11
|
+
* - `estimateSavingsPricing`: moved here from the entry (the savings route
|
|
12
|
+
* and the monitor route share it; keeping it next to the monitor payload
|
|
13
|
+
* avoids a runtime → entry import cycle).
|
|
14
|
+
*
|
|
15
|
+
* The monitor route itself stays in the entry (`registerMonitorRoute`),
|
|
16
|
+
* mirroring the savings/estimator registrars: all webServer wiring lives in
|
|
17
|
+
* one place, the data plane lives here.
|
|
18
|
+
*
|
|
19
|
+
* Contract discipline: the published `/savings` route contract is frozen
|
|
20
|
+
* (estimator-route spec encodes it) — the monitor aggregates but never
|
|
21
|
+
* reshapes it; new fields attach under `intent` / `sessionScope`.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Current host model-group selection, when the service exposes one. */
|
|
25
|
+
export interface AgentDefaultModelLike {
|
|
26
|
+
currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
import { priceOfficialDeepSeekUsage } from './deepseek-official-pricing.ts'
|
|
30
|
+
import { getSavingsLedger, type SavingsLedger, type SavingsSnapshot } from './savings.ts'
|
|
31
|
+
import {
|
|
32
|
+
getLastIntentFold,
|
|
33
|
+
getObservedIntentEnabled,
|
|
34
|
+
getSummaryOverride,
|
|
35
|
+
setSummaryOverride,
|
|
36
|
+
type IntentFoldRecord,
|
|
37
|
+
} from './tokenpilot/advisor-state.ts'
|
|
38
|
+
import { INTENT_GATE_FLOOR_FRACTION, INTENT_GATE_GROWTH_TOKENS } from './tokenpilot/intent-gate.ts'
|
|
39
|
+
|
|
40
|
+
export interface MonitorIntentBlock {
|
|
41
|
+
/** Session-scoped override; absent = settings-driven. */
|
|
42
|
+
override: 'on' | 'off' | undefined
|
|
43
|
+
/** Settings flag as last observed by the gate; absent = gate not evaluated yet. */
|
|
44
|
+
observedEnabled: boolean | undefined
|
|
45
|
+
gate: { floorFraction: number, growthTokens: number }
|
|
46
|
+
lastFold: IntentFoldRecord | undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type MonitorSnapshot = SavingsSnapshot & {
|
|
50
|
+
intent: MonitorIntentBlock
|
|
51
|
+
/** The session the snapshot was filtered to; `null` = all-sessions aggregate. */
|
|
52
|
+
sessionScope: string | null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
57
|
+
* injectable so tests seed a private instance instead of the process
|
|
58
|
+
* singleton.
|
|
59
|
+
*/
|
|
60
|
+
export function buildMonitorSnapshot(
|
|
61
|
+
sessionId?: string,
|
|
62
|
+
ledger: SavingsLedger = getSavingsLedger(),
|
|
63
|
+
): MonitorSnapshot {
|
|
64
|
+
const override = getSummaryOverride(sessionId ?? '')
|
|
65
|
+
return {
|
|
66
|
+
...ledger.snapshot(sessionId),
|
|
67
|
+
intent: {
|
|
68
|
+
override,
|
|
69
|
+
observedEnabled: getObservedIntentEnabled(sessionId ?? ''),
|
|
70
|
+
gate: { floorFraction: INTENT_GATE_FLOOR_FRACTION, growthTokens: INTENT_GATE_GROWTH_TOKENS },
|
|
71
|
+
lastFold: getLastIntentFold(sessionId ?? ''),
|
|
72
|
+
},
|
|
73
|
+
sessionScope: sessionId ?? null,
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type SessionOverrideAction = 'on' | 'off' | 'clear'
|
|
78
|
+
|
|
79
|
+
export function isSessionOverrideAction(value: unknown): value is SessionOverrideAction {
|
|
80
|
+
return value === 'on' || value === 'off' || value === 'clear'
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
85
|
+
* session, `clear` returns it to settings-driven. The resulting override is
|
|
86
|
+
* handed back so the route can echo the post-action truth.
|
|
87
|
+
*/
|
|
88
|
+
export function applySessionOverride(
|
|
89
|
+
sessionId: string,
|
|
90
|
+
action: SessionOverrideAction,
|
|
91
|
+
): { override: 'on' | 'off' | undefined } {
|
|
92
|
+
setSummaryOverride(sessionId, action === 'clear' ? undefined : action)
|
|
93
|
+
return { override: getSummaryOverride(sessionId) }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
98
|
+
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
99
|
+
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
100
|
+
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
101
|
+
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
102
|
+
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
103
|
+
*/
|
|
104
|
+
export function estimateSavingsPricing(readService: (name: string) => unknown, snapshot: {
|
|
105
|
+
startedAt: string
|
|
106
|
+
net: { exact: number; estimated: number }
|
|
107
|
+
usage: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }
|
|
108
|
+
}): { currency: string; actualCost?: string | undefined; estimatedSavedCost?: string | undefined } | undefined {
|
|
109
|
+
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return undefined
|
|
110
|
+
const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
|
|
111
|
+
const selection = defaults?.currentSelection?.()
|
|
112
|
+
const provider = typeof selection?.provider === 'string' ? selection.provider : ''
|
|
113
|
+
const modelId = typeof selection?.model === 'string' ? selection.model : ''
|
|
114
|
+
if (provider !== 'deepseek-official') return undefined
|
|
115
|
+
const now = new Date()
|
|
116
|
+
const startedAt = new Date(snapshot.startedAt)
|
|
117
|
+
const completedAt = now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
118
|
+
const base = {
|
|
119
|
+
provider,
|
|
120
|
+
baseUrlClass: 'official-public',
|
|
121
|
+
apiRoute: 'chat-completions',
|
|
122
|
+
modelId,
|
|
123
|
+
currency: 'USD',
|
|
124
|
+
startedAt,
|
|
125
|
+
completedAt,
|
|
126
|
+
} as const
|
|
127
|
+
const actual = priceOfficialDeepSeekUsage({
|
|
128
|
+
...base,
|
|
129
|
+
usage: {
|
|
130
|
+
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
131
|
+
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
132
|
+
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens)),
|
|
133
|
+
},
|
|
134
|
+
})
|
|
135
|
+
const saved = snapshot.net.exact > 0
|
|
136
|
+
? priceOfficialDeepSeekUsage({
|
|
137
|
+
...base,
|
|
138
|
+
usage: { cacheReadTokens: 0, cacheMissTokens: Math.round(snapshot.net.exact), outputTokens: 0 },
|
|
139
|
+
})
|
|
140
|
+
: undefined
|
|
141
|
+
const decimalOf = (cost: typeof actual): string | undefined =>
|
|
142
|
+
cost.kind === 'exact' ? cost.decimal : cost.kind === 'range' ? cost.minimum.decimal : undefined
|
|
143
|
+
if (actual.kind === 'unpriced' && (saved === undefined || saved.kind === 'unpriced')) return undefined
|
|
144
|
+
return {
|
|
145
|
+
currency: 'USD',
|
|
146
|
+
...(actual.kind === 'unpriced' ? {} : { actualCost: decimalOf(actual) }),
|
|
147
|
+
...(saved === undefined || saved.kind === 'unpriced' ? {} : { estimatedSavedCost: decimalOf(saved) }),
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -141,6 +141,11 @@ export interface IntentSummarySettings {
|
|
|
141
141
|
enabled: boolean
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
+
/** Floating compression-monitor panel (FAB); visibility switch. */
|
|
145
|
+
export interface MonitorPanelSettings {
|
|
146
|
+
enabled: boolean
|
|
147
|
+
}
|
|
148
|
+
|
|
144
149
|
/**
|
|
145
150
|
* Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
|
|
146
151
|
* Absent fields inherit the preset defaults; the section is only meaningful
|
|
@@ -183,6 +188,8 @@ export interface ContextCompressionSettings {
|
|
|
183
188
|
codeSkeleton: CodeSkeletonSettings
|
|
184
189
|
/** Turn-tail intent-summary gate snapped independently of `profile`. */
|
|
185
190
|
intentSummary: IntentSummarySettings
|
|
191
|
+
/** Floating compression-monitor panel (FAB); absent inherits hidden. */
|
|
192
|
+
monitorPanel?: MonitorPanelSettings
|
|
186
193
|
/** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
|
|
187
194
|
presetOptions?: PresetOptionsSettings
|
|
188
195
|
}
|
|
@@ -17,6 +17,8 @@ const CATALOG_ROUTE = '/api/dsh-context-compression-improved/estimator-catalog'
|
|
|
17
17
|
const LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/estimator-catalog'
|
|
18
18
|
const SAVINGS_ROUTE = '/api/dsh-context-compression-improved/savings'
|
|
19
19
|
const SAVINGS_LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/savings'
|
|
20
|
+
const MONITOR_ROUTE = '/api/dsh-context-compression-improved/monitor'
|
|
21
|
+
const MONITOR_LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/monitor'
|
|
20
22
|
|
|
21
23
|
interface RegisteredRoute {
|
|
22
24
|
kind: string
|
|
@@ -106,7 +108,7 @@ describe('estimator catalog route registration', () => {
|
|
|
106
108
|
apply(runtime, { estimatorCatalogRoute: true })
|
|
107
109
|
await settle()
|
|
108
110
|
|
|
109
|
-
expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
|
|
111
|
+
expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE])
|
|
110
112
|
expect(routes.every(route => route.kind === 'exact')).toBe(true)
|
|
111
113
|
})
|
|
112
114
|
|
|
@@ -122,7 +124,7 @@ describe('estimator catalog route registration', () => {
|
|
|
122
124
|
await mountWebServer(runtime, routes)
|
|
123
125
|
await settle()
|
|
124
126
|
|
|
125
|
-
expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
|
|
127
|
+
expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE])
|
|
126
128
|
})
|
|
127
129
|
|
|
128
130
|
it('registers nothing twice when the estimator services arrive later', async () => {
|
|
@@ -176,9 +178,9 @@ describe('estimator catalog route registration', () => {
|
|
|
176
178
|
expect(JSON.parse(String(response.body))).toMatchObject({ ok: true, providers: [] })
|
|
177
179
|
})
|
|
178
180
|
|
|
179
|
-
it('without the estimator opt-in only the always-on savings
|
|
180
|
-
// savings 路由是有意常开的只读面(纯 token
|
|
181
|
-
// catalog 才是 opt-in 行。默认面 = 恰好两条 savings 前缀。
|
|
181
|
+
it('without the estimator opt-in only the always-on read routes register (savings + monitor)', async () => {
|
|
182
|
+
// savings 与 monitor 路由是有意常开的只读面(纯 token 聚合与折叠状态,无会话内容);estimator
|
|
183
|
+
// catalog 才是 opt-in 行。默认面 = 恰好两条 savings 前缀 + 两条 monitor 前缀。
|
|
182
184
|
const routes: RegisteredRoute[] = []
|
|
183
185
|
const runtime = new Context()
|
|
184
186
|
ctx = runtime
|
|
@@ -187,6 +189,6 @@ describe('estimator catalog route registration', () => {
|
|
|
187
189
|
apply(runtime, { presetOverlay: false })
|
|
188
190
|
await settle()
|
|
189
191
|
|
|
190
|
-
expect(routes.map(route => route.path)).toEqual([SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
|
|
192
|
+
expect(routes.map(route => route.path)).toEqual([SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE, MONITOR_LEGACY_ROUTE, MONITOR_ROUTE])
|
|
191
193
|
})
|
|
192
194
|
})
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 压缩监控浮动球(FAB)客户端单测——骨架来自 pm `d29bcb1^` 撤下的
|
|
3
|
+
* longtask-fab(计划 cci-monitor-fab task_3.1-3.4),数据层为注入依赖,
|
|
4
|
+
* 本文件自断言消费侧行为。真实时钟 + initialDelayMs=1,不用假时钟
|
|
5
|
+
* (jsdom × fake-timers 的 async advance 有已知坑)。
|
|
6
|
+
*/
|
|
7
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
8
|
+
import { initMonitorFab, type MonitorFabDeps, type MonitorSnapshotPayload } from '../src/client/monitor-fab.ts'
|
|
9
|
+
|
|
10
|
+
const FAB_ID = 'dsh-cci-monitor-fab'
|
|
11
|
+
|
|
12
|
+
function snapshotPatch(patch: Partial<MonitorSnapshotPayload> = {}): MonitorSnapshotPayload {
|
|
13
|
+
return {
|
|
14
|
+
ok: true,
|
|
15
|
+
startedAt: new Date().toISOString(),
|
|
16
|
+
gross: { exact: 10_000, estimated: 0 },
|
|
17
|
+
offsets: { exact: 1_200, estimated: 0 },
|
|
18
|
+
net: { exact: 8_800, estimated: 0 },
|
|
19
|
+
usage: { requests: 5, cacheHitRate: 0.812 },
|
|
20
|
+
pricing: { currency: 'USD', actualCost: '0.12', estimatedSavedCost: '1.30' },
|
|
21
|
+
intent: { override: undefined, observedEnabled: false, gate: { floorFraction: 0.45, growthTokens: 50_000 }, lastFold: undefined },
|
|
22
|
+
recentOffsets: [{ component: 'fresh', tokens: 1_200 }],
|
|
23
|
+
sessionScope: null,
|
|
24
|
+
...patch,
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function makeDeps(patch: Partial<MonitorFabDeps> & { snapshots?: MonitorSnapshotPayload[] } = {}): MonitorFabDeps & {
|
|
29
|
+
snapshots: MonitorSnapshotPayload[]
|
|
30
|
+
overrides: Array<{ sessionId: string | undefined, action: 'on' | 'off' | 'clear' }>
|
|
31
|
+
} {
|
|
32
|
+
const deps: MonitorFabDeps & {
|
|
33
|
+
snapshots: MonitorSnapshotPayload[]
|
|
34
|
+
overrides: Array<{ sessionId: string | undefined, action: 'on' | 'off' | 'clear' }>
|
|
35
|
+
} = {
|
|
36
|
+
t: (key: string) => key,
|
|
37
|
+
sessionIdOf: () => undefined,
|
|
38
|
+
enabledOf: () => true,
|
|
39
|
+
fetchSnapshot: vi.fn(async () => deps.snapshots[deps.snapshots.length - 1]!),
|
|
40
|
+
applyOverride: vi.fn(async (_sessionId: string | undefined, action: 'on' | 'off' | 'clear') => {
|
|
41
|
+
deps.overrides.push({ sessionId: undefined, action })
|
|
42
|
+
}),
|
|
43
|
+
snapshots: [snapshotPatch()],
|
|
44
|
+
overrides: [],
|
|
45
|
+
initialDelayMs: 1,
|
|
46
|
+
}
|
|
47
|
+
return Object.assign(deps, patch)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 真实时钟下等条件成立(轮询 1ms 一轮,上限 500ms)。 */
|
|
51
|
+
async function waitFor(predicate: () => boolean): Promise<void> {
|
|
52
|
+
const deadline = Date.now() + 500
|
|
53
|
+
while (!predicate()) {
|
|
54
|
+
if (Date.now() > deadline) throw new Error('waitFor timeout')
|
|
55
|
+
await new Promise(resolve => setTimeout(resolve, 5))
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
afterEach(() => {
|
|
60
|
+
document.body.innerHTML = ''
|
|
61
|
+
localStorage.clear()
|
|
62
|
+
vi.restoreAllMocks()
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
describe('monitor fab (body-level overlay)', () => {
|
|
66
|
+
it('mounts idempotently — double init keeps a single FAB', () => {
|
|
67
|
+
const deps = makeDeps()
|
|
68
|
+
initMonitorFab(deps)
|
|
69
|
+
initMonitorFab(deps)
|
|
70
|
+
expect(document.querySelectorAll(`#${FAB_ID}`).length).toBe(1)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('enabled gate hides the ball and suppresses polling', async () => {
|
|
74
|
+
const fetchSnapshot = vi.fn(async () => snapshotPatch())
|
|
75
|
+
initMonitorFab(makeDeps({ enabledOf: () => false, fetchSnapshot, initialDelayMs: 5 }))
|
|
76
|
+
const fab = document.getElementById(FAB_ID) as HTMLElement
|
|
77
|
+
await waitFor(() => fab.style.display === 'none')
|
|
78
|
+
expect(fetchSnapshot).not.toHaveBeenCalled()
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it('enabled: ball visible, first tick renders the snapshot', async () => {
|
|
82
|
+
initMonitorFab(makeDeps())
|
|
83
|
+
const fab = document.getElementById(FAB_ID) as HTMLElement
|
|
84
|
+
await waitFor(() => fab.style.display === 'block')
|
|
85
|
+
const net = document.querySelector('[data-net]') as HTMLElement
|
|
86
|
+
expect(net.textContent).toBe('8,800')
|
|
87
|
+
expect(fab.classList.contains('lit')).toBe(false)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('negative net lights the ball (负节省警示)', async () => {
|
|
91
|
+
initMonitorFab(makeDeps({ snapshots: [snapshotPatch({ net: { exact: -800, estimated: 0 } })] }))
|
|
92
|
+
await waitFor(() => (document.getElementById(FAB_ID) as HTMLElement).classList.contains('lit'))
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it('fetch failure flips the stale marker without throwing', async () => {
|
|
96
|
+
initMonitorFab(makeDeps({ fetchSnapshot: vi.fn(async () => { throw new Error('down') }) }))
|
|
97
|
+
await waitFor(() => document.querySelector('[data-stale]')?.classList.contains('show') === true)
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
it('override buttons drive applyOverride then refetch', async () => {
|
|
101
|
+
const deps = makeDeps()
|
|
102
|
+
initMonitorFab(deps)
|
|
103
|
+
await waitFor(() => (document.querySelector('[data-overoff]') as HTMLButtonElement)?.disabled === false)
|
|
104
|
+
;(document.querySelector('[data-overoff]') as HTMLButtonElement).click()
|
|
105
|
+
await waitFor(() => deps.overrides.length === 1)
|
|
106
|
+
expect(deps.overrides).toEqual([{ sessionId: undefined, action: 'off' }])
|
|
107
|
+
await waitFor(() => (deps.fetchSnapshot as ReturnType<typeof vi.fn>).mock.calls.length >= 2)
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it('position persists across drag-free re-init via localStorage', () => {
|
|
111
|
+
localStorage.setItem('dsh.cci.monitor.pos', JSON.stringify({ x: 40, y: 60 }))
|
|
112
|
+
initMonitorFab(makeDeps())
|
|
113
|
+
const fab = document.getElementById(FAB_ID) as HTMLElement
|
|
114
|
+
expect(fab.style.left).toBe('40px')
|
|
115
|
+
expect(fab.style.top).toBe('60px')
|
|
116
|
+
})
|
|
117
|
+
})
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { parseContextCompressionSettings, DEFAULT_CONTEXT_COMPRESSION_SETTINGS } from '../../src/runtime/config.ts'
|
|
3
|
+
import { SavingsLedger } from '../../src/runtime/savings.ts'
|
|
4
|
+
import {
|
|
5
|
+
applySessionOverride,
|
|
6
|
+
buildMonitorSnapshot,
|
|
7
|
+
estimateSavingsPricing,
|
|
8
|
+
isSessionOverrideAction,
|
|
9
|
+
} from '../../src/runtime/monitor.ts'
|
|
10
|
+
import { getSummaryOverride } from '../../src/runtime/tokenpilot/advisor-state.ts'
|
|
11
|
+
|
|
12
|
+
/** 每用例独立 sessionId:advisor-state 的覆盖表是模块级,防用例间串扰。 */
|
|
13
|
+
let seq = 0
|
|
14
|
+
const uniqueSession = (): string => `monitor-spec-${++seq}`
|
|
15
|
+
|
|
16
|
+
afterEach(() => {
|
|
17
|
+
vi.restoreAllMocks()
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
describe('buildMonitorSnapshot', () => {
|
|
21
|
+
it('savings aggregate plus the intent control block, defaults lossless', () => {
|
|
22
|
+
const snap = buildMonitorSnapshot(undefined, new SavingsLedger())
|
|
23
|
+
expect(snap.gross.exact).toBe(0)
|
|
24
|
+
expect(snap.sessionScope).toBeNull()
|
|
25
|
+
expect(snap.intent.override).toBeUndefined()
|
|
26
|
+
expect(snap.intent.observedEnabled).toBeUndefined()
|
|
27
|
+
expect(snap.intent.gate).toEqual({ floorFraction: 0.45, growthTokens: 50_000 })
|
|
28
|
+
expect(snap.intent.lastFold).toBeUndefined()
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('session filter scopes the savings rows and the control block', () => {
|
|
32
|
+
const ledger = new SavingsLedger()
|
|
33
|
+
ledger.recordSaving({
|
|
34
|
+
sessionId: 's1',
|
|
35
|
+
component: 'fresh',
|
|
36
|
+
tokensBefore: 10_000,
|
|
37
|
+
tokensAfter: 2_000,
|
|
38
|
+
basis: 'exact-tokenizer',
|
|
39
|
+
sourceSeq: 1,
|
|
40
|
+
})
|
|
41
|
+
const scoped = buildMonitorSnapshot('s1', ledger)
|
|
42
|
+
expect(scoped.sessionScope).toBe('s1')
|
|
43
|
+
expect(scoped.gross.exact).toBe(8_000)
|
|
44
|
+
const other = buildMonitorSnapshot('s2', ledger)
|
|
45
|
+
expect(other.gross.exact).toBe(0)
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('reuses the ledger verbatim — no second accounting', () => {
|
|
49
|
+
const ledger = new SavingsLedger()
|
|
50
|
+
ledger.recordSaving({
|
|
51
|
+
sessionId: 's1',
|
|
52
|
+
component: 'fresh',
|
|
53
|
+
tokensBefore: 1_000,
|
|
54
|
+
tokensAfter: 100,
|
|
55
|
+
basis: 'exact-tokenizer',
|
|
56
|
+
sourceSeq: 2,
|
|
57
|
+
originalText: 'x\n'.repeat(400),
|
|
58
|
+
})
|
|
59
|
+
const monitor = buildMonitorSnapshot('s1', ledger)
|
|
60
|
+
expect(monitor).toMatchObject(ledger.snapshot('s1'))
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
describe('applySessionOverride (the /ctx-summary state machine)', () => {
|
|
65
|
+
it('pins on/off and echoes the post-action truth', () => {
|
|
66
|
+
const sessionId = uniqueSession()
|
|
67
|
+
expect(applySessionOverride(sessionId, 'on').override).toBe('on')
|
|
68
|
+
expect(getSummaryOverride(sessionId)).toBe('on')
|
|
69
|
+
expect(applySessionOverride(sessionId, 'off').override).toBe('off')
|
|
70
|
+
expect(getSummaryOverride(sessionId)).toBe('off')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('clear returns the session to settings-driven', () => {
|
|
74
|
+
const sessionId = uniqueSession()
|
|
75
|
+
applySessionOverride(sessionId, 'off')
|
|
76
|
+
expect(applySessionOverride(sessionId, 'clear').override).toBeUndefined()
|
|
77
|
+
expect(getSummaryOverride(sessionId)).toBeUndefined()
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it('isSessionOverrideAction narrows exactly the three actions', () => {
|
|
81
|
+
expect(isSessionOverrideAction('on')).toBe(true)
|
|
82
|
+
expect(isSessionOverrideAction('off')).toBe(true)
|
|
83
|
+
expect(isSessionOverrideAction('clear')).toBe(true)
|
|
84
|
+
expect(isSessionOverrideAction('status')).toBe(false)
|
|
85
|
+
expect(isSessionOverrideAction(42)).toBe(false)
|
|
86
|
+
})
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
describe('estimateSavingsPricing (moved from the entry — shared by savings and monitor routes)', () => {
|
|
90
|
+
const snapshot = {
|
|
91
|
+
startedAt: new Date().toISOString(),
|
|
92
|
+
net: { exact: 4_200, estimated: 0 },
|
|
93
|
+
usage: { requests: 3, inputTokens: 1_000, outputTokens: 500, cacheReadTokens: 200, cacheWriteTokens: 100 },
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
it('third-party routes fail closed to no pricing', () => {
|
|
97
|
+
const readService = (): unknown => ({ currentSelection: () => ({ provider: 'local-35b', model: 'Qwen3.6-35B-A3B' }) })
|
|
98
|
+
expect(estimateSavingsPricing(readService, snapshot)).toBeUndefined()
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it('official routes carry actual cost and the labeled saved-cost estimate', () => {
|
|
102
|
+
const readService = (): unknown => ({ currentSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-v4-flash' }) })
|
|
103
|
+
const pricing = estimateSavingsPricing(readService, snapshot)
|
|
104
|
+
expect(pricing?.currency).toBe('USD')
|
|
105
|
+
expect(typeof pricing?.actualCost).toBe('string')
|
|
106
|
+
expect(typeof pricing?.estimatedSavedCost).toBe('string')
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
it('an empty ledger prices nothing', () => {
|
|
110
|
+
const readService = (): unknown => ({ currentSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-v4-flash' }) })
|
|
111
|
+
expect(estimateSavingsPricing(readService, {
|
|
112
|
+
startedAt: new Date().toISOString(),
|
|
113
|
+
net: { exact: 0, estimated: 0 },
|
|
114
|
+
usage: { requests: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 },
|
|
115
|
+
})).toBeUndefined()
|
|
116
|
+
})
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
121
|
+
import { registerMonitorRoute } from '../../src/index.ts'
|
|
122
|
+
|
|
123
|
+
/** Fake webServer: captures exact-path handlers; fake ctx wires direct arrival. */
|
|
124
|
+
function mountMonitorRoute(): { handler: (req: unknown, res: unknown) => void } {
|
|
125
|
+
let handler: (req: unknown, res: unknown) => void = () => {}
|
|
126
|
+
const webServer = { register: (def: { path: string, handler: typeof handler }) => { handler = def.handler; return () => undefined } }
|
|
127
|
+
const ctx = {
|
|
128
|
+
get: (name: string) => (name === 'webServer' ? webServer : undefined),
|
|
129
|
+
inject: (deps: string[], cb: (injected: Record<string, unknown>) => void) => cb({ webServer }),
|
|
130
|
+
effect: () => undefined,
|
|
131
|
+
} as unknown as Context
|
|
132
|
+
registerMonitorRoute(ctx)
|
|
133
|
+
return { handler }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
interface CapturedResponse {
|
|
137
|
+
status: number
|
|
138
|
+
body: Record<string, unknown>
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function fakeRes(): { res: unknown, captured: CapturedResponse } {
|
|
142
|
+
const captured = {} as CapturedResponse
|
|
143
|
+
const res = {
|
|
144
|
+
writeHead: (status: number) => { captured.status = status },
|
|
145
|
+
end: (body?: string) => { captured.body = JSON.parse(body ?? '{}') as Record<string, unknown> },
|
|
146
|
+
}
|
|
147
|
+
return { res, captured }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function fakeReq(url: string, method: string, body?: string): unknown {
|
|
151
|
+
return {
|
|
152
|
+
url,
|
|
153
|
+
method,
|
|
154
|
+
on: (event: string, cb: (chunk?: Buffer) => void) => {
|
|
155
|
+
if (event === 'data' && body !== undefined) cb(Buffer.from(body, 'utf8'))
|
|
156
|
+
if (event === 'end') cb()
|
|
157
|
+
},
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
describe('monitor route (GET snapshot / POST override)', () => {
|
|
162
|
+
const PATH = '/api/dsh-context-compression-improved/monitor'
|
|
163
|
+
const { handler } = mountMonitorRoute()
|
|
164
|
+
|
|
165
|
+
it('GET returns ok + savings + intent block scoped to the query session', () => {
|
|
166
|
+
const { res, captured } = fakeRes()
|
|
167
|
+
handler(fakeReq(`${PATH}?sessionId=route-s1`, 'GET'), res)
|
|
168
|
+
expect(captured.status).toBe(200)
|
|
169
|
+
expect(captured.body.ok).toBe(true)
|
|
170
|
+
expect(captured.body.sessionScope).toBe('route-s1')
|
|
171
|
+
expect((captured.body.intent as Record<string, unknown>).gate).toEqual({ floorFraction: 0.45, growthTokens: 50_000 })
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
it('POST drives the /ctx-summary override state machine', () => {
|
|
175
|
+
const sessionId = `route-${uniqueSession()}`
|
|
176
|
+
const { res, captured } = fakeRes()
|
|
177
|
+
handler(fakeReq(`${PATH}?sessionId=${sessionId}`, 'POST', '{"action":"off"}'), res)
|
|
178
|
+
expect(captured.status).toBe(200)
|
|
179
|
+
expect(captured.body).toEqual({ ok: true, override: 'off', sessionScope: sessionId })
|
|
180
|
+
expect(getSummaryOverride(sessionId)).toBe('off')
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
it('POST rejects an unknown action with 400 and touches no state', () => {
|
|
184
|
+
const sessionId = uniqueSession()
|
|
185
|
+
const { res, captured } = fakeRes()
|
|
186
|
+
handler(fakeReq(`${PATH}?sessionId=${sessionId}`, 'POST', '{"action":"boom"}'), res)
|
|
187
|
+
expect(captured.status).toBe(400)
|
|
188
|
+
expect(captured.body.ok).toBe(false)
|
|
189
|
+
expect(getSummaryOverride(sessionId)).toBeUndefined()
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
it('POST rejects a non-JSON body with 400', () => {
|
|
193
|
+
const { res, captured } = fakeRes()
|
|
194
|
+
handler(fakeReq(PATH, 'POST', 'not-json'), res)
|
|
195
|
+
expect(captured.status).toBe(400)
|
|
196
|
+
expect(captured.body.ok).toBe(false)
|
|
197
|
+
})
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
describe('monitorPanel settings parsing (schema surface, mirrors intentSummary cases)', () => {
|
|
201
|
+
const base = {
|
|
202
|
+
profile: 'balanced' as const,
|
|
203
|
+
custom: structuredClone(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.custom),
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
it('defaults to hidden', () => {
|
|
207
|
+
expect(DEFAULT_CONTEXT_COMPRESSION_SETTINGS.monitorPanel).toEqual({ enabled: false })
|
|
208
|
+
})
|
|
209
|
+
|
|
210
|
+
it('absent section inherits the default', () => {
|
|
211
|
+
const parsed = parseContextCompressionSettings({ ...base, autoCompact: { thresholdPercent: 80 } })
|
|
212
|
+
expect(parsed.monitorPanel).toEqual({ enabled: false })
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
it('accepts exactly { enabled: boolean }', () => {
|
|
216
|
+
const parsed = parseContextCompressionSettings({ ...base, monitorPanel: { enabled: true } })
|
|
217
|
+
expect(parsed.monitorPanel).toEqual({ enabled: true })
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
it('rejects extra keys (present-but-invalid is never silently defaulted)', () => {
|
|
221
|
+
expect(() => parseContextCompressionSettings({
|
|
222
|
+
...base, monitorPanel: { enabled: true, position: 'left' },
|
|
223
|
+
})).toThrow(/expected exactly "enabled"/)
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
it('rejects non-boolean enabled', () => {
|
|
227
|
+
expect(() => parseContextCompressionSettings({
|
|
228
|
+
...base, monitorPanel: { enabled: 'yes' },
|
|
229
|
+
})).toThrow(/monitorPanel\.enabled must be a boolean/)
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
it('rejects non-object section', () => {
|
|
233
|
+
expect(() => parseContextCompressionSettings({ ...base, monitorPanel: 'yes' }))
|
|
234
|
+
.toThrow(/monitorPanel must be a plain object/)
|
|
235
|
+
})
|
|
236
|
+
})
|
|
@@ -90,7 +90,7 @@ describe('settings-seat contract (standalone settings.section only)', () => {
|
|
|
90
90
|
expect((options['label'] as () => string)()).toBe('nav')
|
|
91
91
|
expect(typeof options['inject']).toBe('function')
|
|
92
92
|
const face = (options['inject'] as () => Record<string, unknown>)()
|
|
93
|
-
expect(Object.keys(face).sort()).toEqual(['hooks', 'saveAutoCompact', 'saveCodeSkeleton', 'saveCustom', 'saveIntentSummary', 'savePresetOptions', 'select', 'resetCustom'].sort())
|
|
93
|
+
expect(Object.keys(face).sort()).toEqual(['hooks', 'saveAutoCompact', 'saveCodeSkeleton', 'saveCustom', 'saveIntentSummary', 'saveMonitorPanel', 'savePresetOptions', 'select', 'resetCustom'].sort())
|
|
94
94
|
expect(component).toBe(ContextCompressionSettingsSection)
|
|
95
95
|
})
|
|
96
96
|
|
|
@@ -416,7 +416,7 @@ async function runOfficialCloneCliSmoke(referenceRoot, registry, upgradeFrom, ca
|
|
|
416
416
|
* ui-slot packages) the web bundler supplies, and that stack is verified
|
|
417
417
|
* from the built client libraries below.
|
|
418
418
|
*/
|
|
419
|
-
const HOST_PLANE_ENTRIES = ['index.js', 'pruner.js', '
|
|
419
|
+
const HOST_PLANE_ENTRIES = ['index.js', 'pruner.js', 'config.js', 'tail-trim.js', 'invariant.js']
|
|
420
420
|
|
|
421
421
|
/**
|
|
422
422
|
* Bare package names the installed package's host-plane runtime files import.
|
|
@@ -49,7 +49,7 @@ const INSTALLATION_PROVIDED_RUNTIME = new Set([
|
|
|
49
49
|
// stack (`react`, the ui-slot packages); its requires are reviewed from the
|
|
50
50
|
// built artifact further down instead.
|
|
51
51
|
const HOST_PLANE_ENTRIES = [
|
|
52
|
-
'lib/
|
|
52
|
+
'lib/config.js',
|
|
53
53
|
'lib/index.js',
|
|
54
54
|
'lib/invariant.js',
|
|
55
55
|
'lib/pruner.js',
|