Skip to content

Commit b7e0523

Browse files
fix(mobile): show and let users skip compaction before sending to stale Claude threads
Mobile compacted stale Claude threads over 200K tokens before a send, but only decided that inside the send handler, so the composer gave no sign of it and no way to keep the history. The client-runtime check now returns the tokens it would compact. The mobile composer reads it during render to show a notice above the composer with a "Keep full history" toggle. Like web, the choice applies to one send per thread. AI-assisted; verified with the tests and tools listed above. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 31eea88 commit b7e0523

7 files changed

Lines changed: 134 additions & 33 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { formatTokens } from "@t3tools/shared/usageFormat";
2+
import { View } from "react-native";
3+
4+
import { AppText } from "../../components/ui/AppText";
5+
import { Chip } from "../../components/ui/Chip";
6+
7+
/** Shown while the next send compacts a stale Claude thread first; the chip keeps the history. */
8+
export function CompactBeforeSendNotice(props: {
9+
readonly tokens: number;
10+
readonly keepFullHistory: boolean;
11+
readonly disabled: boolean;
12+
readonly onToggleKeepFullHistory: () => void;
13+
}) {
14+
const tokens = formatTokens(props.tokens);
15+
return (
16+
<View className="flex-row items-center gap-3 px-4 pb-3">
17+
<AppText
18+
textRole="footnote"
19+
accessibilityLiveRegion="polite"
20+
className="min-w-0 flex-1 text-foreground-muted"
21+
>
22+
{props.keepFullHistory
23+
? `Next send keeps all ${tokens} tokens.`
24+
: `Next send compacts ${tokens} tokens first.`}
25+
</AppText>
26+
<Chip
27+
icon="arrow.down.right.and.arrow.up.left"
28+
label={props.keepFullHistory ? "Compact first" : "Keep full history"}
29+
disabled={props.disabled}
30+
onPress={props.onToggleKeepFullHistory}
31+
/>
32+
</View>
33+
);
34+
}

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ import type {
175175
import { PendingApprovalCard } from "./PendingApprovalCard";
176176
import { ComposerErrorNotice } from "./ComposerErrorNotice";
177177
import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
178+
import { CompactBeforeSendNotice } from "./CompactBeforeSendNotice";
178179
import { FreshSessionNotice } from "./FreshSessionNotice";
179180
import { ComposerFeedback } from "./ComposerFeedback";
180181
import { ComposerUsageLimits } from "./ComposerUsageLimits";
@@ -244,6 +245,12 @@ export interface ThreadDetailScreenProps {
244245
readonly providerSubagentStatus?: ProviderSubagentStatus | null;
245246
readonly extensionStatuses?: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>;
246247
readonly isCompacting: boolean;
248+
/** Set while the next send compacts the thread first. */
249+
readonly compactBeforeSend?: {
250+
readonly tokens: number;
251+
readonly keepFullHistory: boolean;
252+
readonly onToggleKeepFullHistory: () => void;
253+
} | null;
247254
readonly creationState:
248255
| {
249256
readonly kind: "preparing";
@@ -1681,6 +1688,14 @@ function ThreadDetailBody(
16811688
{freshSessionAvailable ? (
16821689
<FreshSessionNotice threadKey={selectedThreadKey} />
16831690
) : null}
1691+
{props.compactBeforeSend && !props.draftMode ? (
1692+
<CompactBeforeSendNotice
1693+
tokens={props.compactBeforeSend.tokens}
1694+
keepFullHistory={props.compactBeforeSend.keepFullHistory}
1695+
disabled={!props.canOperateThread}
1696+
onToggleKeepFullHistory={props.compactBeforeSend.onToggleKeepFullHistory}
1697+
/>
1698+
) : null}
16841699
{props.canOperateThread ? (
16851700
<ManagedRuntimeModeNotice
16861701
threadKey={selectedThreadKey}

‎apps/mobile/src/features/threads/ThreadRouteScreen.tsx‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,6 +985,15 @@ function ThreadRouteContent(
985985
: composer.activeWorkStartedAt
986986
}
987987
isCompacting={composer.isCompacting}
988+
compactBeforeSend={
989+
composer.compactBeforeSendTokens === null
990+
? null
991+
: {
992+
tokens: composer.compactBeforeSendTokens,
993+
keepFullHistory: composer.keepFullHistory,
994+
onToggleKeepFullHistory: composer.toggleKeepFullHistory,
995+
}
996+
}
988997
runlessWorkActive={composer.runlessWorkActive}
989998
extensionStatuses={composer.extensionStatuses}
990999
providerSubagentStatus={composer.providerSubagentStatus}

‎apps/mobile/src/state/thread-task-permissions.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ vi.mock("react", () => ({
7171
useLayoutEffect: () => {},
7272
useRef: <A>(current: A) => ({ current }),
7373
useMemo: <A>(factory: () => A) => factory(),
74+
useSyncExternalStore: <A>(_subscribe: unknown, getSnapshot: () => A) => getSnapshot(),
7475
useState: <A>(initial: A | (() => A)) => [
7576
typeof initial === "function" ? (initial as () => A)() : initial,
7677
vi.fn(),
@@ -79,7 +80,7 @@ vi.mock("react", () => ({
7980
vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
8081
vi.mock("@t3tools/client-runtime/state/context-window", async (importOriginal) => ({
8182
...(await importOriginal<typeof import("@t3tools/client-runtime/state/context-window")>()),
82-
shouldCompactBeforeSend: () => state.compactDue,
83+
resolveCompactBeforeSendTokens: () => (state.compactDue ? 250_000 : null),
8384
}));
8485
vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
8586
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));

‎apps/mobile/src/state/use-thread-composer-state.ts‎

Lines changed: 60 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as Dialog from "../components/ui/Dialog";
33
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
44
import { readEnvironmentScope } from "./session";
55
import { useAtomValue } from "@effect/atom-react";
6-
import { shouldCompactBeforeSend } from "@t3tools/client-runtime/state/context-window";
6+
import { resolveCompactBeforeSendTokens } from "@t3tools/client-runtime/state/context-window";
77
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
88
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
99
import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows";
@@ -42,6 +42,7 @@ import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLega
4242
import { restoreAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
4343
import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
4444
import { uuidv4 } from "../lib/uuid";
45+
import { useNowMinuteMs } from "../lib/clock";
4546

4647
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
4748
import {
@@ -402,6 +403,57 @@ export function useThreadComposerState(input: {
402403
? (selectedThreadRuntime?.activeRunId ?? null)
403404
: null;
404405

406+
const resolveThreadCompactBeforeSendTokens = (send: {
407+
readonly modelSelection: ModelSelection;
408+
readonly text: string;
409+
readonly now: string;
410+
}) =>
411+
selectedEnvironmentRuntime?.connectionState === "connected" &&
412+
selectedThreadProjection !== null &&
413+
serverConfig != null
414+
? resolveCompactBeforeSendTokens({
415+
projection: selectedThreadProjection.projection,
416+
visibleTurnItems: selectedThreadVisibleTurnItems,
417+
selection: send.modelSelection,
418+
providers: serverConfig.providers,
419+
settings: serverConfig.settings,
420+
text: send.text,
421+
threadIdle:
422+
!activeThreadBusy &&
423+
!runlessWorkActive &&
424+
!isCompacting &&
425+
selectedThreadQueuedMessages.length === 0,
426+
now: send.now,
427+
})
428+
: null;
429+
const nowMinuteMs = useNowMinuteMs();
430+
const compactBeforeSendTokens =
431+
modelSelection === null || queuedRunEdit !== null || selectedDraft.freshContext === true
432+
? null
433+
: resolveThreadCompactBeforeSendTokens({
434+
modelSelection,
435+
text: "",
436+
now: new Date(nowMinuteMs).toISOString(),
437+
});
438+
// Per thread and for one send, as on web: the next send compacts again unless kept again.
439+
const [fullHistoryThreadKeys, setFullHistoryThreadKeys] = useState<ReadonlySet<string>>(
440+
() => new Set(),
441+
);
442+
const keepFullHistory =
443+
selectedThreadKey !== null && fullHistoryThreadKeys.has(selectedThreadKey);
444+
const setKeepFullHistory = (threadKey: string, keep: boolean) => {
445+
setFullHistoryThreadKeys((current) => {
446+
if (current.has(threadKey) === keep) return current;
447+
const next = new Set(current);
448+
if (keep) next.add(threadKey);
449+
else next.delete(threadKey);
450+
return next;
451+
});
452+
};
453+
const toggleKeepFullHistory = () => {
454+
if (selectedThreadKey !== null) setKeepFullHistory(selectedThreadKey, !keepFullHistory);
455+
};
456+
405457
const cancelQueuedRunEdit = () => {
406458
if (selectedThreadKey === null || savingQueuedEditRef.current) return;
407459
endQueuedRunEdit(selectedThreadKey);
@@ -734,24 +786,10 @@ export function useThreadComposerState(input: {
734786
// A fresh session drops the context a compaction would summarize.
735787
const compactBeforeSend =
736788
!freshContext &&
789+
!keepFullHistory &&
737790
followUpDispatchMode === null &&
738-
selectedEnvironmentRuntime?.connectionState === "connected" &&
739-
selectedThreadProjection !== null &&
740-
serverConfig != null &&
741-
shouldCompactBeforeSend({
742-
projection: selectedThreadProjection.projection,
743-
visibleTurnItems: selectedThreadVisibleTurnItems,
744-
selection: modelSelection,
745-
providers: serverConfig.providers,
746-
settings: serverConfig.settings,
747-
text,
748-
threadIdle:
749-
!activeThreadBusy &&
750-
!runlessWorkActive &&
751-
!isCompacting &&
752-
selectedThreadQueuedMessages.length === 0,
753-
now: metadata.createdAt,
754-
});
791+
resolveThreadCompactBeforeSendTokens({ modelSelection, text, now: metadata.createdAt }) !==
792+
null;
755793
const messageId = MessageId.make(metadata.messageId);
756794
onWillEnqueue?.();
757795
clearThreadComposerError(threadKey);
@@ -776,6 +814,7 @@ export function useThreadComposerState(input: {
776814
});
777815
clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
778816
if (freshContext) setFreshSessionPending(threadKey, false);
817+
if (keepFullHistory) setKeepFullHistory(threadKey, false);
779818
enqueuePromise.then(
780819
() => scheduleUnusedComposerAttachmentCleanup(attachments),
781820
(error: unknown) => {
@@ -861,6 +900,9 @@ export function useThreadComposerState(input: {
861900
),
862901
providerSubagentStatus,
863902
isCompacting,
903+
compactBeforeSendTokens,
904+
keepFullHistory,
905+
toggleKeepFullHistory,
864906
composerDraftKey,
865907
followUpBehavior,
866908
canSteerActiveTurn,

‎packages/client-runtime/src/state/contextWindow.test.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
import * as DateTime from "effect/DateTime";
1515
import { describe, expect, it } from "vite-plus/test";
1616

17-
import { shouldCompactBeforeSend } from "./contextWindow.ts";
17+
import { resolveCompactBeforeSendTokens } from "./contextWindow.ts";
1818
import type { ThreadStructure } from "./models.ts";
1919
import { v2Projection } from "./orchestrationV2TestFixtures.ts";
2020

@@ -181,7 +181,7 @@ function sendInput(
181181
};
182182
}
183183

184-
describe("shouldCompactBeforeSend", () => {
184+
describe("resolveCompactBeforeSendTokens", () => {
185185
it.each([
186186
{ name: "a stale Claude thread over 200K", expected: true },
187187
{
@@ -257,8 +257,8 @@ describe("shouldCompactBeforeSend", () => {
257257
{ name: "with no conversation but /compact", onlyCompactMessages: true, expected: false },
258258
{ name: "for a typed /compact", text: "/compact keep the plan", expected: false },
259259
] as const)("$name", ({ name: _name, expected, ...overrides }) => {
260-
expect(shouldCompactBeforeSend(sendInput(overrides as Parameters<typeof sendInput>[0]))).toBe(
261-
expected,
262-
);
260+
expect(
261+
resolveCompactBeforeSendTokens(sendInput(overrides as Parameters<typeof sendInput>[0])),
262+
).toBe(expected ? 293_611 : null);
263263
});
264264
});

‎packages/client-runtime/src/state/contextWindow.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -234,11 +234,11 @@ export function shouldOfferResumeCompaction(input: {
234234
}
235235

236236
/**
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.
237+
* The tokens a plain send into an idle thread compacts first, as web's composer does under
238+
* "When you return", or null when it sends as is. A send that hands off to another
239+
* conversation starts that one fresh, so only the resumed one counts.
240240
*/
241-
export function shouldCompactBeforeSend(input: {
241+
export function resolveCompactBeforeSendTokens(input: {
242242
readonly projection: Pick<
243243
ThreadStructure,
244244
| "thread"
@@ -259,7 +259,7 @@ export function shouldCompactBeforeSend(input: {
259259
readonly text: string;
260260
readonly threadIdle: boolean;
261261
readonly now: string;
262-
}): boolean {
262+
}): number | null {
263263
const { projection } = input;
264264
const provider = input.providers.find((entry) => entry.instanceId === input.selection.instanceId);
265265
if (
@@ -290,7 +290,7 @@ export function shouldCompactBeforeSend(input: {
290290
.map((request) => ({ kind: "user-input.resolved", payload: { answers: request.answers } })),
291291
)
292292
) {
293-
return false;
293+
return null;
294294
}
295295
const activeProviderThreadId = projection.thread.activeProviderThreadId;
296296
const providerThread = projection.providerThreads.find(
@@ -306,14 +306,14 @@ export function shouldCompactBeforeSend(input: {
306306
liveUsage,
307307
providerThread,
308308
);
309-
return (
310-
contextWindow !== null &&
309+
return contextWindow !== null &&
311310
shouldOfferResumeCompaction({
312311
provider: provider.driver,
313312
usedTokens: contextWindow.usedTokens,
314313
updatedAt: contextWindow.updatedAt,
315314
promptCacheTtlMs: liveUsage?.promptCacheTtlMs,
316315
now: input.now,
317316
})
318-
);
317+
? contextWindow.usedTokens
318+
: null;
319319
}

0 commit comments

Comments
 (0)