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

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 (65) hide show
  1. package/CHANGELOG.ja.md +226 -220
  2. package/CHANGELOG.ko.md +220 -214
  3. package/CHANGELOG.md +366 -376
  4. package/CHANGELOG.zh.md +204 -199
  5. package/README.ja.md +85 -85
  6. package/README.ko.md +85 -85
  7. package/README.md +98 -97
  8. package/README.zh.md +85 -86
  9. package/eslint.config.js +30 -76
  10. package/package.json +53 -55
  11. package/packages/selector/dsh.plugin.json +2 -2
  12. package/packages/selector/lib/{intent-gate.js → advisor-state.js} +3 -91
  13. package/packages/selector/lib/client.js +3 -14
  14. package/packages/selector/lib/index.js +1 -92
  15. package/packages/selector/lib/profiles.d.ts +0 -9
  16. package/packages/selector/lib/pruner.d.ts +0 -59
  17. package/packages/selector/lib/pruner.js +7 -410
  18. package/packages/selector/lib/style.css +46 -46
  19. package/packages/selector/package.json +114 -114
  20. package/packages/selector/src/client/decode.ts +2 -6
  21. package/packages/selector/src/deepseek-v4-tokenizer.ts +1 -1
  22. package/packages/selector/src/index.ts +411 -418
  23. package/packages/selector/src/preset-overlay.ts +0 -3
  24. package/packages/selector/src/profiles.ts +10 -30
  25. package/packages/selector/src/pruner/content.ts +1 -1
  26. package/packages/selector/src/pruner/state.ts +0 -7
  27. package/packages/selector/src/pruner.ts +9 -253
  28. package/packages/selector/src/runtime/audit.ts +0 -17
  29. package/packages/selector/src/runtime/config.ts +11 -36
  30. package/packages/selector/src/runtime/reducers.ts +1 -1
  31. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +1 -46
  32. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -55
  33. package/packages/selector/src/runtime/tokenpilot/locator.ts +2 -2
  34. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +1 -4
  35. package/packages/selector/src/runtime/types.ts +0 -12
  36. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -214
  37. package/packages/selector/tests/built/client-artifact.spec.ts +59 -61
  38. package/packages/selector/tests/code-skeleton.client.spec.ts +93 -94
  39. package/packages/selector/tests/custom-contract.client.spec.ts +222 -223
  40. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  41. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -204
  42. package/packages/selector/tests/preset-options-write.client.spec.ts +187 -188
  43. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -200
  44. package/packages/selector/tests/profiles.client.spec.tsx +434 -436
  45. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  46. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -230
  47. package/packages/selector/tests/runtime/audit.spec.ts +274 -275
  48. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +3 -3
  49. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +4 -4
  50. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2731 -2736
  51. package/packages/selector/tests/standing-generation.host.spec.ts +724 -704
  52. package/pnpm-workspace.yaml +66 -66
  53. package/scripts/packed-components-smoke.mjs +0 -2
  54. package/scripts/packed-install-e2e.mjs +5 -7
  55. package/scripts/verify-release.mjs +2 -3
  56. package/tsconfig.tests.json +1 -3
  57. package/vitest.config.ts +0 -14
  58. package/packages/selector/src/runtime/summary-command.ts +0 -133
  59. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  60. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  61. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  62. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  63. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  64. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  65. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
@@ -69,7 +69,7 @@ export function buildAdvisorScoringUserPrompt(
69
69
  }
70
70
 
71
71
  /** Pull the first balanced JSON object out of a possibly chatty answer. */
