Skip to content

Commit f5d4576

Browse files
feat: compacting on return reads as compacting after being idle
The /compact the composer sends before a message to an idle thread now carries idleCompaction: "onReturn" (T3 Code's own compaction before cache expiry carries "beforeCacheExpires"). The working row reads "Compacting after being idle…" while it runs, the finished divider notes "After being idle", and the compaction no longer sends its own Done notification ahead of the reply to your message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 999cece commit f5d4576

14 files changed

Lines changed: 129 additions & 51 deletions

File tree

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

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,18 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
2828
import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";
2929
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3030
import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
31-
import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
31+
import {
32+
IDLE_COMPACTION_NOTES,
33+
resolveUserMessagePresentation,
34+
} from "@t3tools/client-runtime/user-message";
3235
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
3336
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
3437
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
3538
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
3639
import {
3740
AuthFilesystemReadScope,
3841
isCompactionCommandMessage,
39-
isIdleCompactionMessage,
42+
idleCompactionOf,
4043
type OrchestrationMessageContext,
4144
ThreadId,
4245
type ChatAttachment,
@@ -1190,6 +1193,11 @@ function ThreadAutomationMessageRow(props: {
11901193
);
11911194
}
11921195

1196+
function idleCompactionNote(message: Parameters<typeof idleCompactionOf>[0]) {
1197+
const reason = idleCompactionOf(message);
1198+
return reason === undefined ? undefined : IDLE_COMPACTION_NOTES[reason];
1199+
}
1200+
11931201
function CompactionNote(props: { readonly note: string | undefined }) {
11941202
return props.note === undefined ? null : (
11951203
<Text className="font-t3-medium text-xs text-foreground-muted opacity-70">· {props.note}</Text>
@@ -1428,9 +1436,7 @@ function renderFeedEntry(
14281436
iconColor={iconSubtleColor}
14291437
active={active}
14301438
>
1431-
<CompactionNote
1432-
note={isIdleCompactionMessage(message) ? "Automatic before cache expiry" : undefined}
1433-
/>
1439+
<CompactionNote note={idleCompactionNote(message)} />
14341440
</ThreadContextDivider>
14351441
);
14361442
}
@@ -2531,18 +2537,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
25312537
const compactionNoteByRunId = useMemo(() => {
25322538
const notes = new Map<RunId, string>();
25332539
for (const entry of props.feed) {
2534-
if (
2535-
entry.type === "message" &&
2536-
entry.message.runId !== null &&
2537-
isIdleCompactionMessage(entry.message)
2538-
) {
2539-
notes.set(entry.message.runId, "Automatic before cache expiry");
2540+
const note = entry.type === "message" ? idleCompactionNote(entry.message) : undefined;
2541+
if (entry.type === "message" && entry.message.runId !== null && note !== undefined) {
2542+
notes.set(entry.message.runId, note);
25402543
} else if (entry.type === "activity-group" && entry.runId !== null) {
25412544
for (const activity of entry.activities) {
25422545
const age = activity.workEntry.questionAnswer
25432546
? claudeResumeCompactionAge(activity.workEntry.questionAnswer)
25442547
: null;
2545-
if (age !== null) notes.set(entry.runId, `On return after ${age} idle`);
2548+
if (age !== null) notes.set(entry.runId, `After ${age} idle`);
25462549
}
25472550
}
25482551
}

‎apps/mobile/src/lib/threadActivity.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ export interface ThreadFeedMessage {
142142
readonly creationSource?: OrchestrationV2CreationSource;
143143
readonly scheduledTaskId?: ScheduledTaskId;
144144
readonly senderThreadId?: ThreadId;
145+
readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
145146
readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
146147
readonly sourceThreadId: ThreadId;
147148
readonly createdAt: string;
@@ -2196,6 +2197,7 @@ export function buildThreadFeed(
21962197
creationSource: item.creationSource,
21972198
...(item.scheduledTaskId ? { scheduledTaskId: item.scheduledTaskId } : {}),
21982199
...(item.senderThreadId ? { senderThreadId: item.senderThreadId } : {}),
2200+
...(item.idleCompaction ? { idleCompaction: item.idleCompaction } : {}),
21992201
}
22002202
: {}),
22012203
visibility: row.visibility,

‎apps/server/src/orchestration-v2/IdleCompactionService.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ export const make = Effect.gen(function* () {
7575
attachments: [],
7676
createdBy: "agent",
7777
creationSource: "server",
78+
idleCompaction: "beforeCacheExpires",
7879
dispatchMode: { type: "start_immediately" },
7980
});
8081
return;

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1875,6 +1875,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
18751875
...(queuedMessage.senderThreadId === undefined
18761876
? {}
18771877
: { senderThreadId: queuedMessage.senderThreadId }),
1878+
...(queuedMessage.idleCompaction === undefined
1879+
? {}
1880+
: { idleCompaction: queuedMessage.idleCompaction }),
18781881
}),
18791882
providerThreadId: queuedProviderThread.id,
18801883
inputIntent: "queued_turn",
@@ -4131,6 +4134,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
41314134
readonly creationSource: OrchestrationV2ConversationMessage["creationSource"];
41324135
readonly scheduledTaskId?: OrchestrationV2ConversationMessage["scheduledTaskId"];
41334136
readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"];
4137+
readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"];
41344138
readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"];
41354139
readonly forceRestart: boolean;
41364140
}) {
@@ -4288,6 +4292,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
42884292
? {}
42894293
: { scheduledTaskId: input.scheduledTaskId }),
42904294
...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
4295+
...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
42914296
id: input.messageId,
42924297
threadId: input.command.threadId,
42934298
runId: messageInput.runId,
@@ -4307,6 +4312,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
43074312
? {}
43084313
: { scheduledTaskId: input.scheduledTaskId }),
43094314
...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
4315+
...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
43104316
id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
43114317
threadId: input.command.threadId,
43124318
runId: messageInput.runId,
@@ -5242,6 +5248,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
52425248
? {}
52435249
: { scheduledTaskId: command.scheduledTaskId }),
52445250
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5251+
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
52455252
forceRestart: dispatchMode.type === "restart_active",
52465253
});
52475254
return;
@@ -5477,6 +5484,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
54775484
? {}
54785485
: { scheduledTaskId: command.scheduledTaskId }),
54795486
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5487+
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
54805488
id: command.messageId,
54815489
threadId: command.threadId,
54825490
runId,
@@ -5817,6 +5825,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
58175825
? {}
58185826
: { scheduledTaskId: command.scheduledTaskId }),
58195827
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5828+
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
58205829
id: command.messageId,
58215830
threadId: command.threadId,
58225831
runId,
@@ -5838,6 +5847,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
58385847
? {}
58395848
: { scheduledTaskId: command.scheduledTaskId }),
58405849
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5850+
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
58415851
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
58425852
threadId: command.threadId,
58435853
runId,
@@ -6504,6 +6514,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
65046514
? {}
65056515
: { scheduledTaskId: command.scheduledTaskId }),
65066516
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
6517+
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
65076518
id: command.messageId,
65086519
threadId: command.threadId,
65096520
runId,
@@ -6525,6 +6536,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
65256536
? {}
65266537
: { scheduledTaskId: command.scheduledTaskId }),
65276538
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
6539+
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
65286540
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
65296541
threadId: command.threadId,
65306542
runId,
@@ -8151,6 +8163,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
81518163
...(queuedMessage.senderThreadId === undefined
81528164
? {}
81538165
: { senderThreadId: queuedMessage.senderThreadId }),
8166+
...(queuedMessage.idleCompaction === undefined
8167+
? {}
8168+
: { idleCompaction: queuedMessage.idleCompaction }),
81548169
forceRestart: false,
81558170
});
81568171
});

