Skip to content

Commit 462eeac

Browse files
fix(mobile): stale Claude threads show a compact-before-send notice (#34263)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 1ab3afe commit 462eeac

6 files changed

Lines changed: 130 additions & 38 deletions

File tree

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,8 @@ import { PendingApprovalCard } from "./PendingApprovalCard";
176176
import { ComposerErrorNotice } from "./ComposerErrorNotice";
177177
import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
178178
import { FreshSessionNotice } from "./FreshSessionNotice";
179+
import { Notice } from "../../components/ui/Notice";
180+
import { formatTokens } from "@t3tools/shared/usageFormat";
179181
import { ComposerFeedback } from "./ComposerFeedback";
180182
import { ComposerUsageLimits } from "./ComposerUsageLimits";
181183
import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -244,6 +246,11 @@ export interface ThreadDetailScreenProps {
244246
readonly providerSubagentStatus?: ProviderSubagentStatus | null;
245247
readonly extensionStatuses?: NonNullable<OrchestrationV2ProviderSession["extensionStatuses"]>;
246248
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;
247254
readonly creationState:
248255
| {
249256
readonly kind: "preparing";
@@ -1681,6 +1688,17 @@ function ThreadDetailBody(
16811688
{freshSessionAvailable ? (
16821689
<FreshSessionNotice threadKey={selectedThreadKey} />
16831690
) : 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}
16841702
{props.canOperateThread ? (
16851703
<ManagedRuntimeModeNotice
16861704
threadKey={selectedThreadKey}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,6 +985,7 @@ function ThreadRouteContent(
985985
: composer.activeWorkStartedAt
986986
}
987987
isCompacting={composer.isCompacting}
988+
compactBeforeSend={composer.compactBeforeSend}
988989
runlessWorkActive={composer.runlessWorkActive}
989990
extensionStatuses={composer.extensionStatuses}
990991
providerSubagentStatus={composer.providerSubagentStatus}

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

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ const state = vi.hoisted(() => ({
3838
pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests,
3939
enqueue: vi.fn(async () => undefined),
4040
freshPending: false,
41-
compactDue: false,
41+
compactModel: null as string | null,
42+
compactDueAt: "",
4243
setFreshPending: vi.fn(),
4344
clearDraft: vi.fn(),
4445
approve: vi.fn(),
@@ -79,8 +80,12 @@ 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+
compactBeforeSendTokens: (input: { readonly selection: ModelSelection; readonly now: string }) =>
84+
input.selection.model === state.compactModel && input.now >= state.compactDueAt
85+
? 248_000
86+
: null,
8387
}));
88+
vi.mock("../lib/clock", () => ({ useNowMinuteMs: () => 0 }));
8489
vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
8590
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
8691
vi.mock("./queued-run-edit", () => ({
@@ -203,7 +208,8 @@ beforeEach(() => {
203208
runtimeMode: undefined,
204209
};
205210
state.freshPending = false;
206-
state.compactDue = false;
211+
state.compactModel = null;
212+
state.compactDueAt = "";
207213
state.thread.latestRun = null;
208214
state.projection = null;
209215
state.serverConfig = {
@@ -288,7 +294,7 @@ describe("mobile task permissions", () => {
288294
expect(state.setFreshPending).toHaveBeenCalledWith("secondary:thread", false);
289295
});
290296

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 () => {
292298
state.grantedEnvironments.add("secondary");
293299
state.projection = {
294300
thread: {
@@ -314,12 +320,41 @@ describe("mobile task permissions", () => {
314320
visibleTurnItems: [],
315321
updatedAt: DateTime.makeUnsafe(0),
316322
} 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 = "";
318333
const composer = useThreadComposerState(NO_SIDE_CHATS);
334+
expect(composer.compactBeforeSend?.tokens).toBe(248_000);
319335
await composer.onSendMessage();
320336
expect(state.enqueue).toHaveBeenLastCalledWith(
321337
expect.objectContaining({ compactBeforeSend: true }),
322338
);
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);
323358
state.freshPending = true;
324359
await composer.onSendMessage();
325360
expect(state.enqueue).toHaveBeenLastCalledWith(

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

Lines changed: 57 additions & 20 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 { compactBeforeSendTokens } 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 {
@@ -120,6 +121,17 @@ import { useAtomCommand } from "./use-atom-command";
120121
const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
121122
Atom.withLabel("mobile-thread-queue-workflow:empty"),
122123
);
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+
123135
const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]);
124136
const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0);
125137

@@ -398,6 +410,34 @@ export function useThreadComposerState(input: {
398410
: null;
399411

400412
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;
401441
const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
402442
? (selectedThreadRuntime?.activeRunId ?? null)
403443
: null;
@@ -731,27 +771,14 @@ export function useThreadComposerState(input: {
731771
// A redirect belongs to the approval it answers; the armed session waits for the next message.
732772
const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey);
733773
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.
735776
const compactBeforeSend =
777+
compactTokens !== null &&
736778
!freshContext &&
737779
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;
755782
const messageId = MessageId.make(metadata.messageId);
756783
onWillEnqueue?.();
757784
clearThreadComposerError(threadKey);
@@ -777,7 +804,10 @@ export function useThreadComposerState(input: {
777804
clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
778805
if (freshContext) setFreshSessionPending(threadKey, false);
779806
enqueuePromise.then(
780-
() => scheduleUnusedComposerAttachmentCleanup(attachments),
807+
() => {
808+
setKeepFullHistory(threadKey, false);
809+
scheduleUnusedComposerAttachmentCleanup(attachments);
810+
},
781811
(error: unknown) => {
782812
// Restore with uncapped append; capped merge could drop attachments added during the failed write.
783813
void mergeComposerDraftContent(threadKey, {
@@ -861,6 +891,13 @@ export function useThreadComposerState(input: {
861891
),
862892
providerSubagentStatus,
863893
isCompacting,
894+
compactBeforeSend:
895+
compactTokens === null || selectedThreadKey === null || keepFullHistory
896+
? null
897+
: {
898+
tokens: compactTokens,
899+
keepFullHistory: () => setKeepFullHistory(selectedThreadKey, true),
900+
},
864901
composerDraftKey,
865902
followUpBehavior,
866903
canSteerActiveTurn,

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

Lines changed: 4 additions & 4 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 { compactBeforeSendTokens } 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("compactBeforeSendTokens", () => {
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,
260+
expect(compactBeforeSendTokens(sendInput(overrides as Parameters<typeof sendInput>[0]))).toBe(
261+
expected ? 293_611 : null,
262262
);
263263
});
264264
});

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

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -234,11 +234,12 @@ 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. 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.
240241
*/
241-
export function shouldCompactBeforeSend(input: {
242+
export function compactBeforeSendTokens(input: {
242243
readonly projection: Pick<
243244
ThreadStructure,
244245
| "thread"
@@ -259,7 +260,7 @@ export function shouldCompactBeforeSend(input: {
259260
readonly text: string;
260261
readonly threadIdle: boolean;
261262
readonly now: string;
262-
}): boolean {
263+
}): number | null {
263264
const { projection } = input;
264265
const provider = input.providers.find((entry) => entry.instanceId === input.selection.instanceId);
265266
if (
@@ -290,7 +291,7 @@ export function shouldCompactBeforeSend(input: {
290291
.map((request) => ({ kind: "user-input.resolved", payload: { answers: request.answers } })),
291292
)
292293
) {
293-
return false;
294+
return null;
294295
}
295296
const activeProviderThreadId = projection.thread.activeProviderThreadId;
296297
const providerThread = projection.providerThreads.find(
@@ -306,14 +307,14 @@ export function shouldCompactBeforeSend(input: {
306307
liveUsage,
307308
providerThread,
308309
);
309-
return (
310-
contextWindow !== null &&
310+
return contextWindow !== null &&
311311
shouldOfferResumeCompaction({
312312
provider: provider.driver,
313313
usedTokens: contextWindow.usedTokens,
314314
updatedAt: contextWindow.updatedAt,
315315
promptCacheTtlMs: liveUsage?.promptCacheTtlMs,
316316
now: input.now,
317317
})
318-
);
318+
? contextWindow.usedTokens
319+
: null;
319320
}

0 commit comments

Comments
 (0)