@devries-cameron20 / t3code Mirror · read-only / commits / 0345e852ed
Fork 0

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 22, 18:15 UTC

feat: compactions T3 Code starts read as one working row, and stay quiet (#24334)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 24, 2026 at 12:37 UTC 0345e852ed009cc17ba1f0eec56d0c431897ba7f
27 files changed +1375 -82
apps/mobile/src/features/threads/ThreadFeed.tsx
+60 -5
@@ -28,13 +28,17 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
28 import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";
29 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
30 import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
31 -import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
31 +import {
32 + IDLE_COMPACTING_LABELS,
33 + resolveUserMessagePresentation,
34 +} from "@t3tools/client-runtime/user-message";
35 import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
36 import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
37 import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
38 import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
39 import {
40 AuthFilesystemReadScope,
41 + idleCompactionOf,
42 type OrchestrationMessageContext,
43 ThreadId,
44 type ChatAttachment,
@@ -195,6 +199,7 @@ import {
199 } from "../../lib/markdownLinks";
200 import {
201 createThreadFeedCache,
202 + threadFeedCompactionLabels,
203 failedFeedRunIds,
204 deriveThreadFeedPresentation,
205 threadFeedRunIsUnsettled,
@@ -224,7 +229,11 @@ import {
229 ThreadWorkLog,
230 WORK_GROUP_TOGGLE_HEIGHT,
231 } from "./thread-work-log";
227 -import { appendPendingThreadMessages, type PendingThreadFeedEntry } from "./pending-thread-feed";
232 +import {
233 + appendPendingThreadMessages,
234 + isCompactionCommandFeedEntry,
235 + type PendingThreadFeedEntry,
236 +} from "./pending-thread-feed";
237 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
238 import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size";
239 import { htmlRenderFrameHeight } from "@t3tools/shared/htmlRender";
@@ -1192,6 +1201,13 @@ function ThreadAutomationMessageRow(props: {
1201 );
1202 }
1203
1204 +/** Leads with why T3 Code compacted, when it did so without being asked. */
1205 +function compactionLabel(label: string, title: string | undefined) {
1206 + return title !== undefined && label.startsWith("Context compacted")
1207 + ? title + label.slice("Context compacted".length)
1208 + : label;
1209 +}
1210 +
1211 function renderFeedEntry(
1212 info: { item: PendingThreadFeedEntry; index: number },
1213 props: Pick<
@@ -1210,6 +1226,7 @@ function renderFeedEntry(
1226 readonly workGroupScrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
1227 readonly terminalAssistantMessageIds: ReadonlySet<string>;
1228 readonly unsettledTurnId: RunId | null;
1229 + readonly compactionLabelsByEntryId: ReadonlyMap<string, { title: string; compacting: string }>;
1230 readonly failedRunIds: ReadonlySet<RunId>;
1231 readonly onCopyWorkRow: (rowId: string, value: string) => void;
1232 readonly onToggleWorkGroup: (groupId: string, anchorKey?: string) => void;
@@ -1361,16 +1378,29 @@ function renderFeedEntry(
1378
1379 if (entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) {
1380 const label = entry.activities[0]!.summary;
1381 + const item = entry.activities[0]!.projectedItem.item;
1382 const active =
1383 props.unsettledTurnId !== null &&
1384 entry.runId === props.unsettledTurnId &&
1367 - entry.activities[0]!.projectedItem.item.status === "running";
1385 + item.status === "running";
1386 + const labels = props.compactionLabelsByEntryId.get(entry.id);
1387 + const failure =
1388 + item.type === "compaction" && item.status === "failed" ? item.summary?.trim() : undefined;
1389 return (
1390 <ThreadContextDivider
1370 - label={label}
1371 - icon="arrow.down.right.and.arrow.up.left"
1391 + label={
1392 + failure
1393 + ? `${label} · ${failure}`
1394 + : active && labels
1395 + ? labels.compacting
1396 + : compactionLabel(label, labels?.title)
1397 + }
1398 + icon={
1399 + item.status === "failed" ? "exclamationmark.circle" : "arrow.down.right.and.arrow.up.left"
1400 + }
1401 iconColor={iconSubtleColor}
1402 active={active}
1403 + failed={item.status === "failed"}
1404 />
1405 );
1406 }
@@ -1409,6 +1439,25 @@ function renderFeedEntry(
1439 />
1440 );
1441 }
1442 + if (isCompactionCommandFeedEntry(entry)) {
1443 + // Stands in for the compaction item until the provider reports it.
1444 + const active = props.unsettledTurnId !== null && message.runId === props.unsettledTurnId;
1445 + const reason = idleCompactionOf(message);
1446 + return (
1447 + <ThreadContextDivider
1448 + label={
1449 + !active
1450 + ? "Context compaction"
1451 + : reason === undefined
1452 + ? "Compacting context"
1453 + : IDLE_COMPACTING_LABELS[reason]
1454 + }
1455 + icon="arrow.down.right.and.arrow.up.left"
1456 + iconColor={iconSubtleColor}
1457 + active={active}
1458 + />
1459 + );
1460 + }
1461 if (isUser && presentation.attribution === "automation") {
1462 const rowId = `automation:${message.id}`;
1463 return (
@@ -2505,6 +2554,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2554 );
2555 const reviewCommentColors = useReviewCommentColors();
2556 const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
2557 + const compactionLabelsByEntryId = useMemo(
2558 + () => threadFeedCompactionLabels(props.feed),
2559 + [props.feed],
2560 + );
2561 // LegendList does not invalidate visible rows when only the renderItem closure changes.
2562 // Include turn completion so unchanged message rows reveal their footer and spacing
2563 // even when the final message update arrives before the turn settles.
@@ -2987,6 +3040,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3040 workGroupScrollPositions,
3041 terminalAssistantMessageIds,
3042 unsettledTurnId,
3043 + compactionLabelsByEntryId,
3044 failedRunIds,
3045 onCopyWorkRow,
3046 onToggleWorkGroup,
@@ -3124,6 +3178,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3178 keyExtractor={(entry) => entry.id}
3179 getItemType={(entry) => {
3180 if (entry.type !== "message") return entry.type;
3181 + if (isCompactionCommandFeedEntry(entry)) return "message:compaction";
3182 const { attribution } = resolveUserMessagePresentation(entry.message);
3183 return attribution === "automation" || attribution === "agent"
3184 ? `message:${attribution}`
apps/mobile/src/features/threads/pending-thread-feed.test.ts
+30 -1
@@ -8,7 +8,7 @@ import {
8 ThreadId,
9 } from "@t3tools/contracts";
10 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
11 -import { appendPendingThreadMessages } from "./pending-thread-feed";
11 +import { appendPendingThreadMessages, isCompactionCommandFeedEntry } from "./pending-thread-feed";
12
13 const pending = (id: string): QueuedThreadMessage => ({
14 environmentId: EnvironmentId.make("env"),
@@ -21,6 +21,35 @@ const pending = (id: string): QueuedThreadMessage => ({
21 });
22
23 describe("pending timeline messages", () => {
24 + it.each([false, true])(
25 + "keeps a queued compact command in the pending message row (attachment: %s)",
26 + (withAttachment) => {
27 + const queued = {
28 + ...pending("compact"),
29 + text: "/compact",
30 + attachments: withAttachment
31 + ? [
32 + {
33 + id: "image-1",
34 + type: "image" as const,
35 + name: "photo.png",
36 + mimeType: "image/png",
37 + sizeBytes: 3,
38 + fileUri: "file:///documents/photo.png",
39 + previewUri: "file:///documents/photo.png",
40 + },
41 + ]
42 + : [],
43 + };
44 + const entry = appendPendingThreadMessages([], [], [queued])[0]!;
45 + expect(isCompactionCommandFeedEntry(entry)).toBe(false);
46 + expect(entry.pendingMessage).toEqual(queued);
47 + if (!withAttachment) {
48 + expect(isCompactionCommandFeedEntry({ ...entry, pendingMessage: undefined })).toBe(true);
49 + }
50 + },
51 + );
52 +
53 it("marks the synthetic creation prompt pending without duplicating it", () => {
54 const queued = {
55 ...pending("creation"),
apps/mobile/src/features/threads/pending-thread-feed.ts
+9
@@ -1,3 +1,4 @@
1 +import { isCompactionCommandMessage } from "@t3tools/contracts";
2 import type { ThreadFeedEntry } from "../../lib/threadActivity";
3 import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
4
@@ -45,3 +46,11 @@ export function appendPendingThreadMessages(
46 })),
47 ];
48 }
49 +
50 +export function isCompactionCommandFeedEntry(entry: PendingThreadFeedEntry): boolean {
51 + return (
52 + entry.type === "message" &&
53 + entry.pendingMessage === undefined &&
54 + isCompactionCommandMessage(entry.message)
55 + );
56 +}
apps/mobile/src/lib/threadActivity.test.ts
+139
@@ -24,6 +24,7 @@ import { describe, expect, it } from "vite-plus/test";
24
25 import {
26 buildThreadFeed,
27 + threadFeedCompactionLabels,
28 createThreadFeedCache,
29 deriveThreadFeedPresentation,
30 messageFoldRunId,
@@ -76,6 +77,144 @@ it("keeps historical plan detail accessible from its paged turn item", () => {
77 expect(presented[2]).toMatchObject({ activities: [{ projectedItem: { item } }] });
78 });
79
80 +it("shows a compact command as one mobile divider before, during, and after compaction", () => {
81 + const startedAt = "2026-06-20T00:00:01.000Z";
82 + const prompt = projected({ ...userMessage(), text: "/compact", idleCompaction: "onReturn" }, 0);
83 + const latestRun = { runId, status: "running" as const, startedAt, completedAt: null };
84 + const present = (items: OrchestrationV2ProjectedTurnItem[]) =>
85 + deriveThreadFeedPresentation(
86 + buildThreadFeed(items),
87 + latestRun,
88 + new Set(),
89 + new Set(),
90 + startedAt,
91 + );
92 +
93 + const waiting = present([prompt]);
94 + expect(waiting.map((entry) => entry.type)).toEqual(["message"]);
95 + expect(waiting[0]?.type === "message" ? waiting[0].message.idleCompaction : null).toBe(
96 + "onReturn",
97 + );
98 + for (const status of ["running", "completed", "failed"] as const) {
99 + const compaction = projected(
100 + {
101 + ...base("compaction", "2026-06-20T00:00:02.000Z", 1),
102 + type: "compaction",
103 + driver: ProviderDriverKind.make("claude"),
104 + status,
105 + beforeTokenCount: 100_000,
106 + ...(status === "completed" ? { afterTokenCount: 20_000 } : {}),
107 + ...(status === "failed" ? { summary: "Not enough messages to compact." } : {}),
108 + },
109 + 1,
110 + );
111 + const rows = present([prompt, compaction]);
112 + expect(rows.map((entry) => entry.type)).toEqual(["activity-group"]);
113 + expect(
114 + rows[0]?.type === "activity-group" ? rows[0].activities[0]?.projectedItem.item : null,
115 + ).toMatchObject({ type: "compaction", status });
116 + }
117 +});
118 +
119 +it.each(["/compact", "Continue"])(
120 + "keeps a completed compaction divider visible while other settled work folds for %s",
121 + (promptText) => {
122 + const rows = deriveThreadFeedPresentation(
123 + buildThreadFeed([
124 + projected({ ...userMessage(), text: promptText }, 0),
125 + projected(command(), 1),
126 + projected(
127 + {
128 + ...base("compaction", "2026-06-20T00:00:03.000Z", 2),
129 + type: "compaction",
130 + driver: ProviderDriverKind.make("claude"),
131 + status: "completed",
132 + beforeTokenCount: 100_000,
133 + afterTokenCount: 20_000,
134 + },
135 + 2,
136 + ),
137 + ]),
138 + {
139 + runId,
140 + status: "completed",
141 + startedAt: "2026-06-20T00:00:01.000Z",
142 + completedAt: "2026-06-20T00:00:03.000Z",
143 + },
144 + new Set(),
145 + );
146 + expect(rows.filter((entry) => entry.type === "run-fold")).toHaveLength(1);
147 + const activities = rows.flatMap((entry) =>
148 + entry.type === "activity-group" ? entry.activities : [],
149 + );
150 + expect(activities.map((activity) => activity.projectedItem.item)).toMatchObject([
151 + {
152 + type: "compaction",
153 + status: "completed",
154 + beforeTokenCount: 100_000,
155 + afterTokenCount: 20_000,
156 + },
157 + ]);
158 + if (promptText === "/compact") {
159 + expect(rows.some((entry) => entry.type === "message")).toBe(false);
160 + }
161 + },
162 +);
163 +
164 +it("binds a persisted resume answer only to the next compaction in its run", () => {
165 + const requestId = RuntimeRequestId.make("resume-compaction");
166 + const question = projected(
167 + {
168 + ...base("resume-question", "2026-06-20T00:00:02.000Z", 1),
169 + type: "user_input_request",
170 + requestId,
171 + questions: [],
172 + questionAnswer: {
173 + requestId,
174 + questionTextById: {
175 + resume:
176 + "This session is 2h 10m old and uses 200,000 tokens. Compact it before continuing?",
177 + },
178 + answers: { resume: "Compact and continue" },
179 + attachmentsByQuestionId: {},
180 + },
181 + },
182 + 1,
183 + );
184 + const compaction = (id: string, position: number, status: "running" | "completed") =>
185 + projected(
186 + {
187 + ...base(id, `2026-06-20T00:00:0${position + 1}.000Z`, position),
188 + type: "compaction",
189 + driver: ProviderDriverKind.make("claude"),
190 + status,
191 + beforeTokenCount: 200_000,
192 + },
193 + position,
194 + );
195 + for (const status of ["running", "completed"] as const) {
196 + // Rebuild from persisted items, without a live question or prior feed cache.
197 + const feed = buildThreadFeed([
198 + projected(userMessage(), 0),
199 + question,
200 + compaction("resume-compact", 2, "completed"),
201 + compaction("auto-compact", 3, status),
202 + ]);
203 + const labels = threadFeedCompactionLabels(feed);
204 + const compactRows = feed.filter(
205 + (entry) =>
206 + entry.type === "activity-group" &&
207 + entry.activities[0]?.projectedItem.item.type === "compaction",
208 + );
209 + expect(compactRows).toHaveLength(2);
210 + expect(labels.get(compactRows[0]!.id)).toEqual({
211 + title: "Context compacted after 2h 10m idle",
212 + compacting: "Compacting after 2h 10m idle…",
213 + });
214 + expect(labels.get(compactRows[1]!.id)).toBeUndefined();
215 + }
216 +});
217 +
218 function base(id: string, updatedAt: string, ordinal: number) {
219 const timestamp = DateTime.makeUnsafe(updatedAt);
220 return {
apps/mobile/src/lib/threadActivity.ts
+85 -1
@@ -53,7 +53,7 @@ import type {
53 ScheduledTaskId,
54 TurnItemId,
55 } from "@t3tools/contracts";
56 -import { RunId, ThreadId } from "@t3tools/contracts";
56 +import { idleCompactionOf, isCompactionCommandMessage, RunId, ThreadId } from "@t3tools/contracts";
57 import {
58 classifyToolActivity,
59 collectToolFilePaths,
@@ -62,6 +62,7 @@ import {
62 formatReadToolLabel,
63 formatSearchToolLabel,
64 } from "@t3tools/shared/toolActivity";
65 +import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
66 import { formatDuration } from "@t3tools/shared/orchestrationTiming";
67 import { truncate } from "@t3tools/shared/String";
68 import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
@@ -72,6 +73,10 @@ import {
73 mcpAppFromToolItem,
74 } from "@t3tools/shared/toolOutput";
75 import * as DateTime from "effect/DateTime";
76 +import {
77 + IDLE_COMPACTION_TITLES,
78 + IDLE_COMPACTING_LABELS,
79 +} from "@t3tools/client-runtime/user-message";
80
81 export type PendingApproval = ThreadPendingApproval;
82 export type PendingUserInput = ThreadPendingUserInput;
@@ -141,6 +146,7 @@ export interface ThreadFeedMessage {
146 readonly creationSource?: OrchestrationV2CreationSource;
147 readonly scheduledTaskId?: ScheduledTaskId;
148 readonly senderThreadId?: ThreadId;
149 + readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
150 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
151 readonly sourceThreadId: ThreadId;
152 readonly createdAt: string;
@@ -352,6 +358,49 @@ export function isContextCompactionActivityGroup(entry: ThreadFeedActivityGroup)
358 );
359 }
360
361 +export function threadFeedCompactionLabels(feed: ReadonlyArray<ThreadFeedEntry>) {
362 + const labelsByRunId = new Map<RunId, { title: string; compacting: string }>();
363 + const labelsByEntryId = new Map<string, { title: string; compacting: string }>();
364 + const pendingResumeAgeByRunId = new Map<RunId, string>();
365 + for (const entry of feed) {
366 + const reason = entry.type === "message" ? idleCompactionOf(entry.message) : undefined;
367 + if (entry.type === "message" && entry.message.runId !== null && reason !== undefined) {
368 + labelsByRunId.set(entry.message.runId, {
369 + title: IDLE_COMPACTION_TITLES[reason],
370 + compacting: IDLE_COMPACTING_LABELS[reason],
371 + });
372 + } else if (entry.type === "activity-group" && entry.runId !== null) {
373 + if (isContextCompactionActivityGroup(entry)) {
374 + const age = pendingResumeAgeByRunId.get(entry.runId);
375 + const labels =
376 + labelsByRunId.get(entry.runId) ??
377 + (age === undefined
378 + ? undefined
379 + : {
380 + title: `Context compacted after ${age} idle`,
381 + compacting: `Compacting after ${age} idle…`,
382 + });
383 + if (labels) labelsByEntryId.set(entry.id, labels);
384 + pendingResumeAgeByRunId.delete(entry.runId);
385 + }
386 + for (const activity of entry.activities) {
387 + const age = activity.workEntry.questionAnswer
388 + ? claudeResumeCompactionAge(activity.workEntry.questionAnswer)
389 + : null;
390 + if (age !== null) pendingResumeAgeByRunId.set(entry.runId, age);
391 + }
392 + }
393 + }
394 + return labelsByEntryId;
395 +}
396 +
397 +function isResumeCompactionAnswerGroup(entry: ThreadFeedActivityGroup): boolean {
398 + return entry.activities.every((activity) => {
399 + const answer = activity.workEntry.questionAnswer;
400 + return answer !== undefined && claudeResumeCompactionAge(answer) !== null;
401 + });
402 +}
403 +
404 export function isContextHandoffActivityGroup(entry: ThreadFeedActivityGroup): boolean {
405 return (
406 entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "handoff"
@@ -1183,6 +1232,7 @@ function deriveThreadFeedRunFolds(
1232 entry.id !== terminalAssistantId &&
1233 entry.type !== "html-render" &&
1234 entry.type !== "mcp-app" &&
1235 + !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) &&
1236 !(
1237 entry.type === "activity-group" &&
1238 entry.activities.some(
@@ -1396,6 +1446,26 @@ export function deriveThreadFeedPresentation(
1446 const failedRunIds = failedFeedRunIds(sourceFeed, latestRun);
1447 const activeTailGroup = sourceFeed.at(-1);
1448 const activeRunId = unsettledRunId(latestRun);
1449 + // A bare `/compact` turn is the compaction itself: its compaction row stands in for the prompt
1450 + // and the live activity row. An answered "compact before continuing?" question folds into the
1451 + // compaction it asked for.
1452 + const compactionCommandRunIds = new Set<RunId>();
1453 + const compactionItemRunIds = new Set<RunId>();
1454 + for (const entry of feed) {
1455 + if (
1456 + entry.type === "message" &&
1457 + entry.message.runId !== null &&
1458 + isCompactionCommandMessage(entry.message)
1459 + ) {
1460 + compactionCommandRunIds.add(entry.message.runId);
1461 + } else if (
1462 + entry.type === "activity-group" &&
1463 + entry.runId !== null &&
1464 + isContextCompactionActivityGroup(entry)
1465 + ) {
1466 + compactionItemRunIds.add(entry.runId);
1467 + }
1468 + }
1469 const isWorking = activeWorkStartedAt !== null && latestRun?.status !== "preparing";
1470 const foldsByAnchorId = deriveThreadFeedRunFolds(
1471 sourceFeed,
@@ -1450,6 +1520,18 @@ export function deriveThreadFeedPresentation(
1520 }
1521 result.push(row);
1522 }
1523 + if (
1524 + (entry.type === "message" &&
1525 + entry.message.runId !== null &&
1526 + compactionItemRunIds.has(entry.message.runId) &&
1527 + isCompactionCommandMessage(entry.message)) ||
1528 + (entry.type === "activity-group" &&
1529 + entry.runId !== null &&
1530 + compactionItemRunIds.has(entry.runId) &&
1531 + isResumeCompactionAnswerGroup(entry))
1532 + ) {
1533 + continue;
1534 + }
1535 if (!collapsedEntryIds.has(entry.id)) {
1536 if (
1537 entry.type === "activity-group" &&
@@ -1487,6 +1569,7 @@ export function deriveThreadFeedPresentation(
1569 isWorking &&
1570 activeWorkStartedAt !== null &&
1571 latestRun?.turnEnded !== true &&
1572 + (activeRunId === null || !compactionCommandRunIds.has(activeRunId)) &&
1573 !result.some(
1574 (row) =>
1575 row.id === LIVE_ACTIVITY_ROW_ID ||
@@ -2177,6 +2260,7 @@ export function buildThreadFeed(
2260 creationSource: item.creationSource,
2261 ...(item.scheduledTaskId ? { scheduledTaskId: item.scheduledTaskId } : {}),
2262 ...(item.senderThreadId ? { senderThreadId: item.senderThreadId } : {}),
2263 + ...(item.idleCompaction ? { idleCompaction: item.idleCompaction } : {}),
2264 }
2265 : {}),
2266 visibility: row.visibility,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+93 -2
@@ -4293,15 +4293,35 @@ describe("ClaudeAdapterV2 background wake turns", () => {
4293 const [running, settled] = updates;
4294 assert.equal(running?.status, "running");
4295 assert.equal(settled?.status, compaction === "success" ? "completed" : "failed");
4296 + assert.equal(
4297 + settled?.type === "compaction" ? settled.summary : undefined,
4298 + compaction === "failed"
4299 + ? limited
4300 + ? compactError
4301 + : "Not enough messages to compact."
4302 + : undefined,
4303 + );
4304 assert.equal(settled?.id, running?.id);
4305 assert.equal(settled?.ordinal, running?.ordinal);
4306 assert.deepEqual(settled?.startedAt, running?.startedAt);
4307 assert.isNotNull(settled?.completedAt);
4308 assert.isEmpty(harness.terminalEvents());
4309
4302 - yield* Queue.offer(
4310 + yield* Queue.offerAll(
4311 harness.sdkMessages,
4304 - compact ? claudeSdkFrame({ ...result, local_command: "compact" }) : result,
4312 + compact
4313 + ? [
4314 + // Claude Code echoes the command's stdout as a synthetic assistant message.
4315 + claudeSdkFrame({
4316 + ...makeAssistantTextFrame({
4317 + uuid: "00000000-0000-4000-8000-000000000615",
4318 + text: "Compacted.",
4319 + }),
4320 + local_command_source: "<local-command-stdout>Compacted.</local-command-stdout>",
4321 + }),
4322 + claudeSdkFrame({ ...result, local_command: "compact" }),
4323 + ]
4324 + : [result],
4325 );
4326 const terminal = yield* Queue.take(harness.terminalReceipts);
4327 assert.deepEqual(
@@ -4313,6 +4333,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
4333 updates,
4334 );
4335 assert.equal(terminal.status, status);
4336 + assert.equal(
4337 + harness.events.some(
4338 + (event) =>
4339 + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message",
4340 + ),
4341 + !compact,
4342 + );
4343 if (terminal.status !== "failed") return;
4344 assert.equal(terminal.failure.class, "usage_limit");
4345 assert.equal(terminal.failure.message, compactError);
@@ -4327,6 +4354,70 @@ describe("ClaudeAdapterV2 background wake turns", () => {
4354 ),
4355 );
4356
4357 + it.effect("keeps an unreported /compact failure's reason on the compaction, not as a reply", () =>
4358 + Effect.gen(function* () {
4359 + const harness = yield* makeWakeHarness;
4360 + const now = yield* DateTime.now;
4361 + yield* harness.runtime.startTurn(
4362 + makeClaudeTestTurnInput({
4363 + threadId: harness.threadId,
4364 + providerThread: harness.providerThread,
4365 + now,
4366 + attemptId: RunAttemptId.make("attempt-claude-compaction-unreported"),
4367 + text: "/compact",
4368 + attachments: [],
4369 + }),
4370 + );
4371 + // Claude can refuse a /compact without a compact_result: the only reason is the result text.
4372 + yield* Queue.offerAll(harness.sdkMessages, [
4373 + claudeSdkFrame({
4374 + type: "system",
4375 + subtype: "status",
4376 + status: "compacting",
4377 + uuid: "00000000-0000-4000-8000-000000000620",
4378 + session_id: WAKE_NATIVE_SESSION,
4379 + }),
4380 + claudeSdkFrame({
4381 + ...makeAssistantTextFrame({
4382 + uuid: "00000000-0000-4000-8000-000000000622",
4383 + text: "Not enough messages to compact.",
4384 + }),
4385 + local_command_source:
4386 + "<local-command-stdout>Not enough messages to compact.</local-command-stdout>",
4387 + }),
4388 + claudeSdkFrame({
4389 + ...makeResultFrame({
4390 + uuid: "00000000-0000-4000-8000-000000000621",
4391 + result: "Not enough messages to compact.",
4392 + numTurns: 0,
4393 + terminalReason: null,
4394 + }),
4395 + local_command: "compact",
4396 + }),
4397 + ]);
4398 + yield* Queue.take(harness.terminalReceipts);
4399 + const settled = harness.events
4400 + .flatMap((event) =>
4401 + event.type === "turn_item.updated" && event.turnItem.type === "compaction"
4402 + ? [event.turnItem]
4403 + : [],
4404 + )
4405 + .at(-1);
4406 + assert.equal(settled?.status, "failed");
4407 + assert.equal(settled?.summary, "Not enough messages to compact.");
4408 + assert.isFalse(
4409 + harness.events.some(
4410 + (event) =>
4411 + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message",
4412 + ),
4413 + );
4414 + }).pipe(
4415 + Effect.provide(
4416 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
4417 + ),
4418 + ),
4419 + );
4420 +
4421 it.effect.each([
4422 { name: "parent limit", parentErrors: ["rate_limit"], expectedLimit: true },
4423 {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+26 -2
@@ -58,6 +58,7 @@ import { AgentScope } from "@t3tools/shared/AgentScope";
58 import * as HostProcess from "@t3tools/shared/HostProcess";
59 import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
60 import {
61 + CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER,
62 CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
63 formatClaudeResumeCompactionQuestion,
64 } from "@t3tools/shared/claudeCompaction";
@@ -66,6 +67,7 @@ import {
67 ClaudeSettings,
68 TrimmedNonEmptyString,
69 defaultInstanceIdForDriver,
70 + isCompactionCommandMessage,
71 type ModelSelection,
72 type OrchestrationV2ConversationMessage,
73 type OrchestrationV2ExecutionNode,
@@ -6641,6 +6643,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6643 }) {
6644 yield* reasoningDeltas.flushTurn(input.context.nativeTurnId);
6645 if (input.context.compaction?.status === "running") {
6646 + const reason = input.result?.subtype === "success" ? input.result.result.trim() : "";
6647 yield* emitProviderEvent({
6648 type: "turn_item.updated",
6649 driver: CLAUDE_PROVIDER,
@@ -6651,6 +6654,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6654 input.status === "completed" || input.status === "failed"
6655 ? "Context compaction failed"
6656 : "Context compaction stopped",
6657 + ...(reason === "" ? {} : { summary: reason }),
6658 completedAt: input.completedAt,
6659 updatedAt: input.completedAt,
6660 },
@@ -7767,6 +7771,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7771 : message.compact_result === "failed"
7772 ? "Context compaction failed"
7773 : "Context compaction stopped",
7774 + ...(message.compact_result === "failed" && message.compact_error
7775 + ? { summary: message.compact_error }
7776 + : {}),
7777 completedAt: now,
7778 updatedAt: now,
7779 };
@@ -8484,6 +8491,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8491 });
8492 return;
8493 }
8494 + // Claude Code echoes /compact's stdout ("Not enough messages to compact.") as a
8495 + // synthetic assistant message. The compaction item reports that outcome; it is not a
8496 + // reply.
8497 + if (
8498 + message.type === "assistant" &&
8499 + "local_command_source" in message &&
8500 + isCompactionCommandMessage({ role: "user", ...context.input.message })
8501 + ) {
8502 + return;
8503 + }
8504 if (assistantText !== null && assistantText.text.length > 0) {
8505 yield* emitAssistantTextArtifacts({
8506 context,
@@ -8535,6 +8552,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8552 ? null
8553 : resultTextFromSdkMessage(message);
8554 if (
8555 + // A /compact's result text reports the compaction ("Not enough messages to
8556 + // compact."), which its compaction item already carries; it is not a reply.
8557 + !(
8558 + message.type === "result" &&
8559 + message.subtype === "success" &&
8560 + message.local_command === "compact"
8561 + ) &&
8562 context.assistant.emittedNativeItemIds.size === 0 &&
8563 context.assistant.fallbackText.length === 0 &&
8564 resultText !== null &&
@@ -9108,7 +9132,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9132 question,
9133 options: [
9134 {
9111 - label: "Compact and continue",
9135 + label: CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER,
9136 description: "Resume with a summary and use fewer tokens.",
9137 },
9138 {
@@ -9142,7 +9166,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9166 return {
9167 behavior: "completed" as const,
9168 result:
9145 - selection === "Compact and continue"
9169 + selection === CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER
9170 ? ("compact" as const)
9171 : selection === CLAUDE_RESUME_COMPACTION_NEVER_ANSWER
9172 ? ("never" as const)
apps/server/src/orchestration-v2/IdleCompactionService.ts
+3 -1
@@ -1,5 +1,6 @@
1 import {
2 CommandId,
3 + IDLE_COMPACTION_TEXT,
4 MessageId,
5 resolveIdleCompaction,
6 resolveProjectProviderInstanceEnabled,
@@ -70,10 +71,11 @@ export const make = Effect.gen(function* () {
71 commandId: CommandId.make(`server:idle-compact:${threadId}:${runId}`),
72 messageId: MessageId.make(`idle-compact:${threadId}:${runId}`),
73 threadId,
73 - text: "/compact",
74 + text: IDLE_COMPACTION_TEXT,
75 attachments: [],
76 createdBy: "agent",
77 creationSource: "server",
78 + idleCompaction: "beforeCacheExpires",
79 dispatchMode: { type: "start_immediately" },
80 });
81 return;
apps/server/src/orchestration-v2/Orchestrator.ts
+15
@@ -1876,6 +1876,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1876 ...(queuedMessage.senderThreadId === undefined
1877 ? {}
1878 : { senderThreadId: queuedMessage.senderThreadId }),
1879 + ...(queuedMessage.idleCompaction === undefined
1880 + ? {}
1881 + : { idleCompaction: queuedMessage.idleCompaction }),
1882 }),
1883 providerThreadId: queuedProviderThread.id,
1884 inputIntent: "queued_turn",
@@ -4145,6 +4148,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4148 readonly creationSource: OrchestrationV2ConversationMessage["creationSource"];
4149 readonly scheduledTaskId?: OrchestrationV2ConversationMessage["scheduledTaskId"];
4150 readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"];
4151 + readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"];
4152 readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"];
4153 readonly forceRestart: boolean;
4154 }) {
@@ -4302,6 +4306,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4306 ? {}
4307 : { scheduledTaskId: input.scheduledTaskId }),
4308 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
4309 + ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
4310 id: input.messageId,
4311 threadId: input.command.threadId,
4312 runId: messageInput.runId,
@@ -4321,6 +4326,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4326 ? {}
4327 : { scheduledTaskId: input.scheduledTaskId }),
4328 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
4329 + ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
4330 id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
4331 threadId: input.command.threadId,
4332 runId: messageInput.runId,
@@ -5256,6 +5262,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5262 ? {}
5263 : { scheduledTaskId: command.scheduledTaskId }),
5264 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5265 + ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
5266 forceRestart: dispatchMode.type === "restart_active",
5267 });
5268 return;
@@ -5491,6 +5498,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5498 ? {}
5499 : { scheduledTaskId: command.scheduledTaskId }),
5500 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5501 + ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
5502 id: command.messageId,
5503 threadId: command.threadId,
5504 runId,
@@ -5831,6 +5839,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5839 ? {}
5840 : { scheduledTaskId: command.scheduledTaskId }),
5841 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5842 + ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
5843 id: command.messageId,
5844 threadId: command.threadId,
5845 runId,
@@ -5852,6 +5861,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5861 ? {}
5862 : { scheduledTaskId: command.scheduledTaskId }),
5863 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
5864 + ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
5865 id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
5866 threadId: command.threadId,
5867 runId,
@@ -6518,6 +6528,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6528 ? {}
6529 : { scheduledTaskId: command.scheduledTaskId }),
6530 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
6531 + ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
6532 id: command.messageId,
6533 threadId: command.threadId,
6534 runId,
@@ -6539,6 +6550,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6550 ? {}
6551 : { scheduledTaskId: command.scheduledTaskId }),
6552 ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
6553 + ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
6554 id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
6555 threadId: command.threadId,
6556 runId,
@@ -8165,6 +8177,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8177 ...(queuedMessage.senderThreadId === undefined
8178 ? {}
8179 : { senderThreadId: queuedMessage.senderThreadId }),
8180 + ...(queuedMessage.idleCompaction === undefined
8181 + ? {}
8182 + : { idleCompaction: queuedMessage.idleCompaction }),
8183 forceRestart: false,
8184 });
8185 });
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+144
@@ -2879,6 +2879,150 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
2879 }),
2880 );
2881
2882 + it.effect.each([
2883 + ["T3 Code's idle compaction", "agent", "server", undefined, true, "/compact"],
2884 + ["compacting on return", "user", "web", "onReturn", true, "/compact"],
2885 + ["a typed /compact", "user", "mobile", undefined, false, "/compact"],
2886 + ["a normalized idle command", "agent", "server", undefined, true, " \t\u00a0/COMPACT\u3000\n"],
2887 + ["an ordinary prompt with idle metadata", "user", "web", "onReturn", false, "Continue"],
2888 + ] as const)(
2889 + "marks the shell's latest run silent only for %s",
2890 + ([name, createdBy, creationSource, idleCompaction, silent, text]) =>
2891 + Effect.gen(function* () {
2892 + const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
2893 + const now = yield* DateTime.now;
2894 + const key = name.replaceAll(/\W+/g, "-");
2895 + const threadId = ThreadId.make(`thread:projection-shell-silent:${key}`);
2896 + const runId = RunId.make(`run:projection-shell-silent:${key}`);
2897 + const messageId = MessageId.make(`message:projection-shell-silent:${key}`);
2898 + yield* projectionStore.apply({
2899 + id: EventId.make(`event:projection-shell-silent:${key}:thread`),
2900 + type: "thread.created",
2901 + threadId,
2902 + occurredAt: now,
2903 + payload: {
2904 + createdBy: "user",
2905 + creationSource: "web",
2906 + id: threadId,
2907 + projectId: ProjectId.make("project:projection-shell-silent"),
2908 + title: "Idle compaction",
2909 + providerInstanceId,
2910 + modelSelection,
2911 + runtimeMode: "full-access",
2912 + interactionMode: "default",
2913 + branch: null,
2914 + worktreePath: null,
2915 + activeProviderThreadId: null,
2916 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
2917 + forkedFrom: null,
2918 + createdAt: now,
2919 + updatedAt: now,
2920 + archivedAt: null,
2921 + settledOverride: null,
2922 + settledAt: null,
2923 + lastVisitedAt: null,
2924 + deletedAt: null,
2925 + },
2926 + });
2927 + yield* projectionStore.apply({
2928 + id: EventId.make(`event:projection-shell-silent:${key}:message`),
2929 + type: "message.updated",
2930 + threadId,
2931 + occurredAt: now,
2932 + payload: {
2933 + createdBy,
2934 + creationSource,
2935 + ...(idleCompaction === undefined ? {} : { idleCompaction }),
2936 + id: messageId,
2937 + threadId,
2938 + runId,
2939 + nodeId: null,
2940 + role: "user",
2941 + text,
2942 + attachments: [],
2943 + streaming: false,
2944 + createdAt: now,
2945 + updatedAt: now,
2946 + },
2947 + });
2948 + yield* projectionStore.apply({
2949 + id: EventId.make(`event:projection-shell-silent:${key}:run`),
2950 + type: "run.created",
2951 + threadId,
2952 + runId,
2953 + nodeId: NodeId.make(`node:projection-shell-silent:${key}`),
2954 + driver,
2955 + occurredAt: now,
2956 + payload: {
2957 + id: runId,
2958 + threadId,
2959 + ordinal: 1,
2960 + providerInstanceId,
2961 + modelSelection,
2962 + providerThreadId: null,
2963 + userMessageId: messageId,
2964 + rootNodeId: null,
2965 + activeAttemptId: null,
2966 + status: "completed",
2967 + requestedAt: now,
2968 + startedAt: now,
2969 + completedAt: now,
2970 + checkpointId: null,
2971 + contextHandoffId: null,
2972 + },
2973 + });
2974 +
2975 + const sqlShell = (yield* projectionStore.getShellSnapshot()).threads.find(
2976 + (thread) => thread.id === threadId,
2977 + );
2978 + const memoryShell = ProjectionStore.threadShellFromProjection(
2979 + yield* projectionStore.getThreadProjection(threadId),
2980 + );
2981 + assert.equal(sqlShell?.latestRunSilent, silent);
2982 + assert.equal(memoryShell.latestRunSilent, silent);
2983 +
2984 + // Claude can finish the run successfully even when its /compact failed.
2985 + yield* projectionStore.apply({
2986 + id: EventId.make(`event:projection-shell-silent:${key}:failure`),
2987 + type: "turn-item.updated",
2988 + threadId,
2989 + runId,
2990 + occurredAt: now,
2991 + payload: {
2992 + id: TurnItemId.make(`item:projection-shell-silent:${key}:compaction`),
2993 + threadId,
2994 + runId,
2995 + nodeId: null,
2996 + providerThreadId: null,
2997 + providerTurnId: null,
2998 + nativeItemRef: null,
2999 + parentItemId: null,
3000 + ordinal: 1,
3001 + type: "compaction",
3002 + driver,
3003 + status: "failed",
3004 + title: "Context compaction failed",
3005 + summary: "Not enough messages to compact.",
3006 + startedAt: now,
3007 + completedAt: now,
3008 + updatedAt: now,
3009 + },
3010 + });
3011 + assert.equal(
3012 + (yield* projectionStore.getShellSnapshot()).threads.find(
3013 + (thread) => thread.id === threadId,
3014 + )?.latestRunSilent,
3015 + false,
3016 + );
3017 + assert.equal(
3018 + ProjectionStore.threadShellFromProjection(
3019 + yield* projectionStore.getThreadProjection(threadId),
3020 + ).latestRunSilent,
3021 + false,
3022 + );
3023 + }),
3024 + );
3025 +
3026 it.effect("only exposes interruptible runs through the shell activeRunId", () =>
3027 Effect.gen(function* () {
3028 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
apps/server/src/orchestration-v2/ProjectionStore.ts
+41
@@ -42,6 +42,8 @@ import type {
42 RunAttemptId,
43 } from "@t3tools/contracts";
44 import {
45 + IDLE_COMPACTION_TEXT,
46 + idleCompactionOf,
47 OrchestrationV2AppThreadJson as OrchestrationV2AppThreadJsonSchema,
48 OrchestrationV2CheckpointJson as OrchestrationV2CheckpointJsonSchema,
49 OrchestrationV2CheckpointScopeJson as OrchestrationV2CheckpointScopeJsonSchema,
@@ -1084,6 +1086,7 @@ type ShellThreadRow = {
1086 readonly latest_run_started_at: string | null;
1087 readonly latest_run_completed_at: string | null;
1088 readonly latest_run_stop_requested: number;
1089 + readonly latest_run_silent: number;
1090 readonly active_run_id: string | null;
1091 readonly active_run_status: string | null;
1092 readonly activity_run_status: string | null;
@@ -1634,6 +1637,16 @@ export function threadShellFromProjection(
1637 projection.turnItems.some(
1638 (item) => item.runId === latestRun.id && item.type === "run_interrupt_request",
1639 ),
1640 + latestRunSilent:
1641 + latestRun != null &&
1642 + projection.messages.some(
1643 + (message) =>
1644 + message.id === latestRun.userMessageId && idleCompactionOf(message) !== undefined,
1645 + ) &&
1646 + !projection.turnItems.some(
1647 + (item) =>
1648 + item.runId === latestRun.id && item.type === "compaction" && item.status === "failed",
1649 + ),
1650 activeRunId: activeRun?.id ?? null,
1651 blockedOnThreadWait: deriveBlockedOnThreadWait({ activeRun, turnItems: projection.turnItems }),
1652 activityRunStatus: activityRun?.status ?? null,
@@ -1735,6 +1748,7 @@ type ShellThreadState = {
1748 readonly latestRunStartedAt: DateTime.Utc | null;
1749 readonly latestRunCompletedAt: DateTime.Utc | null;
1750 readonly latestRunStopRequested: boolean;
1751 + readonly latestRunSilent: boolean;
1752 readonly activeRunId: RunId | null;
1753 readonly blockedOnThreadWait: boolean;
1754 readonly activityRunStatus: ShellActivityRunStatus | null;
@@ -1890,6 +1904,7 @@ function shellFromState(input: {
1904 latestRunStartedAt: input.state.latestRunStartedAt,
1905 latestRunCompletedAt: input.state.latestRunCompletedAt,
1906 latestRunStopRequested: input.state.latestRunStopRequested,
1907 + latestRunSilent: input.state.latestRunSilent,
1908 activeRunId: input.state.activeRunId,
1909 blockedOnThreadWait: input.state.blockedOnThreadWait,
1910 activityRunStatus: input.state.activityRunStatus,
@@ -5687,6 +5702,29 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5702 WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = presented.run_id
5703 AND stop_request.type = 'run_interrupt_request'
5704 ) AS latest_run_stop_requested,
5705 + -- Mirrors idleCompactionOf, including JavaScript trim whitespace.
5706 + EXISTS (
5707 + SELECT 1 FROM orchestration_v2_projection_messages prompt
5708 + WHERE prompt.message_id = json_extract(presented.payload_json, '$.userMessageId')
5709 + AND prompt.role = 'user'
5710 + AND lower(trim(json_extract(prompt.payload_json, '$.text'),
5711 + char(9, 10, 11, 12, 13, 32, 160, 5760, 8192, 8193, 8194, 8195,
5712 + 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288, 65279)
5713 + )) = ${IDLE_COMPACTION_TEXT}
5714 + AND coalesce(json_array_length(prompt.payload_json, '$.attachments'), 0) = 0
5715 + AND (
5716 + json_extract(prompt.payload_json, '$.idleCompaction') IS NOT NULL
5717 + OR (
5718 + json_extract(prompt.payload_json, '$.createdBy') = 'agent'
5719 + AND json_extract(prompt.payload_json, '$.creationSource') = 'server'
5720 + )
5721 + )
5722 + ) AND NOT EXISTS (
5723 + SELECT 1 FROM orchestration_v2_projection_turn_items compaction
5724 + WHERE compaction.thread_id = t.thread_id AND compaction.run_id = presented.run_id
5725 + AND compaction.type = 'compaction'
5726 + AND compaction.status = 'failed'
5727 + ) AS latest_run_silent,
5728 active.run_id AS active_run_id,
5729 active.status AS active_run_status,
5730 (
@@ -6221,6 +6259,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6259 ? null
6260 : DateTime.makeUnsafe(row.latest_run_completed_at);
6261 let latestRunStopRequested = row.latest_run_stop_requested === 1;
6262 + let latestRunSilent = row.latest_run_silent === 1;
6263 if (row.blocking_run_id !== null && row.blocking_failure_payload_json !== null) {
6264 const blockingFailure = yield* decodeTurnItemPayload(
6265 row.blocking_failure_payload_json,
@@ -6234,6 +6273,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6273 terminalFailureItem = blockingFailure;
6274 latestRunId = RunId.make(row.blocking_run_id);
6275 latestRunStopRequested = row.blocking_run_stop_requested === 1;
6276 + latestRunSilent = false;
6277 latestRunStatus = "failed";
6278 latestRunRequestedAt =
6279 row.blocking_run_requested_at === null
@@ -6274,6 +6314,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6314 latestRunStartedAt,
6315 latestRunCompletedAt,
6316 latestRunStopRequested,
6317 + latestRunSilent,
6318 activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
6319 blockedOnThreadWait: deriveBlockedOnThreadWait({
6320 activeRun:
apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx
+23
@@ -80,6 +80,7 @@ const thread = {
80 id: "thread",
81 title: "Test thread",
82 archivedAt: null as string | null,
83 + latestRunSilent: false,
84 hasPendingApprovals: false,
85 hasPendingUserInput: false,
86 session: null as { status: string } | null,
@@ -112,6 +113,7 @@ function toV2ThreadShell(input: typeof thread) {
113 createdBy: "user",
114 creationSource: "web",
115 latestRunId: latestTurn.turnId,
116 + latestRunSilent: input.latestRunSilent,
117 activeRunId: null,
118 status:
119 latestTurn.state === "completed"
@@ -186,6 +188,7 @@ function setup() {
188 );
189 let screen: Screen | undefined;
190 return {
191 + ui,
192 async render() {
193 if (screen) await screen.rerender(ui());
194 else screen = stack.use(await render(ui()));
@@ -215,3 +218,23 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
218 expect(notification.close).toHaveBeenCalled();
219 },
220 );
221 +
222 +it.each([
223 + ["pre-expiry compaction", true, "completed", []],
224 + ["manual compaction", false, "completed", ["Thread completed"]],
225 + ["failed pre-expiry compaction", true, "error", ["Thread failed"]],
226 +] as const)("notifies for %s only when attention is needed", async (_, silent, status, titles) => {
227 + await using app = setup();
228 + state.environmentIds = ["one"];
229 + state.shells.set("one", shell({ latestRunSilent: silent }));
230 + await using screen = await render(app.ui());
231 + state.shells.set(
232 + "one",
233 + shell({
234 + latestRunSilent: silent,
235 + latestTurn: { turnId: "turn", state: status, completedAt: "2026-09-13T07:01:00.000Z" },
236 + }),
237 + );
238 + await screen.rerender(app.ui());
239 + expect(TestNotification.sent.map((notification) => notification.title)).toEqual(titles);
240 +});
apps/web/src/components/ThreadNotificationCoordinator.tsx
+1
@@ -155,6 +155,7 @@ function EnvironmentNotifications({
155 attention && attention !== prior.attention
156 ? "input"
157 : !rawThread.latestRunStopRequested &&
158 + !rawThread.latestRunSilent &&
159 completion !== null &&
160 (prior.completion === null || completion > prior.completion)
161 ? "completion"
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+77
@@ -7,6 +7,8 @@ import "~/index.css";
7
8 import { act, render } from "../../../test/render";
9 import { MessagesTimeline } from "./MessagesTimeline";
10 +import { makeStreamingTimelineFixture } from "../../test-fixtures";
11 +import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
12 import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
13 import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
14 import { collectThreadFindRanges } from "./threadFindHighlights";
@@ -386,3 +388,78 @@ describe("compact reasoning math", () => {
388 ]);
389 });
390 });
391 +
392 +it("renders automatic compaction as one live divider that finishes with its reason and token delta", async () => {
393 + setup();
394 + const fixture = makeStreamingTimelineFixture();
395 + const prompt = fixture.visibleTurnItems[3]!;
396 + const assistant = fixture.visibleTurnItems[5]!;
397 + if (prompt.item.type !== "user_message" || assistant.item.type !== "assistant_message") {
398 + throw new Error("Expected streaming fixture messages");
399 + }
400 + const promptItem = prompt.item;
401 + const compaction = {
402 + ...assistant,
403 + item: {
404 + ...assistant.item,
405 + type: "compaction" as const,
406 + driver: null,
407 + beforeTokenCount: 899_000,
408 + },
409 + };
410 + const entries = (completed: boolean) =>
411 + deriveTimelineEntriesFromVisibleTurnItems({
412 + visibleTurnItems: [
413 + {
414 + ...prompt,
415 + item: { ...promptItem, text: "/compact", idleCompaction: "beforeCacheExpires" },
416 + },
417 + {
418 + ...compaction,
419 + item: {
420 + ...compaction.item,
421 + status: completed ? "completed" : "running",
422 + afterTokenCount: completed ? 19_000 : undefined,
423 + },
424 + },
425 + ],
426 + optimisticMessages: [],
427 + });
428 + const props = baseProps();
429 + const ui = (completed: boolean) => (
430 + <MessagesTimeline
431 + {...props}
432 + timelineEntries={entries(completed)}
433 + isWorking={!completed}
434 + isCompacting={!completed}
435 + activeTurnInProgress={!completed}
436 + activeTurnStartedAt={fixture.time(5)}
437 + latestRun={{
438 + runId: fixture.runId,
439 + status: completed ? "completed" : "running",
440 + startedAt: fixture.time(5),
441 + completedAt: completed ? fixture.time(9) : null,
442 + }}
443 + />
444 + );
445 + const container = document.createElement("div");
446 + container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
447 + await using screen = await render(ui(false), { container });
448 + await expect
449 + .element(screen.getByRole("separator", { name: "Compacting before the cache expires…" }))
450 + .toBeVisible();
451 + expect(container.textContent).not.toContain("/compact");
452 + expect(container.textContent).not.toContain("Thinking");
453 + expect(container.textContent).not.toContain("Working");
454 + expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
455 + await screen.rerender(ui(true));
456 + await expect
457 + .element(
458 + screen.getByRole("separator", {
459 + name: "Context automatically compacted before cache expiry 899K → 19K tokens",
460 + }),
461 + )
462 + .toBeVisible();
463 + expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
464 + expect(container.textContent).not.toContain("Compacting before");
465 +});
apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+326 -47
@@ -457,68 +457,347 @@ describe("deriveMessagesTimelineRows", () => {
457 },
458 );
459
460 - it("gives live compaction the activity slot and restores Thinking when it completes", () => {
460 + it.each([false, true])(
461 + "gives live compaction the activity slot and restores Thinking (runless: %s)",
462 + (runless) => {
463 + const fixture = makeStreamingTimelineFixture();
464 + const last = fixture.visibleTurnItems.at(-1)!;
465 + if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
466 + const compact = {
467 + ...last,
468 + item: {
469 + ...last.item,
470 + type: "compaction" as const,
471 + status: "running" as const,
472 + driver: null,
473 + beforeTokenCount: 899_000,
474 + },
475 + };
476 + const input = {
477 + isWorking: true,
478 + runningRunId: fixture.runId,
479 + activeTurnStartedAt: fixture.time(5),
480 + turnDiffSummaries: [],
481 + supportsConversationRollback: false,
482 + };
483 + const runningEntries = deriveTimelineEntriesFromVisibleTurnItems({
484 + visibleTurnItems: [...fixture.visibleTurnItems.slice(0, -1), compact],
485 + optimisticMessages: [],
486 + });
487 + const runningRows = deriveMessagesTimelineRows({
488 + ...input,
489 + runningRunId: runless ? null : fixture.runId,
490 + runlessWorkActive: runless,
491 + timelineEntries: runless
492 + ? runningEntries.map((entry) =>
493 + entry.kind === "work" ? { ...entry, entry: { ...entry.entry, runId: null } } : entry,
494 + )
495 + : runningEntries,
496 + });
497 + expect(runningRows.find((row) => row.kind === "context-compaction")).toMatchObject({
498 + active: true,
499 + label: "Compacting context",
500 + });
501 + expect(runningRows.some((row) => row.kind === "thinking")).toBe(false);
502 +
503 + const completedRows = deriveMessagesTimelineRows({
504 + ...input,
505 + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
506 + visibleTurnItems: [
507 + ...fixture.visibleTurnItems.slice(0, -1),
508 + {
509 + ...compact,
510 + item: { ...compact.item, status: "completed", afterTokenCount: 19_000 },
511 + },
512 + ],
513 + optimisticMessages: [],
514 + }),
515 + });
516 + expect(completedRows.find((row) => row.kind === "context-compaction")).toMatchObject({
517 + active: false,
518 + label: "Context compacted 899K → 19K tokens",
519 + tokenCounts: { before: "899K", after: "19K" },
520 + });
521 + expect(completedRows.at(-1)?.kind).toBe("thinking");
522 +
523 + const settledRows = deriveMessagesTimelineRows({
524 + ...input,
525 + isWorking: false,
526 + timelineEntries: runningEntries,
527 + });
528 + expect(settledRows.find((row) => row.kind === "context-compaction")).toMatchObject({
529 + active: false,
530 + });
531 + const stable = computeStableMessagesTimelineRows(runningRows, {
532 + result: [],
533 + byId: new Map(),
534 + });
535 + expect(computeStableMessagesTimelineRows(settledRows, stable).result).toEqual(settledRows);
536 + },
537 + );
538 +
539 + it("shows each compaction trigger as one live status, then a reasoned token divider", () => {
540 const fixture = makeStreamingTimelineFixture();
462 - const last = fixture.visibleTurnItems.at(-1)!;
463 - if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
464 - const compact = {
465 - ...last,
541 + const [history0, history1, history2, liveUser, , liveAssistant] = fixture.visibleTurnItems;
542 + if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message")
543 + throw new Error("Expected live fixture items");
544 + const compactPrompt = (idleCompaction: "beforeCacheExpires" | "onReturn" | undefined) => ({
545 + ...liveUser,
546 + item: { ...liveUser.item, text: "/compact", idleCompaction },
547 + });
548 + const compaction = {
549 + ...liveAssistant,
550 item: {
467 - ...last.item,
551 + ...liveAssistant.item,
552 type: "compaction" as const,
469 - status: "running" as const,
553 driver: null,
554 beforeTokenCount: 899_000,
555 },
556 };
474 - const input = {
475 - isWorking: true,
476 - runningRunId: fixture.runId,
477 - activeTurnStartedAt: fixture.time(5),
478 - turnDiffSummaries: [],
479 - supportsConversationRollback: false,
480 - };
481 - const runningEntries = deriveTimelineEntriesFromVisibleTurnItems({
482 - visibleTurnItems: [...fixture.visibleTurnItems.slice(0, -1), compact],
483 - optimisticMessages: [],
484 - });
485 - const runningRows = deriveMessagesTimelineRows({ ...input, timelineEntries: runningEntries });
486 - expect(runningRows.find((row) => row.kind === "context-compaction")).toMatchObject({
487 - active: true,
488 - label: "Compacting context",
489 - });
490 - expect(runningRows.some((row) => row.kind === "thinking")).toBe(false);
557 + const rowsFor = (visibleTurnItems: OrchestrationV2ProjectedTurnItem[], isWorking = true) =>
558 + deriveMessagesTimelineRows({
559 + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
560 + visibleTurnItems: [history0!, history1!, history2!, ...visibleTurnItems],
561 + optimisticMessages: [],
562 + }),
563 + isWorking,
564 + runningRunId: fixture.runId,
565 + latestRun: {
566 + runId: fixture.runId,
567 + status: isWorking ? "running" : "completed",
568 + startedAt: fixture.time(5),
569 + completedAt: isWorking ? null : fixture.time(9),
570 + },
571 + activeTurnStartedAt: fixture.time(5),
572 + turnDiffSummaries: [],
573 + supportsConversationRollback: false,
574 + });
575
492 - const completedRows = deriveMessagesTimelineRows({
493 - ...input,
494 - timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
495 - visibleTurnItems: [
496 - ...fixture.visibleTurnItems.slice(0, -1),
576 + // Only compacting on return holds a sent message back, so only it speaks through the working
577 + // row; the others keep their live divider.
578 + for (const [reason, live, title] of [
579 + [
580 + "beforeCacheExpires",
581 + {
582 + kind: "context-compaction",
583 + active: true,
584 + label: "Compacting before the cache expires…",
585 + },
586 + "Context automatically compacted before cache expiry",
587 + ],
588 + [
589 + "onReturn",
590 + { kind: "working", compacting: "Compacting after being idle…" },
591 + "Context compacted after being idle",
592 + ],
593 + [undefined, { kind: "context-compaction", active: true }, undefined],
594 + ] as const) {
595 + const prompt = compactPrompt(reason);
596 + for (const rows of [rowsFor([prompt]), rowsFor([prompt, compaction])]) {
597 + const liveRows = rows.slice(
598 + rows.findIndex((row) => row.id.includes("history-assistant")) + 1,
599 + );
600 + expect(liveRows).toMatchObject([live]);
601 + }
602 + const completed = rowsFor(
603 + [
604 + prompt,
605 {
498 - ...compact,
499 - item: { ...compact.item, status: "completed", afterTokenCount: 19_000 },
606 + ...compaction,
607 + item: { ...compaction.item, status: "completed", afterTokenCount: 19_000 },
608 },
609 ],
502 - optimisticMessages: [],
503 - }),
504 - });
505 - expect(completedRows.find((row) => row.kind === "context-compaction")).toMatchObject({
506 - active: false,
507 - label: "Context compacted 899K → 19K tokens",
508 - tokenCounts: { before: "899K", after: "19K" },
509 - });
510 - expect(completedRows.at(-1)?.kind).toBe("thinking");
610 + false,
611 + );
612 + const liveRows = completed.slice(
613 + completed.findIndex((row) => row.id.includes("history-assistant")) + 1,
614 + );
615 + expect(liveRows).toMatchObject([
616 + {
617 + kind: "context-compaction",
618 + active: false,
619 + tokenCounts: { before: "899K", after: "19K" },
620 + },
621 + ]);
622 + expect(liveRows[0]?.kind === "context-compaction" ? liveRows[0].title : null).toBe(title);
623 + const terminalCompaction = {
624 + ...compaction,
625 + item: { ...compaction.item, status: "completed" as const, afterTokenCount: 19_000 },
626 + };
627 + const finishingRows = rowsFor([prompt, terminalCompaction]);
628 + const finishingLiveRows = finishingRows.slice(
629 + finishingRows.findIndex((row) => row.id.includes("history-assistant")) + 1,
630 + );
631 + expect(finishingLiveRows).toEqual(liveRows);
632 + const continuingRows = rowsFor([
633 + prompt,
634 + terminalCompaction,
635 + { ...liveAssistant, item: { ...liveAssistant.item, id: TurnItemId.make("continued") } },
636 + ]);
637 + expect(continuingRows.filter((row) => row.kind === "context-compaction")).toHaveLength(1);
638 + expect(continuingRows.filter((row) => row.kind === "working")).toMatchObject([
639 + { kind: "working" },
640 + ]);
641 + expect(continuingRows.some((row) => row.kind === "working" && row.compacting)).toBe(false);
642 + const retries = rowsFor(
643 + [
644 + prompt,
645 + {
646 + ...compaction,
647 + item: { ...compaction.item, status: "failed", summary: "retry needed" },
648 + },
649 + {
650 + ...compaction,
651 + item: {
652 + ...compaction.item,
653 + id: TurnItemId.make("retry-compaction"),
654 + status: "completed",
655 + },
656 + },
657 + ],
658 + false,
659 + ).filter((row) => row.kind === "context-compaction");
660 + expect(retries).toHaveLength(2);
661 + expect(retries[0]).toMatchObject({ failed: true, failure: "retry needed" });
662 + expect(new Set(retries.map((row) => row.id)).size).toBe(2);
663 + const stable = computeStableMessagesTimelineRows(retries, { result: [], byId: new Map() });
664 + expect(computeStableMessagesTimelineRows(retries, stable).result).toEqual(retries);
665 + }
666 + });
667
512 - const settledRows = deriveMessagesTimelineRows({
513 - ...input,
514 - isWorking: false,
515 - timelineEntries: runningEntries,
668 + it.each(["/compact", "Continue"])(
669 + "keeps a completed compaction divider visible while other settled work folds for %s",
670 + (promptText) => {
671 + const fixture = makeStreamingTimelineFixture();
672 + const [, , , liveUser, liveWork, liveAssistant] = fixture.visibleTurnItems;
673 + if (
674 + liveUser?.item.type !== "user_message" ||
675 + liveAssistant?.item.type !== "assistant_message" ||
676 + !liveWork
677 + )
678 + throw new Error("Expected live fixture items");
679 + const rows = deriveMessagesTimelineRows({
680 + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
681 + visibleTurnItems: [
682 + { ...liveUser, item: { ...liveUser.item, text: promptText } },
683 + liveWork,
684 + {
685 + ...liveAssistant,
686 + item: {
687 + ...liveAssistant.item,
688 + type: "compaction",
689 + driver: null,
690 + status: "completed",
691 + beforeTokenCount: 100_000,
692 + afterTokenCount: 20_000,
693 + },
694 + },
695 + ],
696 + optimisticMessages: [],
697 + }),
698 + isWorking: false,
699 + latestRun: {
700 + runId: fixture.runId,
701 + status: "completed",
702 + startedAt: fixture.time(5),
703 + completedAt: fixture.time(8),
704 + },
705 + turnDiffSummaries: [],
706 + supportsConversationRollback: false,
707 + });
708 + expect(rows.filter((row) => row.kind === "turn-fold")).toHaveLength(1);
709 + expect(rows.some((row) => row.kind === "work")).toBe(false);
710 + expect(rows.filter((row) => row.kind === "context-compaction")).toMatchObject([
711 + { active: false, tokenCounts: { before: "100K", after: "20K" } },
712 + ]);
713 + if (promptText === "/compact") {
714 + expect(rows.some((row) => row.kind === "message")).toBe(false);
715 + }
716 + },
717 + );
718 +
719 + it("folds an answered compact-on-return question into its compaction row", () => {
720 + const fixture = makeStreamingTimelineFixture();
721 + const [history0, history1, history2, liveUser, liveWork, liveAssistant] =
722 + fixture.visibleTurnItems;
723 + if (liveWork?.item.type !== "dynamic_tool" || liveAssistant?.item.type !== "assistant_message")
724 + throw new Error("Expected live fixture items");
725 + const { toolName: _toolName, input: _input, output: _output, ...workBase } = liveWork.item;
726 + const question =
727 + "This session is 1h 5m old and uses 412,000 tokens. Compact it before continuing?";
728 + const requestId = RuntimeRequestId.make("resume-compaction");
729 + const answered = {
730 + ...liveWork,
731 + item: {
732 + ...workBase,
733 + type: "user_input_request" as const,
734 + requestId,
735 + questions: [],
736 + questionAnswer: {
737 + requestId,
738 + questionTextById: { resume: question },
739 + answers: { resume: "Compact and continue" },
740 + attachmentsByQuestionId: {},
741 + },
742 + },
743 + };
744 + const assistantItem = liveAssistant.item;
745 + const compactionAt = (status: "running" | "completed") => ({
746 + ...liveAssistant,
747 + item: { ...assistantItem, type: "compaction" as const, status, driver: null },
748 });
517 - expect(settledRows.find((row) => row.kind === "context-compaction")).toMatchObject({
749 + const rowsFor = (status: "running" | "completed", laterCompaction = false) =>
750 + deriveMessagesTimelineRows({
751 + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
752 + visibleTurnItems: [
753 + history0!,
754 + history1!,
755 + history2!,
756 + liveUser!,
757 + answered,
758 + compactionAt(laterCompaction ? "completed" : status),
759 + ...(laterCompaction
760 + ? [
761 + {
762 + ...compactionAt(status),
763 + item: {
764 + ...compactionAt(status).item,
765 + id: TurnItemId.make("later-compaction"),
766 + },
767 + },
768 + ]
769 + : []),
770 + ],
771 + optimisticMessages: [],
772 + }),
773 + isWorking: status === "running",
774 + runningRunId: fixture.runId,
775 + activeTurnStartedAt: fixture.time(5),
776 + turnDiffSummaries: [],
777 + supportsConversationRollback: false,
778 + });
779 + const liveRows = (status: "running" | "completed") => {
780 + const rows = rowsFor(status);
781 + return rows.slice(rows.findIndex((row) => row.id.includes("live-user")) + 1);
782 + };
783 + expect(liveRows("running")).toMatchObject([
784 + { kind: "working", compacting: "Compacting after 1h 5m idle…" },
785 + ]);
786 + expect(liveRows("completed")).toMatchObject([
787 + { kind: "context-compaction", title: "Context compacted after 1h 5m idle" },
788 + ]);
789 + const laterRows = rowsFor("running", true);
790 + const dividers = laterRows.filter((row) => row.kind === "context-compaction");
791 + expect(dividers).toHaveLength(2);
792 + expect(dividers[0]).toMatchObject({
793 + title: "Context compacted after 1h 5m idle",
794 active: false,
795 });
520 - const stable = computeStableMessagesTimelineRows(runningRows, { result: [], byId: new Map() });
521 - expect(computeStableMessagesTimelineRows(settledRows, stable).result).toEqual(settledRows);
796 + expect(dividers[1]).toMatchObject({ active: true });
797 + expect(dividers[1]).not.toHaveProperty("title");
798 + expect(laterRows.some((row) => row.kind === "working" && row.compacting !== undefined)).toBe(
799 + false,
800 + );
801 });
802
803 it("only enables assistant copy for the terminal assistant message in a turn", () => {
apps/web/src/components/chat/MessagesTimeline.logic.ts
+156 -5
@@ -8,6 +8,11 @@ import {
8 collectAssistantCitations,
9 } from "@t3tools/shared/assistantCitations";
10 import { shallow } from "zustand/vanilla/shallow";
11 +import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
12 +import {
13 + IDLE_COMPACTING_LABELS,
14 + IDLE_COMPACTION_TITLES,
15 +} from "@t3tools/client-runtime/user-message";
16 import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff";
17 import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives";
18 import {
@@ -45,7 +50,10 @@ import {
50 type TurnDiffSummary,
51 } from "../../types";
52 import {
53 + idleCompactionOf,
54 + isCompactionCommandMessage,
55 type MessageId,
56 + type OrchestrationV2IdleCompaction,
57 type WorktreeSetupSnapshot,
58 type OrchestrationV2ProjectedTurnItem,
59 type RunAttemptId,
@@ -540,6 +548,8 @@ type MessagesTimelineRowContent =
548 kind: "working";
549 id: string;
550 createdAt: string | null;
551 + /** A running compaction owns the working row, so its divider appears only once it ends. */
552 + compacting?: string;
553 }
554 | {
555 kind: "thinking";
@@ -587,6 +597,11 @@ type MessagesTimelineRowContent =
597 label: string;
598 tokenCounts: ReturnType<typeof contextCompactionTokenCounts>;
599 active: boolean;
600 + /** Replaces "Context compacted" when T3 Code compacted without being asked. */
601 + title?: string;
602 + failed?: true;
603 + /** The provider's reason, when a failed compaction gave one. */
604 + failure?: string;
605 }
606 | {
607 kind: "message";
@@ -1141,6 +1156,7 @@ function deriveTurnFolds(input: {
1156 continue;
1157 }
1158 if (
1159 + isCompaction ||
1160 timelineEntryIsPersistentResourceCard(entry) ||
1161 input.liveSubagentEntryIds.has(entry.id) ||
1162 input.completeSupersededReplyEntryIds.has(entry.id)
@@ -1572,15 +1588,94 @@ export function deriveMessagesTimelineRows(input: {
1588 const activeWorkEntryIds = new Set(
1589 activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [],
1590 );
1591 + // A bare `/compact` turn is the compaction itself: one compaction row stands in for its prompt
1592 + // and working indicator, from the moment the turn starts. Likewise an answered "compact before
1593 + // continuing?" question folds into the compaction it asked for.
1594 + const compactionRuns = new Map<RunId, OrchestrationV2IdleCompaction | undefined>();
1595 + const compactedRunIds = new Set<RunId>();
1596 + const pendingResumeCompactionAgeByRunId = new Map<RunId, string>();
1597 + const resumeCompactionAgeByEntryId = new Map<string, string>();
1598 + for (const entry of timelineEntries) {
1599 + if (
1600 + entry.kind === "message" &&
1601 + entry.message.runId !== null &&
1602 + isCompactionCommandMessage(entry.message)
1603 + ) {
1604 + compactionRuns.set(entry.message.runId, idleCompactionOf(entry.message));
1605 + } else if (entry.kind === "work" && entry.entry.runId) {
1606 + if (timelineEntryIsCompaction(entry)) {
1607 + compactedRunIds.add(entry.entry.runId);
1608 + const age = pendingResumeCompactionAgeByRunId.get(entry.entry.runId);
1609 + if (age !== undefined) {
1610 + resumeCompactionAgeByEntryId.set(entry.id, age);
1611 + pendingResumeCompactionAgeByRunId.delete(entry.entry.runId);
1612 + }
1613 + }
1614 + const age = entry.entry.questionAnswer
1615 + ? claudeResumeCompactionAge(entry.entry.questionAnswer)
1616 + : null;
1617 + if (age !== null) pendingResumeCompactionAgeByRunId.set(entry.entry.runId, age);
1618 + }
1619 + }
1620 + const compactionTitle = (runId: RunId | null | undefined, entryId: string) => {
1621 + if (runId == null) return undefined;
1622 + const reason = compactionRuns.get(runId);
1623 + if (reason !== undefined) return IDLE_COMPACTION_TITLES[reason];
1624 + const age = resumeCompactionAgeByEntryId.get(entryId);
1625 + return age ? `Context compacted after ${age} idle` : undefined;
1626 + };
1627 + const activeCompactionEntry = timelineEntries.find(
1628 + (entry): entry is Extract<TimelineEntry, { kind: "work" }> =>
1629 + timelineEntryIsCompaction(entry) &&
1630 + entry.kind === "work" &&
1631 + workEntryIsInActiveRun(entry.entry),
1632 + );
1633 + const activeRunIsCompaction =
1634 + input.isWorking && unsettledRunId !== null && compactionRuns.has(unsettledRunId);
1635 + // The item can finish before its run settles; only other work should keep activity visible.
1636 + const compactionRunFinished =
1637 + activeRunIsCompaction &&
1638 + compactedRunIds.has(unsettledRunId) &&
1639 + activeCompactionEntry === undefined;
1640 + const compactionOnlyRunFinished =
1641 + compactionRunFinished &&
1642 + !timelineEntries.some(
1643 + (entry) =>
1644 + timelineEntryRunId(entry) === unsettledRunId &&
1645 + !timelineEntryIsCompaction(entry) &&
1646 + !(entry.kind === "message" && isCompactionCommandMessage(entry.message)),
1647 + );
1648 + const runningCompactionRunId =
1649 + activeRunIsCompaction && !compactionRunFinished ? unsettledRunId : null;
1650 + // Compacting on return holds back the message the user just sent, so the working row says why
1651 + // it is waiting. Any other compaction shows only its live divider, never both.
1652 + const activeCompactionRunId =
1653 + runningCompactionRunId !== null && compactionRuns.get(runningCompactionRunId) === "onReturn"
1654 + ? runningCompactionRunId
1655 + : activeCompactionEntry?.entry.runId != null &&
1656 + resumeCompactionAgeByEntryId.has(activeCompactionEntry.id)
1657 + ? activeCompactionEntry.entry.runId
1658 + : null;
1659 + const compactingLabel = (() => {
1660 + if (activeCompactionRunId === null) return undefined;
1661 + const age = activeCompactionEntry
1662 + ? resumeCompactionAgeByEntryId.get(activeCompactionEntry.id)
1663 + : undefined;
1664 + return age ? `Compacting after ${age} idle…` : IDLE_COMPACTING_LABELS.onReturn;
1665 + })();
1666 const appendWorkingRow = () => {
1667 + if (compactionOnlyRunFinished) return;
1668 + if (runningCompactionRunId !== null && activeCompactionRunId === null) return;
1669 nextRows.push({
1670 kind: "working",
1671 id: "working-indicator-row",
1672 createdAt: input.activeTurnStartedAt ?? null,
1673 + ...(compactingLabel ? { compacting: compactingLabel } : {}),
1674 });
1675 };
1676 let hasActivityRow = false;
1583 - let hasActiveCompaction = false;
1677 + const hasActiveCompaction =
1678 + activeCompactionEntry !== undefined || (activeRunIsCompaction && !compactionRunFinished);
1679 const appendActiveWorkRows = () => {
1680 if (activeWorkRow === null) return;
1681 nextRows.push(activeWorkRow);
@@ -1658,13 +1753,26 @@ export function deriveMessagesTimelineRows(input: {
1753 timelineEntry.entry.sourceActivityKind === "context-compaction"
1754 ) {
1755 const active = workEntryIsInActiveRun(timelineEntry.entry);
1661 - hasActiveCompaction ||= active;
1756 + if (
1757 + active &&
1758 + activeCompactionRunId !== null &&
1759 + timelineEntry.entry.runId === activeCompactionRunId
1760 + )
1761 + continue;
1762 const compaction = timelineEntry.entry.structuredPayload;
1763 + const compactionRunId = timelineEntry.entry.runId;
1764 + const title = compactionTitle(compactionRunId, timelineEntry.id);
1765 + const reason = compactionRunId == null ? undefined : compactionRuns.get(compactionRunId);
1766 + const failed = compaction?.type === "compaction" && compaction.status === "failed";
1767 + const failure = failed ? compaction.summary?.trim() || undefined : undefined;
1768 nextRows.push({
1769 kind: "context-compaction",
1770 id: timelineEntry.id,
1771 + ...(title ? { title } : {}),
1772 + ...(failed ? { failed: true } : {}),
1773 + ...(failure ? { failure } : {}),
1774 createdAt: timelineEntry.createdAt,
1667 - label: timelineEntry.entry.label,
1775 + label: active && reason ? IDLE_COMPACTING_LABELS[reason] : timelineEntry.entry.label,
1776 tokenCounts:
1777 compaction?.type === "compaction" ? contextCompactionTokenCounts(compaction) : null,
1778 active,
@@ -1672,6 +1780,16 @@ export function deriveMessagesTimelineRows(input: {
1780 continue;
1781 }
1782
1783 + if (
1784 + timelineEntry.kind === "work" &&
1785 + timelineEntry.entry.runId != null &&
1786 + compactedRunIds.has(timelineEntry.entry.runId) &&
1787 + timelineEntry.entry.questionAnswer !== undefined &&
1788 + claudeResumeCompactionAge(timelineEntry.entry.questionAnswer) !== null
1789 + ) {
1790 + continue;
1791 + }
1792 +
1793 if (timelineEntry.kind === "work") {
1794 if (
1795 (timelineEntry.entry.runId != null && failedRunIds.has(timelineEntry.entry.runId)) ||
@@ -1882,6 +2000,29 @@ export function deriveMessagesTimelineRows(input: {
2000 continue;
2001 }
2002
2003 + const compactionRunId = timelineEntry.message.runId;
2004 + const compactionRun =
2005 + compactionRunId !== null && isCompactionCommandMessage(timelineEntry.message);
2006 + if (compactionRun) {
2007 + if (!compactedRunIds.has(compactionRunId) && compactionRunId !== activeCompactionRunId) {
2008 + const pending = compactionRunId === runningCompactionRunId;
2009 + const reason = compactionRuns.get(compactionRunId);
2010 + nextRows.push({
2011 + kind: "context-compaction",
2012 + id: `compaction:${compactionRunId}`,
2013 + createdAt: timelineEntry.createdAt,
2014 + label: pending
2015 + ? reason
2016 + ? IDLE_COMPACTING_LABELS[reason]
2017 + : "Compacting context"
2018 + : "Context compaction",
2019 + tokenCounts: null,
2020 + active: pending,
2021 + });
2022 + }
2023 + continue;
2024 + }
2025 +
2026 const assistantResponseStillInProgress =
2027 timelineEntry.message.role === "assistant" &&
2028 runIdIsActiveResponse(timelineEntry.message.runId);
@@ -1969,6 +2110,7 @@ export function deriveMessagesTimelineRows(input: {
2110 input.latestRun?.turnEnded !== true &&
2111 !setupOwnsWorkingSlot &&
2112 !hasActiveCompaction &&
2113 + !compactionOnlyRunFinished &&
2114 (!hasActivityRow || latestToolFailed)
2115 ) {
2116 const failedGroupAnchor = latestToolFailed ? activeWorkAnchor : undefined;
@@ -2237,7 +2379,9 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
2379
2380 switch (a.kind) {
2381 case "working":
2240 - return a.createdAt === (b as typeof a).createdAt;
2382 + return (
2383 + a.createdAt === (b as typeof a).createdAt && a.compacting === (b as typeof a).compacting
2384 + );
2385 case "thinking": {
2386 const bt = b as typeof a;
2387 return a.createdAt === bt.createdAt && a.groupId === bt.groupId && a.expanded === bt.expanded;
@@ -2268,7 +2412,14 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
2412
2413 case "context-compaction": {
2414 const bc = b as typeof a;
2271 - return a.createdAt === bc.createdAt && a.label === bc.label && a.active === bc.active;
2415 + return (
2416 + a.createdAt === bc.createdAt &&
2417 + a.label === bc.label &&
2418 + a.active === bc.active &&
2419 + a.title === bc.title &&
2420 + a.failed === bc.failed &&
2421 + a.failure === bc.failure
2422 + );
2423 }
2424
2425 case "proposed-plan":
apps/web/src/components/chat/MessagesTimeline.tsx
+30 -11
@@ -43,7 +43,7 @@ import {
43 import { type TimelineEntry } from "../../session-logic";
44 import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
45 import { type ChatFileAttachment, type TurnDiffSummary } from "../../types";
46 -import { ArrowRightIcon, BotIcon, Minimize2Icon } from "lucide-react";
46 +import { ArrowRightIcon, BotIcon, CircleAlertIcon, Minimize2Icon } from "lucide-react";
47 import { ChevronDown, ChevronRight } from "lucide";
48 import { MorphIcon } from "~/components/MorphIcon";
49 import { ExpandedImagePreview } from "./ExpandedImagePreview";
@@ -946,7 +946,12 @@ const ConversationTimeline = memo(function ConversationTimeline({
946 workGroupViewState,
947 };
948 const compactionAwaitingRow =
949 - isCompacting && !rows.some((row) => row.kind === "context-compaction" && row.active);
949 + isCompacting &&
950 + !rows.some(
951 + (row) =>
952 + (row.kind === "context-compaction" && row.active) ||
953 + (row.kind === "working" && row.compacting),
954 + );
955 const backgroundWorktreeSetup =
956 worktreeSetup !== null &&
957 worktreeSetup.phase === "running" &&
@@ -1336,35 +1341,49 @@ function ContextCompactionTimelineRow({
1341 }: {
1342 row: Extract<TimelineRow, { kind: "context-compaction" }>;
1343 }) {
1344 + const label =
1345 + row.title && row.label.startsWith("Context compacted")
1346 + ? row.title + row.label.slice("Context compacted".length)
1347 + : row.label;
1348 const content = (
1340 - <span className="flex items-center gap-1.5">
1341 - <Minimize2Icon aria-hidden="true" className="size-3" />
1349 + <span className="flex min-w-0 items-center gap-1.5">
1350 + {row.failed ? (
1351 + <CircleAlertIcon aria-hidden="true" className="size-3 shrink-0" />
1352 + ) : (
1353 + <Minimize2Icon aria-hidden="true" className="size-3" />
1354 + )}
1355 {row.tokenCounts ? (
1356 <>
1344 - Context compacted {row.tokenCounts.before}
1357 + {row.title ?? "Context compacted"} {row.tokenCounts.before}
1358 <ArrowRightIcon aria-hidden="true" className="size-3" />
1359 {row.tokenCounts.after} tokens
1360 </>
1361 ) : (
1349 - row.label
1362 + label
1363 )}
1364 + {row.failure ? (
1365 + <span className="min-w-0 truncate opacity-80">&middot; {row.failure}</span>
1366 + ) : null}
1367 </span>
1368 );
1369 return (
1370 <div
1371 role="separator"
1356 - aria-label={row.label}
1357 - className="mx-auto flex w-full max-w-(--chat-content-max-width) items-center gap-3 py-1 text-muted-foreground text-xs"
1372 + aria-label={row.failure ? `${label}: ${row.failure}` : label}
1373 + className={cn(
1374 + "mx-auto flex w-full max-w-(--chat-content-max-width) items-center gap-3 py-1 text-xs",
1375 + row.failed ? "text-destructive" : "text-muted-foreground",
1376 + )}
1377 >
1359 - <span className="h-px flex-1 bg-border/70" />
1378 + <span className={cn("h-px flex-1", row.failed ? "bg-destructive/30" : "bg-border/70")} />
1379 <span
1380 ref={row.active ? observeVisibleAnimation : undefined}
1362 - className="relative shrink-0 overflow-hidden"
1381 + className="relative min-w-0 overflow-hidden"
1382 >
1383 {content}
1384 {row.active ? <ActivityShimmerOverlay>{content}</ActivityShimmerOverlay> : null}
1385 </span>
1367 - <span className="h-px flex-1 bg-border/70" />
1386 + <span className={cn("h-px flex-1", row.failed ? "bg-destructive/30" : "bg-border/70")} />
1387 </div>
1388 );
1389 }
apps/web/src/components/chat/TimelineWorkGroupRows.tsx
+6 -5
@@ -286,11 +286,12 @@ const workEntryKey = (entry: TimelineWorkEntry) => entry.id;
286 export function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
287 const { isCompacting, isPreparingWorktree, backgroundWorktreeSetup } =
288 use(TimelineRowActivityCtx);
289 - const shimmer = isPreparingWorktree || isCompacting;
289 + const compacting = row.compacting ?? (isCompacting ? "Compacting…" : undefined);
290 + const shimmer = isPreparingWorktree || compacting !== undefined;
291 const label = isPreparingWorktree ? (
292 "Setting up worktree…"
292 - ) : isCompacting ? (
293 - <CompactingLabel />
293 + ) : compacting !== undefined ? (
294 + <CompactingLabel label={compacting} />
295 ) : row.createdAt ? (
296 <>
297 Working for <WorkingTimer createdAt={row.createdAt} />
@@ -350,11 +351,11 @@ function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnap
351 );
352 }
353
353 -function CompactingLabel() {
354 +function CompactingLabel({ label }: { label: string }) {
355 return (
356 <span className="inline-flex items-center gap-1.5">
357 <Minimize2Icon aria-hidden="true" className="size-3" />
357 - Compacting…
358 + {label}
359 </span>
360 );
361 }
apps/web/src/components/chat/useComposerSend.ts
+7 -1
@@ -1199,7 +1199,13 @@ export function useComposerSend(input: ComposerSendInput) {
1199 environmentId,
1200 input: {
1201 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 + },
1209 modelSelection: ctxSelectedModelSelection,
1210 runtimeMode,
1211 interactionMode: sendInteractionMode,
apps/web/src/session-logic.ts
+1
@@ -714,6 +714,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems(
714 createdBy: item.createdBy,
715 creationSource: item.creationSource,
716 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
717 + ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
718 ...(item.scheduledTaskId !== undefined
719 ? { scheduledTaskId: item.scheduledTaskId }
720 : {}),
apps/web/src/types.ts
+1
@@ -92,6 +92,7 @@ export interface ChatMessage {
92 readonly creationSource?: OrchestrationV2CreationSource;
93 readonly scheduledTaskId?: ScheduledTaskId;
94 readonly senderThreadId?: ThreadId;
95 + readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
96 readonly createdAt: string;
97 readonly updatedAt: string;
98 readonly inputIntent?: OrchestrationV2UserMessageInputIntent | undefined;
packages/client-runtime/src/operations/commands.ts
+7
@@ -169,6 +169,7 @@ export interface StartThreadTurnInput extends ThreadCommandInput {
169 readonly text: string;
170 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
171 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext;
172 + readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
173 };
174 readonly modelSelection?: ModelSelection;
175 readonly titleSeed?: string;
@@ -704,6 +705,9 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
705 : { manualContinuationOfRunId: input.manualContinuationOfRunId }),
706 text: input.message.text,
707 ...(context ? { context } : {}),
708 + ...(input.message.idleCompaction === undefined
709 + ? {}
710 + : { idleCompaction: input.message.idleCompaction }),
711 attachments,
712 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
713 ...(input.sourceProposedPlan === undefined
@@ -765,6 +769,9 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
769 messageId: input.message.messageId,
770 text: input.message.text,
771 ...(context ? { context } : {}),
772 + ...(input.message.idleCompaction === undefined
773 + ? {}
774 + : { idleCompaction: input.message.idleCompaction }),
775 attachments,
776 ...(shouldSendTitleSeed ? { titleSeed: input.titleSeed } : {}),
777 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
packages/client-runtime/src/userMessage.ts
+13
@@ -1,9 +1,22 @@
1 import {
2 type OrchestrationV2Actor,
3 type OrchestrationV2CreationSource,
4 + type OrchestrationV2IdleCompaction,
5 ScheduledTaskId,
6 } from "@t3tools/contracts";
7
8 +/** The working row while T3 Code's own compaction runs. */
9 +export const IDLE_COMPACTING_LABELS = {
10 + beforeCacheExpires: "Compacting before the cache expires…",
11 + onReturn: "Compacting after being idle…",
12 +} satisfies Record<OrchestrationV2IdleCompaction, string>;
13 +
14 +/** Leads the finished compaction's token counts, in place of "Context compacted". */
15 +export const IDLE_COMPACTION_TITLES = {
16 + beforeCacheExpires: "Context automatically compacted before cache expiry",
17 + onReturn: "Context compacted after being idle",
18 +} satisfies Record<OrchestrationV2IdleCompaction, string>;
19 +
20 const LEGACY_AUTOMATION_PREFIX = /^\[Triggered by schedule task: [^\r\n]+\]\r?\n\r?\n/;
21 const LEGACY_AUTOMATION_MESSAGE_ID = /^scheduled-task-message:(.+):\d+:(?:scheduled|manual)$/;
22
packages/contracts/src/orchestrationV2.ts
+42
@@ -473,6 +473,38 @@ export function isProviderNativeSubagentThread(
473 return thread.lineage.relationshipToParent === "subagent" && thread.creationSource === "provider";
474 }
475
476 +export const IDLE_COMPACTION_TEXT = "/compact";
477 +
478 +interface CompactionMessageFields {
479 + readonly role: string;
480 + readonly text: string;
481 + readonly attachments?: ReadonlyArray<unknown> | undefined;
482 + readonly createdBy?: OrchestrationV2Actor | undefined;
483 + readonly creationSource?: OrchestrationV2CreationSource | undefined;
484 + readonly idleCompaction?: OrchestrationV2IdleCompaction | undefined;
485 +}
486 +
487 +/** A prompt that only asks the provider to compact, so its turn is the compaction itself. */
488 +export function isCompactionCommandMessage(message: CompactionMessageFields): boolean {
489 + return (
490 + message.role === "user" &&
491 + message.text.trim().toLowerCase() === IDLE_COMPACTION_TEXT &&
492 + (message.attachments?.length ?? 0) === 0
493 + );
494 +}
495 +
496 +/** Why T3 Code sent this `/compact` on its own, or undefined for one someone asked for. */
497 +export function idleCompactionOf(
498 + message: CompactionMessageFields,
499 +): OrchestrationV2IdleCompaction | undefined {
500 + if (!isCompactionCommandMessage(message)) return undefined;
501 + if (message.idleCompaction !== undefined) return message.idleCompaction;
502 + // Servers before `idleCompaction` marked their own as agent-created.
503 + return message.createdBy === "agent" && message.creationSource === "server"
504 + ? "beforeCacheExpires"
505 + : undefined;
506 +}
507 +
508 export const OrchestrationV2RunStatus = Schema.Literals([
509 "preparing",
510 "queued",
@@ -1116,11 +1148,16 @@ export const OrchestrationV2Notification = Schema.Struct({
1148 });
1149 export type OrchestrationV2Notification = typeof OrchestrationV2Notification.Type;
1150
1151 +/** Why T3 Code compacted a thread on its own, on the `/compact` it sent. */
1152 +export const OrchestrationV2IdleCompaction = Schema.Literals(["beforeCacheExpires", "onReturn"]);
1153 +export type OrchestrationV2IdleCompaction = typeof OrchestrationV2IdleCompaction.Type;
1154 +
1155 export const OrchestrationV2ConversationMessage = Schema.Struct({
1156 notification: Schema.optional(OrchestrationV2Notification),
1157 ...OrchestrationV2CreationFields,
1158 scheduledTaskId: Schema.optional(ScheduledTaskId),
1159 senderThreadId: Schema.optional(ThreadId),
1160 + idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
1161 /**
1162 * The message is the script a provider-native workflow run executes, not prose. Clients show
1163 * the workflow's opening instead and keep the script behind a disclosure.
@@ -1377,6 +1414,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
1414 messageId: MessageId,
1415 scheduledTaskId: Schema.optional(ScheduledTaskId),
1416 senderThreadId: Schema.optional(ThreadId),
1417 + idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
1418 workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
1419 inputIntent: OrchestrationV2UserMessageInputIntent,
1420 text: Schema.String,
@@ -1857,6 +1895,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
1895 latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
1896 latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
1897 latestRunStopRequested: Schema.optional(Schema.Boolean),
1898 + /** Suppress routine notifications for idle compaction; failures still notify. */
1899 + latestRunSilent: Schema.optional(Schema.Boolean),
1900 activeRunId: Schema.NullOr(RunId),
1901 activityRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
1902 activityRunStatus: Schema.optional(
@@ -2141,6 +2181,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
2181 messageId: MessageId,
2182 scheduledTaskId: Schema.optional(ScheduledTaskId),
2183 senderThreadId: Schema.optional(ThreadId),
2184 + idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
2185 workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
2186 inputIntent: OrchestrationV2UserMessageInputIntent,
2187 text: Schema.String,
@@ -2832,6 +2873,7 @@ export const OrchestrationV2Command = Schema.Union([
2873 ...OrchestrationV2CreationFields,
2874 scheduledTaskId: Schema.optional(ScheduledTaskId),
2875 senderThreadId: Schema.optional(ThreadId),
2876 + idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
2877 commandId: CommandId,
2878 threadId: ThreadId,
2879 messageId: MessageId,
packages/shared/src/agentAwareness.test.ts
+14
@@ -63,6 +63,20 @@ describe("projectThreadAwarenessV2", () => {
63 ).toBeNull();
64 });
65
66 + it.each([
67 + ["running", null],
68 + ["completed", null],
69 + ["failed", "failed"],
70 + ] as const)("keeps an idle compaction's %s run quiet unless it fails", (status, phase) => {
71 + expect(
72 + projectThreadAwarenessV2({
73 + environmentId: "env-1" as EnvironmentId,
74 + project,
75 + thread: { ...v2Thread({ status }), latestRunSilent: true },
76 + })?.phase ?? null,
77 + ).toBe(phase);
78 + });
79 +
80 it.each(["running", "completed", "failed"] as const)(
81 "does not publish %s subagent activity",
82 (status) => {
packages/shared/src/agentAwareness.ts
+6
@@ -46,6 +46,7 @@ export interface ProjectThreadAwarenessV2Input {
46 | "id"
47 | "lineage"
48 | "latestRunStopRequested"
49 + | "latestRunSilent"
50 | "modelSelection"
51 | "pendingBackgroundTasks"
52 | "pendingRuntimeRequest"
@@ -66,6 +67,11 @@ export function projectThreadAwarenessV2(
67 return null;
68 }
69 if (phase === "completed" && thread.latestRunStopRequested === true) return null;
70 + if (
71 + thread.latestRunSilent === true &&
72 + (phase === "starting" || phase === "running" || phase === "completed")
73 + )
74 + return null;
75 // Resolve the phase first so live or waiting work stays visible after settlement.
76 if (
77 thread.settledOverride === "settled" &&
packages/shared/src/claudeCompaction.ts
+20 -1
@@ -6,6 +6,7 @@
6 * live here: reword the question or the answer label in this file only.
7 */
8 export const CLAUDE_RESUME_COMPACTION_NEVER_ANSWER = "Don't ask again";
9 +export const CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER = "Compact and continue";
10
11 export function formatClaudeResumeCompactionQuestion(input: {
12 readonly ageMinutes: number;
@@ -19,12 +20,30 @@ export function formatClaudeResumeCompactionQuestion(input: {
20 }
21
22 const CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN =
22 - /^This session is (?:\d+h \d+m|\d+m) old and uses \d{1,3}(?:,\d{3})* tokens\. Compact it before continuing\?$/u;
23 + /^This session is (\d+h \d+m|\d+m) old and uses \d{1,3}(?:,\d{3})* tokens\. Compact it before continuing\?$/u;
24
25 export function isClaudeResumeCompactionQuestion(question: string): boolean {
26 return CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN.test(question);
27 }
28
29 +/**
30 + * The session age from an answered resume question whose answer was to compact, or null. Answers
31 + * are keyed by question id, and the id may itself be the question text.
32 + */
33 +export function claudeResumeCompactionAge(questionAnswer: {
34 + readonly questionTextById?: Readonly<Record<string, string>> | undefined;
35 + readonly answers: Readonly<Record<string, unknown>>;
36 +}): string | null {
37 + for (const [id, answer] of Object.entries(questionAnswer.answers)) {
38 + const age = CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN.exec(
39 + questionAnswer.questionTextById?.[id] ?? id,
40 + )?.[1];
41 + const chosen = Array.isArray(answer) ? answer : [answer];
42 + if (age !== undefined && chosen.includes(CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER)) return age;
43 + }
44 + return null;
45 +}
46 +
47 /**
48 * Context size below which T3 does not suggest or run a Claude compaction:
49 * the stale-thread Compact chip and idle compaction. Matches Claude Code's