‎apps/server/src/orchestration-v2/ProjectionStore.test.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2880,11 +2880,12 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
28802880
);
28812881

28822882
it.effect.each([
2883-
["T3 Code's idle compaction", "agent", "server", true],
2884-
["a typed /compact", "user", "web", false],
2883+
["T3 Code's idle compaction", "agent", "server", undefined, true],
2884+
["compacting on return", "user", "web", "onReturn", true],
2885+
["a typed /compact", "user", "mobile", undefined, false],
28852886
] as const)(
28862887
"marks the shell's latest run silent only for %s",
2887-
([, createdBy, creationSource, silent]) =>
2888+
([, createdBy, creationSource, idleCompaction, silent]) =>
28882889
Effect.gen(function* () {
28892890
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
28902891
const now = yield* DateTime.now;
@@ -2928,6 +2929,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
29282929
payload: {
29292930
createdBy,
29302931
creationSource,
2932+
...(idleCompaction === undefined ? {} : { idleCompaction }),
29312933
id: messageId,
29322934
threadId,
29332935
runId,

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ import type {
4343
} from "@t3tools/contracts";
4444
import {
4545
IDLE_COMPACTION_TEXT,
46-
isIdleCompactionMessage,
46+
idleCompactionOf,
4747
OrchestrationV2AppThreadJson as OrchestrationV2AppThreadJsonSchema,
4848
OrchestrationV2CheckpointJson as OrchestrationV2CheckpointJsonSchema,
4949
OrchestrationV2CheckpointScopeJson as OrchestrationV2CheckpointScopeJsonSchema,
@@ -1640,7 +1640,8 @@ export function threadShellFromProjection(
16401640
latestRunSilent:
16411641
latestRun != null &&
16421642
projection.messages.some(
1643-
(message) => message.id === latestRun.userMessageId && isIdleCompactionMessage(message),
1643+
(message) =>
1644+
message.id === latestRun.userMessageId && idleCompactionOf(message) !== undefined,
16441645
),
16451646
activeRunId: activeRun?.id ?? null,
16461647
blockedOnThreadWait: deriveBlockedOnThreadWait({ activeRun, turnItems: projection.turnItems }),
@@ -5695,14 +5696,19 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
56955696
WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = presented.run_id
56965697
AND stop_request.type = 'run_interrupt_request'
56975698
) AS latest_run_stop_requested,
5698-
-- Mirrors isIdleCompactionMessage.
5699+
-- Mirrors idleCompactionOf.
56995700
EXISTS (
57005701
SELECT 1 FROM orchestration_v2_projection_messages prompt
57015702
WHERE prompt.message_id = json_extract(presented.payload_json, '$.userMessageId')
57025703
AND prompt.role = 'user'
5703-
AND json_extract(prompt.payload_json, '$.createdBy') = 'agent'
5704-
AND json_extract(prompt.payload_json, '$.creationSource') = 'server'
57055704
AND json_extract(prompt.payload_json, '$.text') = ${IDLE_COMPACTION_TEXT}
5705+
AND (
5706+
json_extract(prompt.payload_json, '$.idleCompaction') IS NOT NULL
5707+
OR (
5708+
json_extract(prompt.payload_json, '$.createdBy') = 'agent'
5709+
AND json_extract(prompt.payload_json, '$.creationSource') = 'server'
5710+
)
5711+
)
57065712
) AS latest_run_silent,
57075713
active.run_id AS active_run_id,
57085714
active.status AS active_run_status,

‎apps/web/src/components/chat/MessagesTimeline.logic.test.ts‎

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -526,15 +526,10 @@ describe("deriveMessagesTimelineRows", () => {
526526
const [history0, history1, history2, liveUser, , liveAssistant] = fixture.visibleTurnItems;
527527
if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message")
528528
throw new Error("Expected live fixture items");
529-
const compactPrompt = {
529+
const compactPrompt = (idleCompaction: "beforeCacheExpires" | "onReturn") => ({
530530
...liveUser,
531-
item: {
532-
...liveUser.item,
533-
text: "/compact",
534-
createdBy: "agent" as const,
535-
creationSource: "server" as const,
536-
},
537-
};
531+
item: { ...liveUser.item, text: "/compact", idleCompaction },
532+
});
538533
const compaction = {
539534
...liveAssistant,
540535
item: { ...liveAssistant.item, type: "compaction" as const, driver: null },
@@ -552,13 +547,17 @@ describe("deriveMessagesTimelineRows", () => {
552547
supportsConversationRollback: false,
553548
});
554549

555-
for (const rows of [rowsFor([compactPrompt]), rowsFor([compactPrompt, compaction])]) {
556-
const liveRows = rows.slice(
557-
rows.findIndex((row) => row.id.includes("history-assistant")) + 1,
558-
);
559-
expect(liveRows).toMatchObject([
560-
{ kind: "working", compacting: "Compacting before the cache expires…" },
561-
]);
550+
for (const [reason, compacting] of [
551+
["beforeCacheExpires", "Compacting before the cache expires…"],
552+
["onReturn", "Compacting after being idle…"],
553+
] as const) {
554+
const prompt = compactPrompt(reason);
555+
for (const rows of [rowsFor([prompt]), rowsFor([prompt, compaction])]) {
556+
const liveRows = rows.slice(
557+
rows.findIndex((row) => row.id.includes("history-assistant")) + 1,
558+
);
559+
expect(liveRows).toMatchObject([{ kind: "working", compacting }]);
560+
}
562561
}
563562
});
564563

@@ -619,7 +618,7 @@ describe("deriveMessagesTimelineRows", () => {
619618
{ kind: "working", compacting: "Compacting after 1h 5m idle…" },
620619
]);
621620
expect(liveRows("completed")).toMatchObject([
622-
{ kind: "context-compaction", note: "On return after 1h 5m idle" },
621+
{ kind: "context-compaction", note: "After 1h 5m idle" },
623622
]);
624623
});
625624

‎apps/web/src/components/chat/MessagesTimeline.logic.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ import {
99
} from "@t3tools/shared/assistantCitations";
1010
import { shallow } from "zustand/vanilla/shallow";
1111
import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
12+
import {
13+
IDLE_COMPACTING_LABELS,
14+
IDLE_COMPACTION_NOTES,
15+
} from "@t3tools/client-runtime/user-message";
1216
import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff";
1317
import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives";
1418
import {
@@ -46,9 +50,10 @@ import {
4650
type TurnDiffSummary,
4751
} from "../../types";
4852
import {
53+
idleCompactionOf,
4954
isCompactionCommandMessage,
50-
isIdleCompactionMessage,
5155
type MessageId,
56+
type OrchestrationV2IdleCompaction,
5257
type WorktreeSetupSnapshot,
5358
type OrchestrationV2ProjectedTurnItem,
5459
type RunAttemptId,
@@ -1582,7 +1587,10 @@ export function deriveMessagesTimelineRows(input: {
15821587
// A bare `/compact` turn is the compaction itself: one compaction row stands in for its prompt
15831588
// and working indicator, from the moment the turn starts. Likewise an answered "compact before
15841589
// continuing?" question folds into the compaction it asked for.
1585-
const compactionRuns = new Map<RunId, { note: string | undefined; hasItem: boolean }>();
1590+
const compactionRuns = new Map<
1591+
RunId,
1592+
{ reason: OrchestrationV2IdleCompaction | undefined; hasItem: boolean }
1593+
>();
15861594
const compactedRunIds = new Set<RunId>();
15871595
const resumeCompactionAgeByRunId = new Map<RunId, string>();
15881596
for (const entry of timelineEntries) {
@@ -1592,7 +1600,7 @@ export function deriveMessagesTimelineRows(input: {
15921600
isCompactionCommandMessage(entry.message)
15931601
) {
15941602
compactionRuns.set(entry.message.runId, {
1595-
note: isIdleCompactionMessage(entry.message) ? "Automatic before cache expiry" : undefined,
1603+
reason: idleCompactionOf(entry.message),
15961604
hasItem: false,
15971605
});
15981606
} else if (entry.kind === "work" && entry.entry.runId) {
@@ -1609,8 +1617,10 @@ export function deriveMessagesTimelineRows(input: {
16091617
}
16101618
const compactionNote = (runId: RunId | null | undefined) => {
16111619
if (runId == null) return undefined;
1620+
const reason = compactionRuns.get(runId)?.reason;
1621+
if (reason !== undefined) return IDLE_COMPACTION_NOTES[reason];
16121622
const age = resumeCompactionAgeByRunId.get(runId);
1613-
return compactionRuns.get(runId)?.note ?? (age ? `On return after ${age} idle` : undefined);
1623+
return age ? `After ${age} idle` : undefined;
16141624
};
16151625
const activeRunIsCompaction =
16161626
input.isWorking && unsettledRunId !== null && compactionRuns.has(unsettledRunId);
@@ -1630,8 +1640,8 @@ export function deriveMessagesTimelineRows(input: {
16301640
: null;
16311641
const compactingLabel = (() => {
16321642
if (activeCompactionRunId === null) return undefined;
1633-
if (compactionRuns.get(activeCompactionRunId)?.note)
1634-
return "Compacting before the cache expires…";
1643+
const reason = compactionRuns.get(activeCompactionRunId)?.reason;
1644+
if (reason !== undefined) return IDLE_COMPACTING_LABELS[reason];
16351645
const age = resumeCompactionAgeByRunId.get(activeCompactionRunId);
16361646
return age ? `Compacting after ${age} idle…` : "Compacting context…";
16371647
})();
@@ -1975,7 +1985,7 @@ export function deriveMessagesTimelineRows(input: {
19751985
label: "Context compaction",
19761986
tokenCounts: null,
19771987
active: false,
1978-
...(compactionRun.note ? { note: compactionRun.note } : {}),
1988+
...(compactionRun.reason ? { note: IDLE_COMPACTION_NOTES[compactionRun.reason] } : {}),
19791989
});
19801990
}
19811991
continue;

‎apps/web/src/components/chat/useComposerSend.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1199,7 +1199,13 @@ export function useComposerSend(input: ComposerSendInput) {
11991199
environmentId,
12001200
input: {
12011201
threadId: threadIdForSend,
1202-
message: { messageId: newMessageId(), role: "user", text: "/compact", attachments: [] },
1202+
message: {
1203+
messageId: newMessageId(),
1204+
role: "user",
1205+
text: "/compact",
1206+
attachments: [],
1207+
idleCompaction: "onReturn",
1208+
},
12031209
modelSelection: ctxSelectedModelSelection,
12041210
runtimeMode,
12051211
interactionMode: sendInteractionMode,

0 commit comments

Comments
 (0)