Skip to content

Commit 71e8b42

Browse files
fix: use env override and settings for usable context ratio calculation (#407)
* fix: validate settings schema before saving to prevent data loss * fix: use env override and settings for usable context ratio calculation * Fix legacy auto-compaction preference and window clamping --------- Co-authored-by: Matthew Breedlove <[email protected]>
1 parent a74aed3 commit 71e8b42

7 files changed

Lines changed: 348 additions & 44 deletions

File tree

‎docs/USAGE.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,17 @@ Block Usage was previously named Session Usage. Its default label is now `5h:`,
7171

7272
An explicit per-model quota at 0% is shown even when its reset timestamp is still missing; the time cursor appears only once a usable window is available. Weekly Fable Usage uses the label `Weekly Fable:` and stays empty when the API reports no Fable quota.
7373

74+
### Usable context estimate
75+
76+
**Context % (usable)** estimates the budget available before auto-compaction. It uses 80% of the full context window by default. These Claude Code settings affect only this widget's usable budget; **Context Window**, **Context %**, and **Context Bar** continue to describe the full window.
77+
78+
- `CLAUDE_CODE_AUTO_COMPACT_WINDOW` sets the compaction window in tokens, ahead of Claude Code's top-level `autoCompactWindow` setting. Environment values accept numbers or `k`/`M` suffixes and are bounded to 100,000–1,000,000 tokens, then capped at the full model window. Suffixes require Claude Code 2.1.304 or later.
79+
- Settings are read from Claude Code's user directory (`CLAUDE_CONFIG_DIR`, otherwise `~/.claude`) and the payload's project directory. Project-local settings override project settings, then user-local and user settings. The reader refreshes these values on each render and leaves malformed files untouched.
80+
- `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` accepts a percentage from 1 through 100. It can lower the 80% estimate, but cannot raise it. For example, `60` with a 200,000-token compaction window gives a 120,000-token usable budget.
81+
- `DISABLE_AUTO_COMPACT=1`, `DISABLE_COMPACT=1`, or Claude Code's `autoCompactEnabled: false` makes the widget use the full model window. The environment switches also accept `true`, `yes`, and `on` (case-insensitive).
82+
83+
The exact live compaction threshold is not included in the status payload. This remains an estimate: model-specific reserves, per-model `modelSettings`, managed settings, and CLI-only overrides may make Claude Code compact at a different point. See [Claude Code's compaction settings](https://code.claude.com/docs/en/settings-reference#autocompactwindow) and [environment variables](https://code.claude.com/docs/en/env-vars). The separate `CCSTATUSLINE_CONTEXT_WINDOW_SIZE` override changes the full window for every context widget and takes precedence over the reported size; its percentage is recalculated from token usage.
84+
7485
### Environment, Layout & Custom
7586

7687
- **Current Working Dir** / **Terminal Width** / **Memory Usage** - Show the current working directory, detected terminal width, and system memory usage. Current Working Dir can prepend an optional custom glyph, including when raw-value mode replaces the `cwd:` label. When combining home abbreviation with a segment limit, `~` is preserved without counting toward that limit. Press `l` in its editor to cycle clickable links (`off` → file manager → VS Code → Cursor). The displayed path still honors home abbreviation, segment limits, and fish-style shortening, while the link always targets the original absolute directory. File-manager links use `file://` URLs on POSIX and Windows, including UNC shares; local terminals need OSC 8 hyperlink support.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import {
2+
afterEach,
3+
beforeEach,
4+
describe,
5+
expect,
6+
it
7+
} from 'vitest';
8+
9+
import { getContextConfig } from '../model-context';
10+
11+
const envKeys = [
12+
'CLAUDE_AUTOCOMPACT_PCT_OVERRIDE',
13+
'CLAUDE_CODE_AUTO_COMPACT_WINDOW',
14+
'DISABLE_AUTO_COMPACT',
15+
'DISABLE_COMPACT',
16+
'CCSTATUSLINE_CONTEXT_WINDOW_SIZE',
17+
'CCSTATUSLINE_CONTEXT_SIZE_FALLBACK'
18+
];
19+
const originalEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]));
20+
21+
beforeEach(() => {
22+
for (const key of envKeys) {
23+
Reflect.deleteProperty(process.env, key);
24+
}
25+
});
26+
27+
afterEach(() => {
28+
for (const key of envKeys) {
29+
const value = originalEnv[key];
30+
if (value === undefined) {
31+
Reflect.deleteProperty(process.env, key);
32+
} else {
33+
process.env[key] = value;
34+
}
35+
}
36+
});
37+
38+
describe('usable context budget', () => {
39+
it('keeps the existing 80% estimate without overrides', () => {
40+
expect(getContextConfig(undefined, 1000000)).toEqual({ maxTokens: 1000000, usableTokens: 800000 });
41+
});
42+
43+
it('treats the configured compaction window as tokens without changing the full model window', () => {
44+
expect(getContextConfig(undefined, 1000000, { windowSize: 200000 }))
45+
.toEqual({ maxTokens: 1000000, usableTokens: 160000 });
46+
});
47+
48+
it('prioritizes the environment window and applies a lower percentage to that window', () => {
49+
process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = '500000';
50+
process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE = '60';
51+
expect(getContextConfig(undefined, 1000000, { windowSize: 200000 }))
52+
.toEqual({ maxTokens: 1000000, usableTokens: 300000 });
53+
});
54+
55+
it('never expands the compaction window past the effective full window', () => {
56+
process.env.CCSTATUSLINE_CONTEXT_WINDOW_SIZE = '300k';
57+
process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = '500000';
58+
expect(getContextConfig(undefined, 200000)).toEqual({ maxTokens: 300000, usableTokens: 240000 });
59+
});
60+
61+
it.each(['1', 'true', 'YES', 'on'])('uses the full window when auto-compaction is disabled with %s', (value) => {
62+
process.env.DISABLE_AUTO_COMPACT = value;
63+
process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = '200000';
64+
process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE = '60';
65+
expect(getContextConfig(undefined, 1000000, { windowSize: 100000, enabled: true }).usableTokens).toBe(1000000);
66+
});
67+
68+
it('honors disabled compaction in settings and the all-compaction environment switch', () => {
69+
process.env.DISABLE_AUTO_COMPACT = 'false';
70+
expect(getContextConfig(undefined, 200000, { enabled: false }).usableTokens).toBe(200000);
71+
process.env.DISABLE_COMPACT = '1';
72+
expect(getContextConfig(undefined, 200000).usableTokens).toBe(200000);
73+
});
74+
75+
it.each(['', 'nope', '60junk', '0', '-1', '0.5', '101', 'Infinity', '90', '100'])('does not raise the estimate for percentage %s', (value) => {
76+
process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE = value;
77+
expect(getContextConfig(undefined, 200000).usableTokens).toBe(160000);
78+
});
79+
80+
it('reads environment changes without a permanent ratio cache', () => {
81+
process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE = '60';
82+
expect(getContextConfig(undefined, 200000).usableTokens).toBe(120000);
83+
process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE = '50';
84+
expect(getContextConfig(undefined, 200000).usableTokens).toBe(100000);
85+
delete process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE;
86+
expect(getContextConfig(undefined, 200000).usableTokens).toBe(160000);
87+
});
88+
89+
it.each(['200000junk', '', '0', '-1', 'Infinity', 'NaN'])('falls back to settings when the environment window is invalid: %s', (value) => {
90+
process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = value;
91+
expect(getContextConfig(undefined, 1000000, { windowSize: 300000 }).usableTokens).toBe(240000);
92+
});
93+
94+
it.each(['200', '1', '999', '0.1', '0.2k'])('clamps the small positive compaction window %s to 100k', (value) => {
95+
process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = value;
96+
expect(getContextConfig(undefined, 1000000, { windowSize: 300000 }))
97+
.toEqual({ maxTokens: 1000000, usableTokens: 80000 });
98+
});
99+
100+
it.each([['50k', 80000], ['500k', 400000], ['2M', 800000]])('bounds the environment window %s', (value, expected) => {
101+
process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = value;
102+
expect(getContextConfig(undefined, 2000000).usableTokens).toBe(expected);
103+
});
104+
});

‎src/utils/__tests__/claude-settings.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
CCSTATUSLINE_COMMANDS,
1818
buildStatusLineCommand,
1919
classifyInstallation,
20+
getAutoCompactConfig,
2021
getClaudeCodeVersion,
2122
getClaudeJsonPath,
2223
getClaudeSettingsPath,
@@ -94,6 +95,72 @@ afterAll(() => {
9495
}
9596
});
9697

98+
describe('getAutoCompactConfig', () => {
99+
function writeLayer(relativePath: string, value: unknown): void {
100+
const file = path.join(testClaudeConfigDir, relativePath);
101+
fs.mkdirSync(path.dirname(file), { recursive: true });
102+
fs.writeFileSync(file, JSON.stringify(value));
103+
}
104+
105+
it('reads token counts from the overridden Claude config directory', () => {
106+
writeLayer('settings.json', { autoCompactWindow: 200000, autoCompactEnabled: false });
107+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project'))).toEqual({ enabled: false, windowSize: 200000 });
108+
});
109+
110+
it.each([true, false])('falls back to the legacy toggle %s without taking its window', (enabled) => {
111+
writeLayer('.claude.json', { autoCompactEnabled: enabled, autoCompactWindow: 100000 });
112+
writeLayer('settings.json', { autoCompactWindow: 300000 });
113+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project'))).toEqual({ enabled, windowSize: 300000 });
114+
});
115+
116+
it('reads the legacy preference from the home directory without a config override', () => {
117+
delete process.env.CLAUDE_CONFIG_DIR;
118+
writeLayer('.claude.json', { autoCompactEnabled: false });
119+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project')).enabled).toBe(false);
120+
});
121+
122+
it.each([true, false])('prioritizes an explicit settings toggle %s over the legacy preference', (enabled) => {
123+
writeLayer('.claude.json', { autoCompactEnabled: !enabled });
124+
writeLayer('settings.json', { autoCompactEnabled: enabled });
125+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project')).enabled).toBe(enabled);
126+
});
127+
128+
it.each(['{ invalid JSON', 'null', '{"autoCompactEnabled":"false"}', '{}'])('ignores invalid legacy preferences: %s', (content) => {
129+
fs.writeFileSync(getClaudeJsonPath(), content);
130+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project'))).toEqual({ enabled: undefined, windowSize: undefined });
131+
});
132+
133+
it('merges each field independently with local settings above project and user settings', () => {
134+
writeLayer('settings.json', { autoCompactWindow: 800000, autoCompactEnabled: false });
135+
writeLayer('settings.local.json', { autoCompactWindow: 600000 });
136+
writeLayer('project/.claude/settings.json', { autoCompactWindow: 400000, autoCompactEnabled: true });
137+
writeLayer('project/.claude/settings.local.json', { autoCompactWindow: 200000 });
138+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project'))).toEqual({ enabled: true, windowSize: 200000 });
139+
});
140+
141+
it('ignores malformed fields individually and never rewrites malformed JSON', () => {
142+
writeLayer('settings.json', { autoCompactWindow: 500000, autoCompactEnabled: true });
143+
writeLayer('project/.claude/settings.json', { autoCompactWindow: '60', autoCompactEnabled: false });
144+
const localFile = path.join(testClaudeConfigDir, 'project/.claude/settings.local.json');
145+
fs.writeFileSync(localFile, '{ invalid JSON');
146+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project'))).toEqual({ enabled: false, windowSize: 500000 });
147+
expect(fs.readFileSync(localFile, 'utf-8')).toBe('{ invalid JSON');
148+
});
149+
150+
it.each([80, 0, -1, 1000001, 200000.5, null, '200000'])('ignores an invalid window of %s', (window) => {
151+
writeLayer('settings.json', { autoCompactWindow: window });
152+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project')).windowSize).toBeUndefined();
153+
});
154+
155+
it('refreshes settings and does not leak values between projects', () => {
156+
writeLayer('project/.claude/settings.json', { autoCompactWindow: 200000 });
157+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project')).windowSize).toBe(200000);
158+
writeLayer('project/.claude/settings.json', { autoCompactWindow: 300000 });
159+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'project')).windowSize).toBe(300000);
160+
expect(getAutoCompactConfig(path.join(testClaudeConfigDir, 'other')).windowSize).toBeUndefined();
161+
});
162+
});
163+
97164
describe('isKnownCommand', () => {
98165
it('should match exact NPM command', () => {
99166
expect(isKnownCommand(CCSTATUSLINE_COMMANDS.NPM)).toBe(true);

‎src/utils/claude-settings.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,45 @@ export async function setRefreshInterval(interval: number | null): Promise<void>
530530

531531
const VoiceConfigSchema = z.object({ enabled: z.boolean().optional() });
532532

533+
const AutoCompactConfigSchema = z.object({
534+
autoCompactEnabled: z.boolean().optional().catch(undefined),
535+
autoCompactWindow: z.number().int().min(100000).max(1000000).optional().catch(undefined)
536+
});
537+
538+
/** Read compaction fields independently so a layer can override just one field. */
539+
export function getAutoCompactConfig(cwd: string = process.cwd()): { enabled?: boolean; windowSize?: number } {
540+
let enabled: boolean | undefined;
541+
let windowSize: number | undefined;
542+
for (const filePath of getLayeredSettingsCandidatePathsByPriority(cwd)) {
543+
try {
544+
const raw: unknown = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
545+
const parsed = AutoCompactConfigSchema.safeParse(raw);
546+
if (parsed.success) {
547+
enabled ??= parsed.data.autoCompactEnabled;
548+
windowSize ??= parsed.data.autoCompactWindow;
549+
}
550+
} catch {
551+
// Missing, unreadable and malformed settings contribute no overrides.
552+
}
553+
if (enabled !== undefined && windowSize !== undefined) {
554+
break;
555+
}
556+
}
557+
if (enabled === undefined) {
558+
try {
559+
// Older /config preferences live outside the layered settings files.
560+
const raw: unknown = JSON.parse(fs.readFileSync(getClaudeJsonPath(), 'utf-8'));
561+
const parsed = AutoCompactConfigSchema.safeParse(raw);
562+
if (parsed.success) {
563+
enabled = parsed.data.autoCompactEnabled;
564+
}
565+
} catch {
566+
// Missing, unreadable and malformed legacy preferences add no override.
567+
}
568+
}
569+
return { enabled, windowSize };
570+
}
571+
533572
function getLayeredSettingsCandidatePathsByPriority(cwd: string): string[] {
534573
const userDir = getClaudeConfigDir();
535574
const projectDir = path.join(cwd, '.claude');

‎src/utils/model-context.ts‎

Lines changed: 57 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ interface ModelIdentifier {
88
display_name?: string;
99
}
1010

11+
export interface AutoCompactConfig {
12+
enabled?: boolean;
13+
windowSize?: number;
14+
}
15+
1116
const DEFAULT_CONTEXT_WINDOW_SIZE = 200000;
1217
const USABLE_CONTEXT_RATIO = 0.8;
1318
const CONTEXT_WINDOW_ENV_VAR = 'CCSTATUSLINE_CONTEXT_WINDOW_SIZE';
@@ -42,7 +47,7 @@ let cachedEnvRaw: string | undefined;
4247
let cachedEnvResult: number | null = null;
4348
let hasCachedEnv = false;
4449

45-
function parseContextWindowEnvValue(raw: string): number | null {
50+
function parsePositiveWindowEnvValue(raw: string): number | null {
4651
const trimmed = raw.trim();
4752
if (!trimmed) {
4853
return null;
@@ -61,7 +66,15 @@ function parseContextWindowEnvValue(raw: string): number | null {
6166

6267
const unit = suffixMatch[2]?.toLowerCase();
6368
const multiplier = unit === 'm' ? 1000000 : unit === 'k' ? 1000 : 1;
64-
const result = Math.round(numeric * multiplier);
69+
return toValidWindowSize(numeric * multiplier);
70+
}
71+
72+
function parseContextWindowEnvValue(raw: string): number | null {
73+
const parsed = parsePositiveWindowEnvValue(raw);
74+
if (parsed === null) {
75+
return null;
76+
}
77+
const result = Math.round(parsed);
6578

6679
// Reject nonsensical tiny windows (e.g. "1.5" without a unit rounds to 2).
6780
if (result < 1000) {
@@ -71,6 +84,12 @@ function parseContextWindowEnvValue(raw: string): number | null {
7184
return result;
7285
}
7386

87+
function parseAutoCompactWindowEnvValue(raw: string): number | null {
88+
const parsed = parsePositiveWindowEnvValue(raw);
89+
// Preserve small positive values so they reach Claude Code's minimum clamp.
90+
return parsed === null ? null : Math.round(Math.max(100000, Math.min(1000000, parsed)));
91+
}
92+
7493
export function getContextWindowEnvOverride(): number | null {
7594
const raw = process.env[CONTEXT_WINDOW_ENV_VAR];
7695
if (hasCachedEnv && raw === cachedEnvRaw) {
@@ -137,43 +156,42 @@ export function getModelContextIdentifier(model?: string | ModelIdentifier): str
137156
return id ?? displayName;
138157
}
139158

140-
export function getContextConfig(modelIdentifier?: string, contextWindowSize?: number | null): ModelContextConfig {
141-
const envOverride = getContextWindowEnvOverride();
142-
if (envOverride !== null) {
143-
return {
144-
maxTokens: envOverride,
145-
usableTokens: Math.floor(envOverride * USABLE_CONTEXT_RATIO)
146-
};
147-
}
148-
149-
const statusWindowSize = toValidWindowSize(contextWindowSize);
150-
if (statusWindowSize !== null) {
151-
return {
152-
maxTokens: statusWindowSize,
153-
usableTokens: Math.floor(statusWindowSize * USABLE_CONTEXT_RATIO)
154-
};
155-
}
156-
157-
// Last-resort fallback when neither the live status window size nor a
158-
// model-name hint is available. Defaults to 200k, overridable via
159-
// CCSTATUSLINE_CONTEXT_SIZE_FALLBACK.
160-
const fallbackWindowSize = getFallbackContextWindowSize();
161-
const defaultConfig = {
162-
maxTokens: fallbackWindowSize,
163-
usableTokens: Math.floor(fallbackWindowSize * USABLE_CONTEXT_RATIO)
164-
};
165-
166-
if (!modelIdentifier) {
167-
return defaultConfig;
168-
}
159+
function isEnabledEnv(value: string | undefined): boolean {
160+
return /^(1|true|yes|on)$/i.test(value?.trim() ?? '');
161+
}
169162

170-
const inferredWindowSize = parseContextWindowSize(modelIdentifier);
171-
if (inferredWindowSize !== null) {
172-
return {
173-
maxTokens: inferredWindowSize,
174-
usableTokens: Math.floor(inferredWindowSize * USABLE_CONTEXT_RATIO)
175-
};
176-
}
163+
function getUsableTokens(maxTokens: number, autoCompact: AutoCompactConfig): number {
164+
if (autoCompact.enabled === false
165+
|| isEnabledEnv(process.env.DISABLE_AUTO_COMPACT)
166+
|| isEnabledEnv(process.env.DISABLE_COMPACT)) {
167+
return maxTokens;
168+
}
169+
170+
const rawWindow = process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
171+
const envWindow = rawWindow === undefined ? null : parseAutoCompactWindowEnvValue(rawWindow);
172+
// Claude Code bounds its compaction window to 100k–1M and the model window.
173+
const configuredWindow = envWindow ?? toValidWindowSize(autoCompact.windowSize);
174+
const windowSize = Math.min(maxTokens, configuredWindow ?? maxTokens);
175+
176+
const rawPercent = process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE;
177+
const percent = rawPercent === undefined ? NaN : Number(rawPercent.replace(/_/g, ''));
178+
// The live trigger isn't in the status payload. Retain the existing 80%
179+
// estimate; an explicit percentage can lower it, never raise it.
180+
const ratio = Number.isFinite(percent) && percent >= 1 && percent <= 100
181+
? Math.min(USABLE_CONTEXT_RATIO, percent / 100)
182+
: USABLE_CONTEXT_RATIO;
183+
return Math.max(1, Math.floor(windowSize * ratio));
184+
}
177185

178-
return defaultConfig;
186+
export function getContextConfig(
187+
modelIdentifier?: string,
188+
contextWindowSize?: number | null,
189+
autoCompact: AutoCompactConfig = {}
190+
): ModelContextConfig {
191+
const maxTokens = getContextWindowEnvOverride()
192+
?? toValidWindowSize(contextWindowSize)
193+
?? (modelIdentifier ? parseContextWindowSize(modelIdentifier) : null)
194+
?? getFallbackContextWindowSize();
195+
196+
return { maxTokens, usableTokens: getUsableTokens(maxTokens, autoCompact) };
179197
}

0 commit comments

Comments
 (0)