TypeScript
feat(server): compact idle Claude threads before the prompt cache expires (beta) (#21682)
Theo Browne5d3875d70339
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsindex 81b27125af3..9af2df087ec 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts@@ -1011,6 +1011,21 @@ describe("ClaudeAdapterV2 context usage", () => {undefined,);});++ it("dates cache expiry from the request start, not the response end", () => {+ const usage = ClaudeAdapterV2.claudeProviderTurnTokenUsage(+ {+ input_tokens: 1,+ output_tokens: 1,+ cache_creation: { ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 300 },+ },+ CLAUDE_TEST_MODEL_SELECTION,+ "2026-08-29T00:03:00.000Z",+ "",+ DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"),+ );+ assert.strictEqual(usage.promptCacheExpiresAt, "2026-08-29T00:05:00.000Z");+ });});describe("ClaudeAdapterV2 session permissions", () => {diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 8e904e9ea53..fd64e236c8c 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -242,11 +242,17 @@ export function claudeProviderTurnTokenUsage(modelSelection: ModelSelection,updatedAt: string,autoCompactWindow = "",+ requestedAt?: DateTime.Utc,) {const inputTokens = claudeMessageInputTokens(usage);const outputTokens = usage.output_tokens;const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation);const maxTokens = claudeContextWindow(modelSelection);+ // The cache lifetime starts with the request, not when its response ends.+ const promptCacheExpiresAt =+ promptCacheTtlMs === undefined || requestedAt === undefined+ ? undefined+ : DateTime.formatIso(DateTime.add(requestedAt, { milliseconds: promptCacheTtlMs }));return {usedTokens: inputTokens + outputTokens,maxTokens,@@ -256,6 +262,7 @@ export function claudeProviderTurnTokenUsage(reasoningOutputTokens: 0,...(promptCacheTtlMs === undefined ? {} : { promptCacheTtlMs }),...claudeAutoCompactThreshold(autoCompactWindow, maxTokens),+ ...(promptCacheExpiresAt === undefined ? {} : { promptCacheExpiresAt }),updatedAt,};}@@ -3254,7 +3261,12 @@ interface ActiveClaudeTurnContext {// assistant snapshots repeat message_start usage, which some proxies send// as zeros, so they only fill in input the stream has not reported. A// compaction makes the usage stale (null) without forgetting the request.- streamUsage: { readonly messageId: string; usage: ClaudeMessageUsage | null } | null;+ // `requestedAt` is when a streamed request started; its prompt cache lifetime starts then.+ streamUsage: {+ readonly messageId: string;+ requestedAt?: DateTime.Utc;+ usage: ClaudeMessageUsage | null;+ } | null;readonly toolCalls: Map<string, ActiveClaudeToolCall>;// A successful status can precede the boundary that supplies its token counts.compaction: Extract<OrchestrationV2TurnItem, { type: "compaction" }> | null;@@ -4121,13 +4133,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (const emitContextUsage = Effect.fnUntraced(function* (context: ActiveClaudeTurnContext,usage: ClaudeMessageUsage,+ requestStarted = false,) {const now = yield* DateTime.now;+ // Only message_start marks the request start; an assistant snapshot+ // arrives after generation, so it leaves the cache expiry unknown.+ if (requestStarted && context.streamUsage !== null) context.streamUsage.requestedAt = now;const tokenUsage = claudeProviderTurnTokenUsage(usage,context.input.modelSelection,DateTime.formatIso(now),adapterOptions.settings.autoCompactWindow,+ context.streamUsage?.requestedAt,);if (tokenUsage.inputTokens <= 0) return;yield* emitProviderEvent({@@ -7388,7 +7405,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (const usage: ClaudeMessageUsage | undefined = event.message.usage;context.streamUsage =usage === undefined ? null : { messageId: event.message.id, usage };- if (usage !== undefined) yield* emitContextUsage(context, usage);+ if (usage !== undefined) yield* emitContextUsage(context, usage, true);} else if (event.type === "message_delta") {const usage: typeof event.usage | undefined = event.usage;const stream = context.streamUsage;diff --git a/apps/server/src/orchestration-v2/IdleCompaction.test.ts b/apps/server/src/orchestration-v2/IdleCompaction.test.tsnew file mode 100644index 00000000000..ebcb3d993b3--- /dev/null+++ b/apps/server/src/orchestration-v2/IdleCompaction.test.ts@@ -0,0 +1,269 @@+import { describe, expect, it } from "@effect/vitest";+import {+ DEFAULT_SERVER_SETTINGS,+ EventId,+ MessageId,+ NodeId,+ ProjectId,+ ProviderDriverKind,+ ProviderInstanceId,+ ProviderThreadId,+ ProviderTurnId,+ RunId,+ ThreadId,+ type OrchestrationV2DomainEvent,+ type OrchestrationV2ServerCommand,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Queue from "effect/Queue";+import * as Stream from "effect/Stream";+import { TestClock } from "effect/testing";++import * as SqlitePersistence from "../persistence/Sqlite.ts";+import * as ServerSettings from "../serverSettings.ts";+import { idleCompactionWindow, type IdleCompactionRecords } from "./IdleCompaction.ts";+import * as IdleCompactionService from "./IdleCompactionService.ts";+import * as Orchestrator from "./Orchestrator.ts";+import * as ProjectionStore from "./ProjectionStore.ts";++const NOW_MS = Date.parse("2026-10-19T12:00:00.000Z");+const MINUTE_MS = 60_000;+const at = (offset = 0) => DateTime.makeUnsafe(NOW_MS + offset);+const threadId = ThreadId.make("idle-thread");+const runId = RunId.make("run-1");+const instanceId = ProviderInstanceId.make("claudeAgent");+const providerThreadId = ProviderThreadId.make("provider-thread");+const modelSelection = { instanceId, model: "claude-opus-5-5" };++function records(+ usage: { readonly usedTokens?: number; readonly cacheExpiresInMs?: number } = {},+): { -readonly [Key in keyof IdleCompactionRecords]: IdleCompactionRecords[Key] } {+ const messageId = MessageId.make("message-1");+ const nodeId = NodeId.make("root-node");+ return {+ thread: {+ id: threadId,+ projectId: ProjectId.make("project"),+ title: "Idle thread",+ createdBy: "user",+ creationSource: "web",+ providerInstanceId: instanceId,+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: providerThreadId,+ lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },+ forkedFrom: null,+ createdAt: at(-MINUTE_MS),+ updatedAt: at(),+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: at(),+ deletedAt: null,+ },+ runs: [+ {+ id: runId,+ threadId,+ ordinal: 1,+ providerInstanceId: instanceId,+ modelSelection,+ providerThreadId,+ userMessageId: messageId,+ rootNodeId: nodeId,+ activeAttemptId: null,+ status: "completed",+ requestedAt: at(-MINUTE_MS),+ startedAt: at(-MINUTE_MS),+ completedAt: at(),+ checkpointId: null,+ contextHandoffId: null,+ },+ ],+ messages: [+ {+ id: messageId,+ threadId,+ runId,+ nodeId,+ role: "user",+ text: "Explain this code",+ attachments: [],+ streaming: false,+ createdBy: "user",+ creationSource: "web",+ createdAt: at(-MINUTE_MS),+ updatedAt: at(-MINUTE_MS),+ },+ ],+ providerThreads: [+ {+ id: providerThreadId,+ driver: ProviderDriverKind.make("claudeAgent"),+ providerInstanceId: instanceId,+ providerSessionId: null,+ appThreadId: threadId,+ ownerNodeId: nodeId,+ nativeThreadRef: null,+ nativeConversationHeadRef: null,+ status: "idle",+ firstRunOrdinal: 1,+ lastRunOrdinal: 1,+ handoffIds: [],+ forkedFrom: null,+ pendingBackgroundTasks: [],+ createdAt: at(-MINUTE_MS),+ updatedAt: at(),+ },+ ],+ providerTurns: [+ {+ id: ProviderTurnId.make("provider-turn-1"),+ providerThreadId,+ nodeId,+ runAttemptId: null,+ nativeTurnRef: null,+ ordinal: 1,+ status: "completed",+ startedAt: at(-MINUTE_MS),+ completedAt: at(),+ tokenUsage: {+ usedTokens: usage.usedTokens ?? 250_000,+ ...(usage.cacheExpiresInMs === undefined+ ? {}+ : { promptCacheExpiresAt: DateTime.formatIso(at(usage.cacheExpiresInMs)) }),+ updatedAt: DateTime.formatIso(at()),+ },+ },+ ],+ runtimeRequests: [],+ turnItems: [],+ contextTransfers: [],+ };+}++describe("idleCompactionWindow", () => {+ it("starts two minutes before the cache Claude reported expires", () => {+ expect(idleCompactionWindow(records({ cacheExpiresInMs: 60 * MINUTE_MS }), NOW_MS)).toEqual({+ runId,+ startMs: NOW_MS + 58 * MINUTE_MS,+ endMs: NOW_MS + 60 * MINUTE_MS,+ });+ // A 5m cache whose last request started 3 minutes before the run ended.+ const late = records({ cacheExpiresInMs: 2 * MINUTE_MS });+ expect(idleCompactionWindow(late, NOW_MS)).toMatchObject({ startMs: NOW_MS });+ expect(idleCompactionWindow(late, NOW_MS + 2 * MINUTE_MS)).toBeNull();+ });++ it("skips small contexts, unknown expiry, other providers, switched threads, and compactions", () => {+ const cache = { cacheExpiresInMs: 60 * MINUTE_MS };+ expect(idleCompactionWindow(records({ ...cache, usedTokens: 199_999 }), NOW_MS)).toBeNull();+ expect(idleCompactionWindow(records(), NOW_MS)).toBeNull();+ const codex = records(cache);+ codex.providerThreads = [+ { ...codex.providerThreads[0]!, driver: ProviderDriverKind.make("codex") },+ ];+ expect(idleCompactionWindow(codex, NOW_MS)).toBeNull();+ const switched = records(cache);+ switched.thread = { ...switched.thread, providerInstanceId: ProviderInstanceId.make("codex") };+ expect(idleCompactionWindow(switched, NOW_MS)).toBeNull();+ const compacted = records(cache);+ compacted.messages = [{ ...compacted.messages[0]!, text: "/compact" }];+ expect(idleCompactionWindow(compacted, NOW_MS)).toBeNull();+ const archived = records(cache);+ archived.thread = { ...archived.thread, archivedAt: at() };+ expect(idleCompactionWindow(archived, NOW_MS)).toBeNull();+ });+});++const seed = Effect.fn("seedIdleThread")(function* (value: IdleCompactionRecords) {+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const event = { threadId, occurredAt: at() };+ yield* store.apply({+ ...event,+ id: EventId.make("e1"),+ type: "thread.created",+ payload: value.thread,+ });+ yield* store.apply({+ ...event,+ id: EventId.make("e2"),+ type: "run.created",+ payload: value.runs[0]!,+ });+ yield* store.apply({+ ...event,+ id: EventId.make("e3"),+ type: "message.updated",+ payload: value.messages[0]!,+ });+ yield* store.apply({+ ...event,+ id: EventId.make("e4"),+ type: "provider-thread.updated",+ payload: value.providerThreads[0]!,+ });+ yield* store.apply({+ ...event,+ id: EventId.make("e5"),+ type: "provider-turn.updated",+ payload: value.providerTurns[0]!,+ });+});++it.effect("sends /compact as T3 Code once the cache is about to expire", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(NOW_MS);+ const value = records({ cacheExpiresInMs: 5 * MINUTE_MS });+ yield* seed(value);+ const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();+ const commands = yield* Queue.unbounded<OrchestrationV2ServerCommand>();+ const reads = yield* Queue.unbounded<void>();+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const dependencies = Layer.mergeAll(+ Layer.succeed(ProjectionStore.ProjectionStoreV2, {+ ...store,+ getThreadRecords: (...args) =>+ store.getThreadRecords(...args).pipe(Effect.tap(() => Queue.offer(reads, undefined))),+ }),+ Layer.mock(ServerSettings.ServerSettingsService)({+ getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: true }),+ }),+ Layer.mock(Orchestrator.OrchestratorV2)({+ streamDomainEvents: Stream.fromQueue(events),+ dispatch: (command) =>+ Queue.offer(commands, command).pipe(Effect.as({ sequence: 1, storedEvents: [] })),+ }),+ );+ yield* Effect.gen(function* () {+ const service = yield* IdleCompactionService.make;+ yield* service.start();+ yield* Queue.offer(events, {+ id: EventId.make("completed"),+ type: "run.updated",+ threadId,+ occurredAt: at(),+ payload: value.runs[0]!,+ });+ yield* Queue.take(reads);+ yield* TestClock.adjust("2 minutes");+ expect(yield* Queue.size(commands)).toBe(0);+ yield* TestClock.adjust("1 minute");+ expect(yield* Queue.take(commands)).toMatchObject({+ type: "message.dispatch",+ threadId,+ text: "/compact",+ createdBy: "agent",+ creationSource: "server",+ });+ }).pipe(Effect.provide(dependencies));+ }).pipe(+ Effect.provide(ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),+ Effect.scoped,+ ),+);diff --git a/apps/server/src/orchestration-v2/IdleCompaction.ts b/apps/server/src/orchestration-v2/IdleCompaction.tsnew file mode 100644index 00000000000..b142dd4efb1--- /dev/null+++ b/apps/server/src/orchestration-v2/IdleCompaction.ts@@ -0,0 +1,103 @@+import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";+import { COMPACTION_SUGGESTION_MIN_TOKENS } from "@t3tools/shared/claudeCompaction";+import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";+import * as DateTime from "effect/DateTime";++// Claude Code's idleCompaction defaults to 200K and won't go below 100K. Below+// that a cold re-read is cheap, so compacting mostly loses context for little+// saving.+const MIN_CONTEXT_TOKENS = COMPACTION_SUGGESTION_MIN_TOKENS;+// Start this long before the cache expires: enough for the session to resume+// and send the compaction while the cache is still warm.+const LEAD_MS = 2 * 60_000;++export type IdleCompactionRecords = Pick<+ OrchestrationV2ThreadProjection,+ | "thread"+ | "runs"+ | "messages"+ | "providerThreads"+ | "providerTurns"+ | "runtimeRequests"+ | "turnItems"+ | "contextTransfers"+>;++/**+ * When an idle Claude thread should compact, or null when it should not. The+ * window ends when the prompt cache of Claude's last request expires (1h on+ * subscriptions, 5m on API keys); compacting after that pays a full uncached+ * read.+ */+export function idleCompactionWindow(+ {+ thread,+ runs,+ messages,+ providerThreads,+ providerTurns,+ runtimeRequests,+ turnItems,+ contextTransfers,+ }: IdleCompactionRecords,+ nowMs: number,+): {+ readonly runId: (typeof runs)[number]["id"];+ readonly startMs: number;+ readonly endMs: number;+} | null {+ if (thread.deletedAt !== null || thread.archivedAt !== null) return null;+ if (thread.settledAt !== null || thread.settledOverride === "settled") return null;+ if (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs)+ return null;+ if (thread.lineage.relationshipToParent === "subagent") return null;+ const latestRun = runs.reduce<(typeof runs)[number] | null>(+ (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),+ null,+ );+ if (latestRun?.status !== "completed" || latestRun.completedAt === null) return null;+ const message = messages.find((candidate) => candidate.id === latestRun.userMessageId);+ // Never compact a compaction, so one idle spell compacts at most once.+ if (message === undefined || message.text.trim().toLowerCase() === "/compact") return null;+ if (+ runtimeRequests.some((request) => request.status === "pending") ||+ // A pending merge-back belongs to the user's next message.+ contextTransfers.some(+ (transfer) =>+ transfer.type === "merge_back" &&+ transfer.targetThreadId === thread.id &&+ transfer.status === "pending",+ ) ||+ // Background work reports into the next turn; compaction would swallow it.+ derivePendingBackgroundWork({+ latestRun,+ runs,+ providerThreads,+ turnItems,+ activeProviderThreadId: thread.activeProviderThreadId,+ }).length > 0+ )+ return null;+ const providerThread = providerThreads.find(+ (candidate) => candidate.id === thread.activeProviderThreadId,+ );+ // The thread's current selection receives the /compact, so it must still be this Claude session.+ if (+ providerThread?.driver !== "claudeAgent" ||+ providerThread.id !== latestRun.providerThreadId ||+ providerThread.providerInstanceId !== thread.providerInstanceId ||+ latestRun.providerInstanceId !== thread.providerInstanceId+ )+ return null;+ const usages = providerTurns+ .filter((turn) => turn.providerThreadId === providerThread.id && turn.tokenUsage !== undefined)+ .map((turn) => turn.tokenUsage!)+ .toSorted((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt));+ if ((usages[0]?.usedTokens ?? 0) < MIN_CONTEXT_TOKENS) return null;+ // A request served fully from cache creates no cache entry and reports no+ // TTL, but it still refreshes the cache. Treat it as unknown and skip.+ const expiresAt = usages[0]?.promptCacheExpiresAt;+ const endMs = expiresAt === undefined ? Number.NaN : Date.parse(expiresAt);+ if (!Number.isFinite(endMs) || nowMs >= endMs) return null;+ return { runId: latestRun.id, startMs: endMs - LEAD_MS, endMs };+}diff --git a/apps/server/src/orchestration-v2/IdleCompactionService.ts b/apps/server/src/orchestration-v2/IdleCompactionService.tsnew file mode 100644index 00000000000..337188753f7--- /dev/null+++ b/apps/server/src/orchestration-v2/IdleCompactionService.ts@@ -0,0 +1,97 @@+import {+ CommandId,+ MessageId,+ resolveProjectProviderInstanceEnabled,+ type RunId,+ type ThreadId,+} from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as FiberMap from "effect/FiberMap";+import * as Stream from "effect/Stream";++import { forkParked } from "../serverActivation.ts";+import * as ServerSettings from "../serverSettings.ts";+import { idleCompactionWindow } from "./IdleCompaction.ts";+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+ * memory, so a server restart skips compactions that were still waiting.+ */+export const make = Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const settings = yield* ServerSettings.ServerSettingsService;++ const compactWhenDue = Effect.fn("IdleCompactionService.compactWhenDue")(+ function* (threadId: ThreadId, runId: RunId) {+ // 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,+ [+ "runs",+ "messages",+ "providerThreads",+ "providerTurns",+ "runtimeRequests",+ "turnItems",+ "contextTransfers",+ ],+ { messageRunIds: [runId], turnItemStatuses: ["pending", "running", "waiting"] },+ );+ if (+ !resolveProjectProviderInstanceEnabled(+ current,+ records.thread.projectId,+ records.thread.providerInstanceId,+ )+ )+ return;+ const nowMs = DateTime.toEpochMillis(yield* DateTime.now);+ const window = idleCompactionWindow(records, nowMs);+ if (window?.runId !== runId) return;+ if (nowMs < window.startMs) {+ yield* Effect.sleep(Duration.millis(window.startMs - nowMs));+ continue;+ }+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ // One compaction per completed run, even across duplicate events.+ commandId: CommandId.make(`server:idle-compact:${threadId}:${runId}`),+ messageId: MessageId.make(`idle-compact:${threadId}:${runId}`),+ threadId,+ text: "/compact",+ attachments: [],+ createdBy: "agent",+ creationSource: "server",+ dispatchMode: { type: "start_immediately" },+ });+ return;+ }+ },+ (effect, threadId) =>+ effect.pipe(+ Effect.catch((cause) => Effect.logWarning("idle compaction skipped", { threadId, cause })),+ ),+ );++ const start = Effect.fn("IdleCompactionService.start")(function* () {+ // Keyed by thread: a newer completed run replaces the waiting timer.+ const timers = yield* FiberMap.make<ThreadId>();+ yield* forkParked(+ Stream.runForEach(orchestrator.streamDomainEvents, (event) =>+ event.type === "run.updated" && event.payload.status === "completed"+ ? FiberMap.run(timers, event.threadId, compactWhenDue(event.threadId, event.payload.id))+ : Effect.void,+ ),+ );+ });+ return { start };+});diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex a02557a25b5..0b0f9c2ac3e 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -175,6 +175,7 @@ import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts";import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts";import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts";+import * as IdleCompactionService from "./orchestration-v2/IdleCompactionService.ts";import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts";import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";import * as EventStoreV2 from "./orchestration-v2/EventStore.ts";@@ -516,6 +517,10 @@ const layerThreadSettlementWorker = Layer.effectDiscard(ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())),).pipe(Layer.provide(layerPullRequestService), Layer.provide(ProjectionStoreV2.layer));+const layerIdleCompactionWorker = Layer.effectDiscard(+ IdleCompactionService.make.pipe(Effect.flatMap((service) => service.start())),+).pipe(Layer.provide(ProjectionStoreV2.layer));+const layerThreadPullRequestWorker = Layer.effectDiscard(ThreadPullRequestService.make.pipe(Effect.flatMap((service) => service.start())),).pipe(Layer.provide(layerPullRequestService));@@ -556,6 +561,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(AgentAwarenessRelay.layer,HeldHooksWaker.layer,layerThreadSettlementWorker,+ layerIdleCompactionWorker,StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)),DatabaseStorage.layer.pipe(Layer.provide(ProjectionMaintenance.layer),diff --git a/apps/web/src/components/chat/ContextWindowMeter.logic.test.ts b/apps/web/src/components/chat/ContextWindowMeter.logic.test.tsindex 581c1dba28a..3188c7963be 100644--- a/apps/web/src/components/chat/ContextWindowMeter.logic.test.ts+++ b/apps/web/src/components/chat/ContextWindowMeter.logic.test.ts@@ -143,11 +143,11 @@ describe("formatContextWindowCompactionMessage", () => {describe("shouldOfferResumeCompaction", () => {const now = "2026-08-24T12:00:00.000Z";- it("matches Claude's old-session age and context thresholds", () => {+ it("offers compaction for old sessions from 200k tokens", () => {expect(shouldOfferResumeCompaction({provider: "claudeAgent",- usedTokens: 100_000,+ usedTokens: 200_000,updatedAt: "2026-08-24T10:50:00.000Z",now,}),@@ -158,7 +158,7 @@ describe("shouldOfferResumeCompaction", () => {expect(shouldOfferResumeCompaction({provider: "claudeAgent",- usedTokens: 99_999,+ usedTokens: 199_999,updatedAt: "2026-08-24T10:00:00.000Z",now,}),diff --git a/apps/web/src/components/chat/ContextWindowMeter.logic.ts b/apps/web/src/components/chat/ContextWindowMeter.logic.tsindex 2e9eed1480c..69c4fbbec5b 100644--- a/apps/web/src/components/chat/ContextWindowMeter.logic.ts+++ b/apps/web/src/components/chat/ContextWindowMeter.logic.ts@@ -1,6 +1,7 @@import type { ModelSelection, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";import {CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,+ COMPACTION_SUGGESTION_MIN_TOKENS,isClaudeResumeCompactionQuestion,} from "@t3tools/shared/claudeCompaction";import {@@ -11,7 +12,6 @@ import { getTriggerDisplayModelName, type ModelEsque } from "./providerIconUtils// Used when the provider did not report its cache TTL: Claude's 1h cache plus slack.const CLAUDE_RESUME_COMPACTION_FALLBACK_MS = 70 * 60_000;-const CLAUDE_RESUME_COMPACTION_TOKENS = 100_000;export function providerSupportsManualCompaction(provider: ProviderInstanceEntry | null | undefined,@@ -70,7 +70,7 @@ export function shouldOfferResumeCompaction(input: {}): boolean {if (input.provider !== "claudeAgent" ||- (input.usedTokens ?? 0) < CLAUDE_RESUME_COMPACTION_TOKENS+ (input.usedTokens ?? 0) < COMPACTION_SUGGESTION_MIN_TOKENS) {return false;}diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex ce336db9aee..16c6ff3fb89 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -2303,6 +2303,35 @@ export function GeneralSettingsPanel() {}/>+ <SettingsRow+ serverScoped+ settingKeys={["compactIdleThreads"]}+ {...searchableSetting("compact-idle-threads")}+ description="Compact long idle Claude threads just before their prompt cache expires, so coming back costs less."+ resetAction={+ settings.compactIdleThreads !== DEFAULT_UNIFIED_SETTINGS.compactIdleThreads ? (+ <SettingResetButton+ label="compact idle Claude threads"+ onClick={() =>+ updateSettings({+ compactIdleThreads: DEFAULT_UNIFIED_SETTINGS.compactIdleThreads,+ })+ }+ />+ ) : null+ }+ control={+ <ScopedSwitch+ settingKeys={["compactIdleThreads"]}+ checked={settings.compactIdleThreads}+ onCheckedChange={(checked) =>+ updateSettings({ compactIdleThreads: Boolean(checked) })+ }+ aria-label="Compact idle Claude threads (beta)"+ />+ }+ />+{supportsAutoSettlement ? (<><SettingsRowdiff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex cd3cb34b5d2..38737b2627b 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -336,6 +336,13 @@ export const SETTINGS_SEARCH_ITEMS = [requiresThreadAutoSettlement: true,scope: "project-defaults",},+ {+ id: "compact-idle-threads",+ title: "Compact idle Claude threads (beta)",+ to: "/settings/general",+ scope: "environment-defaults",+ searchTerms: ["context compaction idle cache tokens usage summary beta experimental"],+ },{id: "auto-settle-merged-threads",title: "Auto-settle merged threads",diff --git a/docs/user/composer.md b/docs/user/composer.mdindex 39eb55a8c28..a784b625108 100644--- a/docs/user/composer.md+++ b/docs/user/composer.md@@ -239,6 +239,12 @@ Provider commands must start the message to run. T3 Code commands such asSend `/compact` in an existing conversation to reduce context usage when theprovider 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.+## GoalsWith Codex and Claude, send `/goal` followed by what "done" means, for examplediff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex 8b5e598ca7e..a60f7b7c513 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -172,6 +172,7 @@ export const OrchestrationV2ProviderTurnTokenUsage = Schema.Struct({reasoningOutputTokens: Schema.optional(NonNegativeInt),promptCacheTtlMs: Schema.optional(PositiveInt),autoCompactThreshold: Schema.optional(PositiveInt),+ promptCacheExpiresAt: Schema.optional(Schema.String),updatedAt: Schema.String,});export type OrchestrationV2ProviderTurnTokenUsage =diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 707c5d0cf63..d4136741fbb 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -1158,6 +1158,7 @@ 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))),snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe(@@ -1471,6 +1472,7 @@ export const ServerSettingsPatch = Schema.Struct({deviceOnboardingCompleted: Schema.optionalKey(Schema.Boolean),deviceHosts: Schema.optionalKey(SshDeviceHostConfigs),sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),+ compactIdleThreads: Schema.optionalKey(Schema.Boolean),sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean),sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean),diff --git a/packages/shared/src/claudeCompaction.ts b/packages/shared/src/claudeCompaction.tsindex cadb870e8dc..b20b9954040 100644--- a/packages/shared/src/claudeCompaction.ts+++ b/packages/shared/src/claudeCompaction.ts@@ -24,3 +24,10 @@ const CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN =export function isClaudeResumeCompactionQuestion(question: string): boolean {return CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN.test(question);}++/**+ * Context size below which T3 does not suggest or run a Claude compaction:+ * the stale-thread Compact chip and idle compaction. Matches Claude Code's+ * idleCompaction default of 200K.+ */+export const COMPACTION_SUGGESTION_MIN_TOKENS = 200_000;