Skip to content

Commit 754e1d1

Browse files
shivamhwpPR Batch Testerclaudemaria-rcks
authored
fix(mobile): compact stale Claude threads before sending (#27935)
Co-authored-by: PR Batch Tester <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent c192c43 commit 754e1d1

21 files changed

Lines changed: 719 additions & 246 deletions

‎apps/mobile/src/state/thread-outbox-model.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ export const QueuedThreadMessageSchema = Schema.Struct({
5656
attachments: Schema.Array(DraftComposerAttachmentSchema),
5757
modelSelection: Schema.optional(ModelSelection),
5858
dispatchMode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
59+
compactBeforeSend: Schema.optional(Schema.Boolean),
5960
runtimeMode: Schema.optional(RuntimeMode),
6061
interactionMode: Schema.optional(ProviderInteractionMode),
6162
creation: Schema.optional(QueuedThreadCreationSchema),
@@ -89,6 +90,8 @@ export interface QueuedThreadMessage {
8990
readonly interactionMode?: ProviderInteractionModeType;
9091
/** Captured at enqueue because draining may occur long after the tap. */
9192
readonly dispatchMode?: ComposerDispatchMode;
93+
/** Sends "When you return"'s `/compact` ahead of the message, which queues behind it. */
94+
readonly compactBeforeSend?: boolean;
9295
readonly creation?: QueuedThreadCreation;
9396
readonly createdAt: string;
9497
}

‎apps/mobile/src/state/thread-outbox.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,8 @@ describe("thread outbox", () => {
329329
},
330330
runtimeMode: "approval-required",
331331
interactionMode: "plan",
332+
dispatchMode: "queue",
333+
compactBeforeSend: true,
332334
} satisfies QueuedThreadMessage;
333335

334336
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,7 @@ describe("mobile handoff preview and submission", () => {
333333
auth: { status: "authenticated" as const },
334334
availability: "available" as "available" | "unavailable",
335335
models: [{ slug: selection.model }],
336+
slashCommands: [],
336337
};
337338
const projectOverride = { enabled: false };
338339
state.serverConfig = {

‎apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,3 +498,52 @@ describe("queued task operation access", () => {
498498
},
499499
);
500500
});
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‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ import {
1616
CommandId,
1717
DEFAULT_PROVIDER_INTERACTION_MODE,
1818
DEFAULT_RUNTIME_MODE,
19+
MessageId,
1920
managedRuntimeModeDenial,
2021
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
2122
type EnvironmentId,
22-
type MessageId,
2323
} from "@t3tools/contracts";
2424
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
2525
import * as Cause from "effect/Cause";
@@ -873,6 +873,37 @@ export function createThreadOutboxDelivery(): {
873873
settings,
874874
currentConfig.providers,
875875
);
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+
}
876907
if (!hasAccess()) return true;
877908
const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, {
878909
environmentId: queuedMessage.environmentId,

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +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";
67
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
78
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
89
import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
@@ -661,6 +662,25 @@ export function useThreadComposerState() {
661662
: "auto";
662663

663664
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+
});
664684
const messageId = MessageId.make(metadata.messageId);
665685
onWillEnqueue?.();
666686
clearThreadComposerError(threadKey);
@@ -678,7 +698,11 @@ export function useThreadComposerState() {
678698
provider,
679699
draft.interactionMode ?? thread.interactionMode,
680700
),
681-
...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
701+
...(compactBeforeSend
702+
? { compactBeforeSend, dispatchMode: "queue" as const }
703+
: followUpDispatchMode === null
704+
? {}
705+
: { dispatchMode: followUpDispatchMode }),
682706
createdAt: metadata.createdAt,
683707
});
684708
clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });

‎apps/web/src/components/ChatView.logic.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
deriveThreadRuntime,
55
} from "@t3tools/client-runtime/state/thread-execution";
66
import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints";
7+
import { COMPACT_COMMAND_PATTERN } from "@t3tools/client-runtime/state/context-window";
78
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
89
import {
910
latestUnheldRun,
@@ -834,10 +835,6 @@ export function shouldShowPlanFollowUpPrompt(input: {
834835
);
835836
}
836837

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-
841838
const sessionDismissedBranchMismatchKeys = new Set<string>();
842839

843840
export function dismissBranchMismatchForSession(key: string): void {

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -314,15 +314,13 @@ import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/Compos
314314
import { modelFallbackBannerItem } from "./chat/ComposerUsageLimits";
315315
import { ComposerSurface } from "./chat/ComposerSurface";
316316
import { resolveThreadSyncPhase } from "../threadSync";
317-
import {
318-
hasAvailableCompactionProvider,
319-
hasDismissedResumeCompaction,
320-
shouldOfferResumeCompaction,
321-
} from "./chat/ContextWindowMeter.logic";
317+
import { hasAvailableCompactionProvider } from "./chat/ContextWindowMeter.logic";
322318
import {
323319
deriveLatestContextWindowSnapshot,
320+
hasDismissedResumeCompaction,
324321
latestProviderTurnTokenUsage,
325-
} from "../lib/contextWindow";
322+
shouldOfferResumeCompaction,
323+
} from "@t3tools/client-runtime/state/context-window";
326324
import {
327325
MOBILE_COMPOSER_VIEW_TRANSITION_NAME,
328326
MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ import {
252252
resolveComposerDispatchMode,
253253
type ComposerDispatchMode,
254254
} from "@t3tools/client-runtime/state/composer-dispatch";
255-
import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
255+
import { deriveLatestContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
256256
import {
257257
resolveProviderSkillsForCwd,
258258
resolveProviderSlashCommandsForCwd,

‎apps/web/src/components/chat/ComposerFooterControls.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { createModelSelection } from "@t3tools/shared/model";
88
import { BotIcon, PencilRulerIcon } from "lucide-react";
99
import { type ComponentProps, memo, useId, useRef, useState } from "react";
1010

11-
import type { ContextWindowSnapshot } from "../../lib/contextWindow";
11+
import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
1212
import { Menu as MenuPrimitive } from "@base-ui/react/menu";
1313
import { Menu, MenuPopup, MenuTrigger } from "../ui/menu";
1414
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";

0 commit comments

Comments
 (0)