dsh-context-compression-improved 0.7.0-beta.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.ja.md +217 -220
  3. package/CHANGELOG.ko.md +211 -214
  4. package/CHANGELOG.md +401 -376
  5. package/CHANGELOG.zh.md +196 -199
  6. package/README.md +97 -97
  7. package/README.zh.md +86 -86
  8. package/package.json +1 -1
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.d.ts +44 -0
  11. package/packages/selector/lib/client.js +1733 -6
  12. package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
  13. package/packages/selector/lib/index.d.ts +13 -1
  14. package/packages/selector/lib/index.js +204 -3
  15. package/packages/selector/lib/profiles.d.ts +6 -0
  16. package/packages/selector/lib/pruner.d.ts +6 -0
  17. package/packages/selector/lib/pruner.js +90 -258
  18. package/packages/selector/lib/style.css +88 -46
  19. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  20. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  21. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  22. package/packages/selector/src/client/decode.ts +57 -53
  23. package/packages/selector/src/client/index.ts +307 -213
  24. package/packages/selector/src/client/locales/de.ts +141 -0
  25. package/packages/selector/src/client/locales/es.ts +141 -0
  26. package/packages/selector/src/client/locales/fr.ts +141 -0
  27. package/packages/selector/src/client/locales/it.ts +141 -0
  28. package/packages/selector/src/client/locales/ja.ts +141 -0
  29. package/packages/selector/src/client/locales/ko.ts +141 -0
  30. package/packages/selector/src/client/locales/ru.ts +141 -0
  31. package/packages/selector/src/client/locales.ts +282 -196
  32. package/packages/selector/src/client/monitor-fab.ts +336 -0
  33. package/packages/selector/src/client/savings-card.tsx +150 -0
  34. package/packages/selector/src/client/settings-section.tsx +140 -124
  35. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  36. package/packages/selector/src/index.ts +207 -5
  37. package/packages/selector/src/preset-overlay.ts +629 -629
  38. package/packages/selector/src/profiles.ts +431 -414
  39. package/packages/selector/src/pruner/content.ts +198 -198
  40. package/packages/selector/src/pruner/state.ts +57 -57
  41. package/packages/selector/src/pruner.ts +2759 -2665
  42. package/packages/selector/src/runtime/audit.ts +303 -303
  43. package/packages/selector/src/runtime/config.ts +756 -731
  44. package/packages/selector/src/runtime/monitor.ts +235 -0
  45. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  46. package/packages/selector/src/runtime/retrieve.ts +479 -457
  47. package/packages/selector/src/runtime/savings.ts +337 -0
  48. package/packages/selector/src/runtime/summary-command.ts +133 -133
  49. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
  50. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
  51. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
  52. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
  53. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
  54. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
  55. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  56. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
  57. package/packages/selector/src/runtime/types.ts +365 -358
  58. package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
  59. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  60. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  61. package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
  62. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  63. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  64. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  65. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  66. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  67. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
  69. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  70. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  71. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  72. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
  73. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
  74. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  75. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  76. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
  77. package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
  78. package/scripts/packed-components-smoke.mjs +734 -734
  79. package/scripts/packed-install-e2e.mjs +1 -1
  80. package/scripts/verify-release.mjs +1 -1
  81. package/tests/TEST_INVENTORY.md +41 -41
  82. package/tsconfig.tests.json +17 -17
  83. package/vitest.config.ts +57 -57
@@ -1,204 +1,204 @@
1
- import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
- import { tmpdir } from 'node:os'
3
- import { dirname, join } from 'node:path'
4
- import { Context, Service } from '@deepseek-ai/cordis'
5
- import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
1
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+ import { Context, Service } from '@deepseek-ai/cordis'
5
+ import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
6
6
  import { type SettingsNamespace } from '@deepseek-ai/dsh-settings'
