dsh-context-compression-improved 0.9.8 → 0.9.9
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/.agents/plans/improve/checklist.md +32 -0
- package/.agents/plans/improve/findings.md +102 -0
- package/.agents/plans/improve/spec.md +53 -0
- package/.agents/plans/improve/tasks.md +70 -0
- package/CHANGELOG.md +4 -0
- package/README.md +14 -2
- package/README.zh.md +14 -2
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +16 -0
- package/packages/selector/lib/client.js +396 -117
- package/packages/selector/lib/index.js +829 -10
- package/packages/selector/lib/invariant.js +2 -1
- package/packages/selector/lib/pruner.d.ts +1 -1
- package/packages/selector/lib/pruner.js +77 -983
- package/packages/selector/lib/savings-integral.js +4515 -0
- package/packages/selector/lib/tail-trim.js +2 -90
- package/packages/selector/lib/tool-result.js +150 -0
- package/packages/selector/package.json +8 -4
- package/packages/selector/src/client/index.ts +15 -12
- package/packages/selector/src/client/locales/de.ts +20 -4
- package/packages/selector/src/client/locales/es.ts +20 -4
- package/packages/selector/src/client/locales/fr.ts +20 -4
- package/packages/selector/src/client/locales/it.ts +20 -4
- package/packages/selector/src/client/locales/ja.ts +20 -4
- package/packages/selector/src/client/locales/ko.ts +20 -4
- package/packages/selector/src/client/locales/ru.ts +20 -4
- package/packages/selector/src/client/locales.ts +40 -8
- package/packages/selector/src/client/monitor-fab.ts +80 -10
- package/packages/selector/src/client/savings-card.tsx +159 -40
- package/packages/selector/src/index.ts +236 -1
- package/packages/selector/src/pruner.ts +54 -8
- package/packages/selector/src/runtime/audit.ts +17 -0
- package/packages/selector/src/runtime/display-prefs.ts +98 -0
- package/packages/selector/src/runtime/monitor.ts +75 -0
- package/packages/selector/src/runtime/panel-command.ts +213 -0
- package/packages/selector/src/runtime/retrieve.ts +31 -12
- package/packages/selector/src/runtime/savings-integral.ts +117 -0
- package/packages/selector/src/runtime/savings-projection.ts +3 -0
- package/packages/selector/src/runtime/savings-verify.ts +446 -0
- package/packages/selector/src/runtime/savings.ts +122 -13
- package/packages/selector/src/runtime/session-file-decode.ts +523 -0
- package/packages/selector/src/runtime/stats-backfill.ts +541 -0
- package/packages/selector/src/runtime/stats-db.ts +492 -0
- package/packages/selector/src/runtime/stats-schema.ts +123 -0
- package/packages/selector/src/runtime/stats-sync.ts +302 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +7 -4
- package/packages/selector/tests/monitor-fab.client.spec.ts +83 -1
- package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +53 -0
- package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -1
- package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
- package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
- package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
- package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
- package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
- package/packages/selector/tests/runtime/stats-backfill.spec.ts +327 -0
- package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
- package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
- package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
- package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +15 -15
- package/pnpm-workspace.yaml +4 -0
- package/scripts/verify-release.mjs +5 -2
- package/vitest.config.ts +8 -0
- package/packages/selector/lib/config.js +0 -1777
- package/packages/selector/lib/host-generation.js +0 -62
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* live 写路径(T6–T9)单测:land/offset/usage 随写随刷对账、水位节流、
|
|
3
|
+
* dispose 残量出口与写失败可见性。
|
|
4
|
+
*
|
|
5
|
+
* 全部落临时目录库,绝不触碰真实 `~/.dsh`;对账口径 = 内存账本 snapshot()
|
|
6
|
+
* 与持久 claims 聚合逐列相等(spec T10 验收)。
|
|
7
|
+
*/
|
|
8
|
+
import { mkdtempSync, rmSync } from 'node:fs'
|
|
9
|
+
import { tmpdir } from 'node:os'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
12
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
13
|
+
import { createMessage } from '@deepseek-ai/dsh-llm'
|
|
14
|
+
import { Session, SessionId } from '@deepseek-ai/dsh-session'
|
|
15
|
+
import { SavingsLedger } from '../../src/runtime/savings.ts'
|
|
16
|
+
import { sessionEvents } from '../../src/runtime/session-events.ts'
|
|
17
|
+
import { closeStatsStore, ensureStatsStore, getStatsStore } from '../../src/runtime/stats-db.ts'
|
|
18
|
+
import {
|
|
19
|
+
cancelPendingUsageFlushes,
|
|
20
|
+
claimFromLand,
|
|
21
|
+
claimOffset,
|
|
22
|
+
flushUsage,
|
|
23
|
+
flushUsageOnDispose,
|
|
24
|
+
reclaimFromTailTrim,
|
|
25
|
+
scheduleUsageFlush,
|
|
26
|
+
} from '../../src/runtime/stats-sync.ts'
|
|
27
|
+
|
|
28
|
+
const dirs: string[] = []
|
|
29
|
+
|
|
30
|
+
function tempDbPath(name: string): string {
|
|
31
|
+
const dir = mkdtempSync(join(tmpdir(), `cci-sync-${name}-`))
|
|
32
|
+
dirs.push(dir)
|
|
33
|
+
return join(dir, 'stats.sqlite')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface ClaimRow {
|
|
37
|
+
session_id: string
|
|
38
|
+
seq: number
|
|
39
|
+
kind: string
|
|
40
|
+
component: string
|
|
41
|
+
basis: string
|
|
42
|
+
tokens: number
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readClaims(path: string): ClaimRow[] {
|
|
46
|
+
const db = new DatabaseSync(path)
|
|
47
|
+
try {
|
|
48
|
+
return db.prepare(
|
|
49
|
+
`SELECT session_id, seq, kind, component, basis, tokens FROM claims ORDER BY session_id, seq, kind, component`,
|
|
50
|
+
).all() as unknown as ClaimRow[]
|
|
51
|
+
} finally {
|
|
52
|
+
db.close()
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function readSessionRow(path: string, sessionId: string): { version: number; source: string } | undefined {
|
|
57
|
+
const db = new DatabaseSync(path)
|
|
58
|
+
try {
|
|
59
|
+
return db.prepare(`SELECT version, source FROM sessions WHERE session_id = ?`).get(sessionId) as unknown as { version: number; source: string } | undefined
|
|
60
|
+
} finally {
|
|
61
|
+
db.close()
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 最小会话构造:每条 assistant/message 带一份官方 usage。 */
|
|
66
|
+
function buildUsageSession(id: string, usages: { inputTokens: number; outputTokens: number; cacheReadTokens?: number; cacheWriteTokens?: number }[]): Session {
|
|
67
|
+
const session = Session.create(SessionId(id))
|
|
68
|
+
session.append('turn/start', { turn: 1 })
|
|
69
|
+
session.append('step/start', { turn: 1, step: 1 })
|
|
70
|
+
usages.forEach((usage, index) => {
|
|
71
|
+
session.append('assistant/message', {
|
|
72
|
+
stream: [],
|
|
73
|
+
turn: 1,
|
|
74
|
+
step: 1,
|
|
75
|
+
message: createMessage({
|
|
76
|
+
role: 'assistant',
|
|
77
|
+
content: [{ type: 'text', text: `answer ${String(index)}` }],
|
|
78
|
+
source: { kind: 'model', provider: 'deepseek', model: 'deepseek-v4-flash' },
|
|
79
|
+
}),
|
|
80
|
+
usage,
|
|
81
|
+
}, { surfaceOp: 'append' })
|
|
82
|
+
})
|
|
83
|
+
session.append('step/end', { turn: 1, step: 1 })
|
|
84
|
+
return session
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function openStore(path: string): Promise<void> {
|
|
88
|
+
const store = await ensureStatsStore(path)
|
|
89
|
+
if (store === null) throw new Error('no sqlite driver in this environment')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 会话末尾事件的绝对 seq(水位断言用)。 */
|
|
93
|
+
function lastEventSeq(session: Session): number {
|
|
94
|
+
const events = sessionEvents(session)
|
|
95
|
+
return Number(events[events.length - 1]?.seq ?? 0)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
afterEach(() => {
|
|
99
|
+
cancelPendingUsageFlushes()
|
|
100
|
+
closeStatsStore()
|
|
101
|
+
vi.restoreAllMocks()
|
|
102
|
+
vi.useRealTimers()
|
|
103
|
+
while (dirs.length > 0) {
|
|
104
|
+
const dir = dirs.pop()!
|
|
105
|
+
try { rmSync(dir, { recursive: true, force: true }) } catch { /* Windows 句柄释放滞后时尽力而为 */ }
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
describe('land/offset 随写随刷(T6:落库与内存账本对账)', () => {
|
|
110
|
+
it('land→落库→snapshot 对账一致;重放幂等零新增', async () => {
|
|
111
|
+
const path = tempDbPath('land')
|
|
112
|
+
await openStore(path)
|
|
113
|
+
const ledger = new SavingsLedger()
|
|
114
|
+
ledger.recordSaving({
|
|
115
|
+
sessionId: 's1',
|
|
116
|
+
component: 'fresh',
|
|
117
|
+
tokensBefore: 5_000,
|
|
118
|
+
tokensAfter: 800,
|
|
119
|
+
basis: 'exact-tokenizer',
|
|
120
|
+
sourceSeq: 7,
|
|
121
|
+
replacementSeq: 100,
|
|
122
|
+
})
|
|
123
|
+
claimFromLand({
|
|
124
|
+
sessionId: 's1',
|
|
125
|
+
component: 'fresh',
|
|
126
|
+
tokensBefore: 5_000,
|
|
127
|
+
tokensAfter: 800,
|
|
128
|
+
basis: 'exact-tokenizer',
|
|
129
|
+
replacementSeq: 100,
|
|
130
|
+
})
|
|
131
|
+
// 同点重放(如热重载后的重复 land 回执):PK 幂等,零新增
|
|
132
|
+
claimFromLand({
|
|
133
|
+
sessionId: 's1',
|
|
134
|
+
component: 'fresh',
|
|
135
|
+
tokensBefore: 5_000,
|
|
136
|
+
tokensAfter: 800,
|
|
137
|
+
basis: 'exact-tokenizer',
|
|
138
|
+
replacementSeq: 100,
|
|
139
|
+
})
|
|
140
|
+
const rows = readClaims(path)
|
|
141
|
+
expect(rows).toHaveLength(1)
|
|
142
|
+
expect(rows[0]).toMatchObject({ session_id: 's1', seq: 100, kind: 'saving', component: 'fresh', basis: 'exact-tokenizer', tokens: 4_200 })
|
|
143
|
+
// 持久聚合与内存 snapshot 逐列相等
|
|
144
|
+
const store = getStatsStore()!
|
|
145
|
+
const agg = store.perSessionAggregates().find(r => r.sessionId === 's1')
|
|
146
|
+
expect(agg?.gross.exact).toBe(ledger.snapshot('s1').gross.exact)
|
|
147
|
+
expect(agg?.net.exact).toBe(ledger.snapshot('s1').net.exact)
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
it('tokensRemoved ≤ 0 不入库(与内存账本同判据)', async () => {
|
|
151
|
+
const path = tempDbPath('land-zero')
|
|
152
|
+
await openStore(path)
|
|
153
|
+
claimFromLand({ sessionId: 's1', component: 'fresh', tokensBefore: 100, tokensAfter: 100, basis: 'characters', replacementSeq: 3 })
|
|
154
|
+
reclaimFromTailTrim({ sessionId: 's1', tokensBefore: 50, tokensAfter: 60, basis: 'characters', replacementSeq: 4 })
|
|
155
|
+
expect(readClaims(path)).toHaveLength(0)
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
it('tail-trim 组回收落 saving claim,component 固定枚举值', async () => {
|
|
159
|
+
const path = tempDbPath('tailtrim')
|
|
160
|
+
await openStore(path)
|
|
161
|
+
reclaimFromTailTrim({ sessionId: 's1', tokensBefore: 1_200, tokensAfter: 300, basis: 'characters', replacementSeq: 77 })
|
|
162
|
+
const rows = readClaims(path)
|
|
163
|
+
expect(rows).toHaveLength(1)
|
|
164
|
+
expect(rows[0]).toMatchObject({ seq: 77, kind: 'saving', component: 'tail-trim', tokens: 900 })
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
it('retrieve 抵消落 offset claim;同源事件反复召回首记幂等去重(定键口径)', async () => {
|
|
168
|
+
const path = tempDbPath('offset')
|
|
169
|
+
await openStore(path)
|
|
170
|
+
claimOffset({ sessionId: 's1', component: 'retrieve', tokens: 250, basis: 'characters', sourceSeq: 12 })
|
|
171
|
+
claimOffset({ sessionId: 's1', component: 'retrieve', tokens: 180, basis: 'characters', sourceSeq: 12 })
|
|
172
|
+
claimOffset({ sessionId: 's1', component: 'tailtrim-retrieve', tokens: 90, basis: 'characters', sourceSeq: 40 })
|
|
173
|
+
const rows = readClaims(path)
|
|
174
|
+
// (session_id, 源 seq, kind, component, basis) 主键:同源同组件重放去重;
|
|
175
|
+
// 不同 component(不同恢复面)分列。
|
|
176
|
+
expect(rows).toHaveLength(2)
|
|
177
|
+
expect(rows.map(r => [r.kind, r.component, r.seq, r.tokens])).toEqual([
|
|
178
|
+
['offset', 'retrieve', 12, 250],
|
|
179
|
+
['offset', 'tailtrim-retrieve', 40, 90],
|
|
180
|
+
])
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
it('store 未开(无驱动/降级)= 空转不抛,warn 由 stats-db 的降级门闩负责', () => {
|
|
184
|
+
expect(getStatsStore()).toBeNull()
|
|
185
|
+
expect(() => claimFromLand({ sessionId: 's1', component: 'fresh', tokensBefore: 10, tokensAfter: 1, basis: 'characters', replacementSeq: 1 })).not.toThrow()
|
|
186
|
+
expect(() => flushUsage(buildUsageSession('noop-open', [{ inputTokens: 1, outputTokens: 1 }]))).not.toThrow()
|
|
187
|
+
})
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
describe('usage claims(T8:按事件求和 + 秒级 debounce + 水位节流)', () => {
|
|
191
|
+
it('逐事件逐科目入账;二次 flush 零新增(水位节流);新事件只覆盖增量', async () => {
|
|
192
|
+
const path = tempDbPath('usage')
|
|
193
|
+
await openStore(path)
|
|
194
|
+
const session = buildUsageSession('u1', [
|
|
195
|
+
{ inputTokens: 100, outputTokens: 40, cacheReadTokens: 900 },
|
|
196
|
+
{ inputTokens: 200, outputTokens: 60 },
|
|
197
|
+
])
|
|
198
|
+
flushUsage(session)
|
|
199
|
+
const first = readClaims(path)
|
|
200
|
+
// 事件1:input/output/cacheRead 三科目;事件2:input/output 两科目
|
|
201
|
+
expect(first).toHaveLength(5)
|
|
202
|
+
expect(first.every(r => r.kind === 'usage' && r.basis === '')).toBe(true)
|
|
203
|
+
const sum = (component: string): number => first.filter(r => r.component === component).reduce((a, r) => a + r.tokens, 0)
|
|
204
|
+
expect(sum('input')).toBe(300)
|
|
205
|
+
expect(sum('output')).toBe(100)
|
|
206
|
+
expect(sum('cacheRead')).toBe(900)
|
|
207
|
+
// 水位已前推到最新事件 seq:重放零新增
|
|
208
|
+
const watermarkBefore = getStatsStore()!.getSessionWatermark('u1')
|
|
209
|
+
expect(watermarkBefore).toBe(lastEventSeq(session))
|
|
210
|
+
flushUsage(session)
|
|
211
|
+
expect(readClaims(path)).toHaveLength(5)
|
|
212
|
+
// 追加一条 usage 事件 → 下一次 flush 只补增量行
|
|
213
|
+
session.append('assistant/message', {
|
|
214
|
+
stream: [],
|
|
215
|
+
turn: 1,
|
|
216
|
+
step: 1,
|
|
217
|
+
message: createMessage({
|
|
218
|
+
role: 'assistant',
|
|
219
|
+
content: [{ type: 'text', text: 'answer 3' }],
|
|
220
|
+
source: { kind: 'model', provider: 'deepseek', model: 'deepseek-v4-flash' },
|
|
221
|
+
}),
|
|
222
|
+
usage: { inputTokens: 7, outputTokens: 9 },
|
|
223
|
+
}, { surfaceOp: 'append' })
|
|
224
|
+
flushUsage(session)
|
|
225
|
+
const after = readClaims(path)
|
|
226
|
+
expect(after).toHaveLength(7)
|
|
227
|
+
expect(getStatsStore()!.getSessionWatermark('u1')).toBe(lastEventSeq(session))
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
it('scheduleUsageFlush 一秒窗口内合并为一次扫描(debounce)', async () => {
|
|
231
|
+
const path = tempDbPath('usage-debounce')
|
|
232
|
+
await openStore(path)
|
|
233
|
+
const session = buildUsageSession('u2', [{ inputTokens: 10, outputTokens: 2 }])
|
|
234
|
+
vi.useFakeTimers()
|
|
235
|
+
scheduleUsageFlush(session)
|
|
236
|
+
scheduleUsageFlush(session)
|
|
237
|
+
expect(readClaims(path)).toHaveLength(0) // 窗口内未刷
|
|
238
|
+
await vi.advanceTimersByTimeAsync(1_000)
|
|
239
|
+
expect(readClaims(path).length).toBeGreaterThan(0) // 到期一次 flush
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
it('dispose 取消在途 debounce 立即 flush 残量,并标记 source=live(T9)', async () => {
|
|
243
|
+
const path = tempDbPath('dispose')
|
|
244
|
+
await openStore(path)
|
|
245
|
+
const session = buildUsageSession('u3', [{ inputTokens: 50, outputTokens: 10 }])
|
|
246
|
+
scheduleUsageFlush(session)
|
|
247
|
+
flushUsageOnDispose(session)
|
|
248
|
+
expect(readClaims(path).some(r => r.kind === 'usage')).toBe(true)
|
|
249
|
+
expect(readSessionRow(path, 'u3')?.source).toBe('live')
|
|
250
|
+
// 零 usage 会话 dispose 也落会话行(面板 live/backfill 归属)
|
|
251
|
+
const silent = Session.create(SessionId('u4'))
|
|
252
|
+
flushUsageOnDispose(silent)
|
|
253
|
+
expect(readSessionRow(path, 'u4')?.source).toBe('live')
|
|
254
|
+
})
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
describe('写失败可见性(T10:门闩 warn 恰一次且不阻断主路径)', () => {
|
|
258
|
+
it('recordClaims 注入抛错 → 多次调用只 warn 一次,调用方零异常', async () => {
|
|
259
|
+
const path = tempDbPath('fail')
|
|
260
|
+
await openStore(path)
|
|
261
|
+
const store = getStatsStore()!
|
|
262
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
|
263
|
+
vi.spyOn(store, 'recordClaims').mockImplementation(() => {
|
|
264
|
+
throw new Error('injected: disk full')
|
|
265
|
+
})
|
|
266
|
+
const input = { sessionId: 's1', component: 'fresh', tokensBefore: 900, tokensAfter: 100, basis: 'characters' as const, replacementSeq: 9 }
|
|
267
|
+
expect(() => claimFromLand(input)).not.toThrow()
|
|
268
|
+
expect(() => claimFromLand(input)).not.toThrow()
|
|
269
|
+
expect(() => claimOffset({ sessionId: 's1', component: 'retrieve', tokens: 10, basis: 'characters', sourceSeq: 3 })).not.toThrow()
|
|
270
|
+
expect(() => flushUsage(buildUsageSession('s9', [{ inputTokens: 1, outputTokens: 1 }]))).not.toThrow()
|
|
271
|
+
expect(warn).toHaveBeenCalledTimes(1)
|
|
272
|
+
expect(String(warn.mock.calls[0]?.[1])).toContain('disk full')
|
|
273
|
+
// 压缩主路径(内存账本)完全不受影响:recordSaving 照常入账
|
|
274
|
+
const ledger = new SavingsLedger()
|
|
275
|
+
ledger.recordSaving({ sessionId: 's1', component: 'fresh', tokensBefore: 900, tokensAfter: 100, basis: 'characters', sourceSeq: 1 })
|
|
276
|
+
expect(ledger.snapshot('s1').gross.estimated).toBe(800)
|
|
277
|
+
})
|
|
278
|
+
})
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* T28:节省卡片 per-session 面板(T26/T32)jsdom 规格——累计/省钱行、持久化
|
|
5
|
+
* 徽标与降级标注、displayPrefs 行开关与 compact、会话账本分页翻页。
|
|
6
|
+
* fetch 全局打桩:按 URL 分流 /savings 与 /savings/sessions。
|
|
7
|
+
*/
|
|
8
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
9
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
10
|
+
import { SavingsCard } from '../src/client/savings-card.tsx'
|
|
11
|
+
import { en } from '../src/client/locales.ts'
|
|
12
|
+
|
|
13
|
+
const t = (key: string) => en[key as keyof typeof en] ?? key
|
|
14
|
+
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
cleanup()
|
|
17
|
+
vi.unstubAllGlobals()
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
const SAVINGS_SNAPSHOT = {
|
|
21
|
+
ok: true,
|
|
22
|
+
startedAt: '2026-10-19T00:00:00.000Z',
|
|
23
|
+
sessions: 1,
|
|
24
|
+
gross: { exact: 1000, estimated: 0 },
|
|
25
|
+
offsets: { exact: 100, estimated: 0 },
|
|
26
|
+
net: { exact: 900, estimated: 0 },
|
|
27
|
+
perComponent: [],
|
|
28
|
+
recentOffsets: [],
|
|
29
|
+
usage: { requests: 3, inputTokens: 500, outputTokens: 100, cacheReadTokens: 400, cacheWriteTokens: 0, cacheHitRate: 0.8 },
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const INTEGRAL = { netExact: 2500, netEstimated: 0, cachedInput: 60_000, uncachedInput: 40_000, calls: 7 }
|
|
33
|
+
|
|
34
|
+
function sessionsPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
|
35
|
+
return {
|
|
36
|
+
ok: true,
|
|
37
|
+
persisted: { persisted: true, driver: 'node:sqlite' },
|
|
38
|
+
displayPrefs: { rows: { stock: true, total: true, money: true }, mode: 'full', focusSessionId: null },
|
|
39
|
+
total: 2,
|
|
40
|
+
offset: 0,
|
|
41
|
+
limit: 20,
|
|
42
|
+
integralTotal: INTEGRAL,
|
|
43
|
+
integralMoney: { decimal: '0.1', currency: 'USD' },
|
|
44
|
+
sessions: [
|
|
45
|
+
{ sessionId: 'aaaaaaaa-1', net: { exact: 1500, estimated: 0 }, integral: { ...INTEGRAL, netExact: 1500, calls: 4 }, source: 'live' },
|
|
46
|
+
{ sessionId: 'bbbbbbbb-2', net: { exact: 1000, estimated: 0 }, integral: { ...INTEGRAL, netExact: 1000, calls: 3 }, source: 'backfill' },
|
|
47
|
+
],
|
|
48
|
+
liveOnly: [],
|
|
49
|
+
...overrides,
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function stubFetch(savings: unknown, sessions: Record<string, unknown>): { calls: string[] } {
|
|
54
|
+
const calls: string[] = []
|
|
55
|
+
vi.stubGlobal('fetch', vi.fn(async (input: unknown) => {
|
|
56
|
+
const url = String(input)
|
|
57
|
+
calls.push(url)
|
|
58
|
+
if (url.includes('/savings/sessions')) {
|
|
59
|
+
return { ok: true, json: async () => sessions } as Response
|
|
60
|
+
}
|
|
61
|
+
return { ok: true, json: async () => savings } as Response
|
|
62
|
+
}))
|
|
63
|
+
return { calls }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function mountCard(): void {
|
|
67
|
+
render(<SavingsCard t={t} />)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
describe('savings card per-session panel (T26/T32)', () => {
|
|
71
|
+
it('渲染累计(按 N 次 call)/省钱行与持久化徽标', async () => {
|
|
72
|
+
stubFetch(SAVINGS_SNAPSHOT, sessionsPayload())
|
|
73
|
+
mountCard()
|
|
74
|
+
await waitFor(() => {
|
|
75
|
+
expect(screen.getByTestId('savings-cumulative')).toBeDefined()
|
|
76
|
+
expect(screen.getByTestId('savings-money')).toBeDefined()
|
|
77
|
+
expect(screen.getByTestId('savings-persisted').textContent).toContain('✓')
|
|
78
|
+
})
|
|
79
|
+
expect(screen.getByTestId('savings-cumulative').textContent).toContain('7')
|
|
80
|
+
expect(screen.getByTestId('savings-money').textContent).toContain('USD 0.1')
|
|
81
|
+
expect(screen.getByTestId('savings-session-list').textContent).toContain('aaaaaaaa')
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it('persisted:false → 降级标注', async () => {
|
|
85
|
+
stubFetch(SAVINGS_SNAPSHOT, sessionsPayload({ persisted: { persisted: false, reason: 'no-driver' } }))
|
|
86
|
+
mountCard()
|
|
87
|
+
await waitFor(() => {
|
|
88
|
+
expect(screen.getByTestId('savings-persisted').textContent).toContain('⚠')
|
|
89
|
+
})
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it('displayPrefs 行开关:stock off 隐藏存量,compact 隐藏分项', async () => {
|
|
93
|
+
stubFetch(SAVINGS_SNAPSHOT, sessionsPayload({
|
|
94
|
+
displayPrefs: { rows: { stock: false, total: true, money: true }, mode: 'compact', focusSessionId: 'aaaaaaaa-1' },
|
|
95
|
+
}))
|
|
96
|
+
mountCard()
|
|
97
|
+
await waitFor(() => {
|
|
98
|
+
expect(screen.queryByTestId('savings-stock-exact')).toBeNull()
|
|
99
|
+
expect(screen.queryByTestId('savings-cumulative')).not.toBeNull()
|
|
100
|
+
})
|
|
101
|
+
// 聚焦会话带 focus 标记
|
|
102
|
+
expect(screen.getByTestId('savings-session-list').textContent).toContain('focus')
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
it('分页:下一页以 offset=20 重取,上一页回到 0', async () => {
|
|
106
|
+
const many = Array.from({ length: 30 }, (_, index) => ({
|
|
107
|
+
sessionId: `sess-${String(index).padStart(3, '0')}`,
|
|
108
|
+
net: { exact: index, estimated: 0 },
|
|
109
|
+
integral: { ...INTEGRAL, calls: 1 },
|
|
110
|
+
source: 'backfill',
|
|
111
|
+
}))
|
|
112
|
+
const { calls } = stubFetch(SAVINGS_SNAPSHOT, sessionsPayload({ total: 30, sessions: many.slice(0, 20) }))
|
|
113
|
+
mountCard()
|
|
114
|
+
await waitFor(() => {
|
|
115
|
+
expect(screen.getByTestId('savings-page-next')).toBeDefined()
|
|
116
|
+
})
|
|
117
|
+
fireEvent.click(screen.getByTestId('savings-page-next'))
|
|
118
|
+
await waitFor(() => {
|
|
119
|
+
expect(calls.some(url => url.includes('offset=20'))).toBe(true)
|
|
120
|
+
})
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('存量与积分双空 → 空态', async () => {
|
|
124
|
+
stubFetch({ ...SAVINGS_SNAPSHOT, gross: { exact: 0, estimated: 0 }, offsets: { exact: 0, estimated: 0 }, net: { exact: 0, estimated: 0 } }, sessionsPayload({ integralTotal: { netExact: 0, netEstimated: 0, cachedInput: 0, uncachedInput: 0, calls: 0 }, sessions: [], integralMoney: undefined }))
|
|
125
|
+
mountCard()
|
|
126
|
+
await waitFor(() => {
|
|
127
|
+
expect(screen.getByText(t('savings.empty'))).toBeDefined()
|
|
128
|
+
})
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
it('存量/积分双空但账本有回填 → 不早退,账本照常渲染(空存量的历史节省可见)', async () => {
|
|
132
|
+
stubFetch({ ...SAVINGS_SNAPSHOT, gross: { exact: 0, estimated: 0 }, offsets: { exact: 0, estimated: 0 }, net: { exact: 0, estimated: 0 } }, sessionsPayload({ integralTotal: { netExact: 0, netEstimated: 0, cachedInput: 0, uncachedInput: 0, calls: 0 }, integralMoney: undefined }))
|
|
133
|
+
mountCard()
|
|
134
|
+
await waitFor(() => {
|
|
135
|
+
expect(screen.getByTestId('savings-session-list')).toBeDefined()
|
|
136
|
+
})
|
|
137
|
+
expect(screen.queryByText(t('savings.empty'))).toBeNull()
|
|
138
|
+
expect(screen.getByTestId('savings-session-list').textContent).toContain('bbbbbbbb')
|
|
139
|
+
})
|
|
140
|
+
})
|
|
@@ -70,14 +70,14 @@ function collectRegistrations(
|
|
|
70
70
|
return { declared, registrations }
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
describe('settings-seat contract (
|
|
73
|
+
describe('settings-seat contract (settings.section + input-bar session view binder + bundle detail card)', () => {
|
|
74
74
|
it('declares the services apply consumes (cordis waits; no lazy-get race)', () => {
|
|
75
75
|
// compat-legacy 单版本(B8):顶层只声明六线通用服务;数据面由 scoped
|
|
76
76
|
// sub-inject 双臂选择(桥默认 + configForms 升级),不再出现在顶层表。
|
|
77
77
|
expect(inject).toEqual(['slots', 'locale'])
|
|
78
78
|
})
|
|
79
79
|
|
|
80
|
-
it('injects exactly three seats: the settings.section panel + the input-bar session binder + the 0.1.7+ bundle detail card', () => {
|
|
80
|
+
it('injects exactly three seats: the settings.section panel + the input-bar session view binder + the 0.1.7+ bundle detail card', () => {
|
|
81
81
|
const { declared, registrations } = collectRegistrations()
|
|
82
82
|
expect(declared).toEqual(['settings.section', 'conversation.input.left', 'plugins.bundle.config'])
|
|
83
83
|
expect(registrations).toHaveLength(3)
|
|
@@ -88,6 +88,18 @@ describe('settings-seat contract (standalone settings.section + input-bar sessio
|
|
|
88
88
|
expect(registrations[2]!.options['key']).toBe('dsh-context-compression-improved')
|
|
89
89
|
})
|
|
90
90
|
|
|
91
|
+
it('pins the input-bar view binder: invisible component consumes the reactive sessionId standard prop', () => {
|
|
92
|
+
// 绑定源 = session 作用域槽的 sessionId 标准 prop(宿主按当前页面会话
|
|
93
|
+
// 响应式下发);inject 回调只在装载时发一次,不作绑定源(陈旧教训)。
|
|
94
|
+
const { registrations } = collectRegistrations()
|
|
95
|
+
const inputSeat = registrations[1]!
|
|
96
|
+
expect(inputSeat.options['id']).toBe('context-compression-session-bind')
|
|
97
|
+
expect(inputSeat.options['order']).toBe(170)
|
|
98
|
+
const component = inputSeat.component as ((props: { sessionId?: string }) => unknown) | undefined
|
|
99
|
+
expect(typeof component).toBe('function')
|
|
100
|
+
expect(component?.({ sessionId: 'sess-view-1' })).toBeNull()
|
|
101
|
+
})
|
|
102
|
+
|
|
91
103
|
it('no longer claims a shell.overlay float (the review panel it served is gone)', () => {
|
|
92
104
|
const { declared } = collectRegistrations()
|
|
93
105
|
expect(declared).not.toContain('shell.overlay')
|
|
@@ -106,17 +118,6 @@ describe('settings-seat contract (standalone settings.section + input-bar sessio
|
|
|
106
118
|
expect(component).toBe(ContextCompressionSettingsSection)
|
|
107
119
|
})
|
|
108
120
|
|
|
109
|
-
it('pins the input-bar binder: invisible component, inject captures the bare sessionId', () => {
|
|
110
|
-
const { registrations } = collectRegistrations()
|
|
111
|
-
const inputSeat = registrations[1]!
|
|
112
|
-
expect(inputSeat.options['id']).toBe('context-compression-session-bind')
|
|
113
|
-
expect(inputSeat.options['order']).toBe(170)
|
|
114
|
-
expect(typeof inputSeat.options['inject']).toBe('function')
|
|
115
|
-
const face = (inputSeat.options['inject'] as (sessionId: string) => Record<string, unknown>)('sess-42')
|
|
116
|
-
expect(face).toEqual({})
|
|
117
|
-
expect(inputSeat.component).toBeTypeOf('function')
|
|
118
|
-
})
|
|
119
|
-
|
|
120
121
|
it('never adds a Plugins-section card or tab alongside the standalone section', () => {
|
|
121
122
|
const { declared } = collectRegistrations()
|
|
122
123
|
expect(declared).not.toContain('settings.plugins.tab')
|
|
@@ -203,8 +204,7 @@ describe('settings-seat contract (standalone settings.section + input-bar sessio
|
|
|
203
204
|
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
204
205
|
try {
|
|
205
206
|
const { declared } = collectRegistrations({ registerThrows: true })
|
|
206
|
-
// It tried all three seats (so the degradation is "loud", not a silent
|
|
207
|
-
// no-op)…
|
|
207
|
+
// It tried all three seats (so the degradation is "loud", not a silent no-op)…
|
|
208
208
|
expect(declared).toEqual(['settings.section', 'conversation.input.left', 'plugins.bundle.config'])
|
|
209
209
|
// …and the rejection never escaped apply().
|
|
210
210
|
expect(warn).toHaveBeenCalled()
|
package/pnpm-workspace.yaml
CHANGED
|
@@ -70,3 +70,7 @@ overrides:
|
|
|
70
70
|
# next release. GHSA-2883-xcg3-v3hh: js-yaml < 4.3.2 does not bound CPU use for
|
|
71
71
|
# empty merge sources.
|
|
72
72
|
'js-yaml@<4.3.2': '^4.3.2'
|
|
73
|
+
|
|
74
|
+
minimumReleaseAgeExclude:
|
|
75
|
+
- dsh-reference-session-collector@0.1.0
|
|
76
|
+
- dsh-reference-session-collector@0.2.0-beta.0
|
|
@@ -49,11 +49,14 @@ const INSTALLATION_PROVIDED_RUNTIME = new Set([
|
|
|
49
49
|
// The client-plane entry loads in the web bundler, which carries the client
|
|
50
50
|
// stack (`react`, the ui-slot packages); its requires are reviewed from the
|
|
51
51
|
// built artifact further down instead.
|
|
52
|
+
// Clean-build output set (tsdown entries + shared chunks). `lib/config.js` and
|
|
53
|
+
// `lib/host-generation.js` were stale committed artifacts of an older entry
|
|
54
|
+
// table — the current bundle no longer emits them; keep this list equal to the
|
|
55
|
+
// real `lib/*.js` set or the scan below dies on ENOENT.
|
|
52
56
|
const HOST_PLANE_ENTRIES = [
|
|
53
|
-
'lib/config.js',
|
|
54
57
|
'lib/index.js',
|
|
55
|
-
'lib/invariant.js',
|
|
56
58
|
'lib/pruner.js',
|
|
59
|
+
'lib/invariant.js',
|
|
57
60
|
'lib/tail-trim.js',
|
|
58
61
|
]
|
|
59
62
|
const RUNTIME_IMPORT = /(?:^|[^.\w])(?:import|export)\s[^;]*?from\s*['"]([^'"]+)['"]|(?:^|[^.\w])(?:import|require)\s*\(\s*['"]([^'"]+)['"]\s*\)/gmu
|
package/vitest.config.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { defineConfig } from 'vitest/config'
|
|
2
2
|
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
// apply() 会把统计持久层(StatsStore)开在 resolveDshHome() 下;host spec
|
|
7
|
+
// 调 apply 时把 DSH_HOME 钉到临时目录,测试绝不写真实 ~/.dsh。
|
|
8
|
+
const VITEST_DSH_HOME = join(tmpdir(), 'cci-vitest-dsh-home')
|
|
3
9
|
|
|
4
10
|
export default defineConfig({
|
|
5
11
|
test: {
|
|
@@ -9,6 +15,7 @@ export default defineConfig({
|
|
|
9
15
|
test: {
|
|
10
16
|
name: 'runtime',
|
|
11
17
|
environment: 'node',
|
|
18
|
+
env: { DSH_HOME: VITEST_DSH_HOME },
|
|
12
19
|
include: [
|
|
13
20
|
'packages/selector/tests/runtime/**/*.spec.ts',
|
|
14
21
|
'packages/selector/tests/compat/**/*.spec.ts',
|
|
@@ -19,6 +26,7 @@ export default defineConfig({
|
|
|
19
26
|
test: {
|
|
20
27
|
name: 'selector-host',
|
|
21
28
|
environment: 'node',
|
|
29
|
+
env: { DSH_HOME: VITEST_DSH_HOME },
|
|
22
30
|
include: [
|
|
23
31
|
'packages/selector/tests/cache-prefix-audit.spec.ts',
|
|
24
32
|
'packages/selector/tests/estimator-catalog.spec.ts',
|