The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 22:15 UTC
fix(mobile): stale Claude threads show a compact-before-send notice (#34263)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Praffi Ramadhani committed
Nov 12, 2026 at 04:23 UTC
462eeac63bb3573d9efca2311d8b9d9b740c2fd3
6 files changed
+130
-38
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+18
@@ -176,6 +176,8 @@ import { PendingApprovalCard } from "./PendingApprovalCard";
176
import { ComposerErrorNotice } from "./ComposerErrorNotice";
177
import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
178
import { FreshSessionNotice } from "./FreshSessionNotice";
179
+import { Notice } from "../../components/ui/Notice";
180
+import { formatTokens } from "@t3tools/shared/usageFormat";
181
import { ComposerFeedback } from "./ComposerFeedback";
182
import { ComposerUsageLimits } from "./ComposerUsageLimits";
183
import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -244,6 +246,11 @@ export interface ThreadDetailScreenProps {
246
readonly providerSubagentStatus?: ProviderSubagentStatus | null;
247
readonly extensionStatuses?: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>;
248
readonly isCompacting: boolean;
249
+ /** Set while the next send compacts the thread first. */
250
+ readonly compactBeforeSend?: {
251
+ readonly tokens: number;
252
+ readonly keepFullHistory: () => void;
253
+ } | null;
254
readonly creationState:
255
| {
256
readonly kind: "preparing";
@@ -1681,6 +1688,17 @@ function ThreadDetailBody(
1688
{freshSessionAvailable ? (
1689
<FreshSessionNotice threadKey={selectedThreadKey} />
1690
) : null}
1691
+ {props.compactBeforeSend ? (
1692
+ <View className="px-4 pb-3">
1693
+ <Notice
1694
+ message={`Your next message compacts ${formatTokens(props.compactBeforeSend.tokens)} tokens of history first.`}
1695
+ icon="arrow.down.right.and.arrow.up.left"
1696
+ floating
1697
+ onDismiss={props.compactBeforeSend.keepFullHistory}
1698
+ dismissLabel="Keep the full history"
1699
+ />
1700
+ </View>
1701
+ ) : null}
1702
{props.canOperateThread ? (
1703
<ManagedRuntimeModeNotice
1704
threadKey={selectedThreadKey}
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+1
@@ -985,6 +985,7 @@ function ThreadRouteContent(
985
: composer.activeWorkStartedAt
986
}
987
isCompacting={composer.isCompacting}
988
+ compactBeforeSend={composer.compactBeforeSend}
989
runlessWorkActive={composer.runlessWorkActive}
990
extensionStatuses={composer.extensionStatuses}
991
providerSubagentStatus={composer.providerSubagentStatus}
apps/mobile/src/state/thread-task-permissions.test.ts
+40
-5
@@ -38,7 +38,8 @@ const state = vi.hoisted(() => ({
38
pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests,
39
enqueue: vi.fn(async () => undefined),
40
freshPending: false,
41
- compactDue: false,
41
+ compactModel: null as string | null,
42
+ compactDueAt: "",
43
setFreshPending: vi.fn(),
44
clearDraft: vi.fn(),
45
approve: vi.fn(),
@@ -79,8 +80,12 @@ vi.mock("react", () => ({
80
vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
81
vi.mock("@t3tools/client-runtime/state/context-window", async (importOriginal) => ({
82
...(await importOriginal<typeof import("@t3tools/client-runtime/state/context-window")>()),
82
- shouldCompactBeforeSend: () => state.compactDue,
83
+ compactBeforeSendTokens: (input: { readonly selection: ModelSelection; readonly now: string }) =>
84
+ input.selection.model === state.compactModel && input.now >= state.compactDueAt
85
+ ? 248_000
86
+ : null,
87
}));
88
+vi.mock("../lib/clock", () => ({ useNowMinuteMs: () => 0 }));
89
vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
90
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
91
vi.mock("./queued-run-edit", () => ({
@@ -203,7 +208,8 @@ beforeEach(() => {
208
runtimeMode: undefined,
209
};
210
state.freshPending = false;
206
- state.compactDue = false;
211
+ state.compactModel = null;
212
+ state.compactDueAt = "";
213
state.thread.latestRun = null;
214
state.projection = null;
215
state.serverConfig = {
@@ -288,7 +294,7 @@ describe("mobile task permissions", () => {
294
expect(state.setFreshPending).toHaveBeenCalledWith("secondary:thread", false);
295
});
296
291
- it("compacts a stale thread before sending unless a fresh session is armed", async () => {
297
+ it("compacts a stale thread before sending unless kept or a fresh session is armed", async () => {
298
state.grantedEnvironments.add("secondary");
299
state.projection = {
300
thread: {
@@ -314,12 +320,41 @@ describe("mobile task permissions", () => {
320
visibleTurnItems: [],
321
updatedAt: DateTime.makeUnsafe(0),
322
} as unknown as OrchestrationV2ThreadProjection;
317
- state.compactDue = true;
323
+ state.compactModel = "gpt-5.4";
324
+ // The notice's minute clock (the epoch here) trails a deadline the send's exact time has passed.
325
+ state.compactDueAt = "2026-01-01T00:00:00.000Z";
326
+ const unannounced = useThreadComposerState(NO_SIDE_CHATS);
327
+ expect(unannounced.compactBeforeSend).toBeNull();
328
+ await unannounced.onSendMessage();
329
+ expect(state.enqueue).toHaveBeenLastCalledWith(
330
+ expect.not.objectContaining({ compactBeforeSend: true }),
331
+ );
332
+ state.compactDueAt = "";
333
const composer = useThreadComposerState(NO_SIDE_CHATS);
334
+ expect(composer.compactBeforeSend?.tokens).toBe(248_000);
335
await composer.onSendMessage();
336
expect(state.enqueue).toHaveBeenLastCalledWith(
337
expect.objectContaining({ compactBeforeSend: true }),
338
);
339
+ // A model picked after the last render still decides the send.
340
+ state.draft = {
341
+ ...state.draft,
342
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.5" },
343
+ };
344
+ await composer.onSendMessage();
345
+ expect(state.enqueue).toHaveBeenLastCalledWith(
346
+ expect.not.objectContaining({ compactBeforeSend: true }),
347
+ );
348
+ state.draft = { ...state.draft, modelSelection: undefined };
349
+ composer.compactBeforeSend?.keepFullHistory();
350
+ const kept = useThreadComposerState(NO_SIDE_CHATS);
351
+ expect(kept.compactBeforeSend).toBeNull();
352
+ await kept.onSendMessage();
353
+ expect(state.enqueue).toHaveBeenLastCalledWith(
354
+ expect.not.objectContaining({ compactBeforeSend: true }),
355
+ );
356
+ // Keeping covers one send, as on web.
357
+ expect(useThreadComposerState(NO_SIDE_CHATS).compactBeforeSend?.tokens).toBe(248_000);
358
state.freshPending = true;
359
await composer.onSendMessage();
360
expect(state.enqueue).toHaveBeenLastCalledWith(
apps/mobile/src/state/use-thread-composer-state.ts
+57
-20
@@ -3,7 +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";
6
+import { compactBeforeSendTokens } 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 { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows";
@@ -42,6 +42,7 @@ import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLega
42
import { restoreAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
43
import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
44
import { uuidv4 } from "../lib/uuid";
45
+import { useNowMinuteMs } from "../lib/clock";
46
47
import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
48
import {
@@ -120,6 +121,17 @@ import { useAtomCommand } from "./use-atom-command";
121
const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
122
Atom.withLabel("mobile-thread-queue-workflow:empty"),
123
);
124
+// Threads whose next send keeps the full history instead of compacting first.
125
+const fullHistoryThreadKeysAtom = Atom.make<Readonly<Record<string, true>>>({}).pipe(
126
+ Atom.keepAlive,
127
+);
128
+
129
+function setKeepFullHistory(threadKey: string, keep: boolean) {
130
+ const { [threadKey]: kept, ...rest } = appAtomRegistry.get(fullHistoryThreadKeysAtom);
131
+ if ((kept === true) === keep) return;
132
+ appAtomRegistry.set(fullHistoryThreadKeysAtom, keep ? { ...rest, [threadKey]: true } : rest);
133
+}
134
+
135
const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]);
136
const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0);
137
@@ -398,6 +410,34 @@ export function useThreadComposerState(input: {
410
: null;
411
412
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
413
+ const resumeCompactionTokens = (selection: ModelSelection | null, text: string, now: string) =>
414
+ selectedEnvironmentRuntime?.connectionState === "connected" &&
415
+ selectedThreadProjection !== null &&
416
+ serverConfig != null &&
417
+ selection !== null
418
+ ? compactBeforeSendTokens({
419
+ projection: selectedThreadProjection.projection,
420
+ visibleTurnItems: selectedThreadVisibleTurnItems,
421
+ selection,
422
+ providers: serverConfig.providers,
423
+ settings: serverConfig.settings,
424
+ text,
425
+ threadIdle:
426
+ !activeThreadBusy &&
427
+ !runlessWorkActive &&
428
+ !isCompacting &&
429
+ selectedThreadQueuedMessages.length === 0,
430
+ now,
431
+ })
432
+ : null;
433
+ const nowMinuteMs = useNowMinuteMs();
434
+ const compactTokens =
435
+ selectedDraft.freshContext === true
436
+ ? null
437
+ : resumeCompactionTokens(modelSelection, "", new Date(nowMinuteMs).toISOString());
438
+ const fullHistoryThreadKeys = useAtomValue(fullHistoryThreadKeysAtom);
439
+ const keepFullHistory =
440
+ selectedThreadKey !== null && fullHistoryThreadKeys[selectedThreadKey] === true;
441
const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
442
? (selectedThreadRuntime?.activeRunId ?? null)
443
: null;
@@ -731,27 +771,14 @@ export function useThreadComposerState(input: {
771
// A redirect belongs to the approval it answers; the armed session waits for the next message.
772
const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey);
773
const metadata = makeQueuedMessageMetadata();
734
- // A fresh session drops the context a compaction would summarize.
774
+ // A fresh session drops the context a compaction would summarize. Only a send the notice
775
+ // announced compacts, since the notice's minute clock can trail the exact deadline.
776
const compactBeforeSend =
777
+ compactTokens !== null &&
778
!freshContext &&
779
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
- });
780
+ appAtomRegistry.get(fullHistoryThreadKeysAtom)[threadKey] !== true &&
781
+ resumeCompactionTokens(modelSelection, text, metadata.createdAt) !== null;
782
const messageId = MessageId.make(metadata.messageId);
783
onWillEnqueue?.();
784
clearThreadComposerError(threadKey);
@@ -777,7 +804,10 @@ export function useThreadComposerState(input: {
804
clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
805
if (freshContext) setFreshSessionPending(threadKey, false);
806
enqueuePromise.then(
780
- () => scheduleUnusedComposerAttachmentCleanup(attachments),
807
+ () => {
808
+ setKeepFullHistory(threadKey, false);
809
+ scheduleUnusedComposerAttachmentCleanup(attachments);
810
+ },
811
(error: unknown) => {
812
// Restore with uncapped append; capped merge could drop attachments added during the failed write.
813
void mergeComposerDraftContent(threadKey, {
@@ -861,6 +891,13 @@ export function useThreadComposerState(input: {
891
),
892
providerSubagentStatus,
893
isCompacting,
894
+ compactBeforeSend:
895
+ compactTokens === null || selectedThreadKey === null || keepFullHistory
896
+ ? null
897
+ : {
898
+ tokens: compactTokens,
899
+ keepFullHistory: () => setKeepFullHistory(selectedThreadKey, true),
900
+ },
901
composerDraftKey,
902
followUpBehavior,
903
canSteerActiveTurn,
packages/client-runtime/src/state/contextWindow.test.ts
+4
-4
@@ -14,7 +14,7 @@ import {
14
import * as DateTime from "effect/DateTime";
15
import { describe, expect, it } from "vite-plus/test";
16
17
-import { shouldCompactBeforeSend } from "./contextWindow.ts";
17
+import { compactBeforeSendTokens } from "./contextWindow.ts";
18
import type { ThreadStructure } from "./models.ts";
19
import { v2Projection } from "./orchestrationV2TestFixtures.ts";
20
@@ -181,7 +181,7 @@ function sendInput(
181
};
182
}
183
184
-describe("shouldCompactBeforeSend", () => {
184
+describe("compactBeforeSendTokens", () => {
185
it.each([
186
{ name: "a stale Claude thread over 200K", expected: true },
187
{
@@ -257,8 +257,8 @@ describe("shouldCompactBeforeSend", () => {
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,
260
+ expect(compactBeforeSendTokens(sendInput(overrides as Parameters<typeof sendInput>[0]))).toBe(
261
+ expected ? 293_611 : null,
262
);
263
});
264
});
packages/client-runtime/src/state/contextWindow.ts
+10
-9
@@ -234,11 +234,12 @@ export function shouldOfferResumeCompaction(input: {
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.
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. Web reads the same state for its "Compact and
239
+ * send" button. A send that hands off to another conversation starts that one fresh, so only the
240
+ * resumed one counts.
241
*/
241
-export function shouldCompactBeforeSend(input: {
242
+export function compactBeforeSendTokens(input: {
243
readonly projection: Pick<
244
ThreadStructure,
245
| "thread"
@@ -259,7 +260,7 @@ export function shouldCompactBeforeSend(input: {
260
readonly text: string;
261
readonly threadIdle: boolean;
262
readonly now: string;
262
-}): boolean {
263
+}): number | null {
264
const { projection } = input;
265
const provider = input.providers.find((entry) => entry.instanceId === input.selection.instanceId);
266
if (
@@ -290,7 +291,7 @@ export function shouldCompactBeforeSend(input: {
291
.map((request) => ({ kind: "user-input.resolved", payload: { answers: request.answers } })),
292
)
293
) {
293
- return false;
294
+ return null;
295
}
296
const activeProviderThreadId = projection.thread.activeProviderThreadId;
297
const providerThread = projection.providerThreads.find(
@@ -306,8 +307,7 @@ export function shouldCompactBeforeSend(input: {
307
liveUsage,
308
providerThread,
309
);
309
- return (
310
- contextWindow !== null &&
310
+ return contextWindow !== null &&
311
shouldOfferResumeCompaction({
312
provider: provider.driver,
313
usedTokens: contextWindow.usedTokens,
@@ -315,5 +315,6 @@ export function shouldCompactBeforeSend(input: {
315
promptCacheTtlMs: liveUsage?.promptCacheTtlMs,
316
now: input.now,
317
})
318
- );
318
+ ? contextWindow.usedTokens
319
+ : null;
320
}