feat(claude): compact old threads before they burn through usage (#8144)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
1baf99195a
commit
c7222ca4df
25 files changed
+1105
-32
No files matched your search
@@ -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}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user