dsh-context-compression-improved 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +333 -135
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +94 -112
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +163 -142
  22. package/packages/selector/README.md +26 -31
  23. package/packages/selector/README.zh.md +24 -31
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +2 -2
  27. package/packages/selector/lib/client.d.ts +320 -228
  28. package/packages/selector/lib/client.js +3254 -1462
  29. package/packages/selector/lib/config.js +1713 -842
  30. package/packages/selector/lib/index.d.ts +46 -38
  31. package/packages/selector/lib/index.js +1099 -645
  32. package/packages/selector/lib/invariant.js +70 -70
  33. package/packages/selector/lib/pruner.d.ts +904 -684
  34. package/packages/selector/lib/pruner.js +5800 -3807
  35. package/packages/selector/lib/style.css +88 -46
  36. package/packages/selector/lib/tail-trim.js +145 -136
  37. package/packages/selector/package.json +18 -19
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +249 -111
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/preset-overlay.ts +60 -1
  61. package/packages/selector/src/profiles.ts +431 -342
  62. package/packages/selector/src/pruner/content.ts +18 -5
  63. package/packages/selector/src/pruner/state.ts +57 -43
  64. package/packages/selector/src/pruner/types.ts +23 -5
  65. package/packages/selector/src/pruner.ts +2736 -2144
  66. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  67. package/packages/selector/src/runtime/audit.ts +303 -215
  68. package/packages/selector/src/runtime/config.ts +756 -613
  69. package/packages/selector/src/runtime/measurement.ts +436 -403
  70. package/packages/selector/src/runtime/monitor.ts +235 -0
  71. package/packages/selector/src/runtime/reducers.ts +1115 -97
  72. package/packages/selector/src/runtime/retrieve.ts +479 -457
  73. package/packages/selector/src/runtime/savings.ts +337 -0
  74. package/packages/selector/src/runtime/session-events.ts +30 -17
  75. package/packages/selector/src/runtime/summary-command.ts +127 -0
  76. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  77. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  78. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  79. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  80. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  81. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  82. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  83. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  84. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  85. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  86. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  87. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  88. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  89. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  90. package/packages/selector/src/runtime/toolclass.ts +103 -0
  91. package/packages/selector/src/runtime/types.ts +365 -309
  92. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  93. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  94. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  96. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  97. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  98. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  99. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  100. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
  104. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  110. package/packages/selector/tests/runtime/audit.spec.ts +275 -129
  111. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  112. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  113. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  114. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  115. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  116. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  117. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  118. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  119. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  120. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  121. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
  122. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  123. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  124. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  125. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  126. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  127. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  128. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  129. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  130. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  131. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  132. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  133. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  134. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  135. package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
  136. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  137. package/pnpm-workspace.yaml +66 -19
  138. package/scripts/capture-profile-baseline.mjs +42 -0
  139. package/scripts/generate-tokenizer-fixtures.py +81 -81
  140. package/scripts/generate-vision-fixtures.py +208 -208
  141. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  142. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  143. package/scripts/toolclass-corpus-replay.mjs +281 -0
  144. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  145. package/tests/TEST_INVENTORY.md +41 -42
  146. package/scripts/capture-profile-baseline.ts +0 -80
  147. package/tsconfig.scripts.json +0 -13
  148. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  149. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,247 +1,253 @@