7
- import { LegacySettingsProvider } from './helpers/legacy-settings/index.ts'
8
- import { afterEach, describe, expect, it } from 'vitest'
9
- import { apply } from '../src/index.ts'
10
- import type { OverlayableAgentPresets } from '../src/preset-overlay.ts'
11
- import { LegacyNamespaceRegistrar } from './helpers/legacy-namespace.ts'
12
-
13
- // 0.1.5 removed the settingsNamespace() wrapper; namespaces are validated at runtime.
14
- const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
15
-
16
- let root: string | undefined
17
- let ctx: Context | undefined
18
-
19
- afterEach(async () => {
20
- await ctx?.fiber.dispose()
21
- ctx = undefined
22
- if (root !== undefined) await rm(root, { recursive: true, force: true })
23
- root = undefined
24
- })
25
-
26
- class MemorySettings extends LegacySettingsProvider {
27
- readonly writable = true
28
- private readonly stored: Record<string, unknown> = {}
29
-
30
- protected load(): Promise<Record<string, unknown>> {
31
- return Promise.resolve(structuredClone(this.stored))
32
- }
33
-
34
- protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
35
- this.stored[ns] = structuredClone(section)
36
- return Promise.resolve()
37
- }
38
- }
39
-
40
- class FakeAgentPresets extends Service implements OverlayableAgentPresets {
41
- constructor(ctx: Context, readonly preset: AgentPreset) {
42
- super(ctx, 'agentPresets')
43
- }
44
-
45
- async resolve(): Promise<AgentPreset> {
46
- return this.preset
47
- }
48
-
49
- async mount(_agentCtx: unknown): Promise<AgentPreset> {
50
- return await this.resolve()
51
- }
52
-
53
- async recompose(_agentCtx: unknown, _id: string): Promise<AgentPreset> {
54
- return await this.resolve()
55
- }
56
-
57
- async standingKeyFor(): Promise<string> {
58
- return (await this.resolve()).path
59
- }
60
- }
61
-
62
- async function sourcePreset(): Promise<AgentPreset> {
63
- root = await mkdtemp(join(tmpdir(), 'dsh-selector-host-overlay-'))
64
- const path = join(root, 'standard', 'agent.cordis.yml')
65
- await mkdir(dirname(path), { recursive: true })
66
- await writeFile(path, "- id: persona\n name: '/opt/preset/persona.js'\n")
67
- return { id: 'standard', trust: 'system', path }
68
- }
69
-
70
- describe('context compression selector Host preset integration', () => {
71
- it('decorates native composition only for the lifetime of the selector fiber', async () => {
72
- const preset = await sourcePreset()
73
- ctx = new Context()
74
- await ctx.plugin(MemorySettings).await()
75
- await ctx.plugin(LegacyNamespaceRegistrar).await()
76
- await ctx.plugin(FakeAgentPresets, preset).await()
77
-
78
- const selector = ctx.plugin({ apply: (child) => {
79
- apply(child, { presetOverlay: true })
80
- } })
81
- await selector.await()
82
-
83
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
84
- const mounted = await service.mount({})
85
- expect(mounted.path).not.toBe(preset.path)
86
- expect(await readFile(mounted.path, 'utf8')).toContain('id: tool-result-pruner')
87
- expect((await service.resolve()).path).toBe(preset.path)
88
-
89
- await selector.dispose()
90
- expect((await service.mount({})).path).toBe(preset.path)
91
- })
92
-
93
- it('0.1.7: duplicate Host rows own independent entry configs — one row\u2019s disposal never disturbs the other', async () => {
94
- const preset = await sourcePreset()
95
- ctx = new Context()
96
- await ctx.plugin(MemorySettings).await()
97
- await ctx.plugin(FakeAgentPresets, preset).await()
98
-
99
- const builtIn = ctx.plugin({ apply })
100
- await builtIn.await()
101
-
102
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
103
- expect((await service.mount({})).path).toBe(preset.path)
104
-
105
- // 0.1.7: there is no shared settings registration to lease — each row
106
- // carries its own compression doc on its entry config, so duplicate rows
107
- // cannot disturb each other and disposal is purely per row.
108
- const bundle = ctx.plugin({ apply: (child) => {
109
- apply(child, { presetOverlay: true, settings: { profile: 'cache-strict' } } as never)
110
- } })
111
- await bundle.await()
112
-
113
- const mounted = await service.mount({})
114
- expect(mounted.path).not.toBe(preset.path)
115
- expect((await service.recompose({}, 'standard')).path).toBe(mounted.path)
116
-
117
- // Disposing the non-overlay row never touches the overlay row's decoration
118
- // or its entry config.
119
- await builtIn.dispose()
120
- expect((await service.mount({})).path).toBe(mounted.path)
121
-
122
- await bundle.dispose()
123
- expect((await service.mount({})).path).toBe(preset.path)
124
- })
125
-
126
- it('writes the saved Auto Compact threshold into the generated compaction-basic composition', async () => {
127
- const preset = await sourcePreset()
128
- ctx = new Context()
129
- await ctx.plugin(MemorySettings).await()
130
- await ctx.plugin(LegacyNamespaceRegistrar).await()
131
- await ctx.plugin(FakeAgentPresets, preset).await()
132
- // A settings-owning row must register the namespace before the update.
133
- await ctx.plugin({ apply }).await()
134
- const namespace = nsBrand('context-compression')
135
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
136
-
137
- const bundle = ctx.plugin({ apply: (child) => {
138
- apply(child, { presetOverlay: true })
139
- } })
140
- await bundle.await()
141
-
142
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
143
- const mounted = await service.mount({})
144
- const rendered = await readFile(mounted.path, 'utf8')
145
- expect(rendered).toContain('id: compaction-basic')
146
- expect(rendered).toContain('thresholdRatio: 0.73')
147
- // First-release retention stays pinned at 0.16 next to the threshold.
148
- expect(rendered).toContain('retainRatio: 0.16')
149
- // The SAME read feeds the runtime deployment config, so one generation
150
- // cannot split Auto Compact and micro compact across two thresholds.
151
- expect(rendered).toContain('id: tool-result-pruner')
152
- expect(rendered).toContain('autoCompactThresholdPercent: 73')
153
- await bundle.dispose()
154
- })
155
-
156
- it('defaults the generated threshold to 0.8 and keeps it absent from settings until saved', async () => {
157
- const preset = await sourcePreset()
158
- ctx = new Context()
159
- await ctx.plugin(MemorySettings).await()
160
- await ctx.plugin(LegacyNamespaceRegistrar).await()
161
- await ctx.plugin(FakeAgentPresets, preset).await()
162
-
163
- const bundle = ctx.plugin({ apply: (child) => {
164
- apply(child, { presetOverlay: true })
165
- } })
166
- await bundle.await()
167
-
168
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
169
- const rendered = await readFile((await service.mount({})).path, 'utf8')
170
- expect(rendered).toContain('thresholdRatio: 0.8')
171
- await bundle.dispose()
172
- })
173
-
174
- it('moves the standing composition generation when an equal-length threshold changes', async () => {
175
- const preset = await sourcePreset()
176
- ctx = new Context()
177
- await ctx.plugin(MemorySettings).await()
178
- await ctx.plugin(LegacyNamespaceRegistrar).await()
179
- await ctx.plugin(FakeAgentPresets, preset).await()
180
- // A settings-owning row must register the namespace before the update.
181
- await ctx.plugin({ apply }).await()
182
- const namespace = nsBrand('context-compression')
183
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
184
-
185
- const bundle = ctx.plugin({ apply: (child) => {
186
- apply(child, { presetOverlay: true })
187
- } })
188
- await bundle.await()
189
-
190
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
191
- const first = await service.mount({})
192
- expect(await readFile(first.path, 'utf8')).toContain('thresholdRatio: 0.7')
193
- expect(await service.standingKeyFor()).toBe(first.path)
194
-
195
- // Same character length, different content: the generated identity and
196
- // standing composition generation must both move to the new threshold.
197
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
198
- const second = await service.mount({})
199
- expect(second.path).not.toBe(first.path)
200
- expect(await readFile(second.path, 'utf8')).toContain('thresholdRatio: 0.8')
201
- expect(await service.standingKeyFor()).toBe(second.path)
202
- await bundle.dispose()
203
- })
204
- })
7
+ import { LegacySettingsProvider } from './helpers/legacy-settings/index.ts'
8
+ import { afterEach, describe, expect, it } from 'vitest'
9
+ import { apply } from '../src/index.ts'
10
+ import type { OverlayableAgentPresets } from '../src/preset-overlay.ts'
11
+ import { LegacyNamespaceRegistrar } from './helpers/legacy-namespace.ts'
12
+
13
+ // 0.1.5 removed the settingsNamespace() wrapper; namespaces are validated at runtime.
14
+ const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
15
+
16
+ let root: string | undefined
17
+ let ctx: Context | undefined
18
+
19
+ afterEach(async () => {
20
+ await ctx?.fiber.dispose()
21
+ ctx = undefined
22
+ if (root !== undefined) await rm(root, { recursive: true, force: true })
23
+ root = undefined
24
+ })
25
+
26
+ class MemorySettings extends LegacySettingsProvider {
27
+ readonly writable = true
28
+ private readonly stored: Record<string, unknown> = {}
29
+
30
+ protected load(): Promise<Record<string, unknown>> {
31
+ return Promise.resolve(structuredClone(this.stored))
32
+ }
33
+
34
+ protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
35
+ this.stored[ns] = structuredClone(section)
36
+ return Promise.resolve()
37
+ }
38
+ }
39
+
40
+ class FakeAgentPresets extends Service implements OverlayableAgentPresets {
41
+ constructor(ctx: Context, readonly preset: AgentPreset) {
42
+ super(ctx, 'agentPresets')
43
+ }
44
+
45
+ async resolve(): Promise<AgentPreset> {
46
+ return this.preset
47
+ }
48
+
49
+ async mount(_agentCtx: unknown): Promise<AgentPreset> {
50
+ return await this.resolve()
51
+ }
52
+
53
+ async recompose(_agentCtx: unknown, _id: string): Promise<AgentPreset> {
54
+ return await this.resolve()
55
+ }
56
+
57
+ async standingKeyFor(): Promise<string> {
58
+ return (await this.resolve()).path
59
+ }
60
+ }
61
+
62
+ async function sourcePreset(): Promise<AgentPreset> {
63
+ root = await mkdtemp(join(tmpdir(), 'dsh-selector-host-overlay-'))
64
+ const path = join(root, 'standard', 'agent.cordis.yml')
65
+ await mkdir(dirname(path), { recursive: true })
66
+ await writeFile(path, "- id: persona\n name: '/opt/preset/persona.js'\n")
67
+ return { id: 'standard', trust: 'system', path }
68
+ }
69
+
70
+ describe('context compression selector Host preset integration', () => {
71
+ it('decorates native composition only for the lifetime of the selector fiber', async () => {
72
+ const preset = await sourcePreset()
73
+ ctx = new Context()
74
+ await ctx.plugin(MemorySettings).await()
75
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
76
+ await ctx.plugin(FakeAgentPresets, preset).await()
77
+
78
+ const selector = ctx.plugin({ apply: (child) => {
79
+ apply(child, { presetOverlay: true })
80
+ } })
81
+ await selector.await()
82
+
83
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
84
+ const mounted = await service.mount({})
85
+ expect(mounted.path).not.toBe(preset.path)
86
+ expect(await readFile(mounted.path, 'utf8')).toContain('id: tool-result-pruner')
87
+ expect((await service.resolve()).path).toBe(preset.path)
88
+
89
+ await selector.dispose()
90
+ expect((await service.mount({})).path).toBe(preset.path)
91
+ })
92
+
93
+ it('0.1.7: duplicate Host rows own independent entry configs — one row\u2019s disposal never disturbs the other', async () => {
94
+ const preset = await sourcePreset()
95
+ ctx = new Context()
96
+ await ctx.plugin(MemorySettings).await()
97
+ await ctx.plugin(FakeAgentPresets, preset).await()
98
+
99
+ const builtIn = ctx.plugin({ apply })
100
+ await builtIn.await()
101
+
102
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
103
+ expect((await service.mount({})).path).toBe(preset.path)
104
+
105
+ // 0.1.7: there is no shared settings registration to lease — each row
106
+ // carries its own compression doc on its entry config, so duplicate rows
107
+ // cannot disturb each other and disposal is purely per row.
108
+ const bundle = ctx.plugin({ apply: (child) => {
109
+ apply(child, { presetOverlay: true, settings: { profile: 'cache-strict' } } as never)
110
+ } })
111
+ await bundle.await()
112
+
113
+ const mounted = await service.mount({})
114
+ expect(mounted.path).not.toBe(preset.path)
115
+ expect((await service.recompose({}, 'standard')).path).toBe(mounted.path)
116
+
117
+ // Disposing the non-overlay row never touches the overlay row's decoration
118
+ // or its entry config.
119
+ await builtIn.dispose()
120
+ expect((await service.mount({})).path).toBe(mounted.path)
121
+
122
+ await bundle.dispose()
123
+ expect((await service.mount({})).path).toBe(preset.path)
124
+ })
125
+
126
+ it('writes the saved Auto Compact threshold into the generated compaction-basic composition', async () => {
127
+ const preset = await sourcePreset()
128
+ ctx = new Context()
129
+ await ctx.plugin(MemorySettings).await()
130
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
131
+ await ctx.plugin(FakeAgentPresets, preset).await()
132
+ // A settings-owning row must register the namespace before the update.
133
+ await ctx.plugin({ apply }).await()
134
+ const namespace = nsBrand('context-compression')
135
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
136
+
137
+ const bundle = ctx.plugin({ apply: (child) => {
138
+ apply(child, { presetOverlay: true })
139
+ } })
140
+ await bundle.await()
141
+
142
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
143
+ const mounted = await service.mount({})
144
+ const rendered = await readFile(mounted.path, 'utf8')
145
+ expect(rendered).toContain('id: compaction-basic')
146
+ expect(rendered).toContain('thresholdRatio: 0.73')
147
+ // First-release retention stays pinned at 0.16 next to the threshold.
148
+ expect(rendered).toContain('retainRatio: 0.16')
149
+ // The SAME read feeds the runtime deployment config, so one generation
150
+ // cannot split Auto Compact and micro compact across two thresholds.
151
+ expect(rendered).toContain('id: tool-result-pruner')
152
+ expect(rendered).toContain('autoCompactThresholdPercent: 73')
153
+ await bundle.dispose()
154
+ })
155
+
156
+ it('defaults the generated threshold to 0.8 and keeps it absent from settings until saved', async () => {
157
+ const preset = await sourcePreset()
158
+ ctx = new Context()
159
+ await ctx.plugin(MemorySettings).await()
160
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
161
+ await ctx.plugin(FakeAgentPresets, preset).await()
162
+
163
+ const bundle = ctx.plugin({ apply: (child) => {
164
+ apply(child, { presetOverlay: true })
165
+ } })
166
+ await bundle.await()
167
+
168
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
169
+ const rendered = await readFile((await service.mount({})).path, 'utf8')
170
+ expect(rendered).toContain('thresholdRatio: 0.8')
171
+ await bundle.dispose()
172
+ })
173
+
174
+ it('moves the standing composition generation when an equal-length threshold changes', async () => {
175
+ const preset = await sourcePreset()
176
+ ctx = new Context()
177
+ await ctx.plugin(MemorySettings).await()
178
+ await ctx.plugin(LegacyNamespaceRegistrar).await()
179
+ await ctx.plugin(FakeAgentPresets, preset).await()
180
+ // A settings-owning row must register the namespace before the update.
181
+ await ctx.plugin({ apply }).await()
182
+ const namespace = nsBrand('context-compression')
183
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
184
+
185
+ const bundle = ctx.plugin({ apply: (child) => {
186
+ apply(child, { presetOverlay: true })
187
+ } })
188
+ await bundle.await()
189
+
190
+ const service = ctx.agentPresets as unknown as OverlayableAgentPresets
191
+ const first = await service.mount({})
192
+ expect(await readFile(first.path, 'utf8')).toContain('thresholdRatio: 0.7')
193
+ expect(await service.standingKeyFor()).toBe(first.path)
194
+
195
+ // Same character length, different content: the generated identity and
196
+ // standing composition generation must both move to the new threshold.
197
+ await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
198
+ const second = await service.mount({})
199
+ expect(second.path).not.toBe(first.path)
200
+ expect(await readFile(second.path, 'utf8')).toContain('thresholdRatio: 0.8')
201
+ expect(await service.standingKeyFor()).toBe(second.path)
202
+ await bundle.dispose()
203
+ })
204
+ })
@@ -0,0 +1,138 @@
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('灾难性遗忘区建议:点亮悬浮球并展示提示行', async () => {
111
+ const deps = makeDeps({
112
+ snapshots: [snapshotPatch({
113
+ net: { exact: 0, estimated: 0 },
114
+ context: { liveTokens: 90_000, contextWindow: 100_000, pct: 0.9 },
115
+ suggestion: { suggest: true, thresholdPct: 0.7, occupancyPct: 0.9 },
116
+ })],
117
+ })
118
+ initMonitorFab(deps)
119
+ await waitFor(() => (document.getElementById(FAB_ID) as HTMLElement).classList.contains('lit'))
120
+ const hint = document.querySelector('[data-hint]') as HTMLElement
121
+ expect(hint.classList.contains('show')).toBe(true)
122
+ expect(hint.textContent).toBe('monitor.panel.suggest')
123
+ })
124
+
125
+ it('无建议时提示行隐藏', async () => {
126
+ initMonitorFab(makeDeps())
127
+ await waitFor(() => (document.querySelector('[data-net]') as HTMLElement).textContent !== '')
128
+ expect(document.querySelector('[data-hint]')?.classList.contains('show')).toBe(false)
129
+ })
130
+
131
+ it('position persists across drag-free re-init via localStorage', () => {
132
+ localStorage.setItem('dsh.cci.monitor.pos', JSON.stringify({ x: 40, y: 60 }))
133
+ initMonitorFab(makeDeps())
134
+ const fab = document.getElementById(FAB_ID) as HTMLElement
135
+ expect(fab.style.left).toBe('40px')
136
+ expect(fab.style.top).toBe('60px')
137
+ })
138
+ })