Skip to content
TypeScript

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

Julius Marminge0345e852ed00
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 48b1346646a..11857f0e2b1 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -28,13 +28,17 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { useViewabilityAmount, type LegendListRef } from "@legendapp/list/react-native";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff";
-import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
+import {
+ IDLE_COMPACTING_LABELS,
+ resolveUserMessagePresentation,
+} from "@t3tools/client-runtime/user-message";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
import {
AuthFilesystemReadScope,
+ idleCompactionOf,
type OrchestrationMessageContext,
ThreadId,
type ChatAttachment,
@@ -195,6 +199,7 @@ import {
} from "../../lib/markdownLinks";
import {
createThreadFeedCache,
+ threadFeedCompactionLabels,
failedFeedRunIds,
deriveThreadFeedPresentation,
threadFeedRunIsUnsettled,
@@ -224,7 +229,11 @@ import {
ThreadWorkLog,
WORK_GROUP_TOGGLE_HEIGHT,
} from "./thread-work-log";
-import { appendPendingThreadMessages, type PendingThreadFeedEntry } from "./pending-thread-feed";
+import {
+ appendPendingThreadMessages,
+ isCompactionCommandFeedEntry,
+ type PendingThreadFeedEntry,
+} from "./pending-thread-feed";
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size";
import { htmlRenderFrameHeight } from "@t3tools/shared/htmlRender";
@@ -1192,6 +1201,13 @@ function ThreadAutomationMessageRow(props: {
);
}
+/** Leads with why T3 Code compacted, when it did so without being asked. */
+function compactionLabel(label: string, title: string | undefined) {
+ return title !== undefined && label.startsWith("Context compacted")
+ ? title + label.slice("Context compacted".length)
+ : label;
+}
+
function renderFeedEntry(
info: { item: PendingThreadFeedEntry; index: number },
props: Pick<
@@ -1210,6 +1226,7 @@ function renderFeedEntry(
readonly workGroupScrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
readonly terminalAssistantMessageIds: ReadonlySet<string>;
readonly unsettledTurnId: RunId | null;
+ readonly compactionLabelsByEntryId: ReadonlyMap<string, { title: string; compacting: string }>;
readonly failedRunIds: ReadonlySet<RunId>;
readonly onCopyWorkRow: (rowId: string, value: string) => void;
readonly onToggleWorkGroup: (groupId: string, anchorKey?: string) => void;
@@ -1361,16 +1378,29 @@ function renderFeedEntry(
if (entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) {
const label = entry.activities[0]!.summary;
+ const item = entry.activities[0]!.projectedItem.item;
const active =
props.unsettledTurnId !== null &&
entry.runId === props.unsettledTurnId &&
- entry.activities[0]!.projectedItem.item.status === "running";
+ item.status === "running";
+ const labels = props.compactionLabelsByEntryId.get(entry.id);
+ const failure =
+ item.type === "compaction" && item.status === "failed" ? item.summary?.trim() : undefined;
return (
<ThreadContextDivider
- label={label}
- icon="arrow.down.right.and.arrow.up.left"
+ label={
+ failure
+ ? `${label} · ${failure}`
+ : active && labels
+ ? labels.compacting
+ : compactionLabel(label, labels?.title)
+ }
+ icon={
+ item.status === "failed" ? "exclamationmark.circle" : "arrow.down.right.and.arrow.up.left"
+ }
iconColor={iconSubtleColor}
active={active}
+ failed={item.status === "failed"}
/>
);
}
@@ -1409,6 +1439,25 @@ function renderFeedEntry(
/>
);
}
+ if (isCompactionCommandFeedEntry(entry)) {
+ // Stands in for the compaction item until the provider reports it.
+ const active = props.unsettledTurnId !== null && message.runId === props.unsettledTurnId;
+ const reason = idleCompactionOf(message);
+ return (
+ <ThreadContextDivider
+ label={
+ !active
+ ? "Context compaction"
+ : reason === undefined
+ ? "Compacting context"
+ : IDLE_COMPACTING_LABELS[reason]
+ }
+ icon="arrow.down.right.and.arrow.up.left"
+ iconColor={iconSubtleColor}
+ active={active}
+ />
+ );
+ }
if (isUser && presentation.attribution === "automation") {
const rowId = `automation:${message.id}`;
return (
@@ -2505,6 +2554,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
const reviewCommentColors = useReviewCommentColors();
const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
+ const compactionLabelsByEntryId = useMemo(
+ () => threadFeedCompactionLabels(props.feed),
+ [props.feed],
+ );
// LegendList does not invalidate visible rows when only the renderItem closure changes.
// Include turn completion so unchanged message rows reveal their footer and spacing
// even when the final message update arrives before the turn settles.
@@ -2987,6 +3040,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
workGroupScrollPositions,
terminalAssistantMessageIds,
unsettledTurnId,
+ compactionLabelsByEntryId,
failedRunIds,
onCopyWorkRow,
onToggleWorkGroup,
@@ -3124,6 +3178,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
keyExtractor={(entry) => entry.id}
getItemType={(entry) => {
if (entry.type !== "message") return entry.type;
+ if (isCompactionCommandFeedEntry(entry)) return "message:compaction";
const { attribution } = resolveUserMessagePresentation(entry.message);
return attribution === "automation" || attribution === "agent"
? `message:${attribution}`
diff --git a/apps/mobile/src/features/threads/pending-thread-feed.test.ts b/apps/mobile/src/features/threads/pending-thread-feed.test.ts
index 92c39ab1b82..be82e4b6510 100644
--- a/apps/mobile/src/features/threads/pending-thread-feed.test.ts
+++ b/apps/mobile/src/features/threads/pending-thread-feed.test.ts
@@ -8,7 +8,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
-import { appendPendingThreadMessages } from "./pending-thread-feed";
+import { appendPendingThreadMessages, isCompactionCommandFeedEntry } from "./pending-thread-feed";
const pending = (id: string): QueuedThreadMessage => ({
environmentId: EnvironmentId.make("env"),
@@ -21,6 +21,35 @@ const pending = (id: string): QueuedThreadMessage => ({
});
describe("pending timeline messages", () => {
+ it.each([false, true])(
+ "keeps a queued compact command in the pending message row (attachment: %s)",
+ (withAttachment) => {
+ const queued = {
+ ...pending("compact"),
+ text: "/compact",
+ attachments: withAttachment
+ ? [
+ {
+ id: "image-1",
+ type: "image" as const,
+ name: "photo.png",
+ mimeType: "image/png",
+ sizeBytes: 3,
+ fileUri: "file:///documents/photo.png",
+ previewUri: "file:///documents/photo.png",
+ },
+ ]
+ : [],
+ };
+ const entry = appendPendingThreadMessages([], [], [queued])[0]!;
+ expect(isCompactionCommandFeedEntry(entry)).toBe(false);
+ expect(entry.pendingMessage).toEqual(queued);
+ if (!withAttachment) {
+ expect(isCompactionCommandFeedEntry({ ...entry, pendingMessage: undefined })).toBe(true);
+ }
+ },
+ );
+
it("marks the synthetic creation prompt pending without duplicating it", () => {
const queued = {
...pending("creation"),
diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.ts
index 6df93566286..80ed9798b98 100644
--- a/apps/mobile/src/features/threads/pending-thread-feed.ts
+++ b/apps/mobile/src/features/threads/pending-thread-feed.ts
@@ -1,3 +1,4 @@
+import { isCompactionCommandMessage } from "@t3tools/contracts";
import type { ThreadFeedEntry } from "../../lib/threadActivity";
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
@@ -45,3 +46,11 @@ export function appendPendingThreadMessages(
})),
];
}
+
+export function isCompactionCommandFeedEntry(entry: PendingThreadFeedEntry): boolean {
+ return (
+ entry.type === "message" &&
+ entry.pendingMessage === undefined &&
+ isCompactionCommandMessage(entry.message)
+ );
+}
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts
index c2740dd0006..d64763aa278 100644
--- a/apps/mobile/src/lib/threadActivity.test.ts
+++ b/apps/mobile/src/lib/threadActivity.test.ts
@@ -24,6 +24,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
buildThreadFeed,
+ threadFeedCompactionLabels,
createThreadFeedCache,
deriveThreadFeedPresentation,
messageFoldRunId,
@@ -76,6 +77,144 @@ it("keeps historical plan detail accessible from its paged turn item", () => {
expect(presented[2]).toMatchObject({ activities: [{ projectedItem: { item } }] });
});
+it("shows a compact command as one mobile divider before, during, and after compaction", () => {
+ const startedAt = "2026-06-20T00:00:01.000Z";
+ const prompt = projected({ ...userMessage(), text: "/compact", idleCompaction: "onReturn" }, 0);
+ const latestRun = { runId, status: "running" as const, startedAt, completedAt: null };
+ const present = (items: OrchestrationV2ProjectedTurnItem[]) =>
+ deriveThreadFeedPresentation(
+ buildThreadFeed(items),
+ latestRun,
+ new Set(),
+ new Set(),
+ startedAt,
+ );
+
+ const waiting = present([prompt]);
+ expect(waiting.map((entry) => entry.type)).toEqual(["message"]);
+ expect(waiting[0]?.type === "message" ? waiting[0].message.idleCompaction : null).toBe(
+ "onReturn",
+ );
+ for (const status of ["running", "completed", "failed"] as const) {
+ const compaction = projected(
+ {
+ ...base("compaction", "2026-06-20T00:00:02.000Z", 1),
+ type: "compaction",
+ driver: ProviderDriverKind.make("claude"),
+ status,
+ beforeTokenCount: 100_000,
+ ...(status === "completed" ? { afterTokenCount: 20_000 } : {}),
+ ...(status === "failed" ? { summary: "Not enough messages to compact." } : {}),
+ },
+ 1,
+ );
+ const rows = present([prompt, compaction]);
+ expect(rows.map((entry) => entry.type)).toEqual(["activity-group"]);
+ expect(
+ rows[0]?.type === "activity-group" ? rows[0].activities[0]?.projectedItem.item : null,
+ ).toMatchObject({ type: "compaction", status });
+ }
+});
+
+it.each(["/compact", "Continue"])(
+ "keeps a completed compaction divider visible while other settled work folds for %s",
+ (promptText) => {
+ const rows = deriveThreadFeedPresentation(
+ buildThreadFeed([
+ projected({ ...userMessage(), text: promptText }, 0),
+ projected(command(), 1),
+ projected(
+ {
+ ...base("compaction", "2026-06-20T00:00:03.000Z", 2),
+ type: "compaction",
+ driver: ProviderDriverKind.make("claude"),
+ status: "completed",
+ beforeTokenCount: 100_000,
+ afterTokenCount: 20_000,
+ },
+ 2,
+ ),
+ ]),
+ {
+ runId,
+ status: "completed",
+ startedAt: "2026-06-20T00:00:01.000Z",
+ completedAt: "2026-06-20T00:00:03.000Z",
+ },
+ new Set(),
+ );
+ expect(rows.filter((entry) => entry.type === "run-fold")).toHaveLength(1);
+ const activities = rows.flatMap((entry) =>
+ entry.type === "activity-group" ? entry.activities : [],
+ );
+ expect(activities.map((activity) => activity.projectedItem.item)).toMatchObject([
+ {
+ type: "compaction",
+ status: "completed",
+ beforeTokenCount: 100_000,
+ afterTokenCount: 20_000,
+ },
+ ]);
+ if (promptText === "/compact") {
+ expect(rows.some((entry) => entry.type === "message")).toBe(false);
+ }
+ },
+);
+
+it("binds a persisted resume answer only to the next compaction in its run", () => {
+ const requestId = RuntimeRequestId.make("resume-compaction");
+ const question = projected(
+ {
+ ...base("resume-question", "2026-06-20T00:00:02.000Z", 1),
+ type: "user_input_request",
+ requestId,
+ questions: [],
+ questionAnswer: {
+ requestId,
+ questionTextById: {
+ resume:
+ "This session is 2h 10m old and uses 200,000 tokens. Compact it before continuing?",
+ },
+ answers: { resume: "Compact and continue" },
+ attachmentsByQuestionId: {},
+ },
+ },
+ 1,
+ );
+ const compaction = (id: string, position: number, status: "running" | "completed") =>
+ projected(
+ {
+ ...base(id, `2026-06-20T00:00:0${position + 1}.000Z`, position),
+ type: "compaction",
+ driver: ProviderDriverKind.make("claude"),
+ status,
+ beforeTokenCount: 200_000,
+ },
+ position,
+ );
+ for (const status of ["running", "completed"] as const) {
+ // Rebuild from persisted items, without a live question or prior feed cache.
+ const feed = buildThreadFeed([
+ projected(userMessage(), 0),
+ question,
+ compaction("resume-compact", 2, "completed"),
+ compaction("auto-compact", 3, status),
+ ]);
+ const labels = threadFeedCompactionLabels(feed);
+ const compactRows = feed.filter(
+ (entry) =>
+ entry.type === "activity-group" &&
+ entry.activities[0]?.projectedItem.item.type === "compaction",
+ );
+ expect(compactRows).toHaveLength(2);
+ expect(labels.get(compactRows[0]!.id)).toEqual({
+ title: "Context compacted after 2h 10m idle",
+ compacting: "Compacting after 2h 10m idle…",
+ });
+ expect(labels.get(compactRows[1]!.id)).toBeUndefined();
+ }
+});
+
function base(id: string, updatedAt: string, ordinal: number) {
const timestamp = DateTime.makeUnsafe(updatedAt);
return {
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index cfa562711cf..485c2458189 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -53,7 +53,7 @@ import type {
ScheduledTaskId,
TurnItemId,
} from "@t3tools/contracts";
-import { RunId, ThreadId } from "@t3tools/contracts";
+import { idleCompactionOf, isCompactionCommandMessage, RunId, ThreadId } from "@t3tools/contracts";
import {
classifyToolActivity,
collectToolFilePaths,
@@ -62,6 +62,7 @@ import {
formatReadToolLabel,
formatSearchToolLabel,
} from "@t3tools/shared/toolActivity";
+import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import { truncate } from "@t3tools/shared/String";
import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
@@ -72,6 +73,10 @@ import {
mcpAppFromToolItem,
} from "@t3tools/shared/toolOutput";
import * as DateTime from "effect/DateTime";
+import {
+ IDLE_COMPACTION_TITLES,
+ IDLE_COMPACTING_LABELS,
+} from "@t3tools/client-runtime/user-message";
export type PendingApproval = ThreadPendingApproval;
export type PendingUserInput = ThreadPendingUserInput;
@@ -141,6 +146,7 @@ export interface ThreadFeedMessage {
readonly creationSource?: OrchestrationV2CreationSource;
readonly scheduledTaskId?: ScheduledTaskId;
readonly senderThreadId?: ThreadId;
+ readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
readonly sourceThreadId: ThreadId;
readonly createdAt: string;
@@ -352,6 +358,49 @@ export function isContextCompactionActivityGroup(entry: ThreadFeedActivityGroup)
);
}
+export function threadFeedCompactionLabels(feed: ReadonlyArray<ThreadFeedEntry>) {
+ const labelsByRunId = new Map<RunId, { title: string; compacting: string }>();
+ const labelsByEntryId = new Map<string, { title: string; compacting: string }>();
+ const pendingResumeAgeByRunId = new Map<RunId, string>();
+ for (const entry of feed) {
+ const reason = entry.type === "message" ? idleCompactionOf(entry.message) : undefined;
+ if (entry.type === "message" && entry.message.runId !== null && reason !== undefined) {
+ labelsByRunId.set(entry.message.runId, {
+ title: IDLE_COMPACTION_TITLES[reason],
+ compacting: IDLE_COMPACTING_LABELS[reason],
+ });
+ } else if (entry.type === "activity-group" && entry.runId !== null) {
+ if (isContextCompactionActivityGroup(entry)) {
+ const age = pendingResumeAgeByRunId.get(entry.runId);
+ const labels =
+ labelsByRunId.get(entry.runId) ??
+ (age === undefined
+ ? undefined
+ : {
+ title: `Context compacted after ${age} idle`,
+ compacting: `Compacting after ${age} idle…`,
+ });
+ if (labels) labelsByEntryId.set(entry.id, labels);
+ pendingResumeAgeByRunId.delete(entry.runId);
+ }
+ for (const activity of entry.activities) {
+ const age = activity.workEntry.questionAnswer
+ ? claudeResumeCompactionAge(activity.workEntry.questionAnswer)
+ : null;
+ if (age !== null) pendingResumeAgeByRunId.set(entry.runId, age);
+ }
+ }
+ }
+ return labelsByEntryId;
+}
+
+function isResumeCompactionAnswerGroup(entry: ThreadFeedActivityGroup): boolean {
+ return entry.activities.every((activity) => {
+ const answer = activity.workEntry.questionAnswer;
+ return answer !== undefined && claudeResumeCompactionAge(answer) !== null;
+ });
+}
+
export function isContextHandoffActivityGroup(entry: ThreadFeedActivityGroup): boolean {
return (
entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "handoff"
@@ -1183,6 +1232,7 @@ function deriveThreadFeedRunFolds(
entry.id !== terminalAssistantId &&
entry.type !== "html-render" &&
entry.type !== "mcp-app" &&
+ !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) &&
!(
entry.type === "activity-group" &&
entry.activities.some(
@@ -1396,6 +1446,26 @@ export function deriveThreadFeedPresentation(
const failedRunIds = failedFeedRunIds(sourceFeed, latestRun);
const activeTailGroup = sourceFeed.at(-1);
const activeRunId = unsettledRunId(latestRun);
+ // A bare `/compact` turn is the compaction itself: its compaction row stands in for the prompt
+ // and the live activity row. An answered "compact before continuing?" question folds into the
+ // compaction it asked for.
+ const compactionCommandRunIds = new Set<RunId>();
+ const compactionItemRunIds = new Set<RunId>();
+ for (const entry of feed) {
+ if (
+ entry.type === "message" &&
+ entry.message.runId !== null &&
+ isCompactionCommandMessage(entry.message)
+ ) {
+ compactionCommandRunIds.add(entry.message.runId);
+ } else if (
+ entry.type === "activity-group" &&
+ entry.runId !== null &&
+ isContextCompactionActivityGroup(entry)
+ ) {
+ compactionItemRunIds.add(entry.runId);
+ }
+ }
const isWorking = activeWorkStartedAt !== null && latestRun?.status !== "preparing";
const foldsByAnchorId = deriveThreadFeedRunFolds(
sourceFeed,
@@ -1450,6 +1520,18 @@ export function deriveThreadFeedPresentation(
}
result.push(row);
}
+ if (
+ (entry.type === "message" &&
+ entry.message.runId !== null &&
+ compactionItemRunIds.has(entry.message.runId) &&
+ isCompactionCommandMessage(entry.message)) ||
+ (entry.type === "activity-group" &&
+ entry.runId !== null &&
+ compactionItemRunIds.has(entry.runId) &&
+ isResumeCompactionAnswerGroup(entry))
+ ) {
+ continue;
+ }
if (!collapsedEntryIds.has(entry.id)) {
if (
entry.type === "activity-group" &&
@@ -1487,6 +1569,7 @@ export function deriveThreadFeedPresentation(
isWorking &&
activeWorkStartedAt !== null &&
latestRun?.turnEnded !== true &&
+ (activeRunId === null || !compactionCommandRunIds.has(activeRunId)) &&
!result.some(
(row) =>
row.id === LIVE_ACTIVITY_ROW_ID ||
@@ -2177,6 +2260,7 @@ export function buildThreadFeed(
creationSource: item.creationSource,
...(item.scheduledTaskId ? { scheduledTaskId: item.scheduledTaskId } : {}),
...(item.senderThreadId ? { senderThreadId: item.senderThreadId } : {}),
+ ...(item.idleCompaction ? { idleCompaction: item.idleCompaction } : {}),
}
: {}),
visibility: row.visibility,
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 0c8b2ad588a..0b6232479c4 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -4293,15 +4293,35 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const [running, settled] = updates;
assert.equal(running?.status, "running");
assert.equal(settled?.status, compaction === "success" ? "completed" : "failed");
+ assert.equal(
+ settled?.type === "compaction" ? settled.summary : undefined,
+ compaction === "failed"
+ ? limited
+ ? compactError
+ : "Not enough messages to compact."
+ : undefined,
+ );
assert.equal(settled?.id, running?.id);
assert.equal(settled?.ordinal, running?.ordinal);
assert.deepEqual(settled?.startedAt, running?.startedAt);
assert.isNotNull(settled?.completedAt);
assert.isEmpty(harness.terminalEvents());
- yield* Queue.offer(
+ yield* Queue.offerAll(
harness.sdkMessages,
- compact ? claudeSdkFrame({ ...result, local_command: "compact" }) : result,
+ compact
+ ? [
+ // Claude Code echoes the command's stdout as a synthetic assistant message.
+ claudeSdkFrame({
+ ...makeAssistantTextFrame({
+ uuid: "00000000-0000-4000-8000-000000000615",
+ text: "Compacted.",
+ }),
+ local_command_source: "<local-command-stdout>Compacted.</local-command-stdout>",
+ }),
+ claudeSdkFrame({ ...result, local_command: "compact" }),
+ ]
+ : [result],
);
const terminal = yield* Queue.take(harness.terminalReceipts);
assert.deepEqual(
@@ -4313,6 +4333,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
updates,
);
assert.equal(terminal.status, status);
+ assert.equal(
+ harness.events.some(
+ (event) =>
+ event.type === "turn_item.updated" && event.turnItem.type === "assistant_message",
+ ),
+ !compact,
+ );
if (terminal.status !== "failed") return;
assert.equal(terminal.failure.class, "usage_limit");
assert.equal(terminal.failure.message, compactError);
@@ -4327,6 +4354,70 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ it.effect("keeps an unreported /compact failure's reason on the compaction, not as a reply", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-compaction-unreported"),
+ text: "/compact",
+ attachments: [],
+ }),
+ );
+ // Claude can refuse a /compact without a compact_result: the only reason is the result text.
+ yield* Queue.offerAll(harness.sdkMessages, [
+ claudeSdkFrame({
+ type: "system",
+ subtype: "status",
+ status: "compacting",
+ uuid: "00000000-0000-4000-8000-000000000620",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ claudeSdkFrame({
+ ...makeAssistantTextFrame({
+ uuid: "00000000-0000-4000-8000-000000000622",
+ text: "Not enough messages to compact.",
+ }),
+ local_command_source:
+ "<local-command-stdout>Not enough messages to compact.</local-command-stdout>",
+ }),
+ claudeSdkFrame({
+ ...makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000621",
+ result: "Not enough messages to compact.",
+ numTurns: 0,
+ terminalReason: null,
+ }),
+ local_command: "compact",
+ }),
+ ]);
+ yield* Queue.take(harness.terminalReceipts);
+ const settled = harness.events
+ .flatMap((event) =>
+ event.type === "turn_item.updated" && event.turnItem.type === "compaction"
+ ? [event.turnItem]
+ : [],
+ )
+ .at(-1);
+ assert.equal(settled?.status, "failed");
+ assert.equal(settled?.summary, "Not enough messages to compact.");
+ assert.isFalse(
+ harness.events.some(
+ (event) =>
+ event.type === "turn_item.updated" && event.turnItem.type === "assistant_message",
+ ),
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
it.effect.each([
{ name: "parent limit", parentErrors: ["rate_limit"], expectedLimit: true },
{
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 0e0868918ea..792195ebfa8 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -58,6 +58,7 @@ import { AgentScope } from "@t3tools/shared/AgentScope";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
import {
+ CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER,
CLAUDE_RESUME_COMPACTION_NEVER_ANSWER,
formatClaudeResumeCompactionQuestion,
} from "@t3tools/shared/claudeCompaction";
@@ -66,6 +67,7 @@ import {
ClaudeSettings,
TrimmedNonEmptyString,
defaultInstanceIdForDriver,
+ isCompactionCommandMessage,
type ModelSelection,
type OrchestrationV2ConversationMessage,
type OrchestrationV2ExecutionNode,
@@ -6641,6 +6643,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
}) {
yield* reasoningDeltas.flushTurn(input.context.nativeTurnId);
if (input.context.compaction?.status === "running") {
+ const reason = input.result?.subtype === "success" ? input.result.result.trim() : "";
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CLAUDE_PROVIDER,
@@ -6651,6 +6654,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
input.status === "completed" || input.status === "failed"
? "Context compaction failed"
: "Context compaction stopped",
+ ...(reason === "" ? {} : { summary: reason }),
completedAt: input.completedAt,
updatedAt: input.completedAt,
},
@@ -7767,6 +7771,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
: message.compact_result === "failed"
? "Context compaction failed"
: "Context compaction stopped",
+ ...(message.compact_result === "failed" && message.compact_error
+ ? { summary: message.compact_error }
+ : {}),
completedAt: now,
updatedAt: now,
};
@@ -8484,6 +8491,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
});
return;
}
+ // Claude Code echoes /compact's stdout ("Not enough messages to compact.") as a
+ // synthetic assistant message. The compaction item reports that outcome; it is not a
+ // reply.
+ if (
+ message.type === "assistant" &&
+ "local_command_source" in message &&
+ isCompactionCommandMessage({ role: "user", ...context.input.message })
+ ) {
+ return;
+ }
if (assistantText !== null && assistantText.text.length > 0) {
yield* emitAssistantTextArtifacts({
context,
@@ -8535,6 +8552,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
? null
: resultTextFromSdkMessage(message);
if (
+ // A /compact's result text reports the compaction ("Not enough messages to
+ // compact."), which its compaction item already carries; it is not a reply.
+ !(
+ message.type === "result" &&
+ message.subtype === "success" &&
+ message.local_command === "compact"
+ ) &&
context.assistant.emittedNativeItemIds.size === 0 &&
context.assistant.fallbackText.length === 0 &&
resultText !== null &&
@@ -9108,7 +9132,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
question,
options: [
{
- label: "Compact and continue",
+ label: CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER,
description: "Resume with a summary and use fewer tokens.",
},
{
@@ -9142,7 +9166,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
return {
behavior: "completed" as const,
result:
- selection === "Compact and continue"
+ selection === CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER
? ("compact" as const)
: selection === CLAUDE_RESUME_COMPACTION_NEVER_ANSWER
? ("never" as const)
diff --git a/apps/server/src/orchestration-v2/IdleCompactionService.ts b/apps/server/src/orchestration-v2/IdleCompactionService.ts
index 30c81ba7033..2b16cb8c1d7 100644
--- a/apps/server/src/orchestration-v2/IdleCompactionService.ts
+++ b/apps/server/src/orchestration-v2/IdleCompactionService.ts
@@ -1,5 +1,6 @@
import {
CommandId,
+ IDLE_COMPACTION_TEXT,
MessageId,
resolveIdleCompaction,
resolveProjectProviderInstanceEnabled,
@@ -70,10 +71,11 @@ export const make = Effect.gen(function* () {
commandId: CommandId.make(`server:idle-compact:${threadId}:${runId}`),
messageId: MessageId.make(`idle-compact:${threadId}:${runId}`),
threadId,
- text: "/compact",
+ text: IDLE_COMPACTION_TEXT,
attachments: [],
createdBy: "agent",
creationSource: "server",
+ idleCompaction: "beforeCacheExpires",
dispatchMode: { type: "start_immediately" },
});
return;
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 77533f593e9..48972ce4cd4 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -1876,6 +1876,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...(queuedMessage.senderThreadId === undefined
? {}
: { senderThreadId: queuedMessage.senderThreadId }),
+ ...(queuedMessage.idleCompaction === undefined
+ ? {}
+ : { idleCompaction: queuedMessage.idleCompaction }),
}),
providerThreadId: queuedProviderThread.id,
inputIntent: "queued_turn",
@@ -4145,6 +4148,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly creationSource: OrchestrationV2ConversationMessage["creationSource"];
readonly scheduledTaskId?: OrchestrationV2ConversationMessage["scheduledTaskId"];
readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"];
+ readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"];
readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"];
readonly forceRestart: boolean;
}) {
@@ -4302,6 +4306,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: input.scheduledTaskId }),
...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
+ ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
id: input.messageId,
threadId: input.command.threadId,
runId: messageInput.runId,
@@ -4321,6 +4326,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: input.scheduledTaskId }),
...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
+ ...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
threadId: input.command.threadId,
runId: messageInput.runId,
@@ -5256,6 +5262,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
forceRestart: dispatchMode.type === "restart_active",
});
return;
@@ -5491,6 +5498,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: command.messageId,
threadId: command.threadId,
runId,
@@ -5831,6 +5839,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: command.messageId,
threadId: command.threadId,
runId,
@@ -5852,6 +5861,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
threadId: command.threadId,
runId,
@@ -6518,6 +6528,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: command.messageId,
threadId: command.threadId,
runId,
@@ -6539,6 +6550,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
threadId: command.threadId,
runId,
@@ -8165,6 +8177,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...(queuedMessage.senderThreadId === undefined
? {}
: { senderThreadId: queuedMessage.senderThreadId }),
+ ...(queuedMessage.idleCompaction === undefined
+ ? {}
+ : { idleCompaction: queuedMessage.idleCompaction }),
forceRestart: false,
});
});
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index fcadd8036b9..14fed37c061 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -2879,6 +2879,150 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
}),
);
+ it.effect.each([
+ ["T3 Code's idle compaction", "agent", "server", undefined, true, "/compact"],
+ ["compacting on return", "user", "web", "onReturn", true, "/compact"],
+ ["a typed /compact", "user", "mobile", undefined, false, "/compact"],
+ ["a normalized idle command", "agent", "server", undefined, true, " \t\u00a0/COMPACT\u3000\n"],
+ ["an ordinary prompt with idle metadata", "user", "web", "onReturn", false, "Continue"],
+ ] as const)(
+ "marks the shell's latest run silent only for %s",
+ ([name, createdBy, creationSource, idleCompaction, silent, text]) =>
+ Effect.gen(function* () {
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
+ const now = yield* DateTime.now;
+ const key = name.replaceAll(/\W+/g, "-");
+ const threadId = ThreadId.make(`thread:projection-shell-silent:${key}`);
+ const runId = RunId.make(`run:projection-shell-silent:${key}`);
+ const messageId = MessageId.make(`message:projection-shell-silent:${key}`);
+ yield* projectionStore.apply({
+ id: EventId.make(`event:projection-shell-silent:${key}:thread`),
+ type: "thread.created",
+ threadId,
+ occurredAt: now,
+ payload: {
+ createdBy: "user",
+ creationSource: "web",
+ id: threadId,
+ projectId: ProjectId.make("project:projection-shell-silent"),
+ title: "Idle compaction",
+ providerInstanceId,
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: null,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ });
+ yield* projectionStore.apply({
+ id: EventId.make(`event:projection-shell-silent:${key}:message`),
+ type: "message.updated",
+ threadId,
+ occurredAt: now,
+ payload: {
+ createdBy,
+ creationSource,
+ ...(idleCompaction === undefined ? {} : { idleCompaction }),
+ id: messageId,
+ threadId,
+ runId,
+ nodeId: null,
+ role: "user",
+ text,
+ attachments: [],
+ streaming: false,
+ createdAt: now,
+ updatedAt: now,
+ },
+ });
+ yield* projectionStore.apply({
+ id: EventId.make(`event:projection-shell-silent:${key}:run`),
+ type: "run.created",
+ threadId,
+ runId,
+ nodeId: NodeId.make(`node:projection-shell-silent:${key}`),
+ driver,
+ occurredAt: now,
+ payload: {
+ id: runId,
+ threadId,
+ ordinal: 1,
+ providerInstanceId,
+ modelSelection,
+ providerThreadId: null,
+ userMessageId: messageId,
+ rootNodeId: null,
+ activeAttemptId: null,
+ status: "completed",
+ requestedAt: now,
+ startedAt: now,
+ completedAt: now,
+ checkpointId: null,
+ contextHandoffId: null,
+ },
+ });
+
+ const sqlShell = (yield* projectionStore.getShellSnapshot()).threads.find(
+ (thread) => thread.id === threadId,
+ );
+ const memoryShell = ProjectionStore.threadShellFromProjection(
+ yield* projectionStore.getThreadProjection(threadId),
+ );
+ assert.equal(sqlShell?.latestRunSilent, silent);
+ assert.equal(memoryShell.latestRunSilent, silent);
+
+ // Claude can finish the run successfully even when its /compact failed.
+ yield* projectionStore.apply({
+ id: EventId.make(`event:projection-shell-silent:${key}:failure`),
+ type: "turn-item.updated",
+ threadId,
+ runId,
+ occurredAt: now,
+ payload: {
+ id: TurnItemId.make(`item:projection-shell-silent:${key}:compaction`),
+ threadId,
+ runId,
+ nodeId: null,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 1,
+ type: "compaction",
+ driver,
+ status: "failed",
+ title: "Context compaction failed",
+ summary: "Not enough messages to compact.",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ },
+ });
+ assert.equal(
+ (yield* projectionStore.getShellSnapshot()).threads.find(
+ (thread) => thread.id === threadId,
+ )?.latestRunSilent,
+ false,
+ );
+ assert.equal(
+ ProjectionStore.threadShellFromProjection(
+ yield* projectionStore.getThreadProjection(threadId),
+ ).latestRunSilent,
+ false,
+ );
+ }),
+ );
+
it.effect("only exposes interruptible runs through the shell activeRunId", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index a50ce6ff352..438cf79138d 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -42,6 +42,8 @@ import type {
RunAttemptId,
} from "@t3tools/contracts";
import {
+ IDLE_COMPACTION_TEXT,
+ idleCompactionOf,
OrchestrationV2AppThreadJson as OrchestrationV2AppThreadJsonSchema,
OrchestrationV2CheckpointJson as OrchestrationV2CheckpointJsonSchema,
OrchestrationV2CheckpointScopeJson as OrchestrationV2CheckpointScopeJsonSchema,
@@ -1084,6 +1086,7 @@ type ShellThreadRow = {
readonly latest_run_started_at: string | null;
readonly latest_run_completed_at: string | null;
readonly latest_run_stop_requested: number;
+ readonly latest_run_silent: number;
readonly active_run_id: string | null;
readonly active_run_status: string | null;
readonly activity_run_status: string | null;
@@ -1634,6 +1637,16 @@ export function threadShellFromProjection(
projection.turnItems.some(
(item) => item.runId === latestRun.id && item.type === "run_interrupt_request",
),
+ latestRunSilent:
+ latestRun != null &&
+ projection.messages.some(
+ (message) =>
+ message.id === latestRun.userMessageId && idleCompactionOf(message) !== undefined,
+ ) &&
+ !projection.turnItems.some(
+ (item) =>
+ item.runId === latestRun.id && item.type === "compaction" && item.status === "failed",
+ ),
activeRunId: activeRun?.id ?? null,
blockedOnThreadWait: deriveBlockedOnThreadWait({ activeRun, turnItems: projection.turnItems }),
activityRunStatus: activityRun?.status ?? null,
@@ -1735,6 +1748,7 @@ type ShellThreadState = {
readonly latestRunStartedAt: DateTime.Utc | null;
readonly latestRunCompletedAt: DateTime.Utc | null;
readonly latestRunStopRequested: boolean;
+ readonly latestRunSilent: boolean;
readonly activeRunId: RunId | null;
readonly blockedOnThreadWait: boolean;
readonly activityRunStatus: ShellActivityRunStatus | null;
@@ -1890,6 +1904,7 @@ function shellFromState(input: {
latestRunStartedAt: input.state.latestRunStartedAt,
latestRunCompletedAt: input.state.latestRunCompletedAt,
latestRunStopRequested: input.state.latestRunStopRequested,
+ latestRunSilent: input.state.latestRunSilent,
activeRunId: input.state.activeRunId,
blockedOnThreadWait: input.state.blockedOnThreadWait,
activityRunStatus: input.state.activityRunStatus,
@@ -5687,6 +5702,29 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = presented.run_id
AND stop_request.type = 'run_interrupt_request'
) AS latest_run_stop_requested,
+ -- Mirrors idleCompactionOf, including JavaScript trim whitespace.
+ EXISTS (
+ SELECT 1 FROM orchestration_v2_projection_messages prompt
+ WHERE prompt.message_id = json_extract(presented.payload_json, '$.userMessageId')
+ AND prompt.role = 'user'
+ AND lower(trim(json_extract(prompt.payload_json, '$.text'),
+ char(9, 10, 11, 12, 13, 32, 160, 5760, 8192, 8193, 8194, 8195,
+ 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288, 65279)
+ )) = ${IDLE_COMPACTION_TEXT}
+ AND coalesce(json_array_length(prompt.payload_json, '$.attachments'), 0) = 0
+ AND (
+ json_extract(prompt.payload_json, '$.idleCompaction') IS NOT NULL
+ OR (
+ json_extract(prompt.payload_json, '$.createdBy') = 'agent'
+ AND json_extract(prompt.payload_json, '$.creationSource') = 'server'
+ )
+ )
+ ) AND NOT EXISTS (
+ SELECT 1 FROM orchestration_v2_projection_turn_items compaction
+ WHERE compaction.thread_id = t.thread_id AND compaction.run_id = presented.run_id
+ AND compaction.type = 'compaction'
+ AND compaction.status = 'failed'
+ ) AS latest_run_silent,
active.run_id AS active_run_id,
active.status AS active_run_status,
(
@@ -6221,6 +6259,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
? null
: DateTime.makeUnsafe(row.latest_run_completed_at);
let latestRunStopRequested = row.latest_run_stop_requested === 1;
+ let latestRunSilent = row.latest_run_silent === 1;
if (row.blocking_run_id !== null && row.blocking_failure_payload_json !== null) {
const blockingFailure = yield* decodeTurnItemPayload(
row.blocking_failure_payload_json,
@@ -6234,6 +6273,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
terminalFailureItem = blockingFailure;
latestRunId = RunId.make(row.blocking_run_id);
latestRunStopRequested = row.blocking_run_stop_requested === 1;
+ latestRunSilent = false;
latestRunStatus = "failed";
latestRunRequestedAt =
row.blocking_run_requested_at === null
@@ -6274,6 +6314,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
latestRunStartedAt,
latestRunCompletedAt,
latestRunStopRequested,
+ latestRunSilent,
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
blockedOnThreadWait: deriveBlockedOnThreadWait({
activeRun:
diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx
index dd537f2a8d0..145d6f740f0 100644
--- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx
+++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx
@@ -80,6 +80,7 @@ const thread = {
id: "thread",
title: "Test thread",
archivedAt: null as string | null,
+ latestRunSilent: false,
hasPendingApprovals: false,
hasPendingUserInput: false,
session: null as { status: string } | null,
@@ -112,6 +113,7 @@ function toV2ThreadShell(input: typeof thread) {
createdBy: "user",
creationSource: "web",
latestRunId: latestTurn.turnId,
+ latestRunSilent: input.latestRunSilent,
activeRunId: null,
status:
latestTurn.state === "completed"
@@ -186,6 +188,7 @@ function setup() {
);
let screen: Screen | undefined;
return {
+ ui,
async render() {
if (screen) await screen.rerender(ui());
else screen = stack.use(await render(ui()));
@@ -215,3 +218,23 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
expect(notification.close).toHaveBeenCalled();
},
);
+
+it.each([
+ ["pre-expiry compaction", true, "completed", []],
+ ["manual compaction", false, "completed", ["Thread completed"]],
+ ["failed pre-expiry compaction", true, "error", ["Thread failed"]],
+] as const)("notifies for %s only when attention is needed", async (_, silent, status, titles) => {
+ await using app = setup();
+ state.environmentIds = ["one"];
+ state.shells.set("one", shell({ latestRunSilent: silent }));
+ await using screen = await render(app.ui());
+ state.shells.set(
+ "one",
+ shell({
+ latestRunSilent: silent,
+ latestTurn: { turnId: "turn", state: status, completedAt: "2026-09-13T07:01:00.000Z" },
+ }),
+ );
+ await screen.rerender(app.ui());
+ expect(TestNotification.sent.map((notification) => notification.title)).toEqual(titles);
+});
diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx
index c9355fc7f82..edc1b8e2f3c 100644
--- a/apps/web/src/components/ThreadNotificationCoordinator.tsx
+++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx
@@ -155,6 +155,7 @@ function EnvironmentNotifications({
attention && attention !== prior.attention
? "input"
: !rawThread.latestRunStopRequested &&
+ !rawThread.latestRunSilent &&
completion !== null &&
(prior.completion === null || completion > prior.completion)
? "completion"
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index 616650f5461..af22e5020a7 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -7,6 +7,8 @@ import "~/index.css";
import { act, render } from "../../../test/render";
import { MessagesTimeline } from "./MessagesTimeline";
+import { makeStreamingTimelineFixture } from "../../test-fixtures";
+import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
import { collectThreadFindRanges } from "./threadFindHighlights";
@@ -386,3 +388,78 @@ describe("compact reasoning math", () => {
]);
});
});
+
+it("renders automatic compaction as one live divider that finishes with its reason and token delta", async () => {
+ setup();
+ const fixture = makeStreamingTimelineFixture();
+ const prompt = fixture.visibleTurnItems[3]!;
+ const assistant = fixture.visibleTurnItems[5]!;
+ if (prompt.item.type !== "user_message" || assistant.item.type !== "assistant_message") {
+ throw new Error("Expected streaming fixture messages");
+ }
+ const promptItem = prompt.item;
+ const compaction = {
+ ...assistant,
+ item: {
+ ...assistant.item,
+ type: "compaction" as const,
+ driver: null,
+ beforeTokenCount: 899_000,
+ },
+ };
+ const entries = (completed: boolean) =>
+ deriveTimelineEntriesFromVisibleTurnItems({
+ visibleTurnItems: [
+ {
+ ...prompt,
+ item: { ...promptItem, text: "/compact", idleCompaction: "beforeCacheExpires" },
+ },
+ {
+ ...compaction,
+ item: {
+ ...compaction.item,
+ status: completed ? "completed" : "running",
+ afterTokenCount: completed ? 19_000 : undefined,
+ },
+ },
+ ],
+ optimisticMessages: [],
+ });
+ const props = baseProps();
+ const ui = (completed: boolean) => (
+ <MessagesTimeline
+ {...props}
+ timelineEntries={entries(completed)}
+ isWorking={!completed}
+ isCompacting={!completed}
+ activeTurnInProgress={!completed}
+ activeTurnStartedAt={fixture.time(5)}
+ latestRun={{
+ runId: fixture.runId,
+ status: completed ? "completed" : "running",
+ startedAt: fixture.time(5),
+ completedAt: completed ? fixture.time(9) : null,
+ }}
+ />
+ );
+ const container = document.createElement("div");
+ container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
+ await using screen = await render(ui(false), { container });
+ await expect
+ .element(screen.getByRole("separator", { name: "Compacting before the cache expires…" }))
+ .toBeVisible();
+ expect(container.textContent).not.toContain("/compact");
+ expect(container.textContent).not.toContain("Thinking");
+ expect(container.textContent).not.toContain("Working");
+ expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
+ await screen.rerender(ui(true));
+ await expect
+ .element(
+ screen.getByRole("separator", {
+ name: "Context automatically compacted before cache expiry 899K → 19K tokens",
+ }),
+ )
+ .toBeVisible();
+ expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
+ expect(container.textContent).not.toContain("Compacting before");
+});
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index 84521d67af0..2fae89baadc 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -457,68 +457,347 @@ describe("deriveMessagesTimelineRows", () => {
},
);
- it("gives live compaction the activity slot and restores Thinking when it completes", () => {
+ it.each([false, true])(
+ "gives live compaction the activity slot and restores Thinking (runless: %s)",
+ (runless) => {
+ const fixture = makeStreamingTimelineFixture();
+ const last = fixture.visibleTurnItems.at(-1)!;
+ if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
+ const compact = {
+ ...last,
+ item: {
+ ...last.item,
+ type: "compaction" as const,
+ status: "running" as const,
+ driver: null,
+ beforeTokenCount: 899_000,
+ },
+ };
+ const input = {
+ isWorking: true,
+ runningRunId: fixture.runId,
+ activeTurnStartedAt: fixture.time(5),
+ turnDiffSummaries: [],
+ supportsConversationRollback: false,
+ };
+ const runningEntries = deriveTimelineEntriesFromVisibleTurnItems({
+ visibleTurnItems: [...fixture.visibleTurnItems.slice(0, -1), compact],
+ optimisticMessages: [],
+ });
+ const runningRows = deriveMessagesTimelineRows({
+ ...input,
+ runningRunId: runless ? null : fixture.runId,
+ runlessWorkActive: runless,
+ timelineEntries: runless
+ ? runningEntries.map((entry) =>
+ entry.kind === "work" ? { ...entry, entry: { ...entry.entry, runId: null } } : entry,
+ )
+ : runningEntries,
+ });
+ expect(runningRows.find((row) => row.kind === "context-compaction")).toMatchObject({
+ active: true,
+ label: "Compacting context",
+ });
+ expect(runningRows.some((row) => row.kind === "thinking")).toBe(false);
+
+ const completedRows = deriveMessagesTimelineRows({
+ ...input,
+ timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
+ visibleTurnItems: [
+ ...fixture.visibleTurnItems.slice(0, -1),
+ {
+ ...compact,
+ item: { ...compact.item, status: "completed", afterTokenCount: 19_000 },
+ },
+ ],
+ optimisticMessages: [],
+ }),
+ });
+ expect(completedRows.find((row) => row.kind === "context-compaction")).toMatchObject({
+ active: false,
+ label: "Context compacted 899K → 19K tokens",
+ tokenCounts: { before: "899K", after: "19K" },
+ });
+ expect(completedRows.at(-1)?.kind).toBe("thinking");
+
+ const settledRows = deriveMessagesTimelineRows({
+ ...input,
+ isWorking: false,
+ timelineEntries: runningEntries,
+ });
+ expect(settledRows.find((row) => row.kind === "context-compaction")).toMatchObject({
+ active: false,
+ });
+ const stable = computeStableMessagesTimelineRows(runningRows, {
+ result: [],
+ byId: new Map(),
+ });
+ expect(computeStableMessagesTimelineRows(settledRows, stable).result).toEqual(settledRows);
+ },
+ );
+
+ it("shows each compaction trigger as one live status, then a reasoned token divider", () => {
const fixture = makeStreamingTimelineFixture();
- const last = fixture.visibleTurnItems.at(-1)!;
- if (last.item.type !== "assistant_message") throw new Error("Expected assistant fixture");
- const compact = {
- ...last,
+ const [history0, history1, history2, liveUser, , liveAssistant] = fixture.visibleTurnItems;
+ if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message")
+ throw new Error("Expected live fixture items");
+ const compactPrompt = (idleCompaction: "beforeCacheExpires" | "onReturn" | undefined) => ({
+ ...liveUser,
+ item: { ...liveUser.item, text: "/compact", idleCompaction },
+ });
+ const compaction = {
+ ...liveAssistant,
item: {
- ...last.item,
+ ...liveAssistant.item,
type: "compaction" as const,
- status: "running" as const,
driver: null,
beforeTokenCount: 899_000,
},
};
- const input = {
- isWorking: true,
- runningRunId: fixture.runId,
- activeTurnStartedAt: fixture.time(5),
- turnDiffSummaries: [],
- supportsConversationRollback: false,
- };
- const runningEntries = deriveTimelineEntriesFromVisibleTurnItems({
- visibleTurnItems: [...fixture.visibleTurnItems.slice(0, -1), compact],
- optimisticMessages: [],
- });
- const runningRows = deriveMessagesTimelineRows({ ...input, timelineEntries: runningEntries });
- expect(runningRows.find((row) => row.kind === "context-compaction")).toMatchObject({
- active: true,
- label: "Compacting context",
- });
- expect(runningRows.some((row) => row.kind === "thinking")).toBe(false);
+ const rowsFor = (visibleTurnItems: OrchestrationV2ProjectedTurnItem[], isWorking = true) =>
+ deriveMessagesTimelineRows({
+ timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
+ visibleTurnItems: [history0!, history1!, history2!, ...visibleTurnItems],
+ optimisticMessages: [],
+ }),
+ isWorking,
+ runningRunId: fixture.runId,
+ latestRun: {
+ runId: fixture.runId,
+ status: isWorking ? "running" : "completed",
+ startedAt: fixture.time(5),
+ completedAt: isWorking ? null : fixture.time(9),
+ },
+ activeTurnStartedAt: fixture.time(5),
+ turnDiffSummaries: [],
+ supportsConversationRollback: false,
+ });
- const completedRows = deriveMessagesTimelineRows({
- ...input,
- timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
- visibleTurnItems: [
- ...fixture.visibleTurnItems.slice(0, -1),
+ // Only compacting on return holds a sent message back, so only it speaks through the working
+ // row; the others keep their live divider.
+ for (const [reason, live, title] of [
+ [
+ "beforeCacheExpires",
+ {
+ kind: "context-compaction",
+ active: true,
+ label: "Compacting before the cache expires…",
+ },
+ "Context automatically compacted before cache expiry",
+ ],
+ [
+ "onReturn",
+ { kind: "working", compacting: "Compacting after being idle…" },
+ "Context compacted after being idle",
+ ],
+ [undefined, { kind: "context-compaction", active: true }, undefined],
+ ] as const) {
+ const prompt = compactPrompt(reason);
+ for (const rows of [rowsFor([prompt]), rowsFor([prompt, compaction])]) {
+ const liveRows = rows.slice(
+ rows.findIndex((row) => row.id.includes("history-assistant")) + 1,
+ );
+ expect(liveRows).toMatchObject([live]);
+ }
+ const completed = rowsFor(
+ [
+ prompt,
{
- ...compact,
- item: { ...compact.item, status: "completed", afterTokenCount: 19_000 },
+ ...compaction,
+ item: { ...compaction.item, status: "completed", afterTokenCount: 19_000 },
},
],
- optimisticMessages: [],
- }),
- });
- expect(completedRows.find((row) => row.kind === "context-compaction")).toMatchObject({
- active: false,
- label: "Context compacted 899K → 19K tokens",
- tokenCounts: { before: "899K", after: "19K" },
- });
- expect(completedRows.at(-1)?.kind).toBe("thinking");
+ false,
+ );
+ const liveRows = completed.slice(
+ completed.findIndex((row) => row.id.includes("history-assistant")) + 1,
+ );
+ expect(liveRows).toMatchObject([
+ {
+ kind: "context-compaction",
+ active: false,
+ tokenCounts: { before: "899K", after: "19K" },
+ },
+ ]);
+ expect(liveRows[0]?.kind === "context-compaction" ? liveRows[0].title : null).toBe(title);
+ const terminalCompaction = {
+ ...compaction,
+ item: { ...compaction.item, status: "completed" as const, afterTokenCount: 19_000 },
+ };
+ const finishingRows = rowsFor([prompt, terminalCompaction]);
+ const finishingLiveRows = finishingRows.slice(
+ finishingRows.findIndex((row) => row.id.includes("history-assistant")) + 1,
+ );
+ expect(finishingLiveRows).toEqual(liveRows);
+ const continuingRows = rowsFor([
+ prompt,
+ terminalCompaction,
+ { ...liveAssistant, item: { ...liveAssistant.item, id: TurnItemId.make("continued") } },
+ ]);
+ expect(continuingRows.filter((row) => row.kind === "context-compaction")).toHaveLength(1);
+ expect(continuingRows.filter((row) => row.kind === "working")).toMatchObject([
+ { kind: "working" },
+ ]);
+ expect(continuingRows.some((row) => row.kind === "working" && row.compacting)).toBe(false);
+ const retries = rowsFor(
+ [
+ prompt,
+ {
+ ...compaction,
+ item: { ...compaction.item, status: "failed", summary: "retry needed" },
+ },
+ {
+ ...compaction,
+ item: {
+ ...compaction.item,
+ id: TurnItemId.make("retry-compaction"),
+ status: "completed",
+ },
+ },
+ ],
+ false,
+ ).filter((row) => row.kind === "context-compaction");
+ expect(retries).toHaveLength(2);
+ expect(retries[0]).toMatchObject({ failed: true, failure: "retry needed" });
+ expect(new Set(retries.map((row) => row.id)).size).toBe(2);
+ const stable = computeStableMessagesTimelineRows(retries, { result: [], byId: new Map() });
+ expect(computeStableMessagesTimelineRows(retries, stable).result).toEqual(retries);
+ }
+ });
- const settledRows = deriveMessagesTimelineRows({
- ...input,
- isWorking: false,
- timelineEntries: runningEntries,
+ it.each(["/compact", "Continue"])(
+ "keeps a completed compaction divider visible while other settled work folds for %s",
+ (promptText) => {
+ const fixture = makeStreamingTimelineFixture();
+ const [, , , liveUser, liveWork, liveAssistant] = fixture.visibleTurnItems;
+ if (
+ liveUser?.item.type !== "user_message" ||
+ liveAssistant?.item.type !== "assistant_message" ||
+ !liveWork
+ )
+ throw new Error("Expected live fixture items");
+ const rows = deriveMessagesTimelineRows({
+ timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
+ visibleTurnItems: [
+ { ...liveUser, item: { ...liveUser.item, text: promptText } },
+ liveWork,
+ {
+ ...liveAssistant,
+ item: {
+ ...liveAssistant.item,
+ type: "compaction",
+ driver: null,
+ status: "completed",
+ beforeTokenCount: 100_000,
+ afterTokenCount: 20_000,
+ },
+ },
+ ],
+ optimisticMessages: [],
+ }),
+ isWorking: false,
+ latestRun: {
+ runId: fixture.runId,
+ status: "completed",
+ startedAt: fixture.time(5),
+ completedAt: fixture.time(8),
+ },
+ turnDiffSummaries: [],
+ supportsConversationRollback: false,
+ });
+ expect(rows.filter((row) => row.kind === "turn-fold")).toHaveLength(1);
+ expect(rows.some((row) => row.kind === "work")).toBe(false);
+ expect(rows.filter((row) => row.kind === "context-compaction")).toMatchObject([
+ { active: false, tokenCounts: { before: "100K", after: "20K" } },
+ ]);
+ if (promptText === "/compact") {
+ expect(rows.some((row) => row.kind === "message")).toBe(false);
+ }
+ },
+ );
+
+ it("folds an answered compact-on-return question into its compaction row", () => {
+ const fixture = makeStreamingTimelineFixture();
+ const [history0, history1, history2, liveUser, liveWork, liveAssistant] =
+ fixture.visibleTurnItems;
+ if (liveWork?.item.type !== "dynamic_tool" || liveAssistant?.item.type !== "assistant_message")
+ throw new Error("Expected live fixture items");
+ const { toolName: _toolName, input: _input, output: _output, ...workBase } = liveWork.item;
+ const question =
+ "This session is 1h 5m old and uses 412,000 tokens. Compact it before continuing?";
+ const requestId = RuntimeRequestId.make("resume-compaction");
+ const answered = {
+ ...liveWork,
+ item: {
+ ...workBase,
+ type: "user_input_request" as const,
+ requestId,
+ questions: [],
+ questionAnswer: {
+ requestId,
+ questionTextById: { resume: question },
+ answers: { resume: "Compact and continue" },
+ attachmentsByQuestionId: {},
+ },
+ },
+ };
+ const assistantItem = liveAssistant.item;
+ const compactionAt = (status: "running" | "completed") => ({
+ ...liveAssistant,
+ item: { ...assistantItem, type: "compaction" as const, status, driver: null },
});
- expect(settledRows.find((row) => row.kind === "context-compaction")).toMatchObject({
+ const rowsFor = (status: "running" | "completed", laterCompaction = false) =>
+ deriveMessagesTimelineRows({
+ timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({
+ visibleTurnItems: [
+ history0!,
+ history1!,
+ history2!,
+ liveUser!,
+ answered,
+ compactionAt(laterCompaction ? "completed" : status),
+ ...(laterCompaction
+ ? [
+ {
+ ...compactionAt(status),
+ item: {
+ ...compactionAt(status).item,
+ id: TurnItemId.make("later-compaction"),
+ },
+ },
+ ]
+ : []),
+ ],
+ optimisticMessages: [],
+ }),
+ isWorking: status === "running",
+ runningRunId: fixture.runId,
+ activeTurnStartedAt: fixture.time(5),
+ turnDiffSummaries: [],
+ supportsConversationRollback: false,
+ });
+ const liveRows = (status: "running" | "completed") => {
+ const rows = rowsFor(status);
+ return rows.slice(rows.findIndex((row) => row.id.includes("live-user")) + 1);
+ };
+ expect(liveRows("running")).toMatchObject([
+ { kind: "working", compacting: "Compacting after 1h 5m idle…" },
+ ]);
+ expect(liveRows("completed")).toMatchObject([
+ { kind: "context-compaction", title: "Context compacted after 1h 5m idle" },
+ ]);
+ const laterRows = rowsFor("running", true);
+ const dividers = laterRows.filter((row) => row.kind === "context-compaction");
+ expect(dividers).toHaveLength(2);
+ expect(dividers[0]).toMatchObject({
+ title: "Context compacted after 1h 5m idle",
active: false,
});
- const stable = computeStableMessagesTimelineRows(runningRows, { result: [], byId: new Map() });
- expect(computeStableMessagesTimelineRows(settledRows, stable).result).toEqual(settledRows);
+ expect(dividers[1]).toMatchObject({ active: true });
+ expect(dividers[1]).not.toHaveProperty("title");
+ expect(laterRows.some((row) => row.kind === "working" && row.compacting !== undefined)).toBe(
+ false,
+ );
});
it("only enables assistant copy for the terminal assistant message in a turn", () => {
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index 5e9dd6b5395..abd091bcb66 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -8,6 +8,11 @@ import {
collectAssistantCitations,
} from "@t3tools/shared/assistantCitations";
import { shallow } from "zustand/vanilla/shallow";
+import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
+import {
+ IDLE_COMPACTING_LABELS,
+ IDLE_COMPACTION_TITLES,
+} from "@t3tools/client-runtime/user-message";
import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff";
import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives";
import {
@@ -45,7 +50,10 @@ import {
type TurnDiffSummary,
} from "../../types";
import {
+ idleCompactionOf,
+ isCompactionCommandMessage,
type MessageId,
+ type OrchestrationV2IdleCompaction,
type WorktreeSetupSnapshot,
type OrchestrationV2ProjectedTurnItem,
type RunAttemptId,
@@ -540,6 +548,8 @@ type MessagesTimelineRowContent =
kind: "working";
id: string;
createdAt: string | null;
+ /** A running compaction owns the working row, so its divider appears only once it ends. */
+ compacting?: string;
}
| {
kind: "thinking";
@@ -587,6 +597,11 @@ type MessagesTimelineRowContent =
label: string;
tokenCounts: ReturnType<typeof contextCompactionTokenCounts>;
active: boolean;
+ /** Replaces "Context compacted" when T3 Code compacted without being asked. */
+ title?: string;
+ failed?: true;
+ /** The provider's reason, when a failed compaction gave one. */
+ failure?: string;
}
| {
kind: "message";
@@ -1141,6 +1156,7 @@ function deriveTurnFolds(input: {
continue;
}
if (
+ isCompaction ||
timelineEntryIsPersistentResourceCard(entry) ||
input.liveSubagentEntryIds.has(entry.id) ||
input.completeSupersededReplyEntryIds.has(entry.id)
@@ -1572,15 +1588,94 @@ export function deriveMessagesTimelineRows(input: {
const activeWorkEntryIds = new Set(
activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [],
);
+ // A bare `/compact` turn is the compaction itself: one compaction row stands in for its prompt
+ // and working indicator, from the moment the turn starts. Likewise an answered "compact before
+ // continuing?" question folds into the compaction it asked for.
+ const compactionRuns = new Map<RunId, OrchestrationV2IdleCompaction | undefined>();
+ const compactedRunIds = new Set<RunId>();
+ const pendingResumeCompactionAgeByRunId = new Map<RunId, string>();
+ const resumeCompactionAgeByEntryId = new Map<string, string>();
+ for (const entry of timelineEntries) {
+ if (
+ entry.kind === "message" &&
+ entry.message.runId !== null &&
+ isCompactionCommandMessage(entry.message)
+ ) {
+ compactionRuns.set(entry.message.runId, idleCompactionOf(entry.message));
+ } else if (entry.kind === "work" && entry.entry.runId) {
+ if (timelineEntryIsCompaction(entry)) {
+ compactedRunIds.add(entry.entry.runId);
+ const age = pendingResumeCompactionAgeByRunId.get(entry.entry.runId);
+ if (age !== undefined) {
+ resumeCompactionAgeByEntryId.set(entry.id, age);
+ pendingResumeCompactionAgeByRunId.delete(entry.entry.runId);
+ }
+ }
+ const age = entry.entry.questionAnswer
+ ? claudeResumeCompactionAge(entry.entry.questionAnswer)
+ : null;
+ if (age !== null) pendingResumeCompactionAgeByRunId.set(entry.entry.runId, age);
+ }
+ }
+ const compactionTitle = (runId: RunId | null | undefined, entryId: string) => {
+ if (runId == null) return undefined;
+ const reason = compactionRuns.get(runId);
+ if (reason !== undefined) return IDLE_COMPACTION_TITLES[reason];
+ const age = resumeCompactionAgeByEntryId.get(entryId);
+ return age ? `Context compacted after ${age} idle` : undefined;
+ };
+ const activeCompactionEntry = timelineEntries.find(
+ (entry): entry is Extract<TimelineEntry, { kind: "work" }> =>
+ timelineEntryIsCompaction(entry) &&
+ entry.kind === "work" &&
+ workEntryIsInActiveRun(entry.entry),
+ );
+ const activeRunIsCompaction =
+ input.isWorking && unsettledRunId !== null && compactionRuns.has(unsettledRunId);
+ // The item can finish before its run settles; only other work should keep activity visible.
+ const compactionRunFinished =
+ activeRunIsCompaction &&
+ compactedRunIds.has(unsettledRunId) &&
+ activeCompactionEntry === undefined;
+ const compactionOnlyRunFinished =
+ compactionRunFinished &&
+ !timelineEntries.some(
+ (entry) =>
+ timelineEntryRunId(entry) === unsettledRunId &&
+ !timelineEntryIsCompaction(entry) &&
+ !(entry.kind === "message" && isCompactionCommandMessage(entry.message)),
+ );
+ const runningCompactionRunId =
+ activeRunIsCompaction && !compactionRunFinished ? unsettledRunId : null;
+ // Compacting on return holds back the message the user just sent, so the working row says why
+ // it is waiting. Any other compaction shows only its live divider, never both.
+ const activeCompactionRunId =
+ runningCompactionRunId !== null && compactionRuns.get(runningCompactionRunId) === "onReturn"
+ ? runningCompactionRunId
+ : activeCompactionEntry?.entry.runId != null &&
+ resumeCompactionAgeByEntryId.has(activeCompactionEntry.id)
+ ? activeCompactionEntry.entry.runId
+ : null;
+ const compactingLabel = (() => {
+ if (activeCompactionRunId === null) return undefined;
+ const age = activeCompactionEntry
+ ? resumeCompactionAgeByEntryId.get(activeCompactionEntry.id)
+ : undefined;
+ return age ? `Compacting after ${age} idle…` : IDLE_COMPACTING_LABELS.onReturn;
+ })();
const appendWorkingRow = () => {
+ if (compactionOnlyRunFinished) return;
+ if (runningCompactionRunId !== null && activeCompactionRunId === null) return;
nextRows.push({
kind: "working",
id: "working-indicator-row",
createdAt: input.activeTurnStartedAt ?? null,
+ ...(compactingLabel ? { compacting: compactingLabel } : {}),
});
};
let hasActivityRow = false;
- let hasActiveCompaction = false;
+ const hasActiveCompaction =
+ activeCompactionEntry !== undefined || (activeRunIsCompaction && !compactionRunFinished);
const appendActiveWorkRows = () => {
if (activeWorkRow === null) return;
nextRows.push(activeWorkRow);
@@ -1658,13 +1753,26 @@ export function deriveMessagesTimelineRows(input: {
timelineEntry.entry.sourceActivityKind === "context-compaction"
) {
const active = workEntryIsInActiveRun(timelineEntry.entry);
- hasActiveCompaction ||= active;
+ if (
+ active &&
+ activeCompactionRunId !== null &&
+ timelineEntry.entry.runId === activeCompactionRunId
+ )
+ continue;
const compaction = timelineEntry.entry.structuredPayload;
+ const compactionRunId = timelineEntry.entry.runId;
+ const title = compactionTitle(compactionRunId, timelineEntry.id);
+ const reason = compactionRunId == null ? undefined : compactionRuns.get(compactionRunId);
+ const failed = compaction?.type === "compaction" && compaction.status === "failed";
+ const failure = failed ? compaction.summary?.trim() || undefined : undefined;
nextRows.push({
kind: "context-compaction",
id: timelineEntry.id,
+ ...(title ? { title } : {}),
+ ...(failed ? { failed: true } : {}),
+ ...(failure ? { failure } : {}),
createdAt: timelineEntry.createdAt,
- label: timelineEntry.entry.label,
+ label: active && reason ? IDLE_COMPACTING_LABELS[reason] : timelineEntry.entry.label,
tokenCounts:
compaction?.type === "compaction" ? contextCompactionTokenCounts(compaction) : null,
active,
@@ -1672,6 +1780,16 @@ export function deriveMessagesTimelineRows(input: {
continue;
}
+ if (
+ timelineEntry.kind === "work" &&
+ timelineEntry.entry.runId != null &&
+ compactedRunIds.has(timelineEntry.entry.runId) &&
+ timelineEntry.entry.questionAnswer !== undefined &&
+ claudeResumeCompactionAge(timelineEntry.entry.questionAnswer) !== null
+ ) {
+ continue;
+ }
+
if (timelineEntry.kind === "work") {
if (
(timelineEntry.entry.runId != null && failedRunIds.has(timelineEntry.entry.runId)) ||
@@ -1882,6 +2000,29 @@ export function deriveMessagesTimelineRows(input: {
continue;
}
+ const compactionRunId = timelineEntry.message.runId;
+ const compactionRun =
+ compactionRunId !== null && isCompactionCommandMessage(timelineEntry.message);
+ if (compactionRun) {
+ if (!compactedRunIds.has(compactionRunId) && compactionRunId !== activeCompactionRunId) {
+ const pending = compactionRunId === runningCompactionRunId;
+ const reason = compactionRuns.get(compactionRunId);
+ nextRows.push({
+ kind: "context-compaction",
+ id: `compaction:${compactionRunId}`,
+ createdAt: timelineEntry.createdAt,
+ label: pending
+ ? reason
+ ? IDLE_COMPACTING_LABELS[reason]
+ : "Compacting context"
+ : "Context compaction",
+ tokenCounts: null,
+ active: pending,
+ });
+ }
+ continue;
+ }
+
const assistantResponseStillInProgress =
timelineEntry.message.role === "assistant" &&
runIdIsActiveResponse(timelineEntry.message.runId);
@@ -1969,6 +2110,7 @@ export function deriveMessagesTimelineRows(input: {
input.latestRun?.turnEnded !== true &&
!setupOwnsWorkingSlot &&
!hasActiveCompaction &&
+ !compactionOnlyRunFinished &&
(!hasActivityRow || latestToolFailed)
) {
const failedGroupAnchor = latestToolFailed ? activeWorkAnchor : undefined;
@@ -2237,7 +2379,9 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
switch (a.kind) {
case "working":
- return a.createdAt === (b as typeof a).createdAt;
+ return (
+ a.createdAt === (b as typeof a).createdAt && a.compacting === (b as typeof a).compacting
+ );
case "thinking": {
const bt = b as typeof a;
return a.createdAt === bt.createdAt && a.groupId === bt.groupId && a.expanded === bt.expanded;
@@ -2268,7 +2412,14 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
case "context-compaction": {
const bc = b as typeof a;
- return a.createdAt === bc.createdAt && a.label === bc.label && a.active === bc.active;
+ return (
+ a.createdAt === bc.createdAt &&
+ a.label === bc.label &&
+ a.active === bc.active &&
+ a.title === bc.title &&
+ a.failed === bc.failed &&
+ a.failure === bc.failure
+ );
}
case "proposed-plan":
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 19b1aeb55a5..ee61f27e20c 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -43,7 +43,7 @@ import {
import { type TimelineEntry } from "../../session-logic";
import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
import { type ChatFileAttachment, type TurnDiffSummary } from "../../types";
-import { ArrowRightIcon, BotIcon, Minimize2Icon } from "lucide-react";
+import { ArrowRightIcon, BotIcon, CircleAlertIcon, Minimize2Icon } from "lucide-react";
import { ChevronDown, ChevronRight } from "lucide";
import { MorphIcon } from "~/components/MorphIcon";
import { ExpandedImagePreview } from "./ExpandedImagePreview";
@@ -946,7 +946,12 @@ const ConversationTimeline = memo(function ConversationTimeline({
workGroupViewState,
};
const compactionAwaitingRow =
- isCompacting && !rows.some((row) => row.kind === "context-compaction" && row.active);
+ isCompacting &&
+ !rows.some(
+ (row) =>
+ (row.kind === "context-compaction" && row.active) ||
+ (row.kind === "working" && row.compacting),
+ );
const backgroundWorktreeSetup =
worktreeSetup !== null &&
worktreeSetup.phase === "running" &&
@@ -1336,35 +1341,49 @@ function ContextCompactionTimelineRow({
}: {
row: Extract<TimelineRow, { kind: "context-compaction" }>;
}) {
+ const label =
+ row.title && row.label.startsWith("Context compacted")
+ ? row.title + row.label.slice("Context compacted".length)
+ : row.label;
const content = (
- <span className="flex items-center gap-1.5">
- <Minimize2Icon aria-hidden="true" className="size-3" />
+ <span className="flex min-w-0 items-center gap-1.5">
+ {row.failed ? (
+ <CircleAlertIcon aria-hidden="true" className="size-3 shrink-0" />
+ ) : (
+ <Minimize2Icon aria-hidden="true" className="size-3" />
+ )}
{row.tokenCounts ? (
<>
- Context compacted {row.tokenCounts.before}
+ {row.title ?? "Context compacted"} {row.tokenCounts.before}
<ArrowRightIcon aria-hidden="true" className="size-3" />
{row.tokenCounts.after} tokens
</>
) : (
- row.label
+ label
)}
+ {row.failure ? (
+ <span className="min-w-0 truncate opacity-80">&middot; {row.failure}</span>
+ ) : null}
</span>
);
return (
<div
role="separator"
- aria-label={row.label}
- className="mx-auto flex w-full max-w-(--chat-content-max-width) items-center gap-3 py-1 text-muted-foreground text-xs"
+ aria-label={row.failure ? `${label}: ${row.failure}` : label}
+ className={cn(
+ "mx-auto flex w-full max-w-(--chat-content-max-width) items-center gap-3 py-1 text-xs",
+ row.failed ? "text-destructive" : "text-muted-foreground",
+ )}
>
- <span className="h-px flex-1 bg-border/70" />
+ <span className={cn("h-px flex-1", row.failed ? "bg-destructive/30" : "bg-border/70")} />
<span
ref={row.active ? observeVisibleAnimation : undefined}
- className="relative shrink-0 overflow-hidden"
+ className="relative min-w-0 overflow-hidden"
>
{content}
{row.active ? <ActivityShimmerOverlay>{content}</ActivityShimmerOverlay> : null}
</span>
- <span className="h-px flex-1 bg-border/70" />
+ <span className={cn("h-px flex-1", row.failed ? "bg-destructive/30" : "bg-border/70")} />
</div>
);
}
diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
index 07d6164817c..90e15502e0a 100644
--- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
+++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
@@ -286,11 +286,12 @@ const workEntryKey = (entry: TimelineWorkEntry) => entry.id;
export function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
const { isCompacting, isPreparingWorktree, backgroundWorktreeSetup } =
use(TimelineRowActivityCtx);
- const shimmer = isPreparingWorktree || isCompacting;
+ const compacting = row.compacting ?? (isCompacting ? "Compacting…" : undefined);
+ const shimmer = isPreparingWorktree || compacting !== undefined;
const label = isPreparingWorktree ? (
"Setting up worktree…"
- ) : isCompacting ? (
- <CompactingLabel />
+ ) : compacting !== undefined ? (
+ <CompactingLabel label={compacting} />
) : row.createdAt ? (
<>
Working for <WorkingTimer createdAt={row.createdAt} />
@@ -350,11 +351,11 @@ function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnap
);
}
-function CompactingLabel() {
+function CompactingLabel({ label }: { label: string }) {
return (
<span className="inline-flex items-center gap-1.5">
<Minimize2Icon aria-hidden="true" className="size-3" />
- Compacting…
+ {label}
</span>
);
}
diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts
index ed7def98c88..597cafb35e9 100644
--- a/apps/web/src/components/chat/useComposerSend.ts
+++ b/apps/web/src/components/chat/useComposerSend.ts
@@ -1199,7 +1199,13 @@ export function useComposerSend(input: ComposerSendInput) {
environmentId,
input: {
threadId: threadIdForSend,
- message: { messageId: newMessageId(), role: "user", text: "/compact", attachments: [] },
+ message: {
+ messageId: newMessageId(),
+ role: "user",
+ text: "/compact",
+ attachments: [],
+ idleCompaction: "onReturn",
+ },
modelSelection: ctxSelectedModelSelection,
runtimeMode,
interactionMode: sendInteractionMode,
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index 1c2b06be8bb..57660b1b1d8 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -714,6 +714,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems(
createdBy: item.createdBy,
creationSource: item.creationSource,
...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
+ ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
...(item.scheduledTaskId !== undefined
? { scheduledTaskId: item.scheduledTaskId }
: {}),
diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts
index b485368671d..22fc2adf376 100644
--- a/apps/web/src/types.ts
+++ b/apps/web/src/types.ts
@@ -92,6 +92,7 @@ export interface ChatMessage {
readonly creationSource?: OrchestrationV2CreationSource;
readonly scheduledTaskId?: ScheduledTaskId;
readonly senderThreadId?: ThreadId;
+ readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
readonly createdAt: string;
readonly updatedAt: string;
readonly inputIntent?: OrchestrationV2UserMessageInputIntent | undefined;
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index d5cd4247b5a..8a626ac28e7 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -169,6 +169,7 @@ export interface StartThreadTurnInput extends ThreadCommandInput {
readonly text: string;
readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
readonly context?: import("@t3tools/contracts").OrchestrationMessageContext;
+ readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
};
readonly modelSelection?: ModelSelection;
readonly titleSeed?: string;
@@ -704,6 +705,9 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
: { manualContinuationOfRunId: input.manualContinuationOfRunId }),
text: input.message.text,
...(context ? { context } : {}),
+ ...(input.message.idleCompaction === undefined
+ ? {}
+ : { idleCompaction: input.message.idleCompaction }),
attachments,
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
...(input.sourceProposedPlan === undefined
@@ -765,6 +769,9 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
messageId: input.message.messageId,
text: input.message.text,
...(context ? { context } : {}),
+ ...(input.message.idleCompaction === undefined
+ ? {}
+ : { idleCompaction: input.message.idleCompaction }),
attachments,
...(shouldSendTitleSeed ? { titleSeed: input.titleSeed } : {}),
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
diff --git a/packages/client-runtime/src/userMessage.ts b/packages/client-runtime/src/userMessage.ts
index 49794123266..93ed98f35fe 100644
--- a/packages/client-runtime/src/userMessage.ts
+++ b/packages/client-runtime/src/userMessage.ts
@@ -1,9 +1,22 @@
import {
type OrchestrationV2Actor,
type OrchestrationV2CreationSource,
+ type OrchestrationV2IdleCompaction,
ScheduledTaskId,
} from "@t3tools/contracts";
+/** The working row while T3 Code's own compaction runs. */
+export const IDLE_COMPACTING_LABELS = {
+ beforeCacheExpires: "Compacting before the cache expires…",
+ onReturn: "Compacting after being idle…",
+} satisfies Record<OrchestrationV2IdleCompaction, string>;
+
+/** Leads the finished compaction's token counts, in place of "Context compacted". */
+export const IDLE_COMPACTION_TITLES = {
+ beforeCacheExpires: "Context automatically compacted before cache expiry",
+ onReturn: "Context compacted after being idle",
+} satisfies Record<OrchestrationV2IdleCompaction, string>;
+
const LEGACY_AUTOMATION_PREFIX = /^\[Triggered by schedule task: [^\r\n]+\]\r?\n\r?\n/;
const LEGACY_AUTOMATION_MESSAGE_ID = /^scheduled-task-message:(.+):\d+:(?:scheduled|manual)$/;
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index 550da8985df..a8d21845ad5 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -473,6 +473,38 @@ export function isProviderNativeSubagentThread(
return thread.lineage.relationshipToParent === "subagent" && thread.creationSource === "provider";
}
+export const IDLE_COMPACTION_TEXT = "/compact";
+
+interface CompactionMessageFields {
+ readonly role: string;
+ readonly text: string;
+ readonly attachments?: ReadonlyArray<unknown> | undefined;
+ readonly createdBy?: OrchestrationV2Actor | undefined;
+ readonly creationSource?: OrchestrationV2CreationSource | undefined;
+ readonly idleCompaction?: OrchestrationV2IdleCompaction | undefined;
+}
+
+/** A prompt that only asks the provider to compact, so its turn is the compaction itself. */
+export function isCompactionCommandMessage(message: CompactionMessageFields): boolean {
+ return (
+ message.role === "user" &&
+ message.text.trim().toLowerCase() === IDLE_COMPACTION_TEXT &&
+ (message.attachments?.length ?? 0) === 0
+ );
+}
+
+/** Why T3 Code sent this `/compact` on its own, or undefined for one someone asked for. */
+export function idleCompactionOf(
+ message: CompactionMessageFields,
+): OrchestrationV2IdleCompaction | undefined {
+ if (!isCompactionCommandMessage(message)) return undefined;
+ if (message.idleCompaction !== undefined) return message.idleCompaction;
+ // Servers before `idleCompaction` marked their own as agent-created.
+ return message.createdBy === "agent" && message.creationSource === "server"
+ ? "beforeCacheExpires"
+ : undefined;
+}
+
export const OrchestrationV2RunStatus = Schema.Literals([
"preparing",
"queued",
@@ -1116,11 +1148,16 @@ export const OrchestrationV2Notification = Schema.Struct({
});
export type OrchestrationV2Notification = typeof OrchestrationV2Notification.Type;
+/** Why T3 Code compacted a thread on its own, on the `/compact` it sent. */
+export const OrchestrationV2IdleCompaction = Schema.Literals(["beforeCacheExpires", "onReturn"]);
+export type OrchestrationV2IdleCompaction = typeof OrchestrationV2IdleCompaction.Type;
+
export const OrchestrationV2ConversationMessage = Schema.Struct({
notification: Schema.optional(OrchestrationV2Notification),
...OrchestrationV2CreationFields,
scheduledTaskId: Schema.optional(ScheduledTaskId),
senderThreadId: Schema.optional(ThreadId),
+ idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
/**
* The message is the script a provider-native workflow run executes, not prose. Clients show
* the workflow's opening instead and keep the script behind a disclosure.
@@ -1377,6 +1414,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
messageId: MessageId,
scheduledTaskId: Schema.optional(ScheduledTaskId),
senderThreadId: Schema.optional(ThreadId),
+ idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
inputIntent: OrchestrationV2UserMessageInputIntent,
text: Schema.String,
@@ -1857,6 +1895,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
latestRunStopRequested: Schema.optional(Schema.Boolean),
+ /** Suppress routine notifications for idle compaction; failures still notify. */
+ latestRunSilent: Schema.optional(Schema.Boolean),
activeRunId: Schema.NullOr(RunId),
activityRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
activityRunStatus: Schema.optional(
@@ -2141,6 +2181,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
messageId: MessageId,
scheduledTaskId: Schema.optional(ScheduledTaskId),
senderThreadId: Schema.optional(ThreadId),
+ idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript,
inputIntent: OrchestrationV2UserMessageInputIntent,
text: Schema.String,
@@ -2832,6 +2873,7 @@ export const OrchestrationV2Command = Schema.Union([
...OrchestrationV2CreationFields,
scheduledTaskId: Schema.optional(ScheduledTaskId),
senderThreadId: Schema.optional(ThreadId),
+ idleCompaction: Schema.optional(OrchestrationV2IdleCompaction),
commandId: CommandId,
threadId: ThreadId,
messageId: MessageId,
diff --git a/packages/shared/src/agentAwareness.test.ts b/packages/shared/src/agentAwareness.test.ts
index 8e60d263ff6..83d85cd5a33 100644
--- a/packages/shared/src/agentAwareness.test.ts
+++ b/packages/shared/src/agentAwareness.test.ts
@@ -63,6 +63,20 @@ describe("projectThreadAwarenessV2", () => {
).toBeNull();
});
+ it.each([
+ ["running", null],
+ ["completed", null],
+ ["failed", "failed"],
+ ] as const)("keeps an idle compaction's %s run quiet unless it fails", (status, phase) => {
+ expect(
+ projectThreadAwarenessV2({
+ environmentId: "env-1" as EnvironmentId,
+ project,
+ thread: { ...v2Thread({ status }), latestRunSilent: true },
+ })?.phase ?? null,
+ ).toBe(phase);
+ });
+
it.each(["running", "completed", "failed"] as const)(
"does not publish %s subagent activity",
(status) => {
diff --git a/packages/shared/src/agentAwareness.ts b/packages/shared/src/agentAwareness.ts
index df912b4bb0f..4bc0937adf9 100644
--- a/packages/shared/src/agentAwareness.ts
+++ b/packages/shared/src/agentAwareness.ts
@@ -46,6 +46,7 @@ export interface ProjectThreadAwarenessV2Input {
| "id"
| "lineage"
| "latestRunStopRequested"
+ | "latestRunSilent"
| "modelSelection"
| "pendingBackgroundTasks"
| "pendingRuntimeRequest"
@@ -66,6 +67,11 @@ export function projectThreadAwarenessV2(
return null;
}
if (phase === "completed" && thread.latestRunStopRequested === true) return null;
+ if (
+ thread.latestRunSilent === true &&
+ (phase === "starting" || phase === "running" || phase === "completed")
+ )
+ return null;
// Resolve the phase first so live or waiting work stays visible after settlement.
if (
thread.settledOverride === "settled" &&
diff --git a/packages/shared/src/claudeCompaction.ts b/packages/shared/src/claudeCompaction.ts
index b20b9954040..cebaf5c42ab 100644
--- a/packages/shared/src/claudeCompaction.ts
+++ b/packages/shared/src/claudeCompaction.ts
@@ -6,6 +6,7 @@
* live here: reword the question or the answer label in this file only.
*/
export const CLAUDE_RESUME_COMPACTION_NEVER_ANSWER = "Don't ask again";
+export const CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER = "Compact and continue";
export function formatClaudeResumeCompactionQuestion(input: {
readonly ageMinutes: number;
@@ -19,12 +20,30 @@ export function formatClaudeResumeCompactionQuestion(input: {
}
const CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN =
- /^This session is (?:\d+h \d+m|\d+m) old and uses \d{1,3}(?:,\d{3})* tokens\. Compact it before continuing\?$/u;
+ /^This session is (\d+h \d+m|\d+m) old and uses \d{1,3}(?:,\d{3})* tokens\. Compact it before continuing\?$/u;
export function isClaudeResumeCompactionQuestion(question: string): boolean {
return CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN.test(question);
}
+/**
+ * The session age from an answered resume question whose answer was to compact, or null. Answers
+ * are keyed by question id, and the id may itself be the question text.
+ */
+export function claudeResumeCompactionAge(questionAnswer: {
+ readonly questionTextById?: Readonly<Record<string, string>> | undefined;
+ readonly answers: Readonly<Record<string, unknown>>;
+}): string | null {
+ for (const [id, answer] of Object.entries(questionAnswer.answers)) {
+ const age = CLAUDE_RESUME_COMPACTION_QUESTION_PATTERN.exec(
+ questionAnswer.questionTextById?.[id] ?? id,
+ )?.[1];
+ const chosen = Array.isArray(answer) ? answer : [answer];
+ if (age !== undefined && chosen.includes(CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER)) return age;
+ }
+ return null;
+}
+
/**
* Context size below which T3 does not suggest or run a Claude compaction:
* the stale-thread Compact chip and idle compaction. Matches Claude Code's