1
- // @vitest-environment jsdom
2
-
3
- import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
4
- import { useSyncExternalStore } from 'react'
5
- import { afterEach, describe, expect, it, vi } from 'vitest'
6
- import {
7
- ContextCompressionSettingsSection,
8
- type CompressionProfileSelectorProps,
9
- type ContextCompressionSettings,
10
- } from '../src/client/CompressionProfileSelector.tsx'
11
- import { en } from '../src/client/locales.ts'
12
-
13
- afterEach(() => {
14
- cleanup()
15
- vi.unstubAllGlobals()
16
- })
17
-
18
- interface SnapshotStore<T> {
19
- readonly getSnapshot: () => T
20
- readonly subscribe: (listener: () => void) => () => void
21
- }
22
-
23
- function createSnapshotStore<T>(initial: T): SnapshotStore<T> {
24
- const snapshot = structuredClone(initial)
25
- const listeners = new Set<() => void>()
26
- return {
27
- getSnapshot: () => snapshot,
28
- subscribe(listener) {
29
- listeners.add(listener)
30
- return () => { listeners.delete(listener) }
31
- },
32
- }
33
- }
34
-
35
- function bindSnapshotSelector<T>(store: SnapshotStore<T>) {
36
- return function useSnapshotSelector<U>(selector: (snapshot: T) => U): U {
37
- return useSyncExternalStore(
38
- store.subscribe,
39
- () => selector(store.getSnapshot()),
40
- () => selector(store.getSnapshot()),
41
- )
42
- }
43
- }
44
-
45
- const DEFAULT_CUSTOM = {
46
- version: 1,
47
- unit: 'tokens',
48
- fresh: { enabled: true, trigger: 4_096, target: 2_048 },
49
- aggregate: { enabled: true, trigger: 16_384, target: 8_192 },
50
- history: {
51
- enabled: true,
52
- trigger: 32_768,
53
- keepRecentTurns: 2,
54
- keepRecent: 16_384,
55
- minReclaim: 8_192,
56
- },
57
- prefixPolicy: 'pressure-break',
58
- } as const satisfies ContextCompressionSettings['custom']
59
-
60
- const t = (key: string) => en[key as keyof typeof en] ?? key
61
-
62
- const PROVIDER_LABEL = 'Provider'
63
- const CHANNEL_LABEL = 'Channel'
64
- const MODEL_LABEL = 'Model'
65
- const API_KEY_LABEL = 'API key (write-only, never echoed)'
66
- const BASE_URL_LABEL = 'Endpoint base URL (/v1)'
67
-
68
- const CATALOG = {
69
- ok: true,
70
- providers: [
71
- {
72
- id: 'local-35b',
73
- name: 'local-35b',
74
- models: [{ id: 'Qwen3.6-35B-A3B', name: 'Qwen3.6-35B-A3B' }, { id: 'Qwen38-27B', name: 'Qwen38-27B' }],
75
- },
76
- { id: 'deepseek-official', name: 'DeepSeek', models: [{ id: 'deepseek-flash', name: 'DeepSeek-V41-Flash' }] },
77
- ],
78
- selection: { provider: 'deepseek-official', model: 'deepseek-flash' },
79
- }
80
-
81
- function mountEstimator(
82
- presetOptions: ContextCompressionSettings['presetOptions'],
83
- options: { readonly catalog?: unknown, readonly profile?: ContextCompressionSettings['profile'] } = {},
84
- ) {
85
- const state = createSnapshotStore({
86
- status: 'ready' as const,
87
- value: {
88
- profile: options.profile ?? ('tokenpilot-inspired' as const),
89
- custom: structuredClone(DEFAULT_CUSTOM),
90
- autoCompact: { thresholdPercent: 80 },
91
- codeSkeleton: { enabled: false },
92
- presetOptions: presetOptions ?? {},
93
- },
94
- base: undefined,
95
- user: undefined,
96
- revision: 0,
97
- writable: true,
98
- mode: 'host' as const,
99
- })
100
- const sessions = createSnapshotStore({
101
- ids: ['s1'],
102
- byId: { s1: { id: 's1', agentPreset: 'standard' } },
103
- current: 's1',
104
- })
105
- const savePresetOptions = vi.fn(() => Promise.resolve())
106
- if (options.catalog !== undefined) {
107
- vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({
108
- ok: true,
109
- json: () => Promise.resolve(options.catalog),
110
- })))
111
- }
112
- render(<ContextCompressionSettingsSection {...({
113
- useCompression: bindSnapshotSelector(state),
114
- useSessions: bindSnapshotSelector(sessions),
115
- select: vi.fn(() => Promise.resolve()),
116
- saveCustom: vi.fn(() => Promise.resolve()),
117
- resetCustom: vi.fn(() => Promise.resolve()),
118
- saveAutoCompact: vi.fn(() => Promise.resolve()),
119
- saveCodeSkeleton: vi.fn(() => Promise.resolve()),
120
- savePresetOptions,
121
- t,
122
- } as unknown as CompressionProfileSelectorProps)} />)
123
- return { savePresetOptions }
124
- }
125
-
126
- describe('estimator channel card', () => {
127
- it('host mode fills comboboxes from the catalog, keeps custom typing, and asks for no API key', async () => {
128
- const { savePresetOptions } = mountEstimator({ estimatorMode: 'host' }, { catalog: CATALOG })
129
-
130
- // Provider/model are always comboboxes (dsh-perm-gate receiver pattern):
131
- // a catalog pick fills the field, and the same input accepts a custom id.
132
- const provider = screen.getByLabelText<HTMLInputElement>(PROVIDER_LABEL)
133
- const model = screen.getByLabelText<HTMLInputElement>(MODEL_LABEL)
134
- await waitFor(() => {
135
- const providerOptions = document.querySelectorAll('#estimator-provider-options option')
136
- expect([...providerOptions].map(option => (option as HTMLOptionElement).value))
137
- .toEqual(['local-35b', 'deepseek-official'])
138
- expect(provider.getAttribute('list')).toBe('estimator-provider-options')
139
- expect(model.getAttribute('list')).toBe('estimator-model-options')
140
- })
141
- expect(screen.getByText(/Effective route: deepseek-official \/ deepseek-flash/)).not.toBeNull()
142
- expect(screen.getByText(/no API key is needed/)).not.toBeNull()
143
-
144
- // No credential input and no base-URL field on this channel.
145
- expect(screen.queryByLabelText(API_KEY_LABEL)).toBeNull()
146
- expect(screen.queryByLabelText(BASE_URL_LABEL)).toBeNull()
147
- expect(document.querySelectorAll('input[type="password"]').length).toBe(0)
148
-
149
- // A datalist pick fires change without blur: it commits immediately.
150
- fireEvent.change(provider, { target: { value: 'local-35b' } })
151
- await waitFor(() => {
152
- expect(savePresetOptions).toHaveBeenCalledWith({ estimatorProvider: 'local-35b' })
153
- })
154
- // Free typing only commits on blur, so mid-edit keystrokes never save.
155
- fireEvent.change(provider, { target: { value: 'my-custom-group' } })
156
- expect(savePresetOptions).not.toHaveBeenCalledWith({ estimatorProvider: 'my-custom-group' })
157
- fireEvent.blur(provider)
158
- await waitFor(() => {
159
- expect(savePresetOptions).toHaveBeenCalledWith({ estimatorProvider: 'my-custom-group' })
160
- })
161
- })
162
-
163
- it('offers the catalog models of the chosen provider and commits one', async () => {
164
- const { savePresetOptions } = mountEstimator(
165
- { estimatorMode: 'host', estimatorProvider: 'local-35b' },
166
- { catalog: CATALOG },
167
- )
168
- // Query before the catalog lands: once the datalist has options, the
169
- // label's textContent includes them and getByLabelText's exact match
170
- // would no longer see a bare "Model".
171
- const model = screen.getByLabelText<HTMLInputElement>(MODEL_LABEL)
172
- expect(model.value).toBe('')
173
- await waitFor(() => {
174
- const modelOptions = document.querySelectorAll('#estimator-model-options option')
175
- expect([...modelOptions].map(option => (option as HTMLOptionElement).value))
176
- .toEqual(['Qwen3.6-35B-A3B', 'Qwen38-27B'])
177
- })
178
- expect(screen.getByText(/Effective route: local-35b/)).not.toBeNull()
179
-
180
- fireEvent.change(model, { target: { value: 'Qwen38-27B' } })
181
- await waitFor(() => {
182
- expect(savePresetOptions).toHaveBeenCalledWith({ estimatorModel: 'Qwen38-27B' })
183
- })
184
- })
185
-
186
- it('still accepts custom names — without a credential field — when no catalog is served', async () => {
187
- vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new Error('no route'))))
188
- const { savePresetOptions } = mountEstimator({ estimatorMode: 'host' })
189
-
190
- const provider = screen.getByLabelText<HTMLInputElement>(PROVIDER_LABEL)
191
- expect(screen.getByLabelText(MODEL_LABEL).tagName).toBe('INPUT')
192
- expect(document.querySelectorAll('#estimator-provider-options option').length).toBe(0)
193
- expect(document.querySelectorAll('#estimator-model-options option').length).toBe(0)
194
- fireEvent.change(provider, { target: { value: 'manual-group' } })
195
- fireEvent.blur(provider)
196
- await waitFor(() => {
197
- expect(savePresetOptions).toHaveBeenCalledWith({ estimatorProvider: 'manual-group' })
198
- })
199
- expect(screen.queryByLabelText(API_KEY_LABEL)).toBeNull()
200
- expect(screen.getByText(/no API key is needed/)).not.toBeNull()
201
- expect(screen.getByText(/not determined yet/)).not.toBeNull()
202
- })
203
-
204
- it('keeps the endpoint and key fields on the direct channel alone', () => {
205
- mountEstimator({ estimatorMode: 'direct' })
206
-
207
- expect(screen.getByLabelText(BASE_URL_LABEL)).not.toBeNull()
208
- expect(screen.getByLabelText(MODEL_LABEL).tagName).toBe('INPUT')
209
- expect(screen.getByLabelText(API_KEY_LABEL)).not.toBeNull()
210
- expect(document.querySelectorAll('input[type="password"]').length).toBe(1)
211
- expect(screen.queryByLabelText(PROVIDER_LABEL)).toBeNull()
212
- expect(screen.queryByText(/no API key is needed/)).toBeNull()
213
- })
214
-
215
- it('renders no channel controls while the estimator is off', () => {
216
- mountEstimator({})
217
- expect(screen.queryByLabelText(API_KEY_LABEL)).toBeNull()
218
- expect(screen.queryByLabelText(BASE_URL_LABEL)).toBeNull()
219
- expect(screen.queryByLabelText(PROVIDER_LABEL)).toBeNull()
220
- })
221
-
222
- // Regression guard for the first real-machine report: the card used to render
223
- // nothing at all off tokenpilot-inspired, which reads as a missing feature.
224
- it('keeps the estimator section, and names the unlocking profile, off tokenpilot-inspired', () => {
225
- mountEstimator({}, { profile: 'balanced' })
226
-
227
- // The heading and its stable anchor survive, so the panel is still findable
228
- // where the reader last saw it.
229
- expect(document.getElementById('context-compression-estimator-title')?.textContent)
230
- .toBe('Estimator (optional)')
231
- // The notice names the current profile and the profile that unlocks the card.
232
- const notice = screen.getByText(/ships only with the TokenPilot-inspired profile/)
233
- expect(notice.textContent).toContain('“Balanced”')
234
- expect(notice.textContent).toContain('Select TokenPilot-inspired')
235
- // Gating semantics are unchanged: no channel control exists here.
236
- expect(screen.queryByLabelText(CHANNEL_LABEL)).toBeNull()
237
- expect(screen.queryByLabelText(PROVIDER_LABEL)).toBeNull()
238
- expect(screen.queryByLabelText(API_KEY_LABEL)).toBeNull()
239
- expect(document.querySelectorAll('input[list]').length).toBe(0)
240
- })
241
-
242
- it('drops the inactive notice once tokenpilot-inspired owns the selector', () => {
243
- mountEstimator({})
244
- expect(screen.queryByText(/ships only with the TokenPilot-inspired profile/)).toBeNull()
245
- expect(screen.getByLabelText(CHANNEL_LABEL)).not.toBeNull()
246
- })
247
- })
1
+ // @vitest-environment jsdom
2
+
3
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
4
+ import { useSyncExternalStore } from 'react'
5
+ import { afterEach, describe, expect, it, vi } from 'vitest'
6
+ import {
7
+ ContextCompressionSettingsSection,
8
+ type CompressionProfileSelectorProps,
9
+ type ContextCompressionSettings,
10
+ } from '../src/client/CompressionProfileSelector.tsx'
11
+ import { en } from '../src/client/locales.ts'
12
+
13
+ afterEach(() => {
14
+ cleanup()
15
+ vi.unstubAllGlobals()
16
+ })
17
+
18
+ interface SettingsScopeSnapshot<T> {
19
+ status: 'loading' | 'ready' | 'unavailable'
20
+ value: T | undefined
21
+ base: T | undefined
22
+ user: T | undefined
23
+ revision: number | undefined
24
+ writable: boolean
25
+ mode: 'host' | 'memory'
26
+ }
27
+
28
+ interface SnapshotStore<T> {
29
+ readonly getSnapshot: () => T
30
+ readonly subscribe: (listener: () => void) => () => void
31
+ }
32
+
33
+ function createSnapshotStore<T>(initial: T): SnapshotStore<T> {
34
+ const snapshot = structuredClone(initial)
35
+ const listeners = new Set<() => void>()
36
+ return {
37
+ getSnapshot: () => snapshot,
38
+ subscribe(listener) {
39
+ listeners.add(listener)
40
+ return () => { listeners.delete(listener) }
41
+ },
42
+ }
43
+ }
44
+
45
+ function bindSnapshotSelector<T>(store: SnapshotStore<T>) {
46
+ return function useSnapshotSelector<U>(selector: (snapshot: T) => U): U {
47
+ return useSyncExternalStore(
48
+ store.subscribe,
49
+ () => selector(store.getSnapshot()),
50
+ () => selector(store.getSnapshot()),
51
+ )
52
+ }
53
+ }
54
+
55
+ const DEFAULT_CUSTOM = {
56
+ version: 1,
57
+ unit: 'tokens',
58
+ fresh: { enabled: true, trigger: 4_096, target: 2_048 },
59
+ aggregate: { enabled: true, trigger: 16_384, target: 8_192 },
60
+ history: {
61
+ enabled: true,
62
+ trigger: 32_768,
63
+ keepRecentTurns: 2,
64
+ keepRecent: 16_384,
65
+ minReclaim: 8_192,
66
+ },
67
+ prefixPolicy: 'pressure-break',
68
+ } as const satisfies ContextCompressionSettings['custom']
69
+
70
+ const t = (key: string) => en[key as keyof typeof en] ?? key
71
+
72
+ const PROVIDER_LABEL = 'Provider'
73
+ const CHANNEL_LABEL = 'Channel'
74
+ const MODEL_LABEL = 'Model'
75
+ const API_KEY_LABEL = 'API key (write-only, never echoed)'
76
+ const BASE_URL_LABEL = 'Endpoint base URL (/v1)'
77
+
78
+ const CATALOG = {
79
+ ok: true,
80
+ providers: [
81
+ {
82
+ id: 'local-35b',
83
+ name: 'local-35b',
84
+ models: [{ id: 'Qwen3.6-35B-A3B', name: 'Qwen3.6-35B-A3B' }, { id: 'Qwen38-27B', name: 'Qwen38-27B' }],
85
+ },
86
+ { id: 'deepseek-official', name: 'DeepSeek', models: [{ id: 'deepseek-flash', name: 'DeepSeek-V41-Flash' }] },
87
+ ],
88
+ selection: { provider: 'deepseek-official', model: 'deepseek-flash' },
89
+ }
90
+
91
+ function mountEstimator(
92
+ presetOptions: ContextCompressionSettings['presetOptions'],
93
+ options: { readonly catalog?: unknown, readonly profile?: ContextCompressionSettings['profile'] } = {},
94
+ ) {
95
+ const state = createSnapshotStore<SettingsScopeSnapshot<ContextCompressionSettings>>({
96
+ status: 'ready',
97
+ value: {
98
+ profile: options.profile ?? 'tokenpilot-inspired',
99
+ custom: structuredClone(DEFAULT_CUSTOM),
100
+ autoCompact: { thresholdPercent: 80 },
101
+ codeSkeleton: { enabled: false },
102
+ intentSummary: { enabled: false },
103
+ presetOptions: presetOptions ?? {},
104
+ },
105
+ base: undefined,
106
+ user: undefined,
107
+ revision: 0,
108
+ writable: true,
109
+ mode: 'host',
110
+ })
111
+ const savePresetOptions = vi.fn(() => Promise.resolve())
112
+ if (options.catalog !== undefined) {
113
+ vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({
114
+ ok: true,
115
+ json: () => Promise.resolve(options.catalog),
116
+ })))
117
+ }
118
+ render(<ContextCompressionSettingsSection {...({
119
+ useCompression: bindSnapshotSelector(state),
120
+ select: vi.fn(() => Promise.resolve()),
121
+ saveCustom: vi.fn(() => Promise.resolve()),
122
+ resetCustom: vi.fn(() => Promise.resolve()),
123
+ saveAutoCompact: vi.fn(() => Promise.resolve()),
124
+ saveCodeSkeleton: vi.fn(() => Promise.resolve()),
125
+ savePresetOptions,
126
+ t,
127
+ } as unknown as CompressionProfileSelectorProps)} />)
128
+ return { savePresetOptions }
129
+ }
130
+
131
+ describe('estimator channel card', () => {
132
+ it('host mode fills comboboxes from the catalog, keeps custom typing, and asks for no API key', async () => {
133
+ const { savePresetOptions } = mountEstimator({ estimatorMode: 'host' }, { catalog: CATALOG })
134
+
135
+ // Provider/model are always comboboxes (dsh-perm-gate receiver pattern):
136
+ // a catalog pick fills the field, and the same input accepts a custom id.
137
+ const provider = screen.getByLabelText<HTMLInputElement>(PROVIDER_LABEL)
138
+ const model = screen.getByLabelText<HTMLInputElement>(MODEL_LABEL)
139
+ await waitFor(() => {
140
+ const providerOptions = document.querySelectorAll('#estimator-provider-options option')
141
+ expect([...providerOptions].map(option => (option as HTMLOptionElement).value))
142
+ .toEqual(['local-35b', 'deepseek-official'])
143
+ expect(provider.getAttribute('list')).toBe('estimator-provider-options')
144
+ expect(model.getAttribute('list')).toBe('estimator-model-options')
145
+ })
146
+ expect(screen.getByText(/Effective route: deepseek-official \/ deepseek-flash/)).not.toBeNull()
147
+ expect(screen.getByText(/no API key is needed/)).not.toBeNull()
148
+
149
+ // No credential input and no base-URL field on this channel.
150
+ expect(screen.queryByLabelText(API_KEY_LABEL)).toBeNull()
151
+ expect(screen.queryByLabelText(BASE_URL_LABEL)).toBeNull()
152
+ expect(document.querySelectorAll('input[type="password"]').length).toBe(0)
153
+
154
+ // A datalist pick fires change without blur: it commits immediately.
155
+ fireEvent.change(provider, { target: { value: 'local-35b' } })
156
+ await waitFor(() => {
157
+ expect(savePresetOptions).toHaveBeenCalledWith({ estimatorProvider: 'local-35b' })
158
+ })
159
+ // Free typing only commits on blur, so mid-edit keystrokes never save.
160
+ fireEvent.change(provider, { target: { value: 'my-custom-group' } })
161
+ expect(savePresetOptions).not.toHaveBeenCalledWith({ estimatorProvider: 'my-custom-group' })
162
+ fireEvent.blur(provider)
163
+ await waitFor(() => {
164
+ expect(savePresetOptions).toHaveBeenCalledWith({ estimatorProvider: 'my-custom-group' })
165
+ })
166
+ })
167
+
168
+ it('offers the catalog models of the chosen provider and commits one', async () => {
169
+ const { savePresetOptions } = mountEstimator(
170
+ { estimatorMode: 'host', estimatorProvider: 'local-35b' },
171
+ { catalog: CATALOG },
172
+ )
173
+ // Query before the catalog lands: once the datalist has options, the
174
+ // label's textContent includes them and getByLabelText's exact match
175
+ // would no longer see a bare "Model".
176
+ const model = screen.getByLabelText<HTMLInputElement>(MODEL_LABEL)
177
+ expect(model.value).toBe('')
178
+ await waitFor(() => {
179
+ const modelOptions = document.querySelectorAll('#estimator-model-options option')
180
+ expect([...modelOptions].map(option => (option as HTMLOptionElement).value))
181
+ .toEqual(['Qwen3.6-35B-A3B', 'Qwen38-27B'])
182
+ })
183
+ expect(screen.getByText(/Effective route: local-35b/)).not.toBeNull()
184
+
185
+ fireEvent.change(model, { target: { value: 'Qwen38-27B' } })
186
+ await waitFor(() => {
187
+ expect(savePresetOptions).toHaveBeenCalledWith({ estimatorModel: 'Qwen38-27B' })
188
+ })
189
+ })
190
+
191
+ it('still accepts custom names — without a credential field — when no catalog is served', async () => {
192
+ vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new Error('no route'))))
193
+ const { savePresetOptions } = mountEstimator({ estimatorMode: 'host' })
194
+
195
+ const provider = screen.getByLabelText<HTMLInputElement>(PROVIDER_LABEL)
196
+ // The model field stays present and editable without a served catalog.
197
+ expect(screen.getByLabelText<HTMLInputElement>(MODEL_LABEL)).toBeTruthy()
198
+ expect(document.querySelectorAll('#estimator-provider-options option').length).toBe(0)
199
+ expect(document.querySelectorAll('#estimator-model-options option').length).toBe(0)
200
+ fireEvent.change(provider, { target: { value: 'manual-group' } })
201
+ fireEvent.blur(provider)
202
+ await waitFor(() => {
203
+ expect(savePresetOptions).toHaveBeenCalledWith({ estimatorProvider: 'manual-group' })
204
+ })
205
+ expect(screen.queryByLabelText(API_KEY_LABEL)).toBeNull()
206
+ expect(screen.getByText(/no API key is needed/)).not.toBeNull()
207
+ expect(screen.getByText(/not determined yet/)).not.toBeNull()
208
+ })
209
+
210
+ it('keeps the endpoint and key fields on the direct channel alone', () => {
211
+ mountEstimator({ estimatorMode: 'direct' })
212
+
213
+ expect(screen.getByLabelText(BASE_URL_LABEL)).not.toBeNull()
214
+ expect(screen.getByLabelText(MODEL_LABEL).tagName).toBe('INPUT')
215
+ expect(screen.getByLabelText(API_KEY_LABEL)).not.toBeNull()
216
+ expect(document.querySelectorAll('input[type="password"]').length).toBe(1)
217
+ expect(screen.queryByLabelText(PROVIDER_LABEL)).toBeNull()
218
+ expect(screen.queryByText(/no API key is needed/)).toBeNull()
219
+ })
220
+
221
+ it('renders no channel controls while the estimator is off', () => {
222
+ mountEstimator({})
223
+ expect(screen.queryByLabelText(API_KEY_LABEL)).toBeNull()
224
+ expect(screen.queryByLabelText(BASE_URL_LABEL)).toBeNull()
225
+ expect(screen.queryByLabelText(PROVIDER_LABEL)).toBeNull()
226
+ })
227
+
228
+ // Regression guard for the first real-machine report: the card used to render
229
+ // nothing at all off tokenpilot-inspired, which reads as a missing feature.
230
+ it('keeps the estimator section, and names the unlocking profile, off tokenpilot-inspired', () => {
231
+ mountEstimator({}, { profile: 'balanced' })
232
+
233
+ // The heading and its stable anchor survive, so the panel is still findable
234
+ // where the reader last saw it.
235
+ expect(document.getElementById('context-compression-estimator-title')?.textContent)
236
+ .toBe('Estimator (optional)')
237
+ // The notice names the current profile and the profile that unlocks the card.
238
+ const notice = screen.getByText(/ships only with the TokenPilot-inspired profile/)
239
+ expect(notice.textContent).toContain('“Balanced”')
240
+ expect(notice.textContent).toContain('Select TokenPilot-inspired')
241
+ // Gating semantics are unchanged: no channel control exists here.
242
+ expect(screen.queryByLabelText(CHANNEL_LABEL)).toBeNull()
243
+ expect(screen.queryByLabelText(PROVIDER_LABEL)).toBeNull()
244
+ expect(screen.queryByLabelText(API_KEY_LABEL)).toBeNull()
245
+ expect(document.querySelectorAll('input[list]').length).toBe(0)
246
+ })
247
+
248
+ it('drops the inactive notice once tokenpilot-inspired owns the selector', () => {
249
+ mountEstimator({})
250
+ expect(screen.queryByText(/ships only with the TokenPilot-inspired profile/)).toBeNull()
251
+ expect(screen.getByLabelText(CHANNEL_LABEL)).not.toBeNull()
252
+ })
253
+ })