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

@@ -413,6 +413,25 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("passes the configured auto-compaction window to Claude", () => {
const harness = makeHarness({ claudeConfig: { autoCompactWindow: "300000" } });
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const options = harness.getLastCreateQueryInput()?.options;
assert.deepEqual(options?.settings, { autoCompactWindow: 300000 });
assert.deepEqual(options?.supportedDialogKinds, ["resume_return"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("forwards claude effort levels into query options", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -730,6 +749,39 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("keeps compact commands intact when ultrathink is selected", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const modelSelection = createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-sonnet-4-6",
[{ id: "effort", value: "ultrathink" }],
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection,
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "/compact",
attachments: [],
modelSelection,
});
const promptText = yield* Effect.promise(() =>
readFirstPromptText(harness.getLastCreateQueryInput()),
);
assert.equal(promptText, "/compact");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("embeds image attachments in Claude user messages", () => {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "claude-attachments-"));
const harness = makeHarness({
@@ -4400,6 +4452,62 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("routes Claude resume compaction through the shared user-input UI", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: RESUME_THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
resumeCursor: { resume: "550e8400-e29b-41d4-a716-446655440000" },
runtimeMode: "full-access",
});
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
const onUserDialog = harness.getLastCreateQueryInput()?.options.onUserDialog;
assert.equal(typeof onUserDialog, "function");
if (!onUserDialog) return;
const dialogPromise = onUserDialog(
{
dialogKind: "resume_return",
payload: { sessionAgeMinutes: 145, estimatedTokens: 275123 },
},
{ signal: new AbortController().signal },
);
const requested = yield* Stream.runHead(adapter.streamEvents);
assert.equal(requested._tag, "Some");
if (requested._tag !== "Some" || requested.value.type !== "user-input.requested") return;
const question = requested.value.payload.questions[0];
assert.equal(question?.header, "Resume session");
assert.match(question?.question ?? "", /2h 25m/);
assert.match(question?.question ?? "", /275,123 tokens/);
assert.deepEqual(
question?.options.map((option) => option.label),
["Compact and continue", "Keep full history", "Don't ask again"],
);
if (!question || !requested.value.requestId) return;
yield* adapter.respondToUserInput(
session.threadId,
ApprovalRequestId.make(requested.value.requestId),
{ [question.id]: "Compact and continue" },
);
const resolved = yield* Stream.runHead(adapter.streamEvents);
assert.equal(resolved._tag, "Some");
if (resolved._tag === "Some") assert.equal(resolved.value.type, "user-input.resolved");
assert.deepEqual(yield* Effect.promise(() => dialogPromise), {
behavior: "completed",
result: "compact",
});
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("handles AskUserQuestion via user-input.requested/resolved lifecycle", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -4689,6 +4797,73 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("denies AskUserQuestion when the signal aborted before the listener registered", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "approval-required",
});
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
const canUseTool = harness.getLastCreateQueryInput()?.options.canUseTool;
assert.equal(typeof canUseTool, "function");
if (!canUseTool) {
return;
}
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 2).pipe(
Stream.runCollect,
Effect.forkChild,
);
// Abort before the call so the adapter's listener registration can
// never observe the abort event, only the recheck can.
const controller = new AbortController();
controller.abort();
const permissionPromise = canUseTool(
"AskUserQuestion",
{
questions: [
{
question: "Continue?",
header: "Continue",
options: [{ label: "Yes", description: "Proceed" }],
multiSelect: false,
},
],
},
{
signal: controller.signal,
toolUseID: "tool-ask-pre-aborted",
},
);
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.deepEqual(permissionResult, {
behavior: "deny",
message: "User cancelled tool execution.",
} satisfies PermissionResult);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
["user-input.requested", "user-input.resolved"],
);
const resolvedEvent = runtimeEvents[1];
if (resolvedEvent?.type === "user-input.resolved") {
assert.deepEqual(resolvedEvent.payload.answers, {});
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("stopping a session settles pending user-input waits", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -57,6 +57,10 @@ import {
getProviderOptionDescriptors,
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import {
CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
formatClaudeResumeCompactionQuestion,
} from "@t3tools/shared/claudeCompaction";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
@@ -543,6 +547,7 @@ function makeClaudeTokenUsageSnapshot(input: {
readonly totalProcessedTokens?: number;
readonly lastUsedTokens?: number;
readonly compactsAutomatically?: boolean;
readonly autoCompactThreshold?: number;
}): ThreadTokenUsageSnapshot | undefined {
const activeTokens = finiteNonNegativeInteger(input.activeTokens);
if (activeTokens === undefined || activeTokens <= 0) {
@@ -570,6 +575,9 @@ function makeClaudeTokenUsageSnapshot(input: {
...(input.compactsAutomatically !== undefined
? { compactsAutomatically: input.compactsAutomatically }
: {}),
...(input.autoCompactThreshold !== undefined
? { autoCompactThreshold: input.autoCompactThreshold }
: {}),
};
}
@@ -604,11 +612,13 @@ function normalizeClaudeContextUsageApiSnapshot(
value: SDKControlGetContextUsageResponse,
totalProcessedTokens?: number,
): ThreadTokenUsageSnapshot | undefined {
const autoCompactThreshold = finitePositiveInteger(value.autoCompactThreshold);
return makeClaudeTokenUsageSnapshot({
activeTokens: value.totalTokens,
contextWindow: value.maxTokens,
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
compactsAutomatically: value.isAutoCompactEnabled,
...(autoCompactThreshold !== undefined ? { autoCompactThreshold } : {}),
});
}
@@ -3953,6 +3963,12 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
callbackOptions.signal.addEventListener("abort", onAbort, {
once: true,
});
// The signal may have aborted during the awaited event emissions
// above, before the listener existed; settle now so the dialog
// cannot hang with a lingering pending question.
if (callbackOptions.signal.aborted) {
yield* settleAsAborted;
}
// Block until the user provides answers.
const answers = yield* Deferred.await(answersDeferred);
@@ -4001,6 +4017,76 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
} satisfies PermissionResult;
});
const handleResumeDialog = Effect.fn("handleResumeDialog")(function* (
request: Parameters<NonNullable<ClaudeQueryOptions["onUserDialog"]>>[0],
callbackOptions: Parameters<NonNullable<ClaudeQueryOptions["onUserDialog"]>>[1],
) {
if (request.dialogKind !== "resume_return") {
return { behavior: "cancelled" as const };
}
const context = yield* Ref.get(contextRef);
if (!context) {
return { behavior: "cancelled" as const };
}
// The question copy lives in @t3tools/shared/claudeCompaction because
// the web client recognizes this exact text (and the "never" answer)
// to mirror a permanent dismissal.
const question = formatClaudeResumeCompactionQuestion({
ageMinutes: finiteNonNegativeInteger(request.payload.sessionAgeMinutes) ?? 0,
estimatedTokens: finiteNonNegativeInteger(request.payload.estimatedTokens) ?? 0,
});
const result = yield* handleAskUserQuestion(
context,
{
questions: [
{
header: "Resume session",
question,
options: [
{
label: "Compact and continue",
description: "Resume with a summary and use fewer tokens.",
},
{
label: "Keep full history",
description: "Resume without changing the conversation.",
},
{
label: CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
description: "Keep full history and skip future resume prompts.",
},
],
multiSelect: false,
},
],
},
{
signal: callbackOptions.signal,
...(request.toolUseID ? { toolUseID: request.toolUseID } : {}),
},
);
if (result.behavior !== "allow") {
return { behavior: "cancelled" as const };
}
const answers = result.updatedInput.answers;
const selection =
answers && typeof answers === "object" && !Array.isArray(answers)
? (answers as Record<string, unknown>)[question]
: undefined;
const action =
selection === "Compact and continue"
? "compact"
: selection === CLAUDE_RESUME_COMPACTION_NEVER_ANSWER
? "never"
: "continue";
return { behavior: "completed" as const, result: action };
});
const canUseToolEffect = Effect.fn("canUseTool")(function* (
toolName: Parameters<CanUseTool>[0],
toolInput: Parameters<CanUseTool>[1],
@@ -4106,6 +4192,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
callbackOptions.signal.addEventListener("abort", onAbort, {
once: true,
});
// Same late-listener race as handleAskUserQuestion: the signal may
// have aborted while the request event emissions were awaited.
if (callbackOptions.signal.aborted) {
onAbort();
}
const decision = yield* Deferred.await(decisionDeferred);
pendingApprovals.delete(requestId);
@@ -4161,6 +4252,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>
runPromise(canUseToolEffect(toolName, toolInput, callbackOptions));
const onUserDialog: NonNullable<ClaudeQueryOptions["onUserDialog"]> = (
request,
callbackOptions,
) => runPromise(handleResumeDialog(request, callbackOptions));
const claudeBinaryPath = claudeSdkExecutablePath;
const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags;
@@ -4196,6 +4291,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
...(fastMode ? { fastMode: true } : {}),
...(ultracode ? { ultracode: true } : {}),
...(claudeSettings.autoCompactWindow
? { autoCompactWindow: Number(claudeSettings.autoCompactWindow) }
: {}),
};
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
// The attachments dir grant lets the agent Read/copy pasted images at
@@ -4228,6 +4326,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(newSessionId ? { sessionId: newSessionId } : {}),
includePartialMessages: true,
canUseTool,
onUserDialog,
supportedDialogKinds: ["resume_return"],
env: claudeEnvironment,
additionalDirectories,
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
@@ -927,7 +927,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
: undefined;
const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
const slashCommands = capabilities?.slashCommands ?? [];
const slashCommands = [
{
name: "compact",
description: "Summarize the conversation and reduce context usage",
},
...(capabilities?.slashCommands ?? []),
];
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
if (!capabilities) {
@@ -106,6 +106,7 @@ const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings =>
homePath: "",
customModels: [],
launchArgs: "",
autoCompactWindow: "",
...overrides,
});
@@ -2151,6 +2151,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
assert.deepStrictEqual(status.slashCommands, [
{
name: "compact",
description: "Summarize the conversation and reduce context usage",
},
{
name: "review",
description: "Review a pull request",
@@ -2194,6 +2198,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
assert.deepStrictEqual(status.slashCommands, [
{
name: "compact",
description: "Summarize the conversation and reduce context usage",
},
{
name: "ui",
description: "Explore and refine UI",
+2
View File
@@ -190,6 +190,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
homePath: "",
customModels: ["claude-custom"],
launchArgs: "",
autoCompactWindow: "",
});
assert.deepEqual(
next.textGenerationModelSelection,
@@ -581,6 +582,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
homePath: "",
customModels: [],
launchArgs: "",
autoCompactWindow: "",
});
assert.deepEqual(next.providers.opencode, {
// OpenCode is disabled by default; this update only touches paths.
+173 -15
View File
@@ -82,6 +82,7 @@ import {
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
import { AsyncResult } from "effect/unstable/reactivity";
import { isElectron } from "../env";
import { readLocalApi } from "../localApi";
@@ -179,6 +180,7 @@ import {
CheckCircle2Icon,
ChevronDownIcon,
GitBranchIcon,
Minimize2Icon,
PaperclipIcon,
WifiOffIcon,
} from "lucide-react";
@@ -196,7 +198,11 @@ import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
import { useBrowserHistoryStore } from "~/browserHistoryStore";
import { registerFaviconProjectForThread } from "~/browserFaviconStore";
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
import {
applyProviderInstanceSettings,
deriveProviderInstanceEntries,
NO_PROVIDER_MODEL_SELECTION,
} from "../providerInstances";
import {
useClientSettings,
useClientSettingsHydrated,
@@ -223,6 +229,7 @@ import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../threadRo
import {
beginBackgroundDraftSubmissionByRef,
clearBackgroundDraftSubmissionByRef,
composerDraftHasUserContent,
type ComposerImageAttachment,
type DraftThreadEnvMode,
finalizePromotedDraftThreadByRef,
@@ -305,6 +312,12 @@ import {
useLinkedThreadPullRequest,
} from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import {
hasAvailableClaudeCompactionProvider,
hasDismissedResumeCompaction,
shouldOfferResumeCompaction,
} from "./chat/ContextWindowMeter.logic";
import { deriveLatestContextWindowSnapshot, formatContextWindowTokens } from "../lib/contextWindow";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
import {
DRAFT_HERO_TRANSITION_ANIMATION_ID,
@@ -1367,6 +1380,9 @@ function ChatViewContent(props: ChatViewProps) {
const composerActiveProvider = useComposerDraftStore(
(store) => store.getComposerDraft(composerDraftTarget)?.activeProvider ?? null,
);
const composerHasUnsentContent = useComposerDraftStore((store) =>
composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)),
);
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
const setComposerDraftTerminalContexts = useComposerDraftStore(
@@ -2299,6 +2315,10 @@ function ChatViewContent(props: ChatViewProps) {
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
const phase = derivePhase(activeThread?.session ?? null);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const activeContextWindow = useMemo(
() => deriveLatestContextWindowSnapshot(threadActivities),
[threadActivities],
);
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
const turnPlans = useMemo(() => deriveTurnPlans(threadActivities), [threadActivities]);
// Native subagent fold: memoized by activity-list identity, shared by the
@@ -2762,6 +2782,29 @@ function ChatViewContent(props: ChatViewProps) {
activeThread?.modelSelection.instanceId ??
activeProject?.defaultModelSelection?.instanceId ??
null;
const compactionProviderAvailable = useMemo(
() =>
hasAvailableClaudeCompactionProvider({
providers: applyProviderInstanceSettings(
deriveProviderInstanceEntries(providerStatuses),
settings,
),
instanceId: activeProviderInstanceId,
lockedInstanceId: lockedProvider
? (activeThread?.session?.providerInstanceId ??
activeThread?.modelSelection.instanceId ??
null)
: null,
}),
[
activeProviderInstanceId,
activeThread?.modelSelection.instanceId,
activeThread?.session?.providerInstanceId,
lockedProvider,
providerStatuses,
settings,
],
);
const activeProviderStatus = useMemo(() => {
if (activeProviderInstanceId) {
return (
@@ -2771,6 +2814,25 @@ function ChatViewContent(props: ChatViewProps) {
const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider);
return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null;
}, [activeProviderInstanceId, providerStatuses, selectedProvider]);
const [resumeCompactionPermanentlyDismissed, setResumeCompactionPermanentlyDismissed] =
useLocalStorage(
`t3code:resume-compaction-dismissed:${environmentId}:${activeProviderInstanceId ?? "claudeAgent"}`,
false,
Schema.Boolean,
);
const nativeResumeCompactionDismissed = useMemo(
() => hasDismissedResumeCompaction(threadActivities),
[threadActivities],
);
useEffect(() => {
if (nativeResumeCompactionDismissed && !resumeCompactionPermanentlyDismissed) {
setResumeCompactionPermanentlyDismissed(true);
}
}, [
nativeResumeCompactionDismissed,
resumeCompactionPermanentlyDismissed,
setResumeCompactionPermanentlyDismissed,
]);
const providerStatusBannerKey = getProviderStatusBannerKey(activeProviderStatus);
const [dismissedProviderStatusBannerKey, setDismissedProviderStatusBannerKey] = useState<
string | null
@@ -4515,18 +4577,6 @@ function ChatViewContent(props: ChatViewProps) {
// Dismissal lives in a module-level set (survives remounts); this tick just
// forces a re-render so the banner leaves immediately.
const [, setBranchMismatchDismissTick] = useState(0);
const composerHasDraftContent = useComposerDraftStore((store) => {
const draft = store.getComposerDraft(composerDraftTarget);
return Boolean(
draft &&
(draft.prompt.trim().length > 0 ||
draft.images.length > 0 ||
draft.terminalContexts.length > 0 ||
draft.elementContexts.length > 0 ||
draft.previewAnnotations.length > 0 ||
draft.reviewComments.length > 0),
);
});
const activeBranchMismatchKey = branchMismatchKey(
activeThread?.id ?? null,
localCheckoutBranchMismatch,
@@ -4534,7 +4584,7 @@ function ChatViewContent(props: ChatViewProps) {
const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
hasMismatch: localCheckoutBranchMismatch !== null,
isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
composerHasContent: composerHasDraftContent,
composerHasContent: composerHasUnsentContent,
wasShownForCurrentMismatch:
revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
});
@@ -4758,6 +4808,107 @@ function ChatViewContent(props: ChatViewProps) {
isUnsnoozing,
isUnsettling,
]);
// Session-scoped dismissals, one key per (thread, snapshot). A set rather
// than a single slot so dismissing the banner on one thread does not
// resurface it on another thread dismissed earlier.
const [dismissedResumeCompactionKeys, setDismissedResumeCompactionKeys] = useState<
ReadonlySet<string>
>(new Set());
const resumeCompactionKey =
activeThread && activeContextWindow
? `${activeThread.id}:${activeContextWindow.updatedAt}`
: null;
const compactDisabled =
!activeThread ||
!activeProject ||
!isServerThread ||
selectedProvider !== "claudeAgent" ||
!compactionProviderAvailable ||
isWorking ||
threadDetailLoading ||
isPreparingWorktree ||
activeEnvironmentUnavailable ||
feedbackUploading ||
pendingApprovals.length > 0 ||
pendingUserInputs.length > 0 ||
showPlanFollowUpPrompt ||
composerHasUnsentContent;
const compactDisabledReason = compactDisabled
? composerHasUnsentContent
? "Send or clear your draft before compacting"
: !activeProject
? "Choose a project before compacting"
: !compactionProviderAvailable
? "Enable a Claude provider before compacting"
: "Compacting is unavailable right now"
: null;
const resumeCompactionBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
if (
!activeThread ||
!activeContextWindow ||
resumeCompactionKey === null ||
dismissedResumeCompactionKeys.has(resumeCompactionKey) ||
resumeCompactionPermanentlyDismissed ||
nativeResumeCompactionDismissed ||
pendingUserInputs.length > 0 ||
phase === "running" ||
!shouldOfferResumeCompaction({
provider: selectedProvider,
usedTokens: activeContextWindow.usedTokens,
updatedAt: activeContextWindow.updatedAt,
now: `${nowMinute}:00.000Z`,
})
) {
return null;
}
const dismiss = () =>
setDismissedResumeCompactionKeys((keys) => new Set(keys).add(resumeCompactionKey));
const compactAction = (
<Button
size="xs"
variant="outline"
disabled={compactDisabled}
onClick={() => {
if (compactDisabled) return;
composerRef.current?.compactContext();
}}
>
Compact
</Button>
);
return {
id: `resume-compaction:${resumeCompactionKey}`,
variant: "info",
icon: <Minimize2Icon />,
title: "Resume with less context",
description: `${formatContextWindowTokens(activeContextWindow.usedTokens)} tokens from an older session`,
actions: compactDisabledReason ? (
<Tooltip>
<TooltipTrigger render={<span className="inline-flex">{compactAction}</span>} />
<TooltipPopup side="top">{compactDisabledReason}</TooltipPopup>
</Tooltip>
) : (
compactAction
),
dismissLabel: "Keep full history",
onDismiss: dismiss,
};
}, [
activeContextWindow,
activeThread,
compactDisabled,
compactDisabledReason,
composerRef,
dismissedResumeCompactionKeys,
nativeResumeCompactionDismissed,
nowMinute,
pendingUserInputs.length,
phase,
resumeCompactionKey,
resumeCompactionPermanentlyDismissed,
selectedProvider,
]);
const handleRestoreThreadBranch = useCallback(() => {
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
setBranchRestoreConfirmOpen(true);
@@ -4772,6 +4923,8 @@ function ChatViewContent(props: ChatViewProps) {
const calmSystemItems = systemComposerBannerItems.filter((item) => !isUrgentSystemItem(item));
const backgroundLivenessItems =
backgroundLivenessBannerItem === null ? [] : [backgroundLivenessBannerItem];
const resumeCompactionItems =
resumeCompactionBannerItem === null ? [] : [resumeCompactionBannerItem];
const wokeThreadItems = wokeThreadBannerItem === null ? [] : [wokeThreadBannerItem];
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
@@ -4779,6 +4932,7 @@ function ChatViewContent(props: ChatViewProps) {
...urgentSystemItems,
...backgroundLivenessItems,
...calmSystemItems,
...resumeCompactionItems,
...wokeThreadItems,
...parkedThreadItems,
];
@@ -4787,6 +4941,7 @@ function ChatViewContent(props: ChatViewProps) {
...urgentSystemItems,
...backgroundLivenessItems,
...calmSystemItems,
...resumeCompactionItems,
...wokeThreadItems,
{
id: `branch-mismatch:${activeBranchMismatchKey}`,
@@ -4836,6 +4991,7 @@ function ChatViewContent(props: ChatViewProps) {
isRestoringThreadBranch,
localCheckoutBranchMismatch,
parkedThreadBannerItem,
resumeCompactionBannerItem,
showBranchMismatchBanner,
systemComposerBannerItems,
wokeThreadBannerItem,
@@ -6916,7 +7072,9 @@ function ChatViewContent(props: ChatViewProps) {
activeProject?.defaultModelSelection
}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
activeContextWindow={activeContextWindow}
compactDisabled={compactDisabled}
compactDisabledReason={compactDisabledReason}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
+80 -10
View File
@@ -266,7 +266,7 @@ import type { UnifiedSettings } from "@t3tools/contracts/settings";
import type { SessionPhase, Thread } from "../../types";
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
import type { PendingApproval, PendingUserInput } from "../../session-logic";
import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
import type { ContextWindowSnapshot } from "../../lib/contextWindow";
import {
formatProviderSkillDisplayName,
getProviderSlashCommandsForSlashMenu,
@@ -438,7 +438,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: {
compact: boolean;
activeContextWindow: ReturnType<typeof deriveLatestContextWindowSnapshot>;
activeContextWindow: ContextWindowSnapshot | null;
activeThreadModelDisplayName: string | null;
isPreparingWorktree: boolean;
pendingAction: {
@@ -461,6 +461,9 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
onPreviousPendingQuestion: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
onCompactContext?: (() => void) | undefined;
compactDisabled: boolean;
compactDisabledReason: string | null;
}) {
return (
<>
@@ -468,6 +471,9 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
<ContextWindowMeter
usage={props.activeContextWindow}
modelDisplayName={props.activeThreadModelDisplayName}
onCompact={props.onCompactContext}
compactDisabled={props.compactDisabled}
compactDisabledReason={props.compactDisabledReason}
/>
) : null}
{props.isPreparingWorktree ? (
@@ -507,6 +513,7 @@ export interface ChatComposerHandle {
openModelPicker: () => void;
toggleModelPicker: () => void;
isModelPickerOpen: () => boolean;
compactContext: () => void;
readSnapshot: () => {
value: string;
cursor: number;
@@ -609,7 +616,9 @@ export interface ChatComposerProps {
activeThreadModelSelection: ModelSelection | null | undefined;
// Context window
activeThreadActivities: Thread["activities"] | undefined;
activeContextWindow: ContextWindowSnapshot | null;
compactDisabled: boolean;
compactDisabledReason: string | null;
// Misc
resolvedTheme: "light" | "dark";
@@ -701,7 +710,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
providerStatuses,
activeProjectDefaultModelSelection,
activeThreadModelSelection,
activeThreadActivities,
activeContextWindow,
compactDisabled,
compactDisabledReason,
resolvedTheme,
settings,
keybindings,
@@ -914,6 +925,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[providerInstanceEntries, selectedInstanceId],
);
const noProviderAvailable = selectedProviderEntry === undefined;
const resolvedCompactDisabledReason =
compactDisabledReason ?? (noProviderAvailable ? "Compacting is unavailable right now" : null);
// The driver kind follows the instance that will actually run the turn,
// which can differ from the persisted selection when that selection is
// disabled.
@@ -1004,10 +1017,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Context window
// ------------------------------------------------------------------
const activeContextWindow = useMemo(
() => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),
[activeThreadActivities],
);
const activeThreadModelDisplayName = useMemo(
() => resolveContextWindowModelDisplayName(activeThreadModelSelection, modelOptionsByInstance),
[activeThreadModelSelection, modelOptionsByInstance],
@@ -1073,8 +1082,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
/**
* Count of pasted images still being compressed, per thread. Reserved
* against the attachment limit so concurrent pastes can't overshoot it,
* and checked by `submitComposer` so a send can't race an image into the
* next draft.
* and checked before sending or compacting so an image cannot move into
* the next draft.
*/
const pendingImageCompressionsRef = useRef<Map<ThreadId, number>>(new Map());
@@ -1986,6 +1995,58 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
shouldBlurMobileComposerOnSubmit,
],
);
const compactThreadContext = useCallback(() => {
if (
compactDisabled ||
noProviderAvailable ||
composerSendState.hasSendableContent ||
activePendingApproval !== null ||
pendingUserInputs.length > 0 ||
phase === "running" ||
isSendBusy ||
isConnecting ||
!activeThreadId
) {
return;
}
// The compact buttons cannot see the compression counter (it lives in
// a ref), so they render enabled during a paste; toast instead of
// silently ignoring the click.
if ((pendingImageCompressionsRef.current.get(activeThreadId) ?? 0) > 0) {
toastManager.add({
type: "info",
title: "Still compressing a pasted image.",
description: "Compact again once its thumbnail appears.",
});
return;
}
promptRef.current = "/compact";
setComposerDraftPrompt(composerDraftTarget, "/compact");
submitComposer();
// A blocked dispatch (busy send ref, provider preflight rejection)
// would leave the injected "/compact" behind as if the user typed it.
// Clearing here is safe even when the send did dispatch: the send
// snapshots its prompt synchronously and clears the draft itself.
if (promptRef.current === "/compact") {
promptRef.current = "";
setComposerDraftPrompt(composerDraftTarget, "");
}
}, [
activePendingApproval,
activeThreadId,
compactDisabled,
composerDraftTarget,
composerSendState.hasSendableContent,
isConnecting,
isSendBusy,
noProviderAvailable,
pendingUserInputs.length,
phase,
promptRef,
setComposerDraftPrompt,
submitComposer,
]);
const expandMobileComposer = useCallback(() => {
if (composerBlurFrameRef.current !== null) {
window.cancelAnimationFrame(composerBlurFrameRef.current);
@@ -2764,6 +2825,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
toggleModelPicker: () => {
setIsComposerModelPickerOpen((open) => !open);
},
compactContext: compactThreadContext,
isModelPickerOpen: () => isComposerModelPickerOpen,
readSnapshot: () => {
return readComposerSnapshot();
@@ -2875,6 +2937,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
selectedPromptEffort,
selectedProvider,
selectedProviderModels,
compactThreadContext,
],
);
@@ -3517,6 +3580,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
onInterrupt={handleInterruptPrimaryAction}
onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
compactDisabled={
compactDisabled || noProviderAvailable || isSendBusy || isConnecting
}
compactDisabledReason={resolvedCompactDisabledReason}
{...(selectedProvider === "claudeAgent"
? { onCompactContext: compactThreadContext }
: {})}
/>
</div>
</div>
@@ -77,4 +77,32 @@ describe("ComposerBannerStack", () => {
expect(markup).toContain("branch-surface");
expect(markup).toContain("branch-actions");
});
it("renders a disabled compaction action on the shared accessible banner surface", () => {
const markup = renderToStaticMarkup(
<ComposerBannerStack
items={[
{
id: "resume-compaction",
variant: "info",
icon: <span aria-hidden="true">!</span>,
title: "Resume with less context",
description: "250k tokens from an older session",
actions: (
<button type="button" disabled>
Compact
</button>
),
dismissLabel: "Keep full history",
onDismiss: () => {},
},
]}
/>,
);
expect(markup).toContain('role="alert"');
expect(markup).toContain("chat-composer-drawer-attached");
expect(markup).toContain('disabled=""');
expect(markup).toContain('aria-label="Keep full history"');
});
});
@@ -1,10 +1,83 @@
import { ProviderInstanceId } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { deriveProviderInstanceEntries } from "../../providerInstances";
import {
formatContextWindowCompactionMessage,
hasAvailableClaudeCompactionProvider,
hasDismissedResumeCompaction,
resolveContextWindowModelDisplayName,
shouldOfferResumeCompaction,
} from "./ContextWindowMeter.logic";
function claudeProvider(input: {
instanceId: string;
continuationGroupKey: string;
enabled?: boolean;
}): ServerProvider {
return {
instanceId: ProviderInstanceId.make(input.instanceId),
driver: ProviderDriverKind.make("claudeAgent"),
continuation: { groupKey: input.continuationGroupKey },
enabled: input.enabled ?? true,
installed: true,
version: null,
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-08-24T12:00:00.000Z",
models: [],
slashCommands: [],
skills: [],
};
}
describe("hasAvailableClaudeCompactionProvider", () => {
const originalInstanceId = ProviderInstanceId.make("claude_original");
it("rejects a fallback in a different locked continuation group", () => {
const providers = deriveProviderInstanceEntries([
claudeProvider({
instanceId: originalInstanceId,
continuationGroupKey: "claude:home:/original",
enabled: false,
}),
claudeProvider({
instanceId: "claude_other",
continuationGroupKey: "claude:home:/other",
}),
]);
expect(
hasAvailableClaudeCompactionProvider({
providers,
instanceId: originalInstanceId,
lockedInstanceId: originalInstanceId,
}),
).toBe(false);
});
it("accepts an enabled fallback in the locked continuation group", () => {
const providers = deriveProviderInstanceEntries([
claudeProvider({
instanceId: originalInstanceId,
continuationGroupKey: "claude:home:/original",
enabled: false,
}),
claudeProvider({
instanceId: "claude_fallback",
continuationGroupKey: "claude:home:/original",
}),
]);
expect(
hasAvailableClaudeCompactionProvider({
providers,
instanceId: originalInstanceId,
lockedInstanceId: originalInstanceId,
}),
).toBe(true);
});
});
describe("resolveContextWindowModelDisplayName", () => {
it("uses the selected model from the exact provider instance", () => {
const primaryInstanceId = ProviderInstanceId.make("codex");
@@ -55,4 +128,109 @@ describe("formatContextWindowCompactionMessage", () => {
"Context compacts automatically when needed.",
);
});
it("shows the configured auto-compaction threshold", () => {
expect(formatContextWindowCompactionMessage("Claude Sonnet 5", 300_000)).toBe(
"Compacts automatically at 300,000 tokens.",
);
});
});
describe("shouldOfferResumeCompaction", () => {
const now = "2026-08-24T12:00:00.000Z";
it("matches Claude's old-session age and context thresholds", () => {
expect(
shouldOfferResumeCompaction({
provider: "claudeAgent",
usedTokens: 100_000,
updatedAt: "2026-08-24T10:50:00.000Z",
now,
}),
).toBe(true);
});
it("does not prompt for recent or smaller sessions", () => {
expect(
shouldOfferResumeCompaction({
provider: "claudeAgent",
usedTokens: 99_999,
updatedAt: "2026-08-24T10:00:00.000Z",
now,
}),
).toBe(false);
expect(
shouldOfferResumeCompaction({
provider: "claudeAgent",
usedTokens: 200_000,
updatedAt: "2026-08-24T10:51:00.000Z",
now,
}),
).toBe(false);
});
it("does not show Claude's resume prompt for another provider", () => {
expect(
shouldOfferResumeCompaction({
provider: "codex",
usedTokens: 300_000,
updatedAt: "2026-08-24T09:00:00.000Z",
now,
}),
).toBe(false);
});
});
describe("hasDismissedResumeCompaction", () => {
it("recognizes the native resume dialog's permanent dismissal", () => {
expect(
hasDismissedResumeCompaction([
{
kind: "user-input.resolved",
payload: {
answers: {
"This session is 2h 0m old and uses 250,000 tokens. Compact it before continuing?":
"Don't ask again",
},
},
},
]),
).toBe(true);
});
it("ignores the same answer on an unrelated question", () => {
expect(
hasDismissedResumeCompaction([
{
kind: "user-input.resolved",
payload: { answers: { "Show this setup reminder?": "Don't ask again" } },
},
]),
).toBe(false);
});
it("ignores unrelated questions that end with Claude's compaction prompt", () => {
expect(
hasDismissedResumeCompaction([
{
kind: "user-input.resolved",
payload: {
answers: {
"The build cache is large. Compact it before continuing?": "Don't ask again",
},
},
},
]),
).toBe(false);
});
it("ignores pending questions and malformed resolved payloads", () => {
expect(
hasDismissedResumeCompaction([
{ kind: "user-input.requested", payload: { answers: { question: "Don't ask again" } } },
{ kind: "user-input.resolved", payload: null },
{ kind: "user-input.resolved", payload: { answers: ["Don't ask again"] } },
]),
).toBe(false);
});
});
@@ -1,6 +1,81 @@
import type { ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
import {
CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
isClaudeResumeCompactionQuestion,
} from "@t3tools/shared/claudeCompaction";
import {
resolveSelectableProviderInstanceEntry,
type ProviderInstanceEntry,
} from "../../providerInstances";
import { getTriggerDisplayModelName, type ModelEsque } from "./providerIconUtils";
export const CLAUDE_RESUME_COMPACTION_MINUTES = 70;
export const CLAUDE_RESUME_COMPACTION_TOKENS = 100_000;
export function hasAvailableClaudeCompactionProvider(input: {
readonly providers: ReadonlyArray<ProviderInstanceEntry>;
readonly instanceId: ProviderInstanceId | null;
readonly lockedInstanceId: ProviderInstanceId | null;
}): boolean {
const claudeProviders = input.providers.filter(
(provider) => provider.driverKind === "claudeAgent",
);
const lockedContinuationGroupKey = input.lockedInstanceId
? claudeProviders.find((provider) => provider.instanceId === input.lockedInstanceId)
?.continuationGroupKey
: undefined;
const compatibleProviders = lockedContinuationGroupKey
? claudeProviders.filter(
(provider) => provider.continuationGroupKey === lockedContinuationGroupKey,
)
: claudeProviders;
return (
resolveSelectableProviderInstanceEntry(compatibleProviders, input.instanceId ?? undefined) !==
undefined
);
}
export function hasDismissedResumeCompaction(
activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>,
): boolean {
return activities.some((activity) => {
if (activity.kind !== "user-input.resolved") return false;
const payload = activity.payload;
if (!payload || typeof payload !== "object") return false;
const answers = (payload as { readonly answers?: unknown }).answers;
if (!answers || typeof answers !== "object" || Array.isArray(answers)) return false;
return Object.entries(answers).some(
([question, answer]) =>
isClaudeResumeCompactionQuestion(question) &&
answer === CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
);
});
}
export function shouldOfferResumeCompaction(input: {
readonly provider: string | null | undefined;
readonly usedTokens: number | null | undefined;
readonly updatedAt: string | null | undefined;
readonly now: string;
}): boolean {
if (
input.provider !== "claudeAgent" ||
(input.usedTokens ?? 0) < CLAUDE_RESUME_COMPACTION_TOKENS
) {
return false;
}
const updatedAt = Date.parse(input.updatedAt ?? "");
const now = Date.parse(input.now);
return (
Number.isFinite(updatedAt) &&
Number.isFinite(now) &&
now - updatedAt >= CLAUDE_RESUME_COMPACTION_MINUTES * 60_000
);
}
export function resolveContextWindowModelDisplayName(
selection: ModelSelection | null | undefined,
modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>,
@@ -18,7 +93,11 @@ export function resolveContextWindowModelDisplayName(
export function formatContextWindowCompactionMessage(
modelDisplayName: string | null | undefined,
autoCompactThreshold?: number | null,
): string {
if (typeof autoCompactThreshold === "number" && autoCompactThreshold > 0) {
return `Compacts automatically at ${autoCompactThreshold.toLocaleString("en-US")} tokens.`;
}
return modelDisplayName
? `Context for ${modelDisplayName} compacts automatically when needed.`
: "Context compacts automatically when needed.";
@@ -0,0 +1,62 @@
import { EventId, TurnId } from "@t3tools/contracts";
import type { ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { deriveLatestContextWindowSnapshot } from "~/lib/contextWindow";
import { ContextWindowMeter } from "./ContextWindowMeter";
vi.mock("../ui/popover", () => ({
Popover: ({ children }: { children: ReactNode }) => children,
PopoverPopup: ({ children }: { children: ReactNode }) => children,
PopoverTrigger: ({ closeDelay, render }: { closeDelay: number; render: ReactNode }) => (
<div data-close-delay={closeDelay}>{render}</div>
),
}));
const usage = deriveLatestContextWindowSnapshot([
{
id: EventId.make("activity-1"),
tone: "info",
kind: "context-window.updated",
summary: "Context updated",
payload: { usedTokens: 100_000, maxTokens: 1_000_000 },
turnId: TurnId.make("turn-1"),
createdAt: "2026-08-24T12:00:00.000Z",
},
]);
if (!usage) {
throw new Error("The context window test fixture did not produce a snapshot.");
}
describe("ContextWindowMeter", () => {
it("keeps the hover popover open while the pointer moves to the compact button", () => {
const markup = renderToStaticMarkup(<ContextWindowMeter usage={usage} onCompact={() => {}} />);
expect(markup).toContain('data-close-delay="150"');
expect(markup).toContain("Compact context");
});
it("closes an informational hover popover without delay", () => {
const markup = renderToStaticMarkup(<ContextWindowMeter usage={usage} />);
expect(markup).toContain('data-close-delay="0"');
expect(markup).not.toContain("Compact context");
});
it("explains why the compact action is disabled", () => {
const markup = renderToStaticMarkup(
<ContextWindowMeter
usage={usage}
onCompact={() => {}}
compactDisabled
compactDisabledReason="Send or clear your draft before compacting"
/>,
);
expect(markup).toContain('disabled=""');
expect(markup).toContain(">Send or clear your draft before compacting<");
expect(markup).not.toContain('aria-label="Send or clear your draft before compacting"');
});
});
@@ -2,6 +2,7 @@ import { Button } from "../ui/button";
import { type ContextWindowSnapshot, formatContextWindowTokens } from "~/lib/contextWindow";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { formatContextWindowCompactionMessage } from "./ContextWindowMeter.logic";
import { Minimize2Icon } from "lucide-react";
function formatPercentage(value: number | null): string | null {
if (value === null || !Number.isFinite(value)) {
@@ -16,8 +17,11 @@ function formatPercentage(value: number | null): string | null {
export function ContextWindowMeter(props: {
usage: ContextWindowSnapshot;
modelDisplayName?: string | null;
onCompact?: (() => void) | undefined;
compactDisabled?: boolean | undefined;
compactDisabledReason?: string | null | undefined;
}) {
const { usage, modelDisplayName } = props;
const { usage, modelDisplayName, onCompact, compactDisabled, compactDisabledReason } = props;
const usedPercentage = formatPercentage(usage.usedPercentage);
const normalizedPercentage = Math.max(0, Math.min(100, usage.usedPercentage ?? 0));
const radius = 9.75;
@@ -35,7 +39,7 @@ export function ContextWindowMeter(props: {
<PopoverTrigger
openOnHover
delay={150}
closeDelay={0}
closeDelay={onCompact ? 150 : 0}
render={
<Button
size="icon-sm"
@@ -128,9 +132,28 @@ export function ContextWindowMeter(props: {
) : null}
{usage.compactsAutomatically ? (
<div className="mt-1 text-pretty text-secondary-label text-[11px] font-medium">
{formatContextWindowCompactionMessage(modelDisplayName)}
{formatContextWindowCompactionMessage(modelDisplayName, usage.autoCompactThreshold)}
</div>
) : null}
{onCompact ? (
<>
<Button
size="xs"
variant="outline"
className="mt-1 w-full justify-center"
disabled={compactDisabled}
onClick={onCompact}
>
<Minimize2Icon aria-hidden="true" />
Compact context
</Button>
{compactDisabled && compactDisabledReason ? (
<div className="text-pretty text-secondary-label text-[11px]">
{compactDisabledReason}
</div>
) : null}
</>
) : null}
</div>
</PopoverPopup>
</Popover>
@@ -37,6 +37,18 @@ describe("ProviderSettingsForm helpers", () => {
});
});
it("shows the auto-compaction threshold for Claude providers", () => {
const claude = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("claudeAgent")];
expect(claude).toBeDefined();
expect(deriveProviderSettingsFields(claude!).map((field) => field.key)).toEqual([
"binaryPath",
"homePath",
"autoCompactWindow",
"launchArgs",
]);
});
it("preserves unknown config keys while omitting empty configurable fields", () => {
const opencode = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencode")];
expect(opencode).toBeDefined();
+2
View File
@@ -26,6 +26,7 @@ describe("contextWindow", () => {
usedTokens: 14_000,
maxTokens: 258_000,
compactsAutomatically: true,
autoCompactThreshold: 200_000,
}),
]);
@@ -34,6 +35,7 @@ describe("contextWindow", () => {
expect(snapshot?.totalProcessedTokens).toBeNull();
expect(snapshot?.maxTokens).toBe(258_000);
expect(snapshot?.compactsAutomatically).toBe(true);
expect(snapshot?.autoCompactThreshold).toBe(200_000);
});
it("ignores malformed payloads", () => {
+1
View File
@@ -88,6 +88,7 @@ export function deriveLatestContextWindowSnapshot(
toolUses: asFiniteNumber(payload?.toolUses),
durationMs: asFiniteNumber(payload?.durationMs),
compactsAutomatically: asBoolean(payload?.compactsAutomatically) ?? false,
autoCompactThreshold: asFiniteNumber(payload?.autoCompactThreshold),
updatedAt: activity.createdAt,
};
}
+12
View File
@@ -34,6 +34,18 @@ When you set this field, T3 Code points Claude Code at that directory with the
`CLAUDE_CONFIG_DIR` environment variable. It does not change `HOME`, so your system keychain and
the rest of your environment stay as they are.
## Reduce Context Usage
In Settings, open your Claude provider and set **Auto-compact after** to a token count between
`100000` and `1000000`. For example, `300000` compacts the conversation into a summary once it
reaches about 300,000 tokens, without changing the model's context window. Leave the field
empty to keep Claude Code's default behavior.
On web and desktop, when you return to an older Claude thread with a large context, T3 Code
offers to compact the conversation before you continue. You can also select **Compact context**
from the context meter. On every client, you can enter `/compact` in the message composer, and
Claude can show its own resume prompt when you continue an old session.
## Where Claude Skills Are Loaded
T3 Code looks for Claude skills in the Claude config directory's `skills` folder, then
@@ -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:")) {