72
- export function firstJsonObject(text: string): Record<string, unknown> | undefined {
72
+ function firstJsonObject(text: string): Record<string, unknown> | undefined {
73
73
  const start = text.indexOf('{')
74
74
  if (start < 0) return undefined
75
75
  let depth = 0
@@ -186,48 +186,3 @@ export function parseAdvisorScores(
186
186
  }
187
187
  return scores.size > 0 ? scores : undefined
188
188
  }
189
-
190
- /** Hard character cap for one intent-summary answer (summary segment only). */
191
- export const INTENT_SUMMARY_CHAR_CAP = 1_600
192
-
193
- /**
194
- * Intent-summary writer prompts (task_2.3). Input records are already
195
- * semantic-role-masked by intent-input-mask.ts: read-class candidates are
196
- * one-line "read X" records, keep-class candidates carry skeleton heads and
197
- * VERBATIM error lines. The model writes ONLY the summary segment — it never
198
- * revoices error lines, and its answer must stay inside the char cap.
199
- */
200
- export function buildIntentSummarySystemPrompt(): string {
201
- return [
202
- 'You write one concise intent summary of folded tool results for a coding agent session.',
203
- 'Input: the session task (todolist) and per-tool slimmed records (read lines, or skeleton heads with verbatim error lines).',
204
- `Write ONLY what the agent DID and LEARNED in this span, as flowing prose under ${INTENT_SUMMARY_CHAR_CAP} characters.`,
205
- 'Mention which files/areas were consulted and what changed, so a later turn can continue without the originals.',
206
- 'Never invent files, commands, or outcomes absent from the records. Never revoice error lines; they are preserved verbatim elsewhere.',
207
- 'Answer with ONLY one JSON object: {"summary":"<prose>"}. Never add commentary.',
208
- ].join(' ')
209
- }
210
-
211
- export function buildIntentSummaryUserPrompt(
212
- taskText: string,
213
- records: readonly string[],
214
- tailText: string,
215
- ): string {
216
- const nl = String.fromCharCode(10)
217
- const lines = [
218
- `task: ${taskText.replace(/\s+/gu, ' ').slice(0, 600)}`,
219
- records.length > 0 ? `records:${nl}${records.join(nl)}` : 'records: (none)',
220
- tailText.trim().length > 0 ? `recent tail:${nl}${tailText.trim().slice(0, 1_200)}` : 'recent tail: (none)',
221
- ]
222
- return lines.join(nl + nl)
223
- }
224
-
225
- /** Fail-open parse of one intent-summary answer; `undefined` on any malformed shape. */
226
- export function parseIntentSummaryAnswer(text: string): { readonly summary: string } | undefined {
227
- const parsed = firstJsonObject(text)
228
- if (parsed === undefined) return undefined
229
- const summary = parsed.summary
230
- if (typeof summary !== 'string' || summary.trim().length === 0) return undefined
231
- if (summary.length > INTENT_SUMMARY_CHAR_CAP * 2) return undefined
232
- return { summary: summary.trim().slice(0, INTENT_SUMMARY_CHAR_CAP) }
233
- }
@@ -147,58 +147,3 @@ export function invalidateOnTaskChange(state: AdvisorState, todoVersion: string)
147
147
  state.lastSummaryTurn = -1
148
148
  return true
149
149
  }
150
-
151
- // ─────────── Turn-tail intent summary: session-scoped overrides and records ───────────
152
-
153
- /**
154
- * `/ctx-summary off|on` overrides, keyed by session id (string). The command
155
- * handler only sees `invocation.agent.session.id`, not the pruner's Session
156
- * object, so these are id-keyed rather than WeakMap'd. Entries are two-char
157
- * strings per session and cleared whenever the override is lifted.
158
- */
159
- const summaryOverrides = new Map<string, 'on' | 'off'>()
160
-
161
- /** Read the session's `/ctx-summary` override; `undefined` = default (settings-driven). */
162
- export function getSummaryOverride(sessionId: string): 'on' | 'off' | undefined {
163
- return summaryOverrides.get(sessionId)
164
- }
165
-
166
- /** Set or clear (`undefined`) the session's `/ctx-summary` override. */
167
- export function setSummaryOverride(sessionId: string, value: 'on' | 'off' | undefined): void {
168
- if (value === undefined) summaryOverrides.delete(sessionId)
169
- else summaryOverrides.set(sessionId, value)
170
- }
171
-
172
- /** Last observed `intentSummary.enabled` for a session, for `/ctx-summary status`. */
173
- const lastObservedIntentEnabled = new Map<string, boolean>()
174
-
175
- /** Record the gate input the pass last evaluated for this session. */
176
- export function observeIntentEnabled(sessionId: string, enabled: boolean): void {
177
- lastObservedIntentEnabled.set(sessionId, enabled)
178
- }
179
-
180
- /** The settings-side enabled flag last observed for the session, if any. */
181
- export function getObservedIntentEnabled(sessionId: string): boolean | undefined {
182
- return lastObservedIntentEnabled.get(sessionId)
183
- }
184
-
185
- /** One landed intent fold, kept for `/ctx-summary status` (one per session). */
186
- export interface IntentFoldRecord {
187
- readonly turn: number
188
- readonly startSeq: number
189
- readonly endSeq: number
190
- readonly liveTokensBefore: number
191
- readonly at: number
192
- }
193
-
194
- const lastIntentFolds = new Map<string, IntentFoldRecord>()
195
-
196
- /** Record a landed intent fold for the session (newest wins). */
197
- export function recordIntentFold(sessionId: string, record: IntentFoldRecord): void {
198
- lastIntentFolds.set(sessionId, record)
199
- }
200
-
201
- /** The most recent landed intent fold for the session, if any. */
202
- export function getLastIntentFold(sessionId: string): IntentFoldRecord | undefined {
203
- return lastIntentFolds.get(sessionId)
204
- }
@@ -105,8 +105,8 @@ export function buildLocatorBlock(
105
105
  const data = event.data as { content?: unknown, message?: { content?: unknown } }
106
106
  const content = Array.isArray(data.content) ? data.content : data.message?.content
107
107
  if (!Array.isArray(content)) continue
108
- for (const block of content as Array<{ type?: unknown, text?: unknown }>) {
109
- if (block.type === 'text' && typeof block.text === 'string') {
108
+ for (const block of content) {
109
+ if (block.type === 'text') {
110
110
  for (const path of extractSpillPaths(block.text)) spillFiles.add(path)
111
111
  }
112
112
  }
@@ -137,10 +137,7 @@ export class SideChannel {
137
137
  private async askHost(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
138
138
  let llm: HostLlmLike | undefined
139
139
  try {
140
- // The standalone checkout has no typed registry entry for the host `llm`
141
- // service (`ctx.get` narrows to `never`); read it through an untyped face
142
- // and restate the minimal shape this module consumes.
143
- llm = (this.ctx as { get(key: string): unknown }).get('llm') as HostLlmLike | undefined
140
+ llm = this.ctx.get('llm' as never) as HostLlmLike | undefined
144
141
  } catch {
145
142
  return undefined
146
143
  }
@@ -131,16 +131,6 @@ export interface CodeSkeletonSettings {
131
131
  enabled: boolean
132
132
  }
133
133
 
134
- /**
135
- * Orthogonal turn-tail intent-summary gate. Independent of every profile:
136
- * when enabled, the turn-boundary growth gate may fold consumed-increment
137
- * tool results into an LLM-written intent block (skeleton + verbatim error
138
- * lines are kept; the model only ever writes the summary segment).
139
- */
140
- export interface IntentSummarySettings {
141
- enabled: boolean
142
- }
143
-
144
134
  /**
145
135
  * Persisted sub-capability overrides for the `tokenpilot-inspired` preset.
146
136
  * Absent fields inherit the preset defaults; the section is only meaningful
@@ -181,8 +171,6 @@ export interface ContextCompressionSettings {
181
171
  autoCompact: AutoCompactSettings
182
172
  /** Code-skeleton reducer gate snapped independently of `profile`. */
183
173
  codeSkeleton: CodeSkeletonSettings
184
- /** Turn-tail intent-summary gate snapped independently of `profile`. */
185
- intentSummary: IntentSummarySettings
186
174
  /** Optional tokenpilot-inspired sub-capability overrides; absent inherits preset defaults. */
187
175
  presetOptions?: PresetOptionsSettings
188
176
  }
@@ -1,214 +1,213 @@
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
- CompressionProfileSelector,
8
- ContextCompressionSettingsSection,
9
- type CompressionProfileSelectorProps,
10
- type ContextCompressionSettings,
11
- } from '../src/client/CompressionProfileSelector.tsx'
12
- import { en } from '../src/client/locales.ts'
13
-
14
- afterEach(cleanup)
15
-
16
- interface SettingsScopeSnapshot<T> {
17
- status: 'loading' | 'ready' | 'unavailable'
18
- value: T | undefined
19
- base: T | undefined
20
- user: T | undefined
21
- revision: number | undefined
22
- writable: boolean
23
- mode: 'host' | 'memory'
24
- }
25
-
26
- interface SnapshotStore<T> {
27
- readonly getSnapshot: () => T
28
- readonly subscribe: (listener: () => void) => () => void
29
- readonly update: (recipe: (draft: T) => void) => void
30
- }
31
-
32
- function createSnapshotStore<T>(initial: T): SnapshotStore<T> {
33
- let snapshot = structuredClone(initial)
34
- const listeners = new Set<() => void>()
35
- return {
36
- getSnapshot: () => snapshot,
37
- subscribe(listener) {
38
- listeners.add(listener)
39
- return () => { listeners.delete(listener) }
40
- },
41
- update(recipe) {
42
- const draft = structuredClone(snapshot)
43
- recipe(draft)
44
- snapshot = draft
45
- for (const listener of listeners) listener()
46
- },
47
- }
48
- }
49
-
50
- function bindSnapshotSelector<T>(store: SnapshotStore<T>) {
51
- return function useSnapshotSelector<U>(selector: (snapshot: T) => U): U {
52
- return useSyncExternalStore(
53
- store.subscribe,
54
- () => selector(store.getSnapshot()),
55
- () => selector(store.getSnapshot()),
56
- )
57
- }
58
- }
59
-
60
- const DEFAULT_CUSTOM = {
61
- version: 1,
62
- unit: 'tokens',
63
- fresh: { enabled: true, trigger: 4_096, target: 2_048 },
64
- aggregate: { enabled: true, trigger: 16_384, target: 8_192 },
65
- history: {
66
- enabled: true,
67
- trigger: 32_768,
68
- keepRecentTurns: 2,
69
- keepRecent: 16_384,
70
- minReclaim: 8_192,
71
- },
72
- prefixPolicy: 'pressure-break',
73
- } as const satisfies ContextCompressionSettings['custom']
74
-
75
- const t = (key: string) => en[key as keyof typeof en] ?? key
76
-
77
- interface MountOptions {
78
- readonly value?: ContextCompressionSettings
79
- readonly saveAutoCompact?: (thresholdPercent: number) => Promise<void>
80
- readonly settingsSection?: boolean
81
- readonly writable?: boolean
82
- readonly status?: 'loading' | 'ready'
83
- }
84
-
85
- function mountAutoCompact(options: MountOptions = {}) {
86
- const state = createSnapshotStore<SettingsScopeSnapshot<ContextCompressionSettings>>({
87
- status: options.status ?? 'ready',
88
- value: options.value ?? {
89
- profile: 'balanced',
90
- custom: structuredClone(DEFAULT_CUSTOM),
91
- autoCompact: { thresholdPercent: 80 },
92
- codeSkeleton: { enabled: false },
93
- intentSummary: { enabled: false },
94
- },
95
- base: undefined,
96
- user: undefined,
97
- revision: 0,
98
- writable: options.writable ?? true,
99
- mode: 'host',
100
- })
101
- const sessions = createSnapshotStore({
102
- ids: ['s1'],
103
- byId: { s1: { id: 's1', displayTitle: 's1', running: false, blank: true, updatedAt: 0, agentPreset: 'standard' } },
104
- current: 's1',
105
- phase: 'ready',
106
- subagentsByParent: {},
107
- jobsBySession: {},
108
- currentAddress: undefined,
109
- })
110
- const saveAutoCompact = options.saveAutoCompact ?? vi.fn(() => Promise.resolve())
111
- const Component = options.settingsSection === false ? CompressionProfileSelector : ContextCompressionSettingsSection
112
- render(<Component {...({
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,
119
- t,
120
- } as unknown as CompressionProfileSelectorProps)} />)
121
- return { state, saveAutoCompact }
122
- }
123
-
124
- const INPUT_LABEL = 'Auto Compact threshold (%)'
125
-
126
- describe('Auto Compact threshold controls', () => {
127
- it('renders the editor only inside the context-compression settings section', () => {
128
- mountAutoCompact({ settingsSection: true })
129
- expect(screen.getByLabelText(INPUT_LABEL)).not.toBeNull()
130
- expect(screen.queryByRole('slider')).toBeNull()
131
- for (const quick of ['70%', '80%', '85%']) expect(screen.queryByRole('button', { name: quick })).toBeNull()
132
-
133
- // The compact workspace selector shows a summary, never a second editor.
134
- cleanup()
135
- mountAutoCompact({ settingsSection: false })
136
- expect(screen.queryByLabelText(INPUT_LABEL)).toBeNull()
137
- expect(screen.queryByRole('slider')).toBeNull()
138
- expect(screen.getByText(/Auto Compact threshold: 80%/)).not.toBeNull()
139
- })
140
-
141
- it('saves a non-quick value like 73 and reads the same value back after remount', async () => {
142
- const saving = vi.fn((thresholdPercent: number): Promise<void> => {
143
- mounted.state.update(draft => {
144
- if (draft.value !== undefined) draft.value.autoCompact = { thresholdPercent }
145
- })
146
- return Promise.resolve()
147
- })
148
- const mounted = mountAutoCompact({ settingsSection: true, saveAutoCompact: saving })
149
- fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '73' } })
150
- fireEvent.click(screen.getByRole('button', { name: 'Save Auto Compact threshold' }))
151
- await waitFor(() => { expect(mounted.state.getSnapshot().value?.autoCompact).toEqual({ thresholdPercent: 73 }) })
152
-
153
- // A fresh mount reads the same persisted settings.
154
- cleanup()
155
- mountAutoCompact({
156
- settingsSection: true,
157
- value: { profile: 'balanced', custom: structuredClone(DEFAULT_CUSTOM), autoCompact: { thresholdPercent: 73 }, codeSkeleton: { enabled: false }, intentSummary: { enabled: false } },
158
- })
159
- expect(screen.getByLabelText<HTMLInputElement>(INPUT_LABEL).value).toBe('73')
160
- })
161
-
162
- it.each(['49', '91', '72.5', 'abc', ''])('blocks saving the invalid draft %s', (draft) => {
163
- const { saveAutoCompact } = mountAutoCompact({ settingsSection: true })
164
- fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: draft } })
165
- expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(true)
166
- expect(screen.getByText(/must be an integer between 50 and 90/)).not.toBeNull()
167
- expect(saveAutoCompact).not.toHaveBeenCalled()
168
- })
169
-
170
- it('uses the typed number input as the only threshold editor', () => {
171
- mountAutoCompact({ settingsSection: true })
172
- const input = screen.getByLabelText<HTMLInputElement>(INPUT_LABEL)
173
- fireEvent.change(input, { target: { value: '73' } })
174
- expect(input.value).toBe('73')
175
- expect(screen.queryByRole('slider')).toBeNull()
176
- for (const quick of ['70%', '80%', '85%']) expect(screen.queryByRole('button', { name: quick })).toBeNull()
177
- })
178
-
179
- it('explains the risk outside the recommended 70–85 band but keeps saving available', () => {
180
- mountAutoCompact({ settingsSection: true })
181
- fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '65' } })
182
- expect(screen.getByText(/summarization calls and prefix rebuilds/)).not.toBeNull()
183
- expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(false)
184
-
185
- fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '90' } })
186
- expect(screen.getByText(/shared by requests and output/)).not.toBeNull()
187
- expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(false)
188
-
189
- fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '80' } })
190
- expect(screen.queryByText(/summarization calls and prefix rebuilds/)).toBeNull()
191
- expect(screen.queryByText(/shared by requests and output/)).toBeNull()
192
- })
193
-
194
- it('disables every control while saving or when the scope is not writable', () => {
195
- const { saveAutoCompact } = mountAutoCompact({ settingsSection: true, status: 'loading' })
196
- expect(screen.getByLabelText<HTMLInputElement>(INPUT_LABEL).disabled).toBe(true)
197
- expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(true)
198
- expect(saveAutoCompact).not.toHaveBeenCalled()
199
-
200
- cleanup()
201
- mountAutoCompact({ settingsSection: true, writable: false })
202
- expect(screen.getByLabelText<HTMLInputElement>(INPUT_LABEL).disabled).toBe(true)
203
- expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(true)
204
- })
205
-
206
- it('shows a failed threshold save inline', async () => {
207
- const rejected = Promise.reject(new Error('threshold write failed'))
208
- void rejected.catch(() => {})
209
- mountAutoCompact({ settingsSection: true, saveAutoCompact: () => rejected })
210
- fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '73' } })
211
- fireEvent.click(screen.getByRole('button', { name: 'Save Auto Compact threshold' }))
212
- await waitFor(() => { expect(screen.getByRole('alert').textContent).toContain('threshold write failed') })
213
- })
214
- })
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
+ CompressionProfileSelector,
8
+ ContextCompressionSettingsSection,
9
+ type CompressionProfileSelectorProps,
10
+ type ContextCompressionSettings,
11
+ } from '../src/client/CompressionProfileSelector.tsx'
12
+ import { en } from '../src/client/locales.ts'
13
+
14
+ afterEach(cleanup)
15
+
16
+ interface SettingsScopeSnapshot<T> {
17
+ status: 'loading' | 'ready' | 'unavailable'
18
+ value: T | undefined
19
+ base: T | undefined
20
+ user: T | undefined
21
+ revision: number | undefined
22
+ writable: boolean
23
+ mode: 'host' | 'memory'
24
+ }
25
+
26
+ interface SnapshotStore<T> {
27
+ readonly getSnapshot: () => T
28
+ readonly subscribe: (listener: () => void) => () => void
29
+ readonly update: (recipe: (draft: T) => void) => void
30
+ }
31
+
32
+ function createSnapshotStore<T>(initial: T): SnapshotStore<T> {
33
+ let snapshot = structuredClone(initial)
34
+ const listeners = new Set<() => void>()
35
+ return {
36
+ getSnapshot: () => snapshot,
37
+ subscribe(listener) {
38
+ listeners.add(listener)
39
+ return () => { listeners.delete(listener) }
40
+ },
41
+ update(recipe) {
42
+ const draft = structuredClone(snapshot)
43
+ recipe(draft)
44
+ snapshot = draft
45
+ for (const listener of listeners) listener()
46
+ },
47
+ }
48
+ }
49
+
50
+ function bindSnapshotSelector<T>(store: SnapshotStore<T>) {
51
+ return function useSnapshotSelector<U>(selector: (snapshot: T) => U): U {
52
+ return useSyncExternalStore(
53
+ store.subscribe,
54
+ () => selector(store.getSnapshot()),
55
+ () => selector(store.getSnapshot()),
56
+ )
57
+ }
58
+ }
59
+
60
+ const DEFAULT_CUSTOM = {
61
+ version: 1,
62
+ unit: 'tokens',
63
+ fresh: { enabled: true, trigger: 4_096, target: 2_048 },
64
+ aggregate: { enabled: true, trigger: 16_384, target: 8_192 },
65
+ history: {
66
+ enabled: true,
67
+ trigger: 32_768,
68
+ keepRecentTurns: 2,
69
+ keepRecent: 16_384,
70
+ minReclaim: 8_192,
71
+ },
72
+ prefixPolicy: 'pressure-break',
73
+ } as const satisfies ContextCompressionSettings['custom']
74
+
75
+ const t = (key: string) => en[key as keyof typeof en] ?? key
76
+
77
+ interface MountOptions {
78
+ readonly value?: ContextCompressionSettings
79
+ readonly saveAutoCompact?: (thresholdPercent: number) => Promise<void>
80
+ readonly settingsSection?: boolean
81
+ readonly writable?: boolean
82
+ readonly status?: 'loading' | 'ready'
83
+ }
84
+
85
+ function mountAutoCompact(options: MountOptions = {}) {
86
+ const state = createSnapshotStore<SettingsScopeSnapshot<ContextCompressionSettings>>({
87
+ status: options.status ?? 'ready',
88
+ value: options.value ?? {
89
+ profile: 'balanced',
90
+ custom: structuredClone(DEFAULT_CUSTOM),
91
+ autoCompact: { thresholdPercent: 80 },
92
+ codeSkeleton: { enabled: false },
93
+ },
94
+ base: undefined,
95
+ user: undefined,
96
+ revision: 0,
97
+ writable: options.writable ?? true,
98
+ mode: 'host',
99
+ })
100
+ const sessions = createSnapshotStore({
101
+ ids: ['s1'],
102
+ byId: { s1: { id: 's1', displayTitle: 's1', running: false, blank: true, updatedAt: 0, agentPreset: 'standard' } },
103
+ current: 's1',
104
+ phase: 'ready',
105
+ subagentsByParent: {},
106
+ jobsBySession: {},
107
+ currentAddress: undefined,
108
+ })
109
+ const saveAutoCompact = options.saveAutoCompact ?? vi.fn(() => Promise.resolve())
110
+ const Component = options.settingsSection === false ? CompressionProfileSelector : ContextCompressionSettingsSection
111
+ render(<Component {...({
112
+ useCompression: bindSnapshotSelector(state),
113
+ useSessions: bindSnapshotSelector(sessions),
114
+ select: vi.fn(() => Promise.resolve()),
115
+ saveCustom: vi.fn(() => Promise.resolve()),
116
+ resetCustom: vi.fn(() => Promise.resolve()),
117
+ saveAutoCompact,
118
+ t,
119
+ } as unknown as CompressionProfileSelectorProps)} />)
120
+ return { state, saveAutoCompact }
121
+ }
122
+
123
+ const INPUT_LABEL = 'Auto Compact threshold (%)'
124
+
125
+ describe('Auto Compact threshold controls', () => {
126
+ it('renders the editor only inside the context-compression settings section', () => {
127
+ mountAutoCompact({ settingsSection: true })
128
+ expect(screen.getByLabelText(INPUT_LABEL)).not.toBeNull()
129
+ expect(screen.queryByRole('slider')).toBeNull()
130
+ for (const quick of ['70%', '80%', '85%']) expect(screen.queryByRole('button', { name: quick })).toBeNull()
131
+
132
+ // The compact workspace selector shows a summary, never a second editor.
133
+ cleanup()
134
+ mountAutoCompact({ settingsSection: false })
135
+ expect(screen.queryByLabelText(INPUT_LABEL)).toBeNull()
136
+ expect(screen.queryByRole('slider')).toBeNull()
137
+ expect(screen.getByText(/Auto Compact threshold: 80%/)).not.toBeNull()
138
+ })
139
+
140
+ it('saves a non-quick value like 73 and reads the same value back after remount', async () => {
141
+ const saving = vi.fn((thresholdPercent: number): Promise<void> => {
142
+ mounted.state.update(draft => {
143
+ if (draft.value !== undefined) draft.value.autoCompact = { thresholdPercent }
144
+ })
145
+ return Promise.resolve()
146
+ })
147
+ const mounted = mountAutoCompact({ settingsSection: true, saveAutoCompact: saving })
148
+ fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '73' } })
149
+ fireEvent.click(screen.getByRole('button', { name: 'Save Auto Compact threshold' }))
150
+ await waitFor(() => { expect(mounted.state.getSnapshot().value?.autoCompact).toEqual({ thresholdPercent: 73 }) })
151
+
152
+ // A fresh mount reads the same persisted settings.
153
+ cleanup()
154
+ mountAutoCompact({
155
+ settingsSection: true,
156
+ value: { profile: 'balanced', custom: structuredClone(DEFAULT_CUSTOM), autoCompact: { thresholdPercent: 73 }, codeSkeleton: { enabled: false } },
157
+ })
158
+ expect(screen.getByLabelText<HTMLInputElement>(INPUT_LABEL).value).toBe('73')
159
+ })
160
+
161
+ it.each(['49', '91', '72.5', 'abc', ''])('blocks saving the invalid draft %s', (draft) => {
162
+ const { saveAutoCompact } = mountAutoCompact({ settingsSection: true })
163
+ fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: draft } })
164
+ expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(true)
165
+ expect(screen.getByText(/must be an integer between 50 and 90/)).not.toBeNull()
166
+ expect(saveAutoCompact).not.toHaveBeenCalled()
167
+ })
168
+
169
+ it('uses the typed number input as the only threshold editor', () => {
170
+ mountAutoCompact({ settingsSection: true })
171
+ const input = screen.getByLabelText<HTMLInputElement>(INPUT_LABEL)
172
+ fireEvent.change(input, { target: { value: '73' } })
173
+ expect(input.value).toBe('73')
174
+ expect(screen.queryByRole('slider')).toBeNull()
175
+ for (const quick of ['70%', '80%', '85%']) expect(screen.queryByRole('button', { name: quick })).toBeNull()
176
+ })
177
+
178
+ it('explains the risk outside the recommended 70–85 band but keeps saving available', () => {
179
+ mountAutoCompact({ settingsSection: true })
180
+ fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '65' } })
181
+ expect(screen.getByText(/summarization calls and prefix rebuilds/)).not.toBeNull()
182
+ expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(false)
183
+
184
+ fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '90' } })
185
+ expect(screen.getByText(/shared by requests and output/)).not.toBeNull()
186
+ expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(false)
187
+
188
+ fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '80' } })
189
+ expect(screen.queryByText(/summarization calls and prefix rebuilds/)).toBeNull()
190
+ expect(screen.queryByText(/shared by requests and output/)).toBeNull()
191
+ })
192
+
193
+ it('disables every control while saving or when the scope is not writable', () => {
194
+ const { saveAutoCompact } = mountAutoCompact({ settingsSection: true, status: 'loading' })
195
+ expect(screen.getByLabelText<HTMLInputElement>(INPUT_LABEL).disabled).toBe(true)
196
+ expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(true)
197
+ expect(saveAutoCompact).not.toHaveBeenCalled()
198
+
199
+ cleanup()
200
+ mountAutoCompact({ settingsSection: true, writable: false })
201
+ expect(screen.getByLabelText<HTMLInputElement>(INPUT_LABEL).disabled).toBe(true)
202
+ expect(screen.getByRole<HTMLButtonElement>('button', { name: 'Save Auto Compact threshold' }).disabled).toBe(true)
203
+ })
204
+
205
+ it('shows a failed threshold save inline', async () => {
206
+ const rejected = Promise.reject(new Error('threshold write failed'))
207
+ void rejected.catch(() => {})
208
+ mountAutoCompact({ settingsSection: true, saveAutoCompact: () => rejected })
209
+ fireEvent.change(screen.getByLabelText(INPUT_LABEL), { target: { value: '73' } })
210
+ fireEvent.click(screen.getByRole('button', { name: 'Save Auto Compact threshold' }))
211
+ await waitFor(() => { expect(screen.getByRole('alert').textContent).toContain('threshold write failed') })
212
+ })
213
+ })