feat(claude): compact old threads before they burn through usage (#8144)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 authored and GitHub committed 2026-08-25 01:08:57 -07:00
1 parent 1baf99195a
commit c7222ca4df
25 files changed
+1105 -32

No files matched your search

@@ -324,6 +324,7 @@ export const ThreadTokenUsageSnapshot = Schema.Struct({
toolUses: Schema.optional(NonNegativeInt),
durationMs: Schema.optional(NonNegativeInt),
compactsAutomatically: Schema.optional(Schema.Boolean),
autoCompactThreshold: Schema.optional(PositiveInt),
});
export type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;
+31
View File
@@ -5,6 +5,7 @@ import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
import {
ClientSettingsSchema,
ClientSettingsPatch,
ClaudeSettings,
DEFAULT_SERVER_SETTINGS,
defaultEnabledForDriver,
resolveProviderInstanceEnabled,
@@ -17,6 +18,36 @@ const decodeClientSettingsPatch = Schema.decodeUnknownSync(ClientSettingsPatch);
const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
describe("ClaudeSettings auto-compaction", () => {
it("uses Claude's default threshold when no override is configured", () => {
expect(decodeClaudeSettings({}).autoCompactWindow).toBe("");
});
it.each(["100000", "300000", "1000000"])(
"accepts a supported auto-compaction threshold: %s",
(value) => {
expect(decodeClaudeSettings({ autoCompactWindow: value }).autoCompactWindow).toBe(value);
},
);
it.each(["99999", "1000001", "300k", "invalid"])(
"rejects an unsupported auto-compaction threshold: %s",
(value) => {
expect(() => decodeClaudeSettings({ autoCompactWindow: value })).toThrow();
},
);
it("rejects an unsupported threshold at the settings patch boundary", () => {
expect(() =>
decodeServerSettingsPatch({ providers: { claudeAgent: { autoCompactWindow: "300k" } } }),
).toThrow();
expect(
decodeServerSettingsPatch({ providers: { claudeAgent: { autoCompactWindow: "300000" } } }),
).toBeDefined();
});
});
describe("ClientSettings word wrap", () => {
it("defaults word wrap on", () => {
+25 -1
View File
@@ -373,6 +373,11 @@ export const CodexSettings = makeProviderSettingsSchema(
);
export type CodexSettings = typeof CodexSettings.Type;
// Empty, or an integer from 100,000 to 1,000,000. Shared by the full
// Claude settings schema and its patch so an out-of-range value fails at
// the update that introduced it.
const CLAUDE_AUTO_COMPACT_WINDOW_PATTERN = /^(?:|[1-9]\d{5}|1000000)$/;
export const ClaudeSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
@@ -410,9 +415,23 @@ export const ClaudeSettings = makeProviderSettingsSchema(
},
}),
),
autoCompactWindow: TrimmedString.check(
Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN),
).pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "Auto-compact after",
description:
"Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude's default.",
providerSettingsForm: {
placeholder: "e.g. 300000",
clearWhenEmpty: "omit",
},
}),
),
},
{
order: ["binaryPath", "homePath", "launchArgs"],
order: ["binaryPath", "homePath", "autoCompactWindow", "launchArgs"],
},
);
export type ClaudeSettings = typeof ClaudeSettings.Type;
@@ -797,6 +816,11 @@ const ClaudeSettingsPatch = Schema.Struct({
homePath: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
launchArgs: Schema.optionalKey(TrimmedString),
// Validated at the patch boundary so a typo fails the one update with a
// schema error instead of a generic whole-settings failure.
autoCompactWindow: Schema.optionalKey(
TrimmedString.check(Schema.isPattern(CLAUDE_AUTO_COMPACT_WINDOW_PATTERN)),
),
});
const CursorSettingsPatch = Schema.Struct({
+4
View File
@@ -226,6 +226,10 @@
"./usageFormat": {
"types": "./src/usageFormat.ts",
"import": "./src/usageFormat.ts"
},
"./claudeCompaction": {
"types": "./src/claudeCompaction.ts",
"import": "./src/claudeCompaction.ts"
}
},
"scripts": {
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vite-plus/test";
import {
formatClaudeResumeCompactionQuestion,
isClaudeResumeCompactionQuestion,
} from "./claudeCompaction.ts";
describe("claude resume compaction copy", () => {
// The matcher must recognize every question the formatter can produce.
// This is the drift guard: rewording one side fails here.
it.each([
{ ageMinutes: 145, estimatedTokens: 275_123 },
{ ageMinutes: 70, estimatedTokens: 100_000 },
{ ageMinutes: 59, estimatedTokens: 1_234_567 },
{ ageMinutes: 0, estimatedTokens: 0 },
])("matches its own formatted question (%o)", (input) => {
const question = formatClaudeResumeCompactionQuestion(input);
expect(isClaudeResumeCompactionQuestion(question)).toBe(true);
});
it("formats ages above and below one hour", () => {
expect(
formatClaudeResumeCompactionQuestion({ ageMinutes: 145, estimatedTokens: 275_123 }),
).toBe("This session is 2h 25m old and uses 275,123 tokens. Compact it before continuing?");
expect(formatClaudeResumeCompactionQuestion({ ageMinutes: 45, estimatedTokens: 1_000 })).toBe(
"This session is 45m old and uses 1,000 tokens. Compact it before continuing?",
);
});
it("does not match unrelated questions", () => {
expect(
isClaudeResumeCompactionQuestion("The build cache is large. Compact it before continuing?"),
).toBe(false);
});
});
+26
View File
@@ -0,0 +1,26 @@
/**
* Copy for Claude's resume compaction dialog, shared by the server adapter
* (which asks the question) and the web client (which recognizes the
* question and its "never" answer in resolved user-input activities to
* mirror the dismissal). Both sides must agree on these strings, so they
* live here: reword the question or the answer label in this file only.
*/
export const CLAUDE_RESUME_COMPACTION_NEVER_ANSWER = "Don't ask again";
export function formatClaudeResumeCompactionQuestion(input: {
readonly ageMinutes: number;
readonly estimatedTokens: number;
}): string {
const ageLabel =
input.ageMinutes >= 60
? `${Math.floor(input.ageMinutes / 60)}h ${input.ageMinutes % 60}m`
: `${input.ageMinutes}m`;
return `This session is ${ageLabel} old and uses ${input.estimatedTokens.toLocaleString("en-US")} tokens. Compact it before continuing?`;
}
const CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN =
/^This session is (?:\d+h \d+m|\d+m) old and uses \d{1,3}(?:,\d{3})* tokens\. Compact it before continuing\?$/u;
export function isClaudeResumeCompactionQuestion(question: string): boolean {
return CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN.test(question);
}
+31
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test";
import { ProviderDriverKind, ProviderInstanceId, type ModelCapabilities } from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
buildProviderOptionSelectionsFromDescriptors,
createModelCapabilities,
createModelSelection,
@@ -155,3 +156,33 @@ describe("model slug normalization", () => {
expect(normalizeCustomModelSlug(" opus ")).toBe("opus");
});
});
describe("applyClaudePromptEffortPrefix", () => {
it("keeps slash commands intact when ultrathink is selected", () => {
expect(applyClaudePromptEffortPrefix("/compact", "ultrathink")).toBe("/compact");
expect(applyClaudePromptEffortPrefix(" /compact keep recent errors ", "ultrathink")).toBe(
"/compact keep recent errors",
);
expect(applyClaudePromptEffortPrefix(" /review src/model.ts ", "ultrathink")).toBe(
"/review src/model.ts",
);
expect(applyClaudePromptEffortPrefix("/security-review", "ultrathink")).toBe(
"/security-review",
);
expect(applyClaudePromptEffortPrefix("/plugin:skill run", "ultrathink")).toBe(
"/plugin:skill run",
);
expect(applyClaudePromptEffortPrefix("/deploy.prod to staging", "ultrathink")).toBe(
"/deploy.prod to staging",
);
});
it("still adds the ultrathink prefix to ordinary prompts", () => {
expect(applyClaudePromptEffortPrefix("Investigate this failure", "ultrathink")).toBe(
"Ultrathink:\nInvestigate this failure",
);
expect(applyClaudePromptEffortPrefix("/home/theo/app.ts crashed on load", "ultrathink")).toBe(
"Ultrathink:\n/home/theo/app.ts crashed on load",
);
});
});
+5 -1
View File
@@ -362,7 +362,11 @@ export function applyClaudePromptEffortPrefix(
if (!trimmed) {
return trimmed;
}
if (effort !== "ultrathink") {
// Prefixing a slash command turns it into plain prose, so Claude never
// runs it. Command names come from arbitrary file names ("/deploy.prod",
// "/plugin:skill"), so accept any first token without a second slash;
// absolute paths like "/home/theo/app.ts" keep the prefix.
if (effort !== "ultrathink" || /^\/[^\s/]+(?:\s|$)/u.test(trimmed)) {
return trimmed;
}
if (trimmed.startsWith("Ultrathink:")) {