@devries-cameron20 / t3code-1 / commits / 754e1d1534
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): compact stale Claude threads before sending (#27935)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

shivam committed Nov 5, 2026 at 06:59 UTC 754e1d1534ce38a21927756cabcaad1d67f944fc
21 files changed +719 -246
apps/mobile/src/state/thread-outbox-model.ts
+3
@@ -56,6 +56,7 @@ export const QueuedThreadMessageSchema = Schema.Struct({
56 attachments: Schema.Array(DraftComposerAttachmentSchema),
57 modelSelection: Schema.optional(ModelSelection),
58 dispatchMode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
59 + compactBeforeSend: Schema.optional(Schema.Boolean),
60 runtimeMode: Schema.optional(RuntimeMode),
61 interactionMode: Schema.optional(ProviderInteractionMode),
62 creation: Schema.optional(QueuedThreadCreationSchema),
@@ -89,6 +90,8 @@ export interface QueuedThreadMessage {
90 readonly interactionMode?: ProviderInteractionModeType;
91 /** Captured at enqueue because draining may occur long after the tap. */
92 readonly dispatchMode?: ComposerDispatchMode;
93 + /** Sends "When you return"'s `/compact` ahead of the message, which queues behind it. */
94 + readonly compactBeforeSend?: boolean;
95 readonly creation?: QueuedThreadCreation;
96 readonly createdAt: string;
97 }
apps/mobile/src/state/thread-outbox.test.ts
+2
@@ -329,6 +329,8 @@ describe("thread outbox", () => {
329 },
330 runtimeMode: "approval-required",
331 interactionMode: "plan",
332 + dispatchMode: "queue",
333 + compactBeforeSend: true,
334 } satisfies QueuedThreadMessage;
335
336 expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
apps/mobile/src/state/thread-task-permissions.test.ts
+1
@@ -333,6 +333,7 @@ describe("mobile handoff preview and submission", () => {
333 auth: { status: "authenticated" as const },
334 availability: "available" as "available" | "unavailable",
335 models: [{ slug: selection.model }],
336 + slashCommands: [],
337 };
338 const projectOverride = { enabled: false };
339 state.serverConfig = {
apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
+49
@@ -498,3 +498,52 @@ describe("queued task operation access", () => {
498 },
499 );
500 });
501 +
502 +describe("compaction before a queued send", () => {
503 + const compactTurn = {
504 + commandId: "command:compact",
505 + message: {
506 + messageId: "message:compact",
507 + role: "user",
508 + text: "/compact",
509 + attachments: [],
510 + idleCompaction: "onReturn",
511 + },
512 + dispatchMode: "queue",
513 + };
514 +
515 + it("queues /compact ahead of the message and resends the same /compact on a retry", async () => {
516 + setOperateGrant("secondary", true);
517 + const queued = message({ compactBeforeSend: true, dispatchMode: "queue" });
518 + await state.manager.enqueue(queued);
519 + state.start
520 + .mockResolvedValueOnce(AsyncResult.success({}))
521 + .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))));
522 + await runDrain();
523 + expect(remaining()).toEqual([queued]);
524 +
525 + // A restarted app delivers the persisted message again.
526 + state.cleanups.splice(0).forEach((cleanup) => cleanup());
527 + await runDrain();
528 + expect(state.start.mock.calls.map(([call]) => call.input)).toEqual([
529 + expect.objectContaining(compactTurn),
530 + expect.objectContaining({ commandId: "command", dispatchMode: "queue" }),
531 + expect.objectContaining(compactTurn),
532 + expect.objectContaining({ commandId: "command", dispatchMode: "queue" }),
533 + ]);
534 + expect(remaining()).toEqual([]);
535 + });
536 +
537 + it("holds the message when its /compact cannot be sent", async () => {
538 + setOperateGrant("secondary", true);
539 + const queued = message({ compactBeforeSend: true, dispatchMode: "queue" });
540 + await state.manager.enqueue(queued);
541 + state.start.mockResolvedValueOnce(
542 + AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))),
543 + );
544 + await runDrain();
545 + expect(state.start).toHaveBeenCalledOnce();
546 + expect(state.start.mock.calls[0]?.[0].input).toMatchObject(compactTurn);
547 + expect(remaining()).toEqual([queued]);
548 + });
549 +});
apps/mobile/src/state/threadOutboxDelivery.ts
+32 -1
@@ -16,10 +16,10 @@ import {
16 CommandId,
17 DEFAULT_PROVIDER_INTERACTION_MODE,
18 DEFAULT_RUNTIME_MODE,
19 + MessageId,
20 managedRuntimeModeDenial,
21 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
22 type EnvironmentId,
22 - type MessageId,
23 } from "@t3tools/contracts";
24 import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
25 import * as Cause from "effect/Cause";
@@ -873,6 +873,37 @@ export function createThreadOutboxDelivery(): {
873 settings,
874 currentConfig.providers,
875 );
876 + if (queuedMessage.compactBeforeSend === true) {
877 + if (!hasAccess()) return true;
878 + // Queued, since steering a running turn with a compaction is rejected.
879 + const compactionResult = await runDeliveryCommand(threadEnvironment.startTurn, {
880 + environmentId: queuedMessage.environmentId,
881 + input: {
882 + commandId: settingsCommandId(queuedMessage, "compact"),
883 + creationSource: "mobile",
884 + threadId: queuedMessage.threadId,
885 + message: {
886 + messageId: MessageId.make(`${queuedMessage.messageId}:compact`),
887 + role: "user",
888 + text: "/compact",
889 + attachments: [],
890 + idleCompaction: "onReturn",
891 + },
892 + modelSelection: sendSettings.modelSelection,
893 + runtimeMode: sendSettings.runtimeMode,
894 + interactionMode: sendSettings.interactionMode,
895 + createdAt: queuedMessage.createdAt,
896 + dispatchMode: "queue",
897 + },
898 + });
899 + if (AsyncResult.isFailure(compactionResult) && !hasAccess()) return true;
900 + const compactionFailure = reportCommandFailure(queuedMessage, compactionResult, "start-turn");
901 + if (compactionFailure?.action === "retry") return false;
902 + if (compactionFailure?.action === "restore") {
903 + return restoreQueuedMessage(persistedMessage, compactionFailure.message);
904 + }
905 + if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) return true;
906 + }
907 if (!hasAccess()) return true;
908 const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, {
909 environmentId: queuedMessage.environmentId,
apps/mobile/src/state/use-thread-composer-state.ts
+25 -1
@@ -3,6 +3,7 @@ import * as Dialog from "../components/ui/Dialog";
3 import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
4 import { readEnvironmentScope } from "./session";
5 import { useAtomValue } from "@effect/atom-react";
6 +import { shouldCompactBeforeSend } from "@t3tools/client-runtime/state/context-window";
7 import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
8 import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
9 import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
@@ -661,6 +662,25 @@ export function useThreadComposerState() {
662 : "auto";
663
664 const metadata = makeQueuedMessageMetadata();
665 + const compactBeforeSend =
666 + followUpDispatchMode === null &&
667 + selectedEnvironmentRuntime?.connectionState === "connected" &&
668 + selectedThreadProjection !== null &&
669 + serverConfig != null &&
670 + shouldCompactBeforeSend({
671 + projection: selectedThreadProjection.projection,
672 + visibleTurnItems: selectedThreadVisibleTurnItems,
673 + selection: modelSelection,
674 + providers: serverConfig.providers,
675 + settings: serverConfig.settings,
676 + text,
677 + threadIdle:
678 + !activeThreadBusy &&
679 + !runlessWorkActive &&
680 + !isCompacting &&
681 + selectedThreadQueuedMessages.length === 0,
682 + now: metadata.createdAt,
683 + });
684 const messageId = MessageId.make(metadata.messageId);
685 onWillEnqueue?.();
686 clearThreadComposerError(threadKey);
@@ -678,7 +698,11 @@ export function useThreadComposerState() {
698 provider,
699 draft.interactionMode ?? thread.interactionMode,
700 ),
681 - ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
701 + ...(compactBeforeSend
702 + ? { compactBeforeSend, dispatchMode: "queue" as const }
703 + : followUpDispatchMode === null
704 + ? {}
705 + : { dispatchMode: followUpDispatchMode }),
706 createdAt: metadata.createdAt,
707 });
708 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
apps/web/src/components/ChatView.logic.ts
+1 -4
@@ -4,6 +4,7 @@ import {
4 deriveThreadRuntime,
5 } from "@t3tools/client-runtime/state/thread-execution";
6 import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints";
7 +import { COMPACT_COMMAND_PATTERN } from "@t3tools/client-runtime/state/context-window";
8 import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
9 import {
10 latestUnheldRun,
@@ -834,10 +835,6 @@ export function shouldShowPlanFollowUpPrompt(input: {
835 );
836 }
837
837 -// A typed `/compact`, with or without instructions, is already the compaction. Queueing a
838 -// bare one ahead of it would run an uninstructed compaction first and charge for two.
839 -const COMPACT_COMMAND_PATTERN = /^\/compact(?:\s|$)/i;
840 -
838 const sessionDismissedBranchMismatchKeys = new Set<string>();
839
840 export function dismissBranchMismatchForSession(key: string): void {
apps/web/src/components/ChatView.tsx
+4 -6
@@ -314,15 +314,13 @@ import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/Compos
314 import { modelFallbackBannerItem } from "./chat/ComposerUsageLimits";
315 import { ComposerSurface } from "./chat/ComposerSurface";
316 import { resolveThreadSyncPhase } from "../threadSync";
317 -import {
318 - hasAvailableCompactionProvider,
319 - hasDismissedResumeCompaction,
320 - shouldOfferResumeCompaction,
321 -} from "./chat/ContextWindowMeter.logic";
317 +import { hasAvailableCompactionProvider } from "./chat/ContextWindowMeter.logic";
318 import {
319 deriveLatestContextWindowSnapshot,
320 + hasDismissedResumeCompaction,
321 latestProviderTurnTokenUsage,
325 -} from "../lib/contextWindow";
322 + shouldOfferResumeCompaction,
323 +} from "@t3tools/client-runtime/state/context-window";
324 import {
325 MOBILE_COMPOSER_VIEW_TRANSITION_NAME,
326 MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
apps/web/src/components/chat/ChatComposer.tsx
+1 -1
@@ -252,7 +252,7 @@ import {
252 resolveComposerDispatchMode,
253 type ComposerDispatchMode,
254 } from "@t3tools/client-runtime/state/composer-dispatch";
255 -import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
255 +import { deriveLatestContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
256 import {
257 resolveProviderSkillsForCwd,
258 resolveProviderSlashCommandsForCwd,
apps/web/src/components/chat/ComposerFooterControls.tsx
+1 -1
@@ -8,7 +8,7 @@ import { createModelSelection } from "@t3tools/shared/model";
8 import { BotIcon, PencilRulerIcon } from "lucide-react";
9 import { type ComponentProps, memo, useId, useRef, useState } from "react";
10
11 -import type { ContextWindowSnapshot } from "../../lib/contextWindow";
11 +import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
12 import { Menu as MenuPrimitive } from "@base-ui/react/menu";
13 import { Menu, MenuPopup, MenuTrigger } from "../ui/menu";
14 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
apps/web/src/components/chat/ContextWindowMeter.logic.test.ts
+1 -1
@@ -1,9 +1,9 @@
1 import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
2 import { describe, expect, it } from "vite-plus/test";
3 import { deriveProviderInstanceEntries } from "../../providerInstances";
4 +import { hasDismissedResumeCompaction } from "@t3tools/client-runtime/state/context-window";
5 import {
6 hasAvailableCompactionProvider,
6 - hasDismissedResumeCompaction,
7 resolveContextWindowModelDisplayName,
8 shouldReserveContextWindowMeter,
9 } from "./ContextWindowMeter.logic";
apps/web/src/components/chat/ContextWindowMeter.logic.ts
-49
@@ -1,18 +1,10 @@
1 import type { ModelSelection, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
2 -import {
3 - CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
4 - COMPACTION_SUGGESTION_MIN_TOKENS,
5 - isClaudeResumeCompactionQuestion,
6 -} from "@t3tools/shared/claudeCompaction";
2 import {
3 resolveSelectableProviderInstanceEntry,
4 type ProviderInstanceEntry,
5 } from "../../providerInstances";
6 import { getDisplayModelName, type ModelEsque } from "./providerIconUtils";
7
13 -// Fallback TTL: Claude's 1h cache plus slack.
14 -const CLAUDE_RESUME_COMPACTION_FALLBACK_MS = 70 * 60_000;
15 -
8 export function providerSupportsManualCompaction(
9 provider: ProviderInstanceEntry | null | undefined,
10 ): boolean {
@@ -43,47 +35,6 @@ export function hasAvailableCompactionProvider(input: {
35 );
36 }
37
46 -export function hasDismissedResumeCompaction(
47 - activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>,
48 -): boolean {
49 - return activities.some((activity) => {
50 - if (activity.kind !== "user-input.resolved") return false;
51 - const payload = activity.payload;
52 - if (!payload || typeof payload !== "object") return false;
53 - const answers = (payload as { readonly answers?: unknown }).answers;
54 - if (!answers || typeof answers !== "object" || Array.isArray(answers)) return false;
55 -
56 - return Object.entries(answers).some(
57 - ([question, answer]) =>
58 - isClaudeResumeCompactionQuestion(question) &&
59 - answer === CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
60 - );
61 - });
62 -}
63 -
64 -export function shouldOfferResumeCompaction(input: {
65 - readonly provider: string | null | undefined;
66 - readonly usedTokens: number | null | undefined;
67 - readonly updatedAt: string | null | undefined;
68 - readonly promptCacheTtlMs?: number | undefined;
69 - readonly now: string;
70 -}): boolean {
71 - if (
72 - input.provider !== "claudeAgent" ||
73 - (input.usedTokens ?? 0) < COMPACTION_SUGGESTION_MIN_TOKENS
74 - ) {
75 - return false;
76 - }
77 -
78 - const updatedAt = Date.parse(input.updatedAt ?? "");
79 - const now = Date.parse(input.now);
80 - return (
81 - Number.isFinite(updatedAt) &&
82 - Number.isFinite(now) &&
83 - now - updatedAt >= (input.promptCacheTtlMs ?? CLAUDE_RESUME_COMPACTION_FALLBACK_MS)
84 - );
85 -}
86 -
38 export function resolveContextWindowModelDisplayName(
39 selection: ModelSelection | null | undefined,
40 modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>,
apps/web/src/components/chat/ContextWindowMeter.tsx
+2 -1
@@ -1,5 +1,6 @@
1 import { Button } from "../ui/button";
2 -import { type ContextWindowSnapshot, formatContextWindowTokens } from "~/lib/contextWindow";
2 +import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
3 +import { formatContextWindowTokens } from "~/lib/contextWindow";
4 import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
5 import {
6 formatContextWindowCompactionMessage,
apps/web/src/components/chat/ThreadDetailsUsage.tsx
+2 -1
@@ -16,7 +16,8 @@ import type { ReactNode } from "react";
16
17 import { usePrimarySettings } from "../../hooks/useSettings";
18 import { useNowMinute } from "../../hooks/useNowMinute";
19 -import { type ContextWindowSnapshot, formatContextWindowTokens } from "../../lib/contextWindow";
19 +import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
20 +import { formatContextWindowTokens } from "../../lib/contextWindow";
21 import { cn } from "../../lib/utils";
22 import { formatUpcomingTimestamp } from "../../timestampFormat";
23 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
apps/web/src/lib/contextWindow.test.ts
+5 -2
@@ -11,8 +11,11 @@ import {
11 ThreadId,
12 } from "@t3tools/contracts";
13 import { makeThreadProjectionFixture } from "../test-fixtures";
14 -import { shouldOfferResumeCompaction } from "../components/chat/ContextWindowMeter.logic";
15 -import { deriveLatestContextWindowSnapshot, latestProviderTurnTokenUsage } from "./contextWindow";
14 +import {
15 + deriveLatestContextWindowSnapshot,
16 + latestProviderTurnTokenUsage,
17 + shouldOfferResumeCompaction,
18 +} from "@t3tools/client-runtime/state/context-window";
19
20 const decodeTokenUsage = Schema.decodeSync(OrchestrationV2ProviderTurnTokenUsage);
21
apps/web/src/lib/contextWindow.ts
-176
@@ -1,179 +1,3 @@
1 -import type { ThreadStructure, ThreadStructureTurnItem } from "@t3tools/client-runtime/state/shell";
2 -import type {
3 - OrchestrationV2ProviderTurn,
4 - OrchestrationV2ProviderTurnTokenUsage,
5 - OrchestrationV2ProviderThread,
6 - ThreadTokenUsageSnapshot,
7 -} from "@t3tools/contracts";
8 -import * as DateTime from "effect/DateTime";
9 -
10 -function asFiniteNumber(value: unknown): number | null {
11 - return typeof value === "number" && Number.isFinite(value) ? value : null;
12 -}
13 -
14 -type NullableContextWindowUsage = {
15 - readonly [Key in keyof ThreadTokenUsageSnapshot]: undefined extends ThreadTokenUsageSnapshot[Key]
16 - ? Exclude<ThreadTokenUsageSnapshot[Key], undefined> | null
17 - : ThreadTokenUsageSnapshot[Key];
18 -};
19 -
20 -export type ContextWindowSnapshot = NullableContextWindowUsage & {
21 - readonly remainingTokens: number | null;
22 - readonly usedPercentage: number | null;
23 - readonly remainingPercentage: number | null;
24 - readonly updatedAt: string;
25 -};
26 -
27 -/** Newest report by timestamp; snapshots order turns by provider thread. */
28 -export function latestProviderTurnTokenUsage(
29 - turns: ReadonlyArray<Pick<OrchestrationV2ProviderTurn, "tokenUsage">>,
30 - projection?: Pick<ThreadStructure, "thread" | "contextTransfers"> | null,
31 - providerThread?: Pick<OrchestrationV2ProviderThread, "contextUsage"> | null,
32 -): OrchestrationV2ProviderTurnTokenUsage | null {
33 - let latest: OrchestrationV2ProviderTurnTokenUsage | null = null;
34 - for (const { tokenUsage } of turns) {
35 - if (tokenUsage === undefined) continue;
36 - // Ties go to the later entry, since live upserts append.
37 - if (latest === null || Date.parse(tokenUsage.updatedAt) >= Date.parse(latest.updatedAt)) {
38 - latest = tokenUsage;
39 - }
40 - }
41 - if (latest !== null || projection == null || providerThread?.contextUsage != null) return latest;
42 - const forkedFrom = projection.thread.forkedFrom;
43 - if (forkedFrom?.type !== "run") return null;
44 - return (
45 - projection.contextTransfers.find(
46 - (transfer) =>
47 - transfer.type === "fork" &&
48 - transfer.targetThreadId === projection.thread.id &&
49 - transfer.sourceThreadId === forkedFrom.threadId &&
50 - transfer.sourcePoint.runId === forkedFrom.runId &&
51 - transfer.sourceProviderInstanceId === projection.thread.modelSelection.instanceId &&
52 - (transfer.status === "pending" || transfer.resolution?.strategy === "native_fork"),
53 - )?.sourceTokenUsage ?? null
54 - );
55 -}
56 -
57 -export function deriveLatestContextWindowSnapshot(
58 - entries: ReadonlyArray<{
59 - readonly item: ThreadStructureTurnItem;
60 - }>,
61 - liveUsage?: OrchestrationV2ProviderTurnTokenUsage | null,
62 - providerThread?: Pick<OrchestrationV2ProviderThread, "contextUsage" | "updatedAt"> | null,
63 -): ContextWindowSnapshot | null {
64 - if (liveUsage != null) {
65 - const usedTokens = Math.max(0, liveUsage.usedTokens);
66 - const maxTokens = liveUsage.maxTokens ?? null;
67 - const usedPercentage =
68 - maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
69 - const remainingTokens =
70 - maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;
71 - const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null;
72 - return {
73 - usedTokens,
74 - totalProcessedTokens: null,
75 - maxTokens,
76 - remainingTokens,
77 - usedPercentage,
78 - remainingPercentage,
79 - inputTokens: liveUsage.inputTokens ?? null,
80 - cachedInputTokens: liveUsage.cachedInputTokens ?? null,
81 - outputTokens: liveUsage.outputTokens ?? null,
82 - reasoningOutputTokens: liveUsage.reasoningOutputTokens ?? null,
83 - lastUsedTokens: null,
84 - lastInputTokens: null,
85 - lastCachedInputTokens: null,
86 - lastOutputTokens: null,
87 - lastReasoningOutputTokens: null,
88 - toolUses: null,
89 - durationMs: null,
90 - compactsAutomatically: true,
91 - autoCompactThreshold: liveUsage.autoCompactThreshold ?? null,
92 - cost: null,
93 - updatedAt: liveUsage.updatedAt,
94 - };
95 - }
96 - const providerUsage = providerThread?.contextUsage;
97 - const providerUsageUpdatedAt = providerThread?.updatedAt;
98 - if (
99 - providerUsage !== null &&
100 - providerUsage !== undefined &&
101 - providerUsageUpdatedAt !== undefined
102 - ) {
103 - const maxTokens = asFiniteNumber(providerUsage.maxTokens);
104 - const usedTokens = providerUsage.usedTokens;
105 - const usedPercentage =
106 - maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
107 - return {
108 - usedTokens,
109 - totalProcessedTokens: asFiniteNumber(providerUsage.totalProcessedTokens),
110 - maxTokens,
111 - remainingTokens: maxTokens === null ? null : Math.max(0, Math.round(maxTokens - usedTokens)),
112 - usedPercentage,
113 - remainingPercentage: usedPercentage === null ? null : Math.max(0, 100 - usedPercentage),
114 - inputTokens: asFiniteNumber(providerUsage.inputTokens),
115 - cachedInputTokens: asFiniteNumber(providerUsage.cachedInputTokens),
116 - outputTokens: asFiniteNumber(providerUsage.outputTokens),
117 - reasoningOutputTokens: asFiniteNumber(providerUsage.reasoningOutputTokens),
118 - lastUsedTokens: asFiniteNumber(providerUsage.lastUsedTokens),
119 - lastInputTokens: asFiniteNumber(providerUsage.lastInputTokens),
120 - lastCachedInputTokens: asFiniteNumber(providerUsage.lastCachedInputTokens),
121 - lastOutputTokens: asFiniteNumber(providerUsage.lastOutputTokens),
122 - lastReasoningOutputTokens: asFiniteNumber(providerUsage.lastReasoningOutputTokens),
123 - toolUses: asFiniteNumber(providerUsage.toolUses),
124 - durationMs: asFiniteNumber(providerUsage.durationMs),
125 - compactsAutomatically: providerUsage.compactsAutomatically ?? null,
126 - cost: providerUsage.cost ?? null,
127 - autoCompactThreshold: providerUsage.autoCompactThreshold ?? null,
128 - updatedAt: DateTime.formatIso(providerUsageUpdatedAt),
129 - };
130 - }
131 - for (let index = entries.length - 1; index >= 0; index -= 1) {
132 - const entry = entries[index];
133 - if (!entry || entry.item.type !== "compaction") {
134 - continue;
135 - }
136 - const payload = entry.item;
137 - const usedTokens = asFiniteNumber(payload.afterTokenCount);
138 - if (usedTokens === null || usedTokens < 0) {
139 - continue;
140 - }
141 -
142 - const maxTokens = null;
143 - const usedPercentage =
144 - maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
145 - const remainingTokens =
146 - maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;
147 - const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null;
148 -
149 - return {
150 - usedTokens,
151 - totalProcessedTokens: asFiniteNumber(payload.beforeTokenCount),
152 - maxTokens,
153 - remainingTokens,
154 - usedPercentage,
155 - remainingPercentage,
156 - inputTokens: null,
157 - cachedInputTokens: null,
158 - outputTokens: null,
159 - reasoningOutputTokens: null,
160 - lastUsedTokens: null,
161 - lastInputTokens: null,
162 - lastCachedInputTokens: null,
163 - lastOutputTokens: null,
164 - lastReasoningOutputTokens: null,
165 - toolUses: null,
166 - durationMs: null,
167 - compactsAutomatically: true,
168 - autoCompactThreshold: null,
169 - cost: null,
170 - updatedAt: DateTime.formatIso(payload.startedAt ?? payload.updatedAt),
171 - };
172 - }
173 -
174 - return null;
175 -}
176 -
1 export function formatContextWindowTokens(value: number | null): string {
2 if (value === null || !Number.isFinite(value)) {
3 return "0";
docs/user/providers-claude.md
+2 -1
@@ -60,7 +60,8 @@ When you return to a large thread after Claude's prompt cache expires, a
60 **Compact** chip with the thread's token count shows
61 next to the send button. While it is on, Enter summarizes the history first, then
62 sends your message. Click the chip to switch it to **Keep** and keep the full
63 -history for that message. The cache lasts about an hour on a Claude
63 +history for that message. The mobile app shows no chip: an eligible message sent
64 +from it summarizes first. The cache lasts about an hour on a Claude
65 subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using
66 composer commands.
67
packages/client-runtime/package.json
+4
@@ -355,6 +355,10 @@
355 "types": "./src/state/composerDispatch.ts",
356 "default": "./src/state/composerDispatch.ts"
357 },
358 + "./state/context-window": {
359 + "types": "./src/state/contextWindow.ts",
360 + "default": "./src/state/contextWindow.ts"
361 + },
362 "./state/thread-subagents": {
363 "types": "./src/state/threadSubagents.ts",
364 "default": "./src/state/threadSubagents.ts"
packages/client-runtime/src/handoff.ts
+1 -1
@@ -24,7 +24,7 @@ export type HandoffTimelineRun = Pick<
24 export type HandoffEndpoints = ReturnType<typeof resolveHandoffEndpoints>;
25
26 export function resolvePendingHandoff(
27 - projection: ThreadStructure | null | undefined,
27 + projection: Pick<ThreadStructure, "runs" | "visibleTurnItems"> | null | undefined,
28 selection: ModelSelection | null | undefined,
29 providers: ReadonlyArray<ServerProvider>,
30 ): HandoffEndpoints | null {
packages/client-runtime/src/state/contextWindow.test.ts new
+264
@@ -0,0 +1,264 @@
1 +import {
2 + DEFAULT_SERVER_SETTINGS,
3 + ProviderDriverKind,
4 + ProviderInstanceId,
5 + ProviderThreadId,
6 + RunId,
7 + type ServerProvider,
8 + type ServerSettings,
9 +} from "@t3tools/contracts";
10 +import {
11 + CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
12 + formatClaudeResumeCompactionQuestion,
13 +} from "@t3tools/shared/claudeCompaction";
14 +import * as DateTime from "effect/DateTime";
15 +import { describe, expect, it } from "vite-plus/test";
16 +
17 +import { shouldCompactBeforeSend } from "./contextWindow.ts";
18 +import type { ThreadStructure } from "./models.ts";
19 +import { v2Projection } from "./orchestrationV2TestFixtures.ts";
20 +
21 +const claude = ProviderInstanceId.make("claudeAgent");
22 +const claudeWork = ProviderInstanceId.make("claude_work");
23 +const claudeOtherHome = ProviderInstanceId.make("claude_other_home");
24 +const codex = ProviderInstanceId.make("codex");
25 +const lastTurnAt = "2026-10-30T14:23:02.000Z";
26 +const returnedAt = "2026-10-30T23:03:21.000Z";
27 +
28 +function sendInput(
29 + overrides: {
30 + readonly usedTokens?: number;
31 + readonly promptCacheTtlMs?: number;
32 + readonly now?: string;
33 + readonly settings?: Partial<ServerSettings>;
34 + readonly source?: ProviderInstanceId;
35 + readonly selected?: ProviderInstanceId;
36 + readonly onlyEarlierConversationUsage?: boolean;
37 + readonly unstartedFork?: boolean;
38 + readonly slashCommands?: ReadonlyArray<string>;
39 + readonly dismissed?: boolean;
40 + readonly heldQueue?: boolean;
41 + readonly pendingRequest?: boolean;
42 + readonly onlyCompactMessages?: boolean;
43 + readonly promptOutsideWindow?: boolean;
44 + readonly text?: string;
45 + readonly threadIdle?: boolean;
46 + } = {},
47 +) {
48 + const source = overrides.source ?? claude;
49 + const sourceSelection = {
50 + instanceId: source,
51 + model: source === codex ? "gpt-5.4" : "claude-opus-4-6",
52 + };
53 + const providers = [
54 + { instanceId: claude, driver: "claudeAgent", groupKey: "claude:~/.claude" },
55 + { instanceId: claudeWork, driver: "claudeAgent", groupKey: "claude:~/.claude" },
56 + { instanceId: claudeOtherHome, driver: "claudeAgent", groupKey: "claude:~/.claude-other" },
57 + { instanceId: codex, driver: "codex", groupKey: "codex:~/.codex" },
58 + ].map(({ instanceId, driver, groupKey }) => ({
59 + instanceId,
60 + driver: ProviderDriverKind.make(driver),
61 + continuation: { groupKey },
62 + slashCommands: (overrides.slashCommands ?? ["compact"]).map((name) => ({ name })),
63 + })) as unknown as ReadonlyArray<ServerProvider>;
64 + const providerThread = (id: string) => ({
65 + id: ProviderThreadId.make(id),
66 + driver: providers.find((provider) => provider.instanceId === source)!.driver,
67 + providerInstanceId: source,
68 + contextUsage: null,
69 + updatedAt: DateTime.makeUnsafe(lastTurnAt),
70 + });
71 + const visibleTurnItems =
72 + overrides.promptOutsideWindow === true
73 + ? [{ item: { type: "assistant_message", text: "Build fixed" } }]
74 + : [
75 + {
76 + item: {
77 + type: "user_message",
78 + runId: RunId.make("run-1"),
79 + text: overrides.onlyCompactMessages === true ? "/compact" : "Fix the build",
80 + attachments: [],
81 + },
82 + },
83 + ];
84 + const projection = {
85 + ...v2Projection,
86 + thread: {
87 + ...v2Projection.thread,
88 + providerInstanceId: source,
89 + modelSelection: sourceSelection,
90 + activeProviderThreadId: ProviderThreadId.make("provider-thread-current"),
91 + },
92 + providerThreads: [
93 + providerThread("provider-thread-earlier"),
94 + providerThread("provider-thread-current"),
95 + ],
96 + providerTurns: [
97 + {
98 + providerThreadId: ProviderThreadId.make(
99 + overrides.onlyEarlierConversationUsage === true
100 + ? "provider-thread-earlier"
101 + : "provider-thread-current",
102 + ),
103 + tokenUsage: {
104 + usedTokens: overrides.usedTokens ?? 293_611,
105 + updatedAt: lastTurnAt,
106 + ...(overrides.promptCacheTtlMs === undefined
107 + ? {}
108 + : { promptCacheTtlMs: overrides.promptCacheTtlMs }),
109 + },
110 + },
111 + ],
112 + runs: [
113 + {
114 + id: RunId.make("run-1"),
115 + ordinal: 1,
116 + providerInstanceId: source,
117 + modelSelection: sourceSelection,
118 + status: "completed",
119 + startedAt: "2026-10-30T14:20:00.000Z",
120 + contextHandoffId: null,
121 + },
122 + ...(overrides.heldQueue === true
123 + ? [{ id: RunId.make("queued-run"), status: "queued", queueHeld: true, startedAt: null }]
124 + : []),
125 + ],
126 + runtimeRequests: [
127 + ...(overrides.dismissed === true
128 + ? [
129 + {
130 + kind: "user_input",
131 + status: "resolved",
132 + answers: {
133 + [formatClaudeResumeCompactionQuestion({
134 + ageMinutes: 90,
135 + estimatedTokens: 250_000,
136 + })]: CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
137 + },
138 + },
139 + ]
140 + : []),
141 + ...(overrides.pendingRequest === true ? [{ kind: "approval", status: "pending" }] : []),
142 + ],
143 + visibleTurnItems,
144 + } as unknown as ThreadStructure;
145 + if (overrides.unstartedFork === true) {
146 + Object.assign(projection, {
147 + thread: {
148 + ...projection.thread,
149 + activeProviderThreadId: null,
150 + forkedFrom: { type: "run", threadId: "source-thread", runId: "source-run" },
151 + },
152 + runs: [],
153 + providerThreads: [],
154 + providerTurns: [],
155 + contextTransfers: [
156 + {
157 + type: "fork",
158 + targetThreadId: projection.thread.id,
159 + sourceThreadId: "source-thread",
160 + sourcePoint: { runId: "source-run" },
161 + sourceProviderInstanceId: source,
162 + status: "pending",
163 + sourceTokenUsage: { usedTokens: 293_611, updatedAt: lastTurnAt },
164 + },
165 + ],
166 + });
167 + }
168 + const selected = overrides.selected ?? claude;
169 + return {
170 + projection,
171 + visibleTurnItems: visibleTurnItems as never,
172 + selection: {
173 + instanceId: selected,
174 + model: selected === codex ? "gpt-5.4" : "claude-opus-4-6",
175 + },
176 + providers,
177 + settings: { ...DEFAULT_SERVER_SETTINGS, ...overrides.settings },
178 + text: overrides.text ?? "back again",
179 + threadIdle: overrides.threadIdle ?? true,
180 + now: overrides.now ?? returnedAt,
181 + };
182 +}
183 +
184 +describe("shouldCompactBeforeSend", () => {
185 + it.each([
186 + { name: "a stale Claude thread over 200K", expected: true },
187 + {
188 + name: "when the original prompt is outside the loaded window",
189 + promptOutsideWindow: true,
190 + expected: true,
191 + },
192 + {
193 + name: "when the environment compacts before the cache expires",
194 + settings: { idleCompaction: "beforeCacheExpires" },
195 + expected: true,
196 + },
197 + {
198 + name: "past a reported TTL shorter than the fallback",
199 + promptCacheTtlMs: 5 * 60_000,
200 + now: "2026-10-30T14:30:00.000Z",
201 + expected: true,
202 + },
203 + { name: "within the fallback TTL", now: "2026-10-30T15:23:02.000Z", expected: false },
204 + { name: "under 200K", usedTokens: 150_000, expected: false },
205 + { name: "with idle compaction off", settings: { idleCompaction: "off" }, expected: false },
206 + {
207 + name: "with the Claude instance overriding idle compaction to off",
208 + settings: {
209 + idleCompaction: "onReturn",
210 + providerInstances: {
211 + [claude]: {
212 + driver: ProviderDriverKind.make("claudeAgent"),
213 + config: { idleCompaction: "off" },
214 + },
215 + },
216 + },
217 + expected: false,
218 + },
219 + { name: "on a Codex thread", source: codex, selected: codex, expected: false },
220 + {
221 + name: "after switching a stale Codex thread to Claude",
222 + source: codex,
223 + selected: claude,
224 + expected: false,
225 + },
226 + {
227 + name: "after switching to a Claude instance that continues the conversation",
228 + selected: claudeWork,
229 + expected: true,
230 + },
231 + {
232 + name: "after switching to a Claude instance with another home",
233 + selected: claudeOtherHome,
234 + expected: false,
235 + },
236 + {
237 + name: "when only an earlier conversation reported usage",
238 + onlyEarlierConversationUsage: true,
239 + expected: false,
240 + },
241 + { name: "an unstarted fork resuming its source instance", unstartedFork: true, expected: true },
242 + {
243 + name: "an unstarted fork selecting another Claude home",
244 + unstartedFork: true,
245 + selected: claudeOtherHome,
246 + expected: false,
247 + },
248 + { name: "for a provider without /compact", slashCommands: [], expected: false },
249 + {
250 + name: "after Claude's resume dialog was answered Don't ask again",
251 + dismissed: true,
252 + expected: false,
253 + },
254 + { name: "while the queue is held", heldQueue: true, expected: false },
255 + { name: "while a request waits for an answer", pendingRequest: true, expected: false },
256 + { name: "while the thread is working", threadIdle: false, expected: false },
257 + { name: "with no conversation but /compact", onlyCompactMessages: true, expected: false },
258 + { name: "for a typed /compact", text: "/compact keep the plan", expected: false },
259 + ] as const)("$name", ({ name: _name, expected, ...overrides }) => {
260 + expect(shouldCompactBeforeSend(sendInput(overrides as Parameters<typeof sendInput>[0]))).toBe(
261 + expected,
262 + );
263 + });
264 +});
packages/client-runtime/src/state/contextWindow.ts new
+319
@@ -0,0 +1,319 @@
1 +import {
2 + resolveIdleCompaction,
3 + type ModelSelection,
4 + type OrchestrationV2ProviderTurn,
5 + type OrchestrationV2ProviderTurnTokenUsage,
6 + type OrchestrationV2ProviderThread,
7 + type ServerProvider,
8 + type ServerSettings,
9 + type ThreadTokenUsageSnapshot,
10 +} from "@t3tools/contracts";
11 +import {
12 + CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
13 + COMPACTION_SUGGESTION_MIN_TOKENS,
14 + isClaudeResumeCompactionQuestion,
15 +} from "@t3tools/shared/claudeCompaction";
16 +import * as DateTime from "effect/DateTime";
17 +
18 +import { resolvePendingHandoff } from "../handoff.ts";
19 +import type { ThreadStructure, ThreadStructureTurnItem } from "./models.ts";
20 +
21 +// Fallback TTL: Claude's 1h cache plus slack.
22 +const CLAUDE_RESUME_COMPACTION_FALLBACK_MS = 70 * 60_000;
23 +
24 +// A typed `/compact`, with or without instructions, is already the compaction. Queueing a
25 +// bare one ahead of it would run an uninstructed compaction first and charge for two.
26 +export const COMPACT_COMMAND_PATTERN = /^\/compact(?:\s|$)/i;
27 +
28 +function asFiniteNumber(value: unknown): number | null {
29 + return typeof value === "number" && Number.isFinite(value) ? value : null;
30 +}
31 +
32 +type NullableContextWindowUsage = {
33 + readonly [Key in keyof ThreadTokenUsageSnapshot]: undefined extends ThreadTokenUsageSnapshot[Key]
34 + ? Exclude<ThreadTokenUsageSnapshot[Key], undefined> | null
35 + : ThreadTokenUsageSnapshot[Key];
36 +};
37 +
38 +export type ContextWindowSnapshot = NullableContextWindowUsage & {
39 + readonly remainingTokens: number | null;
40 + readonly usedPercentage: number | null;
41 + readonly remainingPercentage: number | null;
42 + readonly updatedAt: string;
43 +};
44 +
45 +/** Newest report by timestamp; snapshots order turns by provider thread. */
46 +export function latestProviderTurnTokenUsage(
47 + turns: ReadonlyArray<Pick<OrchestrationV2ProviderTurn, "tokenUsage">>,
48 + projection?: Pick<ThreadStructure, "thread" | "contextTransfers"> | null,
49 + providerThread?: Pick<OrchestrationV2ProviderThread, "contextUsage"> | null,
50 +): OrchestrationV2ProviderTurnTokenUsage | null {
51 + let latest: OrchestrationV2ProviderTurnTokenUsage | null = null;
52 + for (const { tokenUsage } of turns) {
53 + if (tokenUsage === undefined) continue;
54 + // Ties go to the later entry, since live upserts append.
55 + if (latest === null || Date.parse(tokenUsage.updatedAt) >= Date.parse(latest.updatedAt)) {
56 + latest = tokenUsage;
57 + }
58 + }
59 + if (latest !== null || projection == null || providerThread?.contextUsage != null) return latest;
60 + const forkedFrom = projection.thread.forkedFrom;
61 + if (forkedFrom?.type !== "run") return null;
62 + return (
63 + projection.contextTransfers.find(
64 + (transfer) =>
65 + transfer.type === "fork" &&
66 + transfer.targetThreadId === projection.thread.id &&
67 + transfer.sourceThreadId === forkedFrom.threadId &&
68 + transfer.sourcePoint.runId === forkedFrom.runId &&
69 + transfer.sourceProviderInstanceId === projection.thread.modelSelection.instanceId &&
70 + (transfer.status === "pending" || transfer.resolution?.strategy === "native_fork"),
71 + )?.sourceTokenUsage ?? null
72 + );
73 +}
74 +
75 +export function deriveLatestContextWindowSnapshot(
76 + entries: ReadonlyArray<{
77 + readonly item: ThreadStructureTurnItem;
78 + }>,
79 + liveUsage?: OrchestrationV2ProviderTurnTokenUsage | null,
80 + providerThread?: Pick<OrchestrationV2ProviderThread, "contextUsage" | "updatedAt"> | null,
81 +): ContextWindowSnapshot | null {
82 + if (liveUsage != null) {
83 + const usedTokens = Math.max(0, liveUsage.usedTokens);
84 + const maxTokens = liveUsage.maxTokens ?? null;
85 + const usedPercentage =
86 + maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
87 + const remainingTokens =
88 + maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;
89 + const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null;
90 + return {
91 + usedTokens,
92 + totalProcessedTokens: null,
93 + maxTokens,
94 + remainingTokens,
95 + usedPercentage,
96 + remainingPercentage,
97 + inputTokens: liveUsage.inputTokens ?? null,
98 + cachedInputTokens: liveUsage.cachedInputTokens ?? null,
99 + outputTokens: liveUsage.outputTokens ?? null,
100 + reasoningOutputTokens: liveUsage.reasoningOutputTokens ?? null,
101 + lastUsedTokens: null,
102 + lastInputTokens: null,
103 + lastCachedInputTokens: null,
104 + lastOutputTokens: null,
105 + lastReasoningOutputTokens: null,
106 + toolUses: null,
107 + durationMs: null,
108 + compactsAutomatically: true,
109 + autoCompactThreshold: liveUsage.autoCompactThreshold ?? null,
110 + cost: null,
111 + updatedAt: liveUsage.updatedAt,
112 + };
113 + }
114 + const providerUsage = providerThread?.contextUsage;
115 + const providerUsageUpdatedAt = providerThread?.updatedAt;
116 + if (
117 + providerUsage !== null &&
118 + providerUsage !== undefined &&
119 + providerUsageUpdatedAt !== undefined
120 + ) {
121 + const maxTokens = asFiniteNumber(providerUsage.maxTokens);
122 + const usedTokens = providerUsage.usedTokens;
123 + const usedPercentage =
124 + maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
125 + return {
126 + usedTokens,
127 + totalProcessedTokens: asFiniteNumber(providerUsage.totalProcessedTokens),
128 + maxTokens,
129 + remainingTokens: maxTokens === null ? null : Math.max(0, Math.round(maxTokens - usedTokens)),
130 + usedPercentage,
131 + remainingPercentage: usedPercentage === null ? null : Math.max(0, 100 - usedPercentage),
132 + inputTokens: asFiniteNumber(providerUsage.inputTokens),
133 + cachedInputTokens: asFiniteNumber(providerUsage.cachedInputTokens),
134 + outputTokens: asFiniteNumber(providerUsage.outputTokens),
135 + reasoningOutputTokens: asFiniteNumber(providerUsage.reasoningOutputTokens),
136 + lastUsedTokens: asFiniteNumber(providerUsage.lastUsedTokens),
137 + lastInputTokens: asFiniteNumber(providerUsage.lastInputTokens),
138 + lastCachedInputTokens: asFiniteNumber(providerUsage.lastCachedInputTokens),
139 + lastOutputTokens: asFiniteNumber(providerUsage.lastOutputTokens),
140 + lastReasoningOutputTokens: asFiniteNumber(providerUsage.lastReasoningOutputTokens),
141 + toolUses: asFiniteNumber(providerUsage.toolUses),
142 + durationMs: asFiniteNumber(providerUsage.durationMs),
143 + compactsAutomatically: providerUsage.compactsAutomatically ?? null,
144 + cost: providerUsage.cost ?? null,
145 + autoCompactThreshold: providerUsage.autoCompactThreshold ?? null,
146 + updatedAt: DateTime.formatIso(providerUsageUpdatedAt),
147 + };
148 + }
149 + for (let index = entries.length - 1; index >= 0; index -= 1) {
150 + const entry = entries[index];
151 + if (!entry || entry.item.type !== "compaction") {
152 + continue;
153 + }
154 + const payload = entry.item;
155 + const usedTokens = asFiniteNumber(payload.afterTokenCount);
156 + if (usedTokens === null || usedTokens < 0) {
157 + continue;
158 + }
159 +
160 + const maxTokens = null;
161 + const usedPercentage =
162 + maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;
163 + const remainingTokens =
164 + maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;
165 + const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null;
166 +
167 + return {
168 + usedTokens,
169 + totalProcessedTokens: asFiniteNumber(payload.beforeTokenCount),
170 + maxTokens,
171 + remainingTokens,
172 + usedPercentage,
173 + remainingPercentage,
174 + inputTokens: null,
175 + cachedInputTokens: null,
176 + outputTokens: null,
177 + reasoningOutputTokens: null,
178 + lastUsedTokens: null,
179 + lastInputTokens: null,
180 + lastCachedInputTokens: null,
181 + lastOutputTokens: null,
182 + lastReasoningOutputTokens: null,
183 + toolUses: null,
184 + durationMs: null,
185 + compactsAutomatically: true,
186 + autoCompactThreshold: null,
187 + cost: null,
188 + updatedAt: DateTime.formatIso(payload.startedAt ?? payload.updatedAt),
189 + };
190 + }
191 +
192 + return null;
193 +}
194 +
195 +export function hasDismissedResumeCompaction(
196 + activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>,
197 +): boolean {
198 + return activities.some((activity) => {
199 + if (activity.kind !== "user-input.resolved") return false;
200 + const payload = activity.payload;
201 + if (!payload || typeof payload !== "object") return false;
202 + const answers = (payload as { readonly answers?: unknown }).answers;
203 + if (!answers || typeof answers !== "object" || Array.isArray(answers)) return false;
204 +
205 + return Object.entries(answers).some(
206 + ([question, answer]) =>
207 + isClaudeResumeCompactionQuestion(question) &&
208 + answer === CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
209 + );
210 + });
211 +}
212 +
213 +export function shouldOfferResumeCompaction(input: {
214 + readonly provider: string | null | undefined;
215 + readonly usedTokens: number | null | undefined;
216 + readonly updatedAt: string | null | undefined;
217 + readonly promptCacheTtlMs?: number | undefined;
218 + readonly now: string;
219 +}): boolean {
220 + if (
221 + input.provider !== "claudeAgent" ||
222 + (input.usedTokens ?? 0) < COMPACTION_SUGGESTION_MIN_TOKENS
223 + ) {
224 + return false;
225 + }
226 +
227 + const updatedAt = Date.parse(input.updatedAt ?? "");
228 + const now = Date.parse(input.now);
229 + return (
230 + Number.isFinite(updatedAt) &&
231 + Number.isFinite(now) &&
232 + now - updatedAt >= (input.promptCacheTtlMs ?? CLAUDE_RESUME_COMPACTION_FALLBACK_MS)
233 + );
234 +}
235 +
236 +/**
237 + * Whether a plain send into an idle thread compacts it first, as web's composer does under
238 + * "When you return". Web reads the same state for its "Compact and send" button. A send that
239 + * hands off to another conversation starts that one fresh, so only the resumed one counts.
240 + */
241 +export function shouldCompactBeforeSend(input: {
242 + readonly projection: Pick<
243 + ThreadStructure,
244 + | "thread"
245 + | "contextTransfers"
246 + | "providerThreads"
247 + | "providerTurns"
248 + | "runtimeRequests"
249 + | "runs"
250 + | "visibleTurnItems"
251 + >;
252 + readonly visibleTurnItems: ReadonlyArray<{ readonly item: ThreadStructureTurnItem }>;
253 + readonly selection: ModelSelection;
254 + readonly providers: ReadonlyArray<ServerProvider>;
255 + readonly settings: Pick<
256 + ServerSettings,
257 + "providerInstances" | "compactIdleThreads" | "idleCompaction"
258 + >;
259 + readonly text: string;
260 + readonly threadIdle: boolean;
261 + readonly now: string;
262 +}): boolean {
263 + const { projection } = input;
264 + const provider = input.providers.find((entry) => entry.instanceId === input.selection.instanceId);
265 + if (
266 + provider === undefined ||
267 + !input.threadIdle ||
268 + COMPACT_COMMAND_PATTERN.test(input.text) ||
269 + resolveIdleCompaction(input.settings, provider.instanceId) === "off" ||
270 + !provider.slashCommands.some((command) => command.name === "compact") ||
271 + resolvePendingHandoff(projection, input.selection, input.providers) !== null ||
272 + projection.runtimeRequests.some((request) => request.status === "pending") ||
273 + projection.runs.some((run) => run.status === "queued" && run.queueHeld === true) ||
274 + (!input.visibleTurnItems.some(
275 + ({ item }) =>
276 + item.type === "user_message" &&
277 + (item.text.trim().toLowerCase() !== "/compact" || item.attachments.length > 0),
278 + ) &&
279 + !projection.runs.some(
280 + (run) =>
281 + run.status !== "rolled_back" &&
282 + run.startedAt !== null &&
283 + !input.visibleTurnItems.some(
284 + ({ item }) => item.type === "user_message" && item.runId === run.id,
285 + ),
286 + )) ||
287 + hasDismissedResumeCompaction(
288 + projection.runtimeRequests
289 + .filter((request) => request.kind === "user_input" && request.status === "resolved")
290 + .map((request) => ({ kind: "user-input.resolved", payload: { answers: request.answers } })),
291 + )
292 + ) {
293 + return false;
294 + }
295 + const activeProviderThreadId = projection.thread.activeProviderThreadId;
296 + const providerThread = projection.providerThreads.find(
297 + (thread) => thread.id === activeProviderThreadId,
298 + );
299 + const liveUsage = latestProviderTurnTokenUsage(
300 + projection.providerTurns.filter((turn) => turn.providerThreadId === activeProviderThreadId),
301 + input.selection.instanceId === projection.thread.modelSelection.instanceId ? projection : null,
302 + providerThread,
303 + );
304 + const contextWindow = deriveLatestContextWindowSnapshot(
305 + input.visibleTurnItems,
306 + liveUsage,
307 + providerThread,
308 + );
309 + return (
310 + contextWindow !== null &&
311 + shouldOfferResumeCompaction({
312 + provider: provider.driver,
313 + usedTokens: contextWindow.usedTokens,
314 + updatedAt: contextWindow.updatedAt,
315 + promptCacheTtlMs: liveUsage?.promptCacheTtlMs,
316 + now: input.now,
317 + })
318 + );
319 +}