Skip to content
TypeScript

feat: /clear starts a fresh session in the same thread (#30325)

Julius Marminge99e361e4153f
diff --git a/apps/mobile/src/features/threads/FreshSessionNotice.tsx b/apps/mobile/src/features/threads/FreshSessionNotice.tsx
new file mode 100644
index 00000000000..43ad7e6f32b
--- /dev/null
+++ b/apps/mobile/src/features/threads/FreshSessionNotice.tsx
@@ -0,0 +1,20 @@
+import { View } from "react-native";
+
+import { Notice } from "../../components/ui/Notice";
+import { setFreshSessionPending, useComposerDraftSettings } from "../../state/use-composer-drafts";
+
+/** Shown while `/clear` is armed; dismissing it keeps the current session. */
+export function FreshSessionNotice(props: { readonly threadKey: string }) {
+ if (useComposerDraftSettings(props.threadKey).freshContext !== true) return null;
+ return (
+ <View className="px-4 pb-3">
+ <Notice
+ message="Your next message starts a fresh session. The agent won't see earlier messages in this thread."
+ icon="arrow.clockwise"
+ floating
+ onDismiss={() => setFreshSessionPending(props.threadKey, false)}
+ dismissLabel="Keep the current session"
+ />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index f68f9787f49..0de134de7c2 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -215,6 +215,8 @@ export interface ThreadComposerProps {
readonly selectedThread: EnvironmentThreadShell;
readonly reportedModelSelection?: ModelSelection | null;
readonly hasCompactableConversation: boolean;
+ /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
+ readonly onFreshSession?: () => void;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
@@ -561,6 +563,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
offersUsageLimits: usageLimitsOffered,
onUsageLimits:
usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
+ ...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }),
});
const voiceInput = useVoiceInputController({
ownerKey: composerDraftKey,
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index c7a37b2938f..0d3258dd3be 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -129,7 +129,7 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
-import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
+import { getComposerDraftSnapshot, setFreshSessionPending } from "../../state/use-composer-drafts";
import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
import {
ANDROID_READING_MAX_WIDTH,
@@ -174,6 +174,7 @@ import type {
import { PendingApprovalCard } from "./PendingApprovalCard";
import { ComposerErrorNotice } from "./ComposerErrorNotice";
import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
+import { FreshSessionNotice } from "./FreshSessionNotice";
import { ComposerFeedback } from "./ComposerFeedback";
import { ComposerUsageLimits } from "./ComposerUsageLimits";
import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -890,6 +891,15 @@ function ThreadDetailBody(
jumpMessageLoaded,
selectedThreadKey,
]);
+ // A queued-run edit, question or approval owns the composer, and its send carries no fresh session.
+ const freshSessionAvailable =
+ !props.draftMode &&
+ props.canOperateThread &&
+ props.queuedRunEdit === null &&
+ props.activePendingApproval === null &&
+ props.activePendingUserInput === null &&
+ props.selectedThread.latestRun != null &&
+ props.serverConfig?.environment.capabilities.freshContext === true;
const hasCompactableConversation =
selectedThreadFeed.some(
(entry) =>
@@ -1638,6 +1648,9 @@ function ThreadDetailBody(
onDismiss={() => props.onDismissFeedback(submission.id)}
/>
))}
+ {freshSessionAvailable ? (
+ <FreshSessionNotice threadKey={selectedThreadKey} />
+ ) : null}
{props.canOperateThread ? (
<ManagedRuntimeModeNotice
threadKey={selectedThreadKey}
@@ -1801,6 +1814,11 @@ function ThreadDetailBody(
hasCompactableConversation={
hasCompactableConversation && !props.isCompacting
}
+ {...(freshSessionAvailable
+ ? {
+ onFreshSession: () => setFreshSessionPending(selectedThreadKey, true),
+ }
+ : {})}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 1abfb6061a6..a15037a5bc6 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -3730,6 +3730,15 @@ export const ThreadFeed = memo(function ThreadFeed({
workspaceRoot={props.workspaceRoot}
>
<ThreadMediaVisibility>
+ {info.item.type === "message" &&
+ info.item.message.projectedItem?.item.type === "user_message" &&
+ info.item.message.projectedItem.item.freshContext ? (
+ <ThreadContextDivider
+ label="New session"
+ icon="arrow.clockwise"
+ iconColor={iconSubtleColor}
+ />
+ ) : null}
{info.item.type === "message" &&
!isCompactionCommandFeedEntry(info.item) &&
info.item.message.projectedItem?.item.type === "user_message" &&
diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
index 3d26799c450..82c7df56da2 100644
--- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx
+++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
@@ -238,7 +238,10 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
{queuedRuns.map(({ run, text, attachments, context, message }, index) => {
const controls = resolveThreadQueueRowControls({
busy: busyRunId !== null,
- canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
+ // A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
+ canPromoteToSteer:
+ (workflow?.canPromoteToSteer ?? false) &&
+ (run.freshContext !== true || workflow?.promoteSkipsCompaction === true),
canSendNow: workflow?.canSendNow ?? false,
editBlocked: editBlockedReason !== null,
isEditing: editing?.runId === run.id,
diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.test.ts b/apps/mobile/src/features/threads/use-composer-command-menu.test.ts
index c0044a74f79..253c8d9e806 100644
--- a/apps/mobile/src/features/threads/use-composer-command-menu.test.ts
+++ b/apps/mobile/src/features/threads/use-composer-command-menu.test.ts
@@ -94,6 +94,25 @@ describe("mobile slash commands", () => {
},
);
+ it("offers T3's /clear in place of the provider's, only at the message start", () => {
+ const claude = {
+ driver: ProviderDriverKind.make("claudeAgent"),
+ slashCommands: [{ name: "clear", description: "Clear conversation history" }],
+ };
+ const build = (offersFreshSession: boolean, atMessageStart = true) =>
+ buildComposerSlashCommandItems({
+ query: "cle",
+ atMessageStart,
+ hasThread: true,
+ allowInteractionMode: true,
+ offersFreshSession,
+ selectedProviderStatus: claude,
+ }).map((item) => item.id);
+ expect(build(true)).toEqual(["cmd:clear"]);
+ expect(build(false)).toEqual(["pcmd:clear"]);
+ expect(build(true, false)).toEqual([]);
+ });
+
it("still applies the T3 plan command for supported providers", () => {
const items = buildComposerSlashCommandItems({
query: "plan",
diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts
index 72987599f48..4363f26ad3b 100644
--- a/apps/mobile/src/features/threads/use-composer-command-menu.ts
+++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts
@@ -104,6 +104,8 @@ export function buildComposerSlashCommandItems(input: {
readonly hasThread: boolean;
readonly hasCompactableConversation?: boolean;
readonly offersUsageLimits?: boolean;
+ /** T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live. */
+ readonly offersFreshSession?: boolean;
readonly allowInteractionMode: boolean;
readonly selectedProviderStatus: Pick<
ServerProvider,
@@ -141,10 +143,20 @@ export function buildComposerSlashCommandItems(input: {
);
// Providers expand commands only at the start of a message. T3 commands
- // change local state and do not have this restriction.
+ // change local state and do not have this restriction, except `/clear`.
if (!input.atMessageStart) return items;
+ if (input.offersFreshSession && "clear".includes(query)) {
+ items.push({
+ id: "cmd:clear",
+ type: "slash-command",
+ command: "clear",
+ label: "/clear",
+ description: "Start a fresh session",
+ });
+ }
for (const command of input.selectedProviderStatus?.slashCommands ?? []) {
if (!command.name.toLowerCase().includes(query)) continue;
+ if (command.name === "clear" && input.offersFreshSession) continue;
if (command.name === "compact" && !input.hasCompactableConversation) continue;
if (command.name === USAGE_LIMITS_COMMAND.name && input.offersUsageLimits && !input.hasThread) {
continue;
@@ -225,6 +237,7 @@ export function useComposerCommandMenu({
onChangeDraftMessage,
onUpdateInteractionMode,
onUsageLimits,
+ onFreshSession,
}: {
readonly draftMessage: string;
readonly ownerKey: string | null;
@@ -246,6 +259,8 @@ export function useComposerCommandMenu({
readonly onChangeDraftMessage: (value: string) => void;
readonly onUpdateInteractionMode?: (mode: ProviderInteractionMode) => void;
readonly onUsageLimits?: () => void;
+ /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
+ readonly onFreshSession?: () => void;
}) {
const [localSelection, setLocalSelection] = useState(() => ({
ownerKey,
@@ -349,6 +364,7 @@ export function useComposerCommandMenu({
hasThread,
hasCompactableConversation,
offersUsageLimits,
+ offersFreshSession: onFreshSession !== undefined,
allowInteractionMode: onUpdateInteractionMode !== undefined,
selectedProviderStatus: selectedProviderStatus
? {
@@ -582,6 +598,13 @@ export function useComposerCommandMenu({
return;
}
+ if (item.type === "slash-command" && item.command === "clear" && onFreshSession) {
+ const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
+ setSelection({ start: cleared.cursor, end: cleared.cursor });
+ onChangeDraftMessage(cleared.text);
+ onFreshSession();
+ return;
+ }
if (
item.type === "provider-slash-command" &&
item.command.name === USAGE_LIMITS_COMMAND.name &&
diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts
index 703d9f8450f..4796ec19f27 100644
--- a/apps/mobile/src/state/thread-outbox-model.ts
+++ b/apps/mobile/src/state/thread-outbox-model.ts
@@ -57,6 +57,7 @@ export const QueuedThreadMessageSchema = Schema.Struct({
modelSelection: Schema.optional(ModelSelection),
dispatchMode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
compactBeforeSend: Schema.optional(Schema.Boolean),
+ freshContext: Schema.optional(Schema.Boolean),
runtimeMode: Schema.optional(RuntimeMode),
interactionMode: Schema.optional(ProviderInteractionMode),
creation: Schema.optional(QueuedThreadCreationSchema),
@@ -92,6 +93,8 @@ export interface QueuedThreadMessage {
readonly dispatchMode?: ComposerDispatchMode;
/** Sends "When you return"'s `/compact` ahead of the message, which queues behind it. */
readonly compactBeforeSend?: boolean;
+ /** Starts a new provider session (`/clear`). */
+ readonly freshContext?: boolean;
readonly creation?: QueuedThreadCreation;
readonly createdAt: string;
}
diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.ts
index adf72cc6527..c1f83f5a620 100644
--- a/apps/mobile/src/state/thread-task-permissions.test.ts
+++ b/apps/mobile/src/state/thread-task-permissions.test.ts
@@ -19,6 +19,7 @@ import {
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
import { sendApprovalFeedback } from "@t3tools/client-runtime/state/thread-requests";
+import { DateTime } from "effect";
import { AsyncResult, type Atom } from "effect/reactivity";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
@@ -34,6 +35,9 @@ const state = vi.hoisted(() => ({
projection: null as OrchestrationV2ThreadProjection | null,
pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests,
enqueue: vi.fn(async () => undefined),
+ freshPending: false,
+ compactDue: false,
+ setFreshPending: vi.fn(),
clearDraft: vi.fn(),
approve: vi.fn(),
answer: vi.fn(),
@@ -54,7 +58,7 @@ const state = vi.hoisted(() => ({
runtimeMode: "full-access",
interactionMode: "default",
runtime: null,
- latestRun: null,
+ latestRun: null as unknown,
},
}));
@@ -70,6 +74,10 @@ vi.mock("react", () => ({
],
}));
vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
+vi.mock("@t3tools/client-runtime/state/context-window", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@t3tools/client-runtime/state/context-window")>()),
+ shouldCompactBeforeSend: () => state.compactDue,
+}));
vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
vi.mock("./queued-run-edit", () => ({
@@ -142,6 +150,8 @@ vi.mock("./use-composer-drafts", async () => {
composerDraftsAtom: Atom.make({}),
composerContextImportsAtom: Atom.make({}),
getComposerDraftSnapshot: () => state.draft,
+ isFreshSessionPending: () => state.freshPending,
+ setFreshSessionPending: state.setFreshPending,
clearComposerDraftContent: state.clearDraft,
clearComposerDraft: state.clearDraft,
setComposerDraftText: (_key: string, text: string) => {
@@ -181,6 +191,9 @@ beforeEach(() => {
state.grantedEnvironments = new Set(["primary"]);
state.connectionState = "connected";
state.draft = { text: "Keep my draft", attachments: [], modelSelection: undefined };
+ state.freshPending = false;
+ state.compactDue = false;
+ state.thread.latestRun = null;
state.projection = null;
state.serverConfig = {
providers: [{ instanceId: "codex", driver: "codex", enabled: true }],
@@ -254,6 +267,75 @@ describe("mobile task permissions", () => {
});
});
+ it("keeps an armed fresh session for the message after an approval redirect", async () => {
+ state.grantedEnvironments.add("secondary");
+ state.freshPending = true;
+ const composer = useThreadComposerState();
+ expect(await composer.onSendMessage(undefined, async () => true)).toBe("message");
+ expect(state.enqueue).toHaveBeenLastCalledWith(
+ expect.not.objectContaining({ freshContext: true }),
+ );
+ expect(state.setFreshPending).not.toHaveBeenCalled();
+ expect(await composer.onSendMessage()).toBe("message");
+ expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true }));
+ expect(state.setFreshPending).toHaveBeenCalledWith("secondary:thread", false);
+ });
+
+ it("compacts a stale thread before sending unless a fresh session is armed", async () => {
+ state.grantedEnvironments.add("secondary");
+ state.projection = {
+ thread: {
+ ...state.thread,
+ activeProviderThreadId: null,
+ lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null },
+ },
+ runs: [],
+ attempts: [],
+ nodes: [],
+ subagents: [],
+ providerSessions: [],
+ providerThreads: [],
+ providerTurns: [],
+ runtimeRequests: [],
+ messages: [],
+ plans: [],
+ turnItems: [],
+ checkpointScopes: [],
+ checkpoints: [],
+ contextHandoffs: [],
+ contextTransfers: [],
+ visibleTurnItems: [],
+ updatedAt: DateTime.makeUnsafe(0),
+ } as unknown as OrchestrationV2ThreadProjection;
+ state.compactDue = true;
+ const composer = useThreadComposerState();
+ await composer.onSendMessage();
+ expect(state.enqueue).toHaveBeenLastCalledWith(
+ expect.objectContaining({ compactBeforeSend: true }),
+ );
+ state.freshPending = true;
+ await composer.onSendMessage();
+ expect(state.enqueue).toHaveBeenLastCalledWith(
+ expect.not.objectContaining({ compactBeforeSend: true }),
+ );
+ expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true }));
+ });
+
+ it("sends a typed /clear with an approval redirect as that reply's text", async () => {
+ state.grantedEnvironments.add("secondary");
+ state.serverConfig = {
+ ...state.serverConfig,
+ environment: { capabilities: { freshContext: true } },
+ } as ServerConfig;
+ state.thread.latestRun = { runId: "run" };
+ state.draft = { ...state.draft, text: "/clear" };
+ const composer = useThreadComposerState();
+ const beforeDispatch = vi.fn(async () => "responded" as const);
+ expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
+ expect(beforeDispatch).toHaveBeenCalledWith("/clear", false);
+ expect(state.setFreshPending).not.toHaveBeenCalled();
+ });
+
it("rechecks a retained send callback before clearing or queueing the draft", async () => {
state.grantedEnvironments.add("secondary");
const composer = useThreadComposerState();
diff --git a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
index fdd5c710941..3222101bf92 100644
--- a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
+++ b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
@@ -151,6 +151,7 @@ vi.mock("./use-composer-drafts", async () => {
state.draftText += `\n${input.text}`;
}),
replaceComposerDraftAttachments: vi.fn(),
+ setFreshSessionPending: vi.fn(),
undoComposerDraftMerge: vi.fn(),
updateComposerDraftSettings: vi.fn(),
waitForComposerDraftsLoaded: vi.fn(),
diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts
index 44bd564ef89..9b2da676eee 100644
--- a/apps/mobile/src/state/threadOutboxDelivery.ts
+++ b/apps/mobile/src/state/threadOutboxDelivery.ts
@@ -449,6 +449,7 @@ export async function restoreRejectedQueuedMessage(
...(queuedMessage.modelSelection ? { modelSelection: queuedMessage.modelSelection } : {}),
...(queuedMessage.runtimeMode ? { runtimeMode: queuedMessage.runtimeMode } : {}),
...(queuedMessage.interactionMode ? { interactionMode: queuedMessage.interactionMode } : {}),
+ ...(queuedMessage.freshContext ? { freshContext: true } : {}),
...(queuedMessage.creation
? {
workspaceSelection: {
@@ -933,6 +934,7 @@ export function createThreadOutboxDelivery(): {
interactionMode: sendSettings.interactionMode,
createdAt: queuedMessage.createdAt,
dispatchMode: queuedMessage.dispatchMode ?? "start",
+ ...(queuedMessage.freshContext ? { freshContext: true } : {}),
},
});
if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true;
diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts
index 07da494625e..ed7a79c1f7a 100644
--- a/apps/mobile/src/state/use-composer-drafts.ts
+++ b/apps/mobile/src/state/use-composer-drafts.ts
@@ -403,6 +403,8 @@ export interface ComposerDraft {
readonly modelSelection?: ModelSelection;
readonly runtimeMode?: RuntimeMode;
readonly interactionMode?: ProviderInteractionMode;
+ /** `/clear` armed this draft: its next message starts a fresh provider session. */
+ readonly freshContext?: boolean;
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
readonly project?: ComposerDraftProject;
}
@@ -436,7 +438,12 @@ export interface ComposerDraftWorkspaceSelection {
export type ComposerDraftSettingsUpdate = Pick<
ComposerDraft,
- "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection" | "project"
+ | "modelSelection"
+ | "runtimeMode"
+ | "interactionMode"
+ | "freshContext"
+ | "workspaceSelection"
+ | "project"
>;
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
@@ -468,6 +475,7 @@ const ComposerDraftSchema = Schema.Struct({
modelSelection: Schema.optional(ModelSelectionSchema),
runtimeMode: Schema.optional(RuntimeModeSchema),
interactionMode: Schema.optional(ProviderInteractionModeSchema),
+ freshContext: Schema.optional(Schema.Boolean),
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
project: Schema.optional(ComposerDraftProjectSchema),
});
@@ -647,6 +655,7 @@ function isEmptyDraft(draft: ComposerDraft): boolean {
draft.modelSelection === undefined &&
draft.runtimeMode === undefined &&
draft.interactionMode === undefined &&
+ draft.freshContext !== true &&
draft.workspaceSelection === undefined
);
}
@@ -1532,6 +1541,15 @@ export function updateComposerDraftSettings(
});
}
+export function setFreshSessionPending(draftKey: string, pending: boolean): void {
+ if ((getComposerDraftSnapshot(draftKey).freshContext === true) === pending) return;
+ updateComposerDraftSettings(draftKey, { freshContext: pending ? true : undefined });
+}
+
+export function isFreshSessionPending(draftKey: string): boolean {
+ return getComposerDraftSnapshot(draftKey).freshContext === true;
+}
+
export function subscribeComposerDraftModelReconciliation(input: {
readonly registry: AtomRegistry.AtomRegistry;
readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
@@ -1777,6 +1795,7 @@ export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): bool
a.modelSelection === b.modelSelection &&
a.runtimeMode === b.runtimeMode &&
a.interactionMode === b.interactionMode &&
+ a.freshContext === b.freshContext &&
a.workspaceSelection === b.workspaceSelection
);
}
@@ -1802,7 +1821,12 @@ export function undoComposerDraftMergeState(
.map((attachment) => attachment.id),
);
const undoSetting = <
- K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection",
+ K extends
+ | "modelSelection"
+ | "runtimeMode"
+ | "interactionMode"
+ | "freshContext"
+ | "workspaceSelection",
>(
key: K,
): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
@@ -1822,6 +1846,7 @@ export function undoComposerDraftMergeState(
modelSelection: undoSetting("modelSelection"),
runtimeMode: undoSetting("runtimeMode"),
interactionMode: undoSetting("interactionMode"),
+ freshContext: undoSetting("freshContext"),
workspaceSelection: undoSetting("workspaceSelection"),
};
return withComposerDraft(current, draftKey, draft);
@@ -2054,7 +2079,7 @@ export const composerDraftUploadSourcesAtom = Atom.make((get): ComposerDraftUplo
type ComposerDraftSettings = Pick<
ComposerDraft,
- "modelSelection" | "runtimeMode" | "interactionMode"
+ "modelSelection" | "runtimeMode" | "interactionMode" | "freshContext"
>;
const EMPTY_DRAFT_SETTINGS: ComposerDraftSettings = {};
const composerDraftSettingsAtom = Atom.family((draftKey: string) =>
@@ -2064,13 +2089,15 @@ const composerDraftSettingsAtom = Atom.family((draftKey: string) =>
modelSelection: draft.modelSelection,
runtimeMode: draft.runtimeMode,
interactionMode: draft.interactionMode,
+ freshContext: draft.freshContext,
};
}).pipe(
Atom.withEquality(
(a: ComposerDraftSettings, b: ComposerDraftSettings) =>
a.modelSelection === b.modelSelection &&
a.runtimeMode === b.runtimeMode &&
- a.interactionMode === b.interactionMode,
+ a.interactionMode === b.interactionMode &&
+ a.freshContext === b.freshContext,
),
),
);
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index 75b3b0df01f..d10f3fb48c9 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -72,14 +72,17 @@ import {
clearComposerDraftContent,
composerContextImportsAtom,
getComposerDraftSnapshot,
+ isFreshSessionPending,
mergeComposerDraftContent,
removeComposerDraftAttachment,
scheduleUnusedComposerAttachmentCleanup,
setComposerDraftText,
+ setFreshSessionPending,
updateComposerDraftSettings,
useComposerDraft,
useComposerDraftSettings,
} from "./use-composer-drafts";
+import { isClearComposerCommand } from "@t3tools/shared/composerTrigger";
import {
resolveComposerDispatchMode,
type ActiveTurnComposerAction,
@@ -554,6 +557,19 @@ export function useThreadComposerState() {
if (text.length === 0 && attachments.length === 0) {
return null;
}
+ // A redirect's text answers its approval, so /clear there is that text, not the command.
+ if (
+ beforeDispatch === undefined &&
+ selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.freshContext === true &&
+ thread.latestRun != null &&
+ attachments.length === 0 &&
+ draft.context === undefined &&
+ isClearComposerCommand(text)
+ ) {
+ setFreshSessionPending(threadKey, true);
+ clearComposerDraftContent(threadKey);
+ return null;
+ }
// Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely.
if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
Dialog.alert(
@@ -672,8 +688,12 @@ export function useThreadComposerState() {
? "queue"
: "auto";
+ // A redirect belongs to the approval it answers; the armed session waits for the next message.
+ const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey);
const metadata = makeQueuedMessageMetadata();
+ // A fresh session drops the context a compaction would summarize.
const compactBeforeSend =
+ !freshContext &&
followUpDispatchMode === null &&
selectedEnvironmentRuntime?.connectionState === "connected" &&
selectedThreadProjection !== null &&
@@ -714,9 +734,11 @@ export function useThreadComposerState() {
: followUpDispatchMode === null
? {}
: { dispatchMode: followUpDispatchMode }),
+ ...(freshContext ? { freshContext: true } : {}),
createdAt: metadata.createdAt,
});
clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
+ if (freshContext) setFreshSessionPending(threadKey, false);
enqueuePromise.then(
() => scheduleUnusedComposerAttachmentCleanup(attachments),
(error: unknown) => {
@@ -727,6 +749,7 @@ export function useThreadComposerState() {
attachments: [],
});
appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
+ if (freshContext) setFreshSessionPending(threadKey, true);
setThreadComposerError(
threadKey,
error instanceof Error ? error.message : "Failed to save the queued message.",
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index e53ed03a7c6..36fe752eb8f 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -3133,6 +3133,7 @@ const make = Effect.gen(function* () {
text: input.message,
attachments: [],
mode,
+ ...(input.freshContext ? { freshContext: true } : {}),
createdBy: "agent",
creationSource: "mcp",
})
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
index 993ee5c3010..23b46afceca 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
@@ -521,6 +521,21 @@ it.effect("retains automation and sender attribution while a message waits in th
assert.equal(message?.scheduledTaskId, scheduledTaskId);
assert.equal(message?.senderThreadId, senderThreadId);
assert.equal(message?.text, "Run the audit");
+ // A fresh send queues instead of steering, so it needs no steerable run.
+ const fresh = yield* threads.sendToThread({
+ projectId,
+ commandId: CommandId.make("command:automation:queued-fresh"),
+ threadId: launched.threadId,
+ messageId: MessageId.make("message:automation:queued-fresh"),
+ text: "Start over",
+ attachments: [],
+ mode: "steer",
+ freshContext: true,
+ createdBy: "agent",
+ creationSource: "mcp",
+ });
+ assert.equal(fresh.delivery, "queued");
+ assert.isTrue(fresh.run.freshContext);
}).pipe(Effect.provide(harness.layer));
});
diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts
index 7aff0137562..b6c1e27120a 100644
--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts
+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts
@@ -146,6 +146,8 @@ export interface ThreadManagementSendInput {
readonly attachments: ReadonlyArray<ChatAttachment>;
readonly modelSelection?: ModelSelection;
readonly mode: ThreadManagementSendMode;
+ /** Start a new provider session; the orchestrator queues it instead of steering. */
+ readonly freshContext?: boolean;
readonly createdBy: OrchestrationV2Actor;
readonly creationSource: OrchestrationV2CreationSource;
}
@@ -820,26 +822,31 @@ const make = Effect.gen(function* () {
});
}
const steerableRun = latestSteerableRun(target);
+ // A fresh send never joins a running turn, so it needs none to steer or restart.
+ const mode =
+ input.freshContext && (input.mode === "steer" || input.mode === "restart")
+ ? "queue"
+ : input.mode;
let dispatchMode: Extract<
OrchestrationV2Command,
{ readonly type: "message.dispatch" }
>["dispatchMode"];
- if (input.mode === "steer" || input.mode === "restart") {
+ if (mode === "steer" || mode === "restart") {
if (steerableRun === undefined) {
return yield* new ThreadManagementNoSteerableRunError({
threadId: input.threadId,
- mode: input.mode,
+ mode,
});
}
dispatchMode = {
- type: input.mode === "steer" ? "steer_active" : "restart_active",
+ type: mode === "steer" ? "steer_active" : "restart_active",
targetRunId: steerableRun.id,
};
- } else if (input.mode === "auto" && steerableRun !== undefined) {
+ } else if (mode === "auto" && steerableRun !== undefined) {
dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
} else {
dispatchMode = {
- type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
+ type: mode === "queue" ? "queue_after_active" : "start_immediately",
};
}
@@ -853,6 +860,7 @@ const make = Effect.gen(function* () {
text: input.text,
attachments: input.attachments,
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
+ ...(input.freshContext ? { freshContext: true } : {}),
dispatchMode,
createdBy: input.createdBy,
creationSource: input.creationSource,
@@ -888,7 +896,7 @@ const make = Effect.gen(function* () {
? "queued"
: turnItem.inputIntent === "turn_start"
? "started"
- : input.mode === "restart"
+ : mode === "restart"
? "restarted"
: "steered";
return { dispatch: dispatched, projection, message, run, turnItem, delivery };
diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json
index bb586d5b9f4..de57d486651 100644
--- a/apps/server/src/provider/agentContextBudget.json
+++ b/apps/server/src/provider/agentContextBudget.json
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 5133,
"codexAdditionalContextBytes": 6863,
- "mcpToolListJsonBytes": 47498
+ "mcpToolListJsonBytes": 47642
}
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index 81b6992a59d..2e772cc0998 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -1077,6 +1077,7 @@ describe("planComposerTurn", () => {
keepFullHistory: false,
phase: "ready" as const,
dispatchMode: "auto" as const,
+ freshContext: false,
};
it("prepares a worktree from the selected branch on a new thread", () => {
@@ -1126,6 +1127,19 @@ describe("planComposerTurn", () => {
shouldQueueBehindActiveRun: false,
baseBranchForWorktree: null,
});
+ // A fresh session cannot join the running turn, and a stale one is not compacted first.
+ expect(
+ planComposerTurn({
+ ...running,
+ dispatchMode: "steer",
+ freshContext: true,
+ resumeCompactionTokens: 120_000,
+ }),
+ ).toMatchObject({
+ compactBeforeSend: false,
+ turnDispatchMode: "queue",
+ shouldQueueBehindActiveRun: true,
+ });
});
});
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index e933abf86b2..d4b54a7e5a8 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -1411,6 +1411,8 @@ export function planComposerTurn(input: {
readonly keepFullHistory: boolean;
readonly phase: SessionPhase;
readonly dispatchMode: ComposerDispatchMode;
+ /** The turn starts a new provider session, so it neither compacts first nor steers. */
+ readonly freshContext: boolean;
}) {
const isFirstMessage =
!input.sendQueuesBehindSetup && (!input.isServerThread || input.activeMessageCount === 0);
@@ -1420,9 +1422,14 @@ export function planComposerTurn(input: {
// old history. The message queues behind the /compact run, since steering into it is
// rejected.
const compactBeforeSend =
+ !input.freshContext &&
input.resumeCompactionTokens !== null &&
!input.keepFullHistory &&
!COMPACT_COMMAND_PATTERN.test(input.messageText);
+ const dispatchMode =
+ input.freshContext && (input.dispatchMode === "steer" || input.dispatchMode === "restart")
+ ? "queue"
+ : input.dispatchMode;
return {
// In worktree mode, require an explicit base branch so we don't silently
// fall back to local execution when branch selection is missing.
@@ -1430,11 +1437,11 @@ export function planComposerTurn(input: {
baseBranchForWorktree: shouldCreateWorktree ? input.activeThreadBranch : null,
compactBeforeSend,
turnDispatchMode:
- compactBeforeSend || input.sendQueuesBehindSetup ? ("queue" as const) : input.dispatchMode,
+ compactBeforeSend || input.sendQueuesBehindSetup ? ("queue" as const) : dispatchMode,
shouldQueueBehindActiveRun:
compactBeforeSend ||
input.sendQueuesBehindSetup ||
- (input.phase === "running" && input.dispatchMode === "queue"),
+ (input.phase === "running" && dispatchMode === "queue"),
};
}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 192505ea454..4408bee38ad 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -45,6 +45,8 @@ import { isScratchProject } from "@t3tools/client-runtime/state/projects";
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";
import { feedbackBannerItem } from "./chat/ComposerFeedback";
+import { freshSessionBannerItem } from "./chat/ComposerFreshSession";
+import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms";
import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";
import { useWorktreeSetup } from "./chat/useWorktreeSetup";
import { useChatShortcuts } from "./chat/useChatShortcuts";
@@ -2510,8 +2512,15 @@ export default function ChatView(props: ChatViewProps) {
return next;
});
};
+ const freshSessionAvailable =
+ activeMessageCount > 0 && serverConfig?.environment.capabilities.freshContext === true;
+ // While a question or approval owns the composer, its text answers that, not the agent.
+ const freshSessionCommandAvailable =
+ freshSessionAvailable && activePendingApproval === null && pendingUserInputs.length === 0;
+ const freshSessionArmed = useFreshSessionArmed(routeThreadKey);
const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory);
const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory);
+ const armFreshSessionStable = useStableCallback(() => armFreshSession(routeThreadKey));
const handleRestoreThreadBranch = () => {
if (!canWriteSourceControl) return;
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
@@ -2602,6 +2611,11 @@ export default function ChatView(props: ChatViewProps) {
const limitRecoveryItems = limitRecoveryBanner === null ? [] : [limitRecoveryBanner];
const usageLimitsItems = usageLimitsBanner === null ? [] : [usageLimitsBanner];
const projectCloneItems = projectCloneBannerItem === null ? [] : [projectCloneBannerItem];
+ // An approval's feedback goes to that approval; the armed session waits for the next message.
+ const freshSessionItems =
+ freshSessionAvailable && freshSessionArmed && activePendingApproval === null
+ ? [freshSessionBannerItem(() => disarmFreshSession(routeThreadKey))]
+ : [];
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
return [
...feedbackBannerItems,
@@ -2609,6 +2623,7 @@ export default function ChatView(props: ChatViewProps) {
...limitRecoveryItems,
...usageLimitsItems,
...projectCloneItems,
+ ...freshSessionItems,
...systemComposerBannerItems,
];
}
@@ -2618,6 +2633,7 @@ export default function ChatView(props: ChatViewProps) {
...limitRecoveryItems,
...usageLimitsItems,
...projectCloneItems,
+ ...freshSessionItems,
...systemComposerBannerItems,
branchMismatchBannerItem({
mismatchKey: activeBranchMismatchKey,
@@ -2922,6 +2938,7 @@ export default function ChatView(props: ChatViewProps) {
panelAnimationsActive,
panelAnimationDurationMs,
keepFullHistory,
+ freshSessionAvailable: freshSessionCommandAvailable,
resumeCompactionTokens,
showPlanFollowUpPrompt,
usageLimitsKey,
@@ -3640,6 +3657,9 @@ export default function ChatView(props: ChatViewProps) {
onToggleKeepFullHistory={toggleKeepFullHistoryStable}
sideChatAvailable={sideChat.available}
sideChatDisabledReason={sideChatDisabledReason}
+ onFreshSession={
+ freshSessionCommandAvailable ? armFreshSessionStable : undefined
+ }
onUsageLimitsCommand={
usageLimitsOffered &&
usageLimitsKey !== null &&
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 95fa71d9532..e4515f759fd 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -383,6 +383,8 @@ export interface ChatComposerProps {
onUsageLimitsCommand?: (() => void) | undefined;
sideChatAvailable?: boolean;
sideChatDisabledReason?: string | null;
+ /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
+ onFreshSession?: (() => void) | undefined;
environmentUnavailable: {
readonly label: string;
readonly connection: EnvironmentConnectionPresentation;
@@ -1151,6 +1153,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
planModeUiEnabled,
sideChatAvailable: props.sideChatAvailable === true,
sideChatDisabledReason: props.sideChatDisabledReason ?? null,
+ freshSessionAvailable: props.onFreshSession !== undefined,
compactSlashCommandAvailable,
selectedProvider,
selectedProviderSkills,
@@ -1880,6 +1883,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
return;
}
+ if (item.command === "clear") {
+ const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
+ expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
+ });
+ if (applied) {
+ setComposerHighlightedItemId(null);
+ props.onFreshSession?.();
+ }
+ return;
+ }
if (item.command === "side" || item.command === "btw") {
if (props.sideChatDisabledReason) return;
const applied = applyPromptReplacement(
diff --git a/apps/web/src/components/chat/ComposerFreshSession.tsx b/apps/web/src/components/chat/ComposerFreshSession.tsx
new file mode 100644
index 00000000000..3ae2cafdc32
--- /dev/null
+++ b/apps/web/src/components/chat/ComposerFreshSession.tsx
@@ -0,0 +1,16 @@
+import { EraserIcon } from "lucide-react";
+
+import type { ComposerBannerStackItem } from "./ComposerBannerStack";
+
+/** Shown while `/clear` is armed; dismissing it keeps the current conversation. */
+export function freshSessionBannerItem(onUndo: () => void): ComposerBannerStackItem {
+ return {
+ id: "fresh-session",
+ variant: "info",
+ icon: <EraserIcon />,
+ title: "Your next message starts a fresh session",
+ description: "The agent won't see earlier messages in this thread.",
+ dismissLabel: "Keep the current session",
+ onDismiss: onUndo,
+ };
+}
diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx
index 97b74a75a73..2b2cfa78dce 100644
--- a/apps/web/src/components/chat/QueuedRunsControl.tsx
+++ b/apps/web/src/components/chat/QueuedRunsControl.tsx
@@ -113,7 +113,11 @@ export function QueuedRunsControl({
const workflow = projection ? deriveThreadQueueWorkflowState(projection) : null;
const queued = workflow?.queuedRuns ?? [];
const activeRun = workflow?.activeRun ?? null;
- const canSend = workflow?.canSendNow === true || workflow?.canPromoteToSteer === true;
+ // A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
+ const canSendRun = (freshContext: boolean) =>
+ workflow?.canSendNow === true ||
+ (workflow?.canPromoteToSteer === true &&
+ (!freshContext || workflow.promoteSkipsCompaction === true));
const queuedImageUrlById = new Map(
queuedImageAttachmentUrls.flatMap((url, index) => {
const resource = queuedImageAttachmentResources[index];
@@ -129,6 +133,7 @@ export function QueuedRunsControl({
message,
runId: run.id,
messageId: run.userMessageId,
+ freshContext: run.freshContext === true,
serverIndex,
text,
// A guest's message keeps the guest's words; the owner can cancel it, not rewrite it.
@@ -148,6 +153,7 @@ export function QueuedRunsControl({
message: undefined,
runId: null,
messageId: null,
+ freshContext: false,
serverIndex: null,
text: message.text,
editable: true,
@@ -164,7 +170,10 @@ export function QueuedRunsControl({
];
const sendQueuedMessage = async (queuedRunId: RunId) => {
- if (!canSend || steerInFlightRef.current) return;
+ const freshContext = queued.some(
+ ({ run }) => run.id === queuedRunId && run.freshContext === true,
+ );
+ if (!canSendRun(freshContext) || steerInFlightRef.current) return;
steerInFlightRef.current = true;
setBusyRunId(queuedRunId);
if (workflow?.canSendNow) {
@@ -185,7 +194,7 @@ export function QueuedRunsControl({
useImperativeHandle(ref, () => ({
steerNext(repeat) {
const next = queued[0];
- if (!next || !canSend) return false;
+ if (!next || !canSendRun(next.run.freshContext === true)) return false;
if (!repeat && busyRunId === null) void sendQueuedMessage(next.run.id);
return true;
},
@@ -266,7 +275,7 @@ export function QueuedRunsControl({
timestampFormat={props.timestampFormat}
onOpenThread={props.onOpenThread}
>
- {canSend && !isEditing ? (
+ {canSendRun(item.freshContext) && !isEditing ? (
<>
<Tooltip>
<TooltipTrigger render={<span className="flex shrink-0" />}>
diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx
index bf52aad538e..66bb9b586c6 100644
--- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx
+++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx
@@ -38,7 +38,7 @@ import {
} from "lucide-react";
import { Link as LinkIconNode } from "lucide";
import { Button, InlineButton } from "../ui/button";
-import { ModelSwitchRow } from "./V2LifecycleRow";
+import { FreshSessionRow, ModelSwitchRow } from "./V2LifecycleRow";
import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls";
import { AttachmentImage } from "../media/AttachmentImage";
import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
@@ -252,6 +252,7 @@ export function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "mes
const modelSwitch = item?.type === "user_message" ? item.modelSwitch : undefined;
return (
<>
+ {item?.type === "user_message" && item.freshContext ? <FreshSessionRow /> : null}
{modelSwitch ? (
<ModelSwitchRow environmentId={ctx.activeThreadEnvironmentId} modelSwitch={modelSwitch} />
) : null}
diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx
index c0dd0e0900d..40fffaf6084 100644
--- a/apps/web/src/components/chat/V2LifecycleRow.tsx
+++ b/apps/web/src/components/chat/V2LifecycleRow.tsx
@@ -43,6 +43,7 @@ import {
CircleStopIcon,
ArrowRightLeftIcon,
ArrowRightIcon,
+ EraserIcon,
GitForkIcon,
MessageSquareIcon,
} from "lucide-react";
@@ -597,6 +598,11 @@ function EnvironmentHandoffRow({
return <HandoffRow {...props} environmentId={environmentId} providers={providers} />;
}
+/** Marks where `/clear` or an automation started a new provider session in this thread. */
+export function FreshSessionRow() {
+ return <TimelineSystemDivider label="New session" icon={EraserIcon} />;
+}
+
/** A same-harness model or effort change. Shows only what changed. */
export function ModelSwitchRow(props: {
readonly environmentId: EnvironmentId;
diff --git a/apps/web/src/components/chat/composerSlashCommandSearch.ts b/apps/web/src/components/chat/composerSlashCommandSearch.ts
index 0c5c04e28ca..ba1aacb83de 100644
--- a/apps/web/src/components/chat/composerSlashCommandSearch.ts
+++ b/apps/web/src/components/chat/composerSlashCommandSearch.ts
@@ -12,7 +12,7 @@ type SlashSearchItem = Extract<
{ type: "slash-command" | "provider-slash-command" | "skill" }
>;
-/** Provider commands, `/side` and `/btw` work only at the message start. */
+/** Provider commands, `/side`, `/btw` and `/clear` work only at the message start. */
export function slashCommandItemsForPromptPosition(
items: ReadonlyArray<SlashSearchItem>,
isAtPromptStart: boolean,
@@ -23,7 +23,10 @@ export function slashCommandItemsForPromptPosition(
return items.filter(
(item) =>
item.type === "skill" ||
- (item.type === "slash-command" && item.command !== "side" && item.command !== "btw"),
+ (item.type === "slash-command" &&
+ item.command !== "side" &&
+ item.command !== "btw" &&
+ item.command !== "clear"),
);
}
diff --git a/apps/web/src/components/chat/freshSessionArms.ts b/apps/web/src/components/chat/freshSessionArms.ts
new file mode 100644
index 00000000000..cd2dc9b52e4
--- /dev/null
+++ b/apps/web/src/components/chat/freshSessionArms.ts
@@ -0,0 +1,30 @@
+import { useAtomValue } from "@effect/atom-react";
+import { Atom } from "effect/reactivity";
+
+import { appAtomRegistry } from "../../rpc/atomRegistry";
+
+/** Threads whose next message starts a fresh provider session, keyed by thread, valued by when it was armed. */
+const freshSessionArmsAtom = Atom.make<Readonly<Record<string, number>>>({}).pipe(Atom.keepAlive);
+
+export function armFreshSession(threadKey: string): void {
+ appAtomRegistry.set(freshSessionArmsAtom, {
+ ...appAtomRegistry.get(freshSessionArmsAtom),
+ [threadKey]: Date.now(),
+ });
+}
+
+/** With `arm`, clears only that arm, so a send never consumes one made while it was in flight. */
+export function disarmFreshSession(threadKey: string, arm?: number): void {
+ const current = appAtomRegistry.get(freshSessionArmsAtom);
+ if (current[threadKey] === undefined || (arm !== undefined && current[threadKey] !== arm)) return;
+ const { [threadKey]: _removed, ...rest } = current;
+ appAtomRegistry.set(freshSessionArmsAtom, rest);
+}
+
+export function readFreshSessionArm(threadKey: string): number | undefined {
+ return appAtomRegistry.get(freshSessionArmsAtom)[threadKey];
+}
+
+export function useFreshSessionArmed(threadKey: string): boolean {
+ return useAtomValue(freshSessionArmsAtom)[threadKey] !== undefined;
+}
diff --git a/apps/web/src/components/chat/useComposerMenuItems.ts b/apps/web/src/components/chat/useComposerMenuItems.ts
index 5f778ac6cac..741d1290293 100644
--- a/apps/web/src/components/chat/useComposerMenuItems.ts
+++ b/apps/web/src/components/chat/useComposerMenuItems.ts
@@ -66,6 +66,7 @@ export function useComposerMenuItems({
planModeUiEnabled,
sideChatAvailable,
sideChatDisabledReason,
+ freshSessionAvailable,
compactSlashCommandAvailable,
selectedProvider,
selectedProviderSkills,
@@ -85,6 +86,7 @@ export function useComposerMenuItems({
readonly planModeUiEnabled: boolean;
readonly sideChatAvailable: boolean;
readonly sideChatDisabledReason: string | null;
+ readonly freshSessionAvailable: boolean;
readonly compactSlashCommandAvailable: boolean;
readonly selectedProvider: ProviderDriverKind;
readonly selectedProviderSkills: ServerProvider["skills"];
@@ -260,6 +262,17 @@ export function useComposerMenuItems({
},
] as const)
: []),
+ ...(freshSessionAvailable
+ ? ([
+ {
+ id: "slash:clear",
+ type: "slash-command",
+ command: "clear",
+ label: "/clear",
+ description: "Start a fresh session; earlier messages stay visible",
+ },
+ ] as const)
+ : []),
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
const slashMenuSkills = getProviderSkillsForSlashMenu(
selectedProviderSkills,
@@ -288,8 +301,11 @@ export function useComposerMenuItems({
skill.description ??
(skill.scope ? `${skill.scope} skill` : ""),
}));
+ // T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live.
const visibleProviderSlashCommandItems = providerSlashCommandItems.filter(
- (item) => item.command.name !== "compact" || compactSlashCommandAvailable,
+ (item) =>
+ (item.command.name !== "compact" || compactSlashCommandAvailable) &&
+ (item.command.name !== "clear" || !freshSessionAvailable),
);
const slashCommandItems = slashCommandItemsForPromptPosition(
[...builtInSlashCommandItems, ...visibleProviderSlashCommandItems, ...skillItems],
diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts
index 98084e97954..db2fa10feb8 100644
--- a/apps/web/src/components/chat/useComposerSend.ts
+++ b/apps/web/src/components/chat/useComposerSend.ts
@@ -1,3 +1,5 @@
+import { isClearComposerCommand } from "@t3tools/shared/composerTrigger";
+import { armFreshSession, disarmFreshSession, readFreshSessionArm } from "./freshSessionArms";
import {
mergeDirectPreviewAnnotation,
resolveBackgroundDraftWorkspaceOptions,
@@ -207,6 +209,8 @@ interface ComposerSendInput {
readonly panelAnimationsActive: boolean;
readonly panelAnimationDurationMs: number;
readonly keepFullHistory: boolean;
+ /** `/clear` can arm a fresh session on this thread. */
+ readonly freshSessionAvailable: boolean;
readonly resumeCompactionTokens: number | null;
readonly showPlanFollowUpPrompt: boolean;
readonly usageLimitsKey: string | null;
@@ -302,6 +306,7 @@ export function useComposerSend(input: ComposerSendInput) {
panelAnimationsActive,
panelAnimationDurationMs,
keepFullHistory,
+ freshSessionAvailable,
resumeCompactionTokens,
showPlanFollowUpPrompt,
usageLimitsKey,
@@ -716,8 +721,26 @@ export function useComposerSend(input: ComposerSendInput) {
return;
}
+ const composerHoldsOnlyText =
+ composerImages.length === 0 &&
+ composerFiles.length === 0 &&
+ sendableComposerTerminalContexts.length === 0 &&
+ composerPreviewAnnotations.length === 0 &&
+ composerReviewComments.length === 0 &&
+ composerThreadContexts.length === 0 &&
+ composerEnvironmentContexts.length === 0;
+ if (freshSessionAvailable && composerHoldsOnlyText && isClearComposerCommand(trimmed)) {
+ armFreshSession(routeThreadKey);
+ promptRef.current = "";
+ clearComposerDraftContent(composerDraftTarget);
+ composerRef.current?.resetCursorState();
+ return;
+ }
+ // Read once: an arm made while this send is in flight belongs to the next message.
+ const freshArm = freshSessionAvailable ? readFreshSessionArm(routeThreadKey) : undefined;
if (
!directAnnotation &&
+ freshArm === undefined &&
sendInteractionModeEnabled &&
showPlanFollowUpPrompt &&
activeProposedPlan &&
@@ -798,14 +821,7 @@ export function useComposerSend(input: ComposerSendInput) {
return;
}
const standaloneSlashCommand =
- sendInteractionModeEnabled &&
- composerImages.length === 0 &&
- composerFiles.length === 0 &&
- sendableComposerTerminalContexts.length === 0 &&
- composerPreviewAnnotations.length === 0 &&
- composerReviewComments.length === 0 &&
- composerThreadContexts.length === 0 &&
- composerEnvironmentContexts.length === 0
+ sendInteractionModeEnabled && composerHoldsOnlyText
? parseStandaloneComposerSlashCommand(trimmed)
: null;
if (standaloneSlashCommand && multipleModelSelections === null) {
@@ -881,6 +897,7 @@ export function useComposerSend(input: ComposerSendInput) {
keepFullHistory,
phase,
dispatchMode,
+ freshContext: freshArm !== undefined,
});
if (missingWorktreeBaseBranch) {
setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
@@ -1364,6 +1381,7 @@ export function useComposerSend(input: ComposerSendInput) {
runtimeMode,
interactionMode: sendInteractionMode,
dispatchMode: turnDispatchMode,
+ ...(freshArm === undefined ? {} : { freshContext: true }),
...(bootstrap ? { bootstrap } : {}),
createdAt: messageCreatedAt,
},
@@ -1397,6 +1415,7 @@ export function useComposerSend(input: ComposerSendInput) {
} else {
turnStartSucceeded = true;
setKeepFullHistory(routeThreadKey, false);
+ if (freshArm !== undefined) disarmFreshSession(routeThreadKey, freshArm);
clearUsageLimitsFor(routeThreadKey);
if (turnUsesAttachmentUploads) {
releaseDraftAttachments(composerAttachmentsSnapshot);
diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts
index 51635a651d4..cb65ab6bde0 100644
--- a/apps/web/src/composer-logic.test.ts
+++ b/apps/web/src/composer-logic.test.ts
@@ -564,7 +564,7 @@ describe("parseSideChatCommand", () => {
expect(parseSideChatCommand("/sidebar")).toBeNull();
expect(parseSideChatCommand("/btwx")).toBeNull();
expect(parseSideChatCommand("ask /side later")).toBeNull();
- const items = (["side", "btw", "plan"] as const).map((command) => ({
+ const items = (["side", "btw", "clear", "plan"] as const).map((command) => ({
id: `slash:${command}`,
type: "slash-command" as const,
command,
diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts
index 9b722379719..1cfbaceb4b2 100644
--- a/apps/web/src/composer-logic.ts
+++ b/apps/web/src/composer-logic.ts
@@ -18,7 +18,7 @@ import {
import { resolveShortcutCommand, type ShortcutEventLike } from "./keybindings";
export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill";
-export type ComposerSlashCommand = "model" | "plan" | "default" | "side" | "btw";
+export type ComposerSlashCommand = "model" | "plan" | "default" | "side" | "btw" | "clear";
export type ComposerSubmissionIntent = "foreground" | "background" | "alternate";
export interface ComposerTrigger {
@@ -326,7 +326,7 @@ export function parseSideChatCommand(text: string): { prompt: string } | null {
export function parseStandaloneComposerSlashCommand(
text: string,
-): Exclude<ComposerSlashCommand, "model" | "side" | "btw"> | null {
+): Exclude<ComposerSlashCommand, "model" | "side" | "btw" | "clear"> | null {
const match = /^\/(plan|default)\s*$/i.exec(text.trim());
if (!match) {
return null;
diff --git a/docs/user/composer.md b/docs/user/composer.md
index c236da3c82c..d1b0562203f 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -264,6 +264,12 @@ Provider commands must start the message to run. T3 Code commands such as
Send `/compact` in an existing conversation to reduce context usage when the
provider supports it, even with the context meter turned off.
+Send `/clear` on its own, or pick it from the slash menu, to start a fresh session
+in the same thread. Your next message goes to a new provider session that doesn't see the
+earlier messages, and the thread marks where it began with **New session**.
+Earlier messages and diffs stay in the thread. Dismiss the notice above the
+composer to keep the current session instead.
+
On web and desktop, turn on **Settings → Labs → Legacy → Context
window indicator (legacy)** to see context usage. The meter is off by default
and appears once the provider reports usage. Open it for usage details and
diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md
index 9a62a65efdc..1d3c72936f0 100644
--- a/docs/user/providers-antigravity.md
+++ b/docs/user/providers-antigravity.md
@@ -88,7 +88,7 @@ its conversation. Reverting a thread or editing and resubmitting an earlier turn
is unavailable. Continue with a follow-up message or start a new thread.
Manual context compaction is unavailable through Antigravity's ACP runtime, even
-though its CLI has `/compact`. Start a new thread when you need a fresh context.
+though its CLI has `/compact`. Send `/clear` when you need a fresh context.
### Skills and attachments
diff --git a/evals/mcp-tool-use/cases/orchestration.ndjson b/evals/mcp-tool-use/cases/orchestration.ndjson
index dc79eb774df..41eb03e0939 100644
--- a/evals/mcp-tool-use/cases/orchestration.ndjson
+++ b/evals/mcp-tool-use/cases/orchestration.ndjson
@@ -25,7 +25,7 @@
{"id": "opus-review-too-via-delegate", "area": "orchestration", "kind": "guard", "pattern": "same-provider review via delegate_task", "experience": "'Have Opus review the things too' from a Claude parent with no extra settings runs a native Opus subagent the parent waits for.", "rule": "Use your native tool when the child uses your provider, a model it offers, and no settings beyond yours, and you need it only in this turn.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Get a Sol review on https://github.com/acme/app/pull/123 before we file anything else."}, {"role": "assistant", "text": "Sol approved PR 123 after one fix to its description.", "toolCalls": [{"tool": "delegate_task", "input": {"title": "Sol review PR 123", "mode": "async", "clientRequestId": "sol-123-r1", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol", "options": {"reasoningEffort": "high"}}, "task": "Review https://github.com/acme/app/pull/123. Read only."}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "childRunId": "run-child-1", "status": "running", "workState": "working", "providerInstanceId": "codex", "model": "gpt-6.1-sol"}}, {"tool": "task_status", "input": {"taskId": "task-1"}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "status": "completed", "workState": "result_available", "summary": "APPROVE after S1 (description wording)."}}]}], "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}, "world": {"prs": [{"number": 123, "title": "fix(web): keep scroll position on thread switch", "headRefName": "fix/scroll"}]}, "harness": "claude"}, "prompt": "Have Opus review the things too, not just Sol", "expect": {"calls": [{"tool": "Agent", "args": {"model": "~opus"}}], "notCalls": ["delegate_task", "t3_thread_send"], "callsMustNot": [{"tool": "Agent", "args": {"run_in_background": true}}]}, "notes": "T3's 'prefer native for same-provider' line pulls toward the native Agent tool here; this stayed correct in the real thread."}
{"id": "delegates-then-new-thread-with-model", "area": "orchestration", "kind": "guard", "pattern": "new thread asked: t3_thread_launch with model", "experience": "'Spin up 2 Opus delegates ... then start a new thread using Grok 4.7 to implement' gave 2 delegate_task calls and 1 t3_thread_launch on Grok.", "rule": "t3_thread_launch and create_threads ... Use them only when the user explicitly asks for separate/new/top-level threads.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Spin up 2 Opus 5.5 delegates to explore performance wins in this app."}, {"role": "assistant", "text": "Both Opus delegates are done.\n- Client: the thread list re-renders every row on each streamed token.\n- Server: each event write runs a full projection rebuild.", "toolCalls": [{"tool": "delegate_task", "input": {"title": "Opus: client performance", "mode": "wait", "clientRequestId": "perf-client", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Find concrete client performance wins. Read only."}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "childRunId": "run-child-1", "status": "completed", "workState": "result_available", "providerInstanceId": "claudeAgent", "model": "claude-opus-5-5", "summary": "Client: the thread list re-renders every row on each streamed token. Memoize rows by thread id and select only the active thread's stream."}}, {"tool": "delegate_task", "input": {"title": "Opus: server performance", "mode": "wait", "clientRequestId": "perf-server", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Find concrete server performance wins. Read only."}, "result": {"taskId": "task-2", "childThreadId": "44444444-4444-4444-8444-000000000002", "childRunId": "run-child-2", "status": "completed", "workState": "result_available", "providerInstanceId": "claudeAgent", "model": "claude-opus-5-5", "summary": "Server: each event write runs a full projection rebuild. Apply events to the projection incrementally."}}]}], "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "t3_thread_launch": {"threadId": "11111111-1111-4111-8111-111111111111", "projectId": "22222222-2222-4222-8222-222222222222", "modelSelection": {"instanceId": "grok", "model": "grok-4.7"}, "status": "starting"}}}, "prompt": "Summarize their thoughts, then start a new thread using Grok 4.7 to implement your findings.", "expect": {"calls": [{"tool": "t3_thread_launch", "args": {"modelSelection.model": "~grok"}}], "notCalls": ["delegate_task", "create_threads"]}, "notes": "Pattern 2 (new thread asked but delegate used) had only 1-2 real cases in 40 asks, so this is a guard. Check the arg path against the current t3_thread_launch schema."}
{"id": "subagent-ask-no-new-threads", "area": "orchestration", "kind": "guard", "pattern": "subagent asked: no t3_thread_launch/create_threads", "experience": "'Have Haiku 5.5 subagents do the exploration' must give child tasks, not top-level threads. 0 of 98 subagent asks went wrong, and the user still warns about it.", "rule": "Never use them merely because the user said \"subagent\" or requested parallel delegated work.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}, "world": {"files": {"package.json": "{\n \"name\": \"app\",\n \"private\": true,\n \"packageManager\": \"[email protected]\",\n \"scripts\": {\n \"dev\": \"turbo run dev\",\n \"build\": \"turbo run build\",\n \"test\": \"vitest run\",\n \"typecheck\": \"turbo run typecheck\"\n }\n}\n", "pnpm-workspace.yaml": "packages:\n - apps/*\n - packages/*\n", "turbo.json": "{\n \"tasks\": {\n \"build\": { \"outputs\": [\"dist/**\"] },\n \"typecheck\": {},\n \"dev\": { \"cache\": false }\n }\n}\n", "apps/web/package.json": "{ \"name\": \"@app/web\", \"scripts\": { \"dev\": \"vite\", \"build\": \"vite build\" } }\n", "apps/server/package.json": "{ \"name\": \"@app/server\", \"scripts\": { \"dev\": \"tsx watch src/index.ts\", \"build\": \"tsc\" } }\n", ".github/workflows/ci.yml": "name: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - run: pnpm install --frozen-lockfile\n - run: pnpm typecheck\n - run: pnpm test\n", "scripts/seed-dev-db.ts": "import { db } from '../apps/server/src/db';\n\n// Seeds the dev database with 20 fake users.\nfor (let i = 0; i < 20; i++) await db.insert('users', { name: `user${i}` });\n", "apps/web/src/main.tsx": "import { createRoot } from 'react-dom/client';\nimport { App } from './App';\n\ncreateRoot(document.getElementById('root')!).render(<App />);\n", "apps/web/src/App.tsx": "export function App() {\n return <ThreadList />;\n}\n", "apps/server/src/index.ts": "import { createServer } from './server';\n\ncreateServer().listen(Number(process.env.PORT ?? 3773));\n", "apps/server/src/db.ts": "import { Database } from 'better-sqlite3';\n\nexport const db = new Database(process.env.DB_PATH ?? 'dev.sqlite');\n"}}}, "prompt": "I want your honest thoughts on this project. Do a deep dive and really read through it so you know it well. Have Haiku 5.5 subagents do the exploration.", "expect": {"notCalls": ["t3_thread_launch", "create_threads"]}, "notes": "Narrow on purpose: native vs delegate is graded in the bad cases. The user's preemptive guard: 'Please don't make new threads with the T3 Code MCP, only create delegates, workflows, subagents etc.'."}
-{"id": "thread-send-to-named-top-level-thread", "area": "orchestration", "kind": "guard", "pattern": "t3_thread_send to a top-level thread the user names", "experience": "Given another top-level thread id to talk to, the agent used t3_thread_send on it and linked it in the reply.", "rule": "To mention another thread to the user, write its `link` verbatim: <t3-thread://v2/<environmentId>/<threadId>>, with no title.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The other agent disagreed:\n\nTheirs is the better plan to execute. Mine is the wider survey. Start from theirs and graft three items from mine.\n\nTheir 5 points: 1) cache tsc output per package, 2) split the web typecheck into two projects, 3) drop the duplicate lint step in CI, 4) run typecheck only for changed packages in CI (memo), 5) measure before and after on main."}, {"role": "assistant", "text": "We now agree on almost everything. I accept points 1, 2, 3, and 5. I disagree with one detail of the memo in point 4: CI must also typecheck the packages that depend on a changed package, not only the changed ones. From my plan I would graft: project references, a warm tsc cache restored in CI, and a per-package timing report."}], "mocks": {"t3_thread_send": {"threadId": "11111111-1111-4111-8111-111111111111", "messageId": "msg-1", "runId": "run-1", "queued": true}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Faster type checking", "link": "<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>", "status": "idle"}, "items": [{"position": 41, "createdBy": "assistant", "text": "Plan: 1) cache tsc output per package, 2) split the web typecheck, 3) drop the duplicate lint step, 4) memo: typecheck only changed packages in CI, 5) measure on main."}, {"position": 42, "createdBy": "user", "text": "Another agent has a wider survey. I'll bring its answer back here."}], "nextPosition": 43, "hasMore": false}}}, "prompt": "That thread is on this machine, you can talk to it directly with t3 code: 11111111-1111-4111-8111-111111111111", "expect": {"calls": [{"tool": "t3_thread_send", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}], "notCalls": ["delegate_task", "t3_thread_launch"], "textMust": ["<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>"]}, "notes": "Keeps a rewrite from over-banning t3_thread_send. The ban is only for delegated childThreadIds."}
+{"id": "thread-send-to-named-top-level-thread", "area": "orchestration", "kind": "guard", "pattern": "t3_thread_send to a top-level thread the user names", "experience": "Given another top-level thread id to talk to, the agent used t3_thread_send on it and linked it in the reply.", "rule": "To mention another thread to the user, write its `link` verbatim: <t3-thread://v2/<environmentId>/<threadId>>, with no title.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The other agent disagreed:\n\nTheirs is the better plan to execute. Mine is the wider survey. Start from theirs and graft three items from mine.\n\nTheir 5 points: 1) cache tsc output per package, 2) split the web typecheck into two projects, 3) drop the duplicate lint step in CI, 4) run typecheck only for changed packages in CI (memo), 5) measure before and after on main."}, {"role": "assistant", "text": "We now agree on almost everything. I accept points 1, 2, 3, and 5. I disagree with one detail of the memo in point 4: CI must also typecheck the packages that depend on a changed package, not only the changed ones. From my plan I would graft: project references, a warm tsc cache restored in CI, and a per-package timing report."}], "mocks": {"t3_thread_send": {"threadId": "11111111-1111-4111-8111-111111111111", "messageId": "msg-1", "runId": "run-1", "queued": true}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Faster type checking", "link": "<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>", "status": "idle"}, "items": [{"position": 41, "createdBy": "assistant", "text": "Plan: 1) cache tsc output per package, 2) split the web typecheck, 3) drop the duplicate lint step, 4) memo: typecheck only changed packages in CI, 5) measure on main."}, {"position": 42, "createdBy": "user", "text": "Another agent has a wider survey. I'll bring its answer back here."}], "nextPosition": 43, "hasMore": false}}}, "prompt": "That thread is on this machine, you can talk to it directly with t3 code: 11111111-1111-4111-8111-111111111111", "expect": {"calls": [{"tool": "t3_thread_send", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}], "notCalls": ["delegate_task", "t3_thread_launch"], "textMust": ["<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>"], "callsMustNot": [{"tool": "t3_thread_send", "args": {"freshContext": true}}]}, "notes": "Keeps a rewrite from over-banning t3_thread_send. The ban is only for delegated childThreadIds. An ordinary send keeps the thread's context."}
{"id": "too-many-delegates-cancel-extras", "area": "orchestration", "kind": "guard", "pattern": "volume complaint: cancel, do not add", "experience": "After 'You're doing too much man, we have like 6+ delegates going', the agent stopped the stale review tasks and made the next fix without a new round.", "rule": "none (task_cancel description covers the action)", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Take over https://github.com/acme/app/pull/123. Have Sol and Opus delegates audit it hard."}, {"role": "assistant", "text": "Five audits are running on the PR: three Sol (error handling, concurrency, API surface) and two Opus (tests, migration safety).", "toolCalls": [{"tool": "delegate_task", "input": {"title": "Sol audit: error handling", "mode": "async", "clientRequestId": "pr123-sol-error", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol", "options": {"reasoningEffort": "high"}}, "task": "Audit https://github.com/acme/app/pull/123 for error handling problems. Report each with file:line. Read only."}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "childRunId": "run-child-1", "status": "running", "workState": "working", "providerInstanceId": "codex", "model": "gpt-6.1-sol"}}, {"tool": "delegate_task", "input": {"title": "Sol audit: concurrency", "mode": "async", "clientRequestId": "pr123-sol-concurrency", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol", "options": {"reasoningEffort": "high"}}, "task": "Audit https://github.com/acme/app/pull/123 for concurrency problems. Report each with file:line. Read only."}, "result": {"taskId": "task-2", "childThreadId": "44444444-4444-4444-8444-000000000002", "childRunId": "run-child-2", "status": "running", "workState": "working", "providerInstanceId": "codex", "model": "gpt-6.1-sol"}}, {"tool": "delegate_task", "input": {"title": "Sol audit: API surface", "mode": "async", "clientRequestId": "pr123-sol-api", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol", "options": {"reasoningEffort": "high"}}, "task": "Audit https://github.com/acme/app/pull/123 for API surface problems. Report each with file:line. Read only."}, "result": {"taskId": "task-3", "childThreadId": "44444444-4444-4444-8444-000000000003", "childRunId": "run-child-3", "status": "running", "workState": "working", "providerInstanceId": "codex", "model": "gpt-6.1-sol"}}, {"tool": "delegate_task", "input": {"title": "Opus audit: tests", "mode": "async", "clientRequestId": "pr123-opus-tests", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Audit https://github.com/acme/app/pull/123 for tests problems. Report each with file:line. Read only."}, "result": {"taskId": "task-4", "childThreadId": "44444444-4444-4444-8444-000000000004", "childRunId": "run-child-4", "status": "running", "workState": "working", "providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}}, {"tool": "delegate_task", "input": {"title": "Opus audit: migration safety", "mode": "async", "clientRequestId": "pr123-opus-migration", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Audit https://github.com/acme/app/pull/123 for migration safety problems. Report each with file:line. Read only."}, "result": {"taskId": "task-5", "childThreadId": "44444444-4444-4444-8444-000000000005", "childRunId": "run-child-5", "status": "running", "workState": "working", "providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}}]}], "mocks": {"task_status": {"status": "running", "workState": "working"}, "task_cancel": {"status": "cancel_requested"}}, "world": {"prs": [{"number": 123, "title": "feat(server): resumable uploads", "headRefName": "feat/resumable-uploads"}]}}, "prompt": "You're doing too much man, we have like 6+ delegates going. We don't need to go that hard.", "expect": {"calls": [{"tool": "task_cancel"}], "maxCalls": {"delegate_task": 0}, "notCalls": ["t3_thread_interrupt"]}, "notes": "Pairs with review-round-per-bot-nit."}
{"id": "control-new-thread-view-wording", "area": "orchestration", "kind": "control", "pattern": "'new thread' as product text", "experience": "A UI bug report that says 'new thread view' needs a code fix, not a new T3 thread or delegate.", "rule": "t3_thread_launch and create_threads ... only when the user explicitly asks for separate/new/top-level threads.", "privacy": "commit-safe", "setup": {"role": "top", "world": {"files": {"apps/mobile/src/Sidebar.tsx": "export function Sidebar() {\n return (\n <View style={styles.sidebar} pointerEvents={isFoldable ? 'box-none' : 'auto'}>\n <ThreadList onPress={openThread} />\n </View>\n );\n}\n", "apps/mobile/src/NewThreadView.tsx": "export function NewThreadView() {\n return <View style={StyleSheet.absoluteFill}>{/* composer */}</View>;\n}\n"}}}, "prompt": "On Android foldables the sidebar is visible but tapping threads does nothing in some places, like the new thread view or settings. It makes the sidebar feel broken. Fix it.", "expect": {"notCalls": ["t3_thread_launch", "create_threads", "delegate_task", "orchestrator_capabilities"]}, "notes": ""}
{"id": "control-subagent-label-bug-wording", "area": "orchestration", "kind": "control", "pattern": "'subagent' as product text", "experience": "A bug report about how subagent models are labeled is a code task. It needs no delegation.", "rule": "none", "privacy": "commit-safe", "setup": {"role": "top", "world": {"commits": [{"sha": "61b0e9d", "subject": "fix(web): label subagent messages with the subagent's model"}], "files": {"apps/web/src/subagentLabel.ts": "export function subagentModelLabel(run: Run, parent: Thread) {\n return run.model ?? parent.model;\n}\n"}}}, "prompt": "I recently fixed a bug where models were labeled wrong inside subagents that run through Claude Code. I think it came back in a different form. A Sol subagent shows the parent's model name in the UI. Find the cause and fix it.", "expect": {"notCalls": ["delegate_task", "orchestrator_capabilities", "t3_thread_launch", "create_threads", "Workflow"]}, "notes": ""}
@@ -34,3 +34,4 @@
{"id": "two-children-same-model", "area": "orchestration", "kind": "bad", "pattern": "named-model rule read as a cap", "experience": "Asked for two Sol xhigh subagents, an Astra parent started one and refused the second, citing 'One child per named model' (#24967).", "rule": "Before delegate_task ... One child per named model. (intended: every named model gets a child; read as a cap of one child per model)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}}, "prompt": "Launch two Sol xhigh subagents. Give each a trivial task that only replies OK.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "gpt-6.1-sol", "target.options.reasoningEffort": "xhigh"}}], "minCalls": {"delegate_task": 2}, "callsMustNot": [{"tool": "delegate_task", "args": {"target.model": "~muse"}}, {"tool": "delegate_task", "args": {"target.model": "~claude"}}]}, "notes": "From #24967. One child plus the parent doing the work fails, and so does a second model in place of Sol."}
{"id": "worker-counts-per-model", "area": "orchestration", "kind": "bad", "pattern": "named-model rule read as a cap", "experience": "Asked for 20 Sol workers and 20 Luna workers, the agent started one worker per model (#25359).", "rule": "Before delegate_task ... One child per named model. (intended: every named model gets a child; read as a cap of one child per model)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}, "world": {"files": {"tests/flaky/retry.test.ts": "it('retry is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/upload.test.ts": "it('upload is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/session.test.ts": "it('session is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/search.test.ts": "it('search is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/billing.test.ts": "it('billing is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/webhook.test.ts": "it('webhook is flaky', async () => { /* fails 1 in 5 runs */ });\n"}}}, "prompt": "Six tests in tests/flaky/ fail now and then. Start 3 Muse Wonder Full workers and 3 Grok workers, one test file each, to find and fix the flake.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "muse-wonder-full"}}, {"tool": "delegate_task", "args": {"target.model": "grok-4.7"}}], "minCalls": {"delegate_task": 6}}, "notes": "Scaled down from the real 20 Sol + 20 Luna ask. Muse and Grok need delegate_task from every parent, so a native Sol helper cannot pass or fail it."}
{"id": "linked-thread-chip-reads-there", "area": "orchestration", "kind": "guard", "pattern": "thread chip from a linked machine read on this one", "experience": "A thread chip from a linked machine names its environmentId; an agent that reads it without passing that id reads this machine, where the thread does not exist.", "rule": "The thread chip names its environmentId; t3_thread_read takes it.", "privacy": "commit-safe", "setup": {"role": "top", "linkedEnvironments": true, "mocks": {"t3_environment_links": {"environmentId": "environment-laptop", "links": [{"environmentId": "environment-vps", "label": "Hetzner VPS", "status": "reachable", "access": "auto-accept-edits", "expiresAt": "2026-12-01T00:00:00.000Z", "lastError": null}], "notListed": "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words."}, "t3_thread_read": {"thread": {"threadId": "thread-deploy-api", "title": "Deploy the API", "status": "idle"}, "items": [{"position": 1, "createdBy": "user", "text": "Deploy the API to the VPS and check the health endpoint."}, {"position": 2, "createdBy": "assistant", "text": "Deployed. /health returns 200, but /health/db times out after 5s: the API can't reach Postgres on 10.0.0.5:5432."}], "nextPosition": 3, "hasMore": false}}}, "prompt": "Pick up where [Deploy the API](t3-context://v1/thread/thread_deploy-api) left off. What is still failing?", "promptContext": {"records": [{"version": 1, "kind": "thread", "contextId": "thread_deploy-api", "label": "Deploy the API", "environmentId": "environment-vps", "threadId": "thread-deploy-api", "title": "Deploy the API"}]}, "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "thread-deploy-api", "environmentId": "environment-vps"}}], "notCalls": ["t3_environment_link"]}, "source": {"request": "akj on #17130: attach a linked machine's thread without dragging"}}
+{"id": "thread-send-fresh-context", "area": "orchestration", "kind": "guard", "pattern": "t3_thread_send that should start a fresh provider session", "experience": "The user wanted a confused long-running thread to start over in the same thread without its old context; a plain send would keep feeding it the history.", "rule": "`freshContext: true` on t3_thread_send starts a new provider session in the same thread, like /clear.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The thread working on the CSV importer keeps reverting to the old column mapping from early in its history."}, {"role": "assistant", "text": "That thread has a long history with three different mappings in it, so the model keeps picking up the stale one."}], "mocks": {"t3_thread_send": {"threadId": "11111111-1111-4111-8111-111111111111", "link": "<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>", "messageId": "msg-1", "runId": "run-1", "status": "starting", "delivery": "started"}}}, "prompt": "Send it the final mapping below and have it start over with a clean context in that same thread, so the old history stops leaking in: thread 11111111-1111-4111-8111-111111111111.\n\nFinal mapping: id -> customer_id, amt -> amount_cents, ts -> created_at.", "expect": {"calls": [{"tool": "t3_thread_send", "args": {"threadId": "11111111-1111-4111-8111-111111111111", "freshContext": true}}], "notCalls": ["delegate_task", "t3_thread_launch", "create_threads"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-11-03: fresh provider sessions in one T3 thread"}, "notes": "Pairs with thread-send-to-named-top-level-thread, where an ordinary send must not set freshContext."}
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index 777f7e2adb4..f813ece95dc 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -183,6 +183,8 @@ export interface StartThreadTurnInput extends ThreadCommandInput {
readonly bootstrap?: StartThreadBootstrap;
readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
readonly dispatchMode?: "auto" | "queue" | "steer" | "restart" | "start";
+ /** Start a new provider session; needs the server's `freshContext` capability. */
+ readonly freshContext?: boolean;
}
export interface InterruptThreadTurnInput extends ThreadCommandInput {
@@ -752,6 +754,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
...(input.sourceProposedPlan === undefined
? {}
: { sourcePlanRef: input.sourceProposedPlan }),
+ ...(input.freshContext ? { freshContext: true } : {}),
dispatchMode: { type: "start_immediately" },
});
}
@@ -776,6 +779,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
...(input.titleSeed === undefined ? {} : { titleSeed: input.titleSeed }),
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
+ ...(input.freshContext ? { freshContext: true } : {}),
...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}),
dispatchMode,
});
diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts
index 6756225666f..17f41e9f8d1 100644
--- a/packages/contracts/src/orchestratorMcp.ts
+++ b/packages/contracts/src/orchestratorMcp.ts
@@ -503,6 +503,12 @@ export const OrchestratorMcpThreadSendInput = Schema.Struct({
threadId: ThreadId,
message: OrchestratorMcpPrompt,
mode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
+ freshContext: Schema.optional(
+ Schema.Boolean.annotate({
+ description:
+ "Start a new provider session without the thread's earlier context, like /clear. Never steers.",
+ }),
+ ),
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
});
export type OrchestratorMcpThreadSendInput = typeof OrchestratorMcpThreadSendInput.Type;
diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts
index 77566a2b096..68e3c51087b 100644
--- a/packages/shared/src/composerTrigger.ts
+++ b/packages/shared/src/composerTrigger.ts
@@ -169,3 +169,8 @@ export function replaceTextRange(
const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
return { text: nextText, cursor: safeStart + replacement.length };
}
+
+/** `/clear` as the whole message arms a fresh session instead of sending. */
+export function isClearComposerCommand(text: string): boolean {
+ return /^\/clear\s*$/i.test(text.trim());
+}