Skip to content
TypeScript

feat(claude): idle compaction has a global default and per-instance overrides (#23037)

Julius Marminged13fc846700e
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 5d3e9a56799..97ebde00ac2 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -97,6 +97,7 @@ import {
type ProviderThreadId,
type RunId,
type ThreadId,
+ resolveIdleCompaction,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
@@ -133,6 +134,7 @@ import {
type CompiledClaudeModelSelection,
} from "../../claudeModelOptions.ts";
import * as ServerConfig from "../../config.ts";
+import * as ServerSettings from "../../serverSettings.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
@@ -3886,6 +3888,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
adapterOptions: ClaudeAdapterV2Options,
) {
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
+ const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
const { attachmentsDir, fileSystem, path, crypto, idAllocator, queryRunner } = adapterOptions;
const subagentModelCatalog = scopeClaudeModelCatalog(
BUNDLED_CLAUDE_MODEL_CATALOG,
@@ -9036,6 +9039,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
if (request.dialogKind !== "resume_return") {
return { behavior: "cancelled" as const };
}
+ const idleCompaction = Option.isSome(serverSettings)
+ ? yield* serverSettings.value.getSettings.pipe(
+ Effect.map((settings) =>
+ resolveIdleCompaction(settings, adapterOptions.instanceId),
+ ),
+ Effect.orElseSucceed(() => adapterOptions.settings.idleCompaction),
+ )
+ : adapterOptions.settings.idleCompaction;
+ if (idleCompaction === "off") {
+ return { behavior: "completed" as const, result: "continue" as const };
+ }
const ageMinutes =
typeof request.payload.sessionAgeMinutes === "number" &&
Number.isFinite(request.payload.sessionAgeMinutes)
diff --git a/apps/server/src/orchestration-v2/IdleCompactionService.ts b/apps/server/src/orchestration-v2/IdleCompactionService.ts
index 337188753f7..30c81ba7033 100644
--- a/apps/server/src/orchestration-v2/IdleCompactionService.ts
+++ b/apps/server/src/orchestration-v2/IdleCompactionService.ts
@@ -1,6 +1,7 @@
import {
CommandId,
MessageId,
+ resolveIdleCompaction,
resolveProjectProviderInstanceEnabled,
type RunId,
type ThreadId,
@@ -18,8 +19,9 @@ import * as Orchestrator from "./Orchestrator.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
/**
- * Beta: when a Claude run completes, waits until shortly before its prompt
- * cache expires and sends `/compact` as a visible T3 Code turn. Timers live in
+ * Beta: when a run completes on a Claude instance set to compact before the
+ * cache expires, waits until shortly before its prompt cache expires and sends
+ * `/compact` as a visible T3 Code turn. Timers live in
* memory, so a server restart skips compactions that were still waiting.
*/
export const make = Effect.gen(function* () {
@@ -32,7 +34,6 @@ export const make = Effect.gen(function* () {
// Loops once after the wait: the thread may have moved on.
while (true) {
const current = yield* settings.getSettings;
- if (!current.compactIdleThreads) return;
const records = yield* projections.getThreadRecords(
threadId,
[
@@ -47,6 +48,8 @@ export const make = Effect.gen(function* () {
{ messageRunIds: [runId], turnItemStatuses: ["pending", "running", "waiting"] },
);
if (
+ resolveIdleCompaction(current, records.thread.providerInstanceId) !==
+ "beforeCacheExpires" ||
!resolveProjectProviderInstanceEnabled(
current,
records.thread.projectId,
diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts
index f91e63047cc..01a3bdc63b9 100644
--- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts
+++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts
@@ -97,6 +97,7 @@ const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings =>
customModels: [],
launchArgs: "",
autoCompactWindow: "",
+ idleCompaction: "default",
...overrides,
});
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index da367a88d0f..e794426afbe 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -70,6 +70,7 @@ import {
type RunId,
type RunAttemptId,
ProviderInteractionMode,
+ resolveIdleCompaction,
RuntimeMode,
} from "@t3tools/contracts";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
@@ -4011,6 +4012,10 @@ export default function ChatView(props: ChatViewProps) {
: null;
const resumeCompactionTokens =
activeContextWindow &&
+ resolveIdleCompaction(
+ settings,
+ activeProviderInstanceId ?? ProviderInstanceId.make("claudeAgent"),
+ ) !== "off" &&
!resumeCompactionPermanentlyDismissed &&
!nativeResumeCompactionDismissed &&
!compactDisabled &&
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index cdf7d618390..5e9797f21d0 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -6,6 +6,7 @@ import { Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import {
type DesktopUpdateChannel,
+ IDLE_COMPACTION_MODES,
ProviderDriverKind,
type ProviderInstanceId,
type SidebarProjectGroupingMode,
@@ -997,11 +998,11 @@ export function GeneralSettingsPanel() {
serverScoped
settingKeys={["compactIdleThreads"]}
{...searchableSetting("compact-idle-threads")}
- description="Compact long idle Claude threads just before their prompt cache expires, so coming back costs less."
+ description="When to compact an idle Claude thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Each Claude provider can override this."
resetAction={
settings.compactIdleThreads !== DEFAULT_UNIFIED_SETTINGS.compactIdleThreads ? (
<SettingResetButton
- label="compact idle Claude threads"
+ label="compact idle threads"
onClick={() =>
updateSettings({
compactIdleThreads: DEFAULT_UNIFIED_SETTINGS.compactIdleThreads,
@@ -1011,14 +1012,29 @@ export function GeneralSettingsPanel() {
) : null
}
control={
- <ScopedSwitch
- settingKeys={["compactIdleThreads"]}
- checked={settings.compactIdleThreads}
- onCheckedChange={(checked) =>
- updateSettings({ compactIdleThreads: Boolean(checked) })
- }
- aria-label="Compact idle Claude threads (beta)"
- />
+ <Select
+ value={settings.compactIdleThreads}
+ onValueChange={(value) => {
+ const mode = IDLE_COMPACTION_MODES.find((candidate) => candidate.value === value);
+ if (mode) updateSettings({ compactIdleThreads: mode.value });
+ }}
+ >
+ <SelectTrigger size="sm" className="w-full sm:w-56" aria-label="Compact idle threads">
+ <SelectValue>
+ {
+ IDLE_COMPACTION_MODES.find((mode) => mode.value === settings.compactIdleThreads)
+ ?.label
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectPopup align="end" alignItemWithTrigger={false}>
+ {IDLE_COMPACTION_MODES.map((mode) => (
+ <SelectItem hideIndicator key={mode.value} value={mode.value}>
+ {mode.label}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
}
/>
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 38737b2627b..c7c5f26ae90 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -338,10 +338,10 @@ export const SETTINGS_SEARCH_ITEMS = [
},
{
id: "compact-idle-threads",
- title: "Compact idle Claude threads (beta)",
+ title: "Compact idle threads",
to: "/settings/general",
scope: "environment-defaults",
- searchTerms: ["context compaction idle cache tokens usage summary beta experimental"],
+ searchTerms: ["claude context compaction idle cache tokens usage summary resume"],
},
{
id: "auto-settle-merged-threads",
diff --git a/docs/user/composer.md b/docs/user/composer.md
index a784b625108..67a8c0bc846 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -239,11 +239,8 @@ Provider commands must start the message to run. T3 Code commands such as
Send `/compact` in an existing conversation to reduce context usage when the
provider supports it. Web and desktop also offer compaction from the context meter.
-Enable **Compact idle Claude threads (beta)** in **Settings > General** to compact
-an idle Claude thread with at least 200,000 tokens of context shortly before its
-prompt cache expires, so coming back does not reprocess the whole conversation.
-The cache lasts 1 hour on Claude subscriptions and 5 minutes with an API key. The
-compaction appears in the thread as a `/compact` turn sent by T3 Code.
+Claude instances can also compact idle threads for you. See
+[compact long conversations](./providers-claude.md#compact-long-conversations).
## Goals
diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md
index 344cffb4780..cd9c22c5428 100644
--- a/docs/user/providers-claude.md
+++ b/docs/user/providers-claude.md
@@ -57,6 +57,16 @@ history for that message. The cache lasts about an hour on a Claude
subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using
composer commands.
+**Compact idle threads** in **Settings > General** controls this for threads
+over 200,000 tokens. Each Claude provider's settings can override it:
+
+- **When you return** shows the **Compact** chip described above. This is the default.
+- **Before the cache expires (beta)** compacts an idle thread shortly before its
+ prompt cache expires, so coming back does not reprocess the whole conversation.
+ The compaction appears in the thread as a `/compact` turn sent by T3 Code.
+- **Never** skips idle compaction and Claude's resume prompt. **Auto-compact after**
+ still applies, and you can still compact by hand.
+
## Usage limits
If your Claude subscription runs out of usage mid-turn, the thread shows which
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index 9cce0c7e970..fb25e1c1869 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -9,6 +9,7 @@ import {
ClaudeSettings,
DEFAULT_SERVER_SETTINGS,
requiredScopesForProjectMutation,
+ resolveIdleCompaction,
resolveProjectProviderInstanceEnabled,
resolveProviderInstanceEnabled,
ServerSettings,
@@ -134,6 +135,30 @@ describe("custom model settings", () => {
});
});
+describe("resolveIdleCompaction", () => {
+ it("lets a Claude instance override the global default", () => {
+ const settings = decodeServerSettings({
+ compactIdleThreads: "off",
+ providerInstances: {
+ claude_work: { driver: "claudeAgent", config: { idleCompaction: "onReturn" } },
+ claude_personal: { driver: "claudeAgent" },
+ },
+ });
+ expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claude_work"))).toBe(
+ "onReturn",
+ );
+ expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claude_personal"))).toBe("off");
+ expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claudeAgent"))).toBe("off");
+ });
+
+ it("keeps the legacy beta switch's behavior", () => {
+ expect(decodeServerSettings({ compactIdleThreads: true }).compactIdleThreads).toBe(
+ "beforeCacheExpires",
+ );
+ expect(decodeServerSettings({}).compactIdleThreads).toBe("onReturn");
+ });
+});
+
describe("ClientSettings notifications", () => {
it("requires opt-in when existing settings omit notification preferences", () => {
expect(decodeClientSettings({}).notificationMode).toBe("off");
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 620f659befe..67b850f2d7e 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -6,6 +6,7 @@ import {
type AuthEnvironmentScope,
} from "./auth.ts";
import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import * as Duration from "effect/Duration";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
@@ -643,6 +644,34 @@ export type CodexSettings = typeof CodexSettings.Type;
const CLAUDE_AUTO_COMPACT_WINDOW_PATTERN = /^(?:|[1-9]\d{5}|1000000)$/;
+export const IDLE_COMPACTION_MODES = [
+ { value: "onReturn", label: "When you return" },
+ { value: "beforeCacheExpires", label: "Before the cache expires (beta)" },
+ { value: "off", label: "Never" },
+] as const;
+export const IdleCompactionMode = Schema.Literals(IDLE_COMPACTION_MODES.map((mode) => mode.value));
+export type IdleCompactionMode = typeof IdleCompactionMode.Type;
+
+// `compactIdleThreads` was a beta on/off switch for compacting before the cache expires.
+const LegacyCompactIdleThreads = Schema.Boolean.pipe(
+ Schema.decodeTo(
+ IdleCompactionMode,
+ SchemaTransformation.transform({
+ decode: (enabled): IdleCompactionMode => (enabled ? "beforeCacheExpires" : "onReturn"),
+ encode: (mode) => mode === "beforeCacheExpires",
+ }),
+ ),
+);
+const IdleCompactionModeSetting = Schema.Union([IdleCompactionMode, LegacyCompactIdleThreads]);
+
+const INSTANCE_IDLE_COMPACTION_MODES = [
+ { value: "default", label: "Use default" },
+ ...IDLE_COMPACTION_MODES,
+] as const;
+const InstanceIdleCompaction = Schema.Literals(
+ INSTANCE_IDLE_COMPACTION_MODES.map((mode) => mode.value),
+);
+
export const ClaudeSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
@@ -694,9 +723,22 @@ export const ClaudeSettings = makeProviderSettingsSchema(
},
}),
),
+ idleCompaction: InstanceIdleCompaction.pipe(
+ Schema.withDecodingDefault(Effect.succeed("default" as const)),
+ Schema.annotateKey({
+ title: "Compact idle threads",
+ description:
+ "When to compact an idle thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Overrides the default in General settings.",
+ providerSettingsForm: {
+ control: "select",
+ options: INSTANCE_IDLE_COMPACTION_MODES,
+ clearWhenEmpty: "omit",
+ },
+ }),
+ ),
},
{
- order: ["binaryPath", "homePath", "autoCompactWindow", "launchArgs"],
+ order: ["binaryPath", "homePath", "autoCompactWindow", "idleCompaction", "launchArgs"],
},
);
export type ClaudeSettings = typeof ClaudeSettings.Type;
@@ -1160,7 +1202,9 @@ export const ServerSettings = Schema.Struct({
sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
),
- compactIdleThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
+ compactIdleThreads: IdleCompactionModeSetting.pipe(
+ Schema.withDecodingDefault(Effect.succeed("onReturn" as const)),
+ ),
snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(
@@ -1334,6 +1378,22 @@ export const resolveProjectProviderInstanceEnabled = (
: isUnconfiguredDefaultInstanceEnabled(instanceId);
};
+const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
+
+export const resolveIdleCompaction = (
+ settings: Pick<ServerSettings, "providerInstances" | "compactIdleThreads">,
+ instanceId: ProviderInstanceId,
+): IdleCompactionMode => {
+ const instance = Object.hasOwn(settings.providerInstances, instanceId)
+ ? settings.providerInstances[instanceId]
+ : undefined;
+ const override = decodeClaudeSettings(instance?.config ?? {}).pipe(
+ Option.map((config) => config.idleCompaction),
+ Option.getOrElse(() => "default" as const),
+ );
+ return override === "default" ? settings.compactIdleThreads : override;
+};
+
export const ServerSettingsOperation = Schema.Literals([
"normalize",
"check-exists",
@@ -1475,7 +1535,7 @@ export const ServerSettingsPatch = Schema.Struct({
deviceHosts: Schema.optionalKey(SshDeviceHostConfigs),
easDeviceHosts: Schema.optionalKey(EasDeviceHostConfigs),
sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
- compactIdleThreads: Schema.optionalKey(Schema.Boolean),
+ compactIdleThreads: Schema.optionalKey(IdleCompactionMode),
sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean),
sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean),