@devries-cameron20 / t3code-1 / commits / 99e361e415
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

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

Julius Marminge committed Nov 5, 2026 at 11:29 UTC 99e361e4153fdf9fd361c5c0df279a3e5f2c56c6
37 files changed +471 -38
apps/mobile/src/features/threads/FreshSessionNotice.tsx new
+20
@@ -0,0 +1,20 @@
1 +import { View } from "react-native";
2 +
3 +import { Notice } from "../../components/ui/Notice";
4 +import { setFreshSessionPending, useComposerDraftSettings } from "../../state/use-composer-drafts";
5 +
6 +/** Shown while `/clear` is armed; dismissing it keeps the current session. */
7 +export function FreshSessionNotice(props: { readonly threadKey: string }) {
8 + if (useComposerDraftSettings(props.threadKey).freshContext !== true) return null;
9 + return (
10 + <View className="px-4 pb-3">
11 + <Notice
12 + message="Your next message starts a fresh session. The agent won't see earlier messages in this thread."
13 + icon="arrow.clockwise"
14 + floating
15 + onDismiss={() => setFreshSessionPending(props.threadKey, false)}
16 + dismissLabel="Keep the current session"
17 + />
18 + </View>
19 + );
20 +}
apps/mobile/src/features/threads/ThreadComposer.tsx
+3
@@ -215,6 +215,8 @@ export interface ThreadComposerProps {
215 readonly selectedThread: EnvironmentThreadShell;
216 readonly reportedModelSelection?: ModelSelection | null;
217 readonly hasCompactableConversation: boolean;
218 + /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
219 + readonly onFreshSession?: () => void;
220 readonly serverConfig: T3ServerConfig | null;
221 readonly queueCount: number;
222 readonly activeThreadBusy: boolean;
@@ -561,6 +563,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
563 offersUsageLimits: usageLimitsOffered,
564 onUsageLimits:
565 usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
566 + ...(props.onFreshSession === undefined ? {} : { onFreshSession: props.onFreshSession }),
567 });
568 const voiceInput = useVoiceInputController({
569 ownerKey: composerDraftKey,
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+19 -1
@@ -129,7 +129,7 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
129 import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
130 import type { ComposerEditorHandle } from "../../components/ComposerEditor";
131 import type { StatusTone } from "../../components/StatusPill";
132 -import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
132 +import { getComposerDraftSnapshot, setFreshSessionPending } from "../../state/use-composer-drafts";
133 import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
134 import {
135 ANDROID_READING_MAX_WIDTH,
@@ -174,6 +174,7 @@ import type {
174 import { PendingApprovalCard } from "./PendingApprovalCard";
175 import { ComposerErrorNotice } from "./ComposerErrorNotice";
176 import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
177 +import { FreshSessionNotice } from "./FreshSessionNotice";
178 import { ComposerFeedback } from "./ComposerFeedback";
179 import { ComposerUsageLimits } from "./ComposerUsageLimits";
180 import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -890,6 +891,15 @@ function ThreadDetailBody(
891 jumpMessageLoaded,
892 selectedThreadKey,
893 ]);
894 + // A queued-run edit, question or approval owns the composer, and its send carries no fresh session.
895 + const freshSessionAvailable =
896 + !props.draftMode &&
897 + props.canOperateThread &&
898 + props.queuedRunEdit === null &&
899 + props.activePendingApproval === null &&
900 + props.activePendingUserInput === null &&
901 + props.selectedThread.latestRun != null &&
902 + props.serverConfig?.environment.capabilities.freshContext === true;
903 const hasCompactableConversation =
904 selectedThreadFeed.some(
905 (entry) =>
@@ -1638,6 +1648,9 @@ function ThreadDetailBody(
1648 onDismiss={() => props.onDismissFeedback(submission.id)}
1649 />
1650 ))}
1651 + {freshSessionAvailable ? (
1652 + <FreshSessionNotice threadKey={selectedThreadKey} />
1653 + ) : null}
1654 {props.canOperateThread ? (
1655 <ManagedRuntimeModeNotice
1656 threadKey={selectedThreadKey}
@@ -1801,6 +1814,11 @@ function ThreadDetailBody(
1814 hasCompactableConversation={
1815 hasCompactableConversation && !props.isCompacting
1816 }
1817 + {...(freshSessionAvailable
1818 + ? {
1819 + onFreshSession: () => setFreshSessionPending(selectedThreadKey, true),
1820 + }
1821 + : {})}
1822 serverConfig={props.serverConfig}
1823 queueCount={props.selectedThreadQueueCount}
1824 activeThreadBusy={props.activeThreadBusy}
apps/mobile/src/features/threads/ThreadFeed.tsx
+9
@@ -3730,6 +3730,15 @@ export const ThreadFeed = memo(function ThreadFeed({
3730 workspaceRoot={props.workspaceRoot}
3731 >
3732 <ThreadMediaVisibility>
3733 + {info.item.type === "message" &&
3734 + info.item.message.projectedItem?.item.type === "user_message" &&
3735 + info.item.message.projectedItem.item.freshContext ? (
3736 + <ThreadContextDivider
3737 + label="New session"
3738 + icon="arrow.clockwise"
3739 + iconColor={iconSubtleColor}
3740 + />
3741 + ) : null}
3742 {info.item.type === "message" &&
3743 !isCompactionCommandFeedEntry(info.item) &&
3744 info.item.message.projectedItem?.item.type === "user_message" &&
apps/mobile/src/features/threads/ThreadQueueControl.tsx
+4 -1
@@ -238,7 +238,10 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
238 {queuedRuns.map(({ run, text, attachments, context, message }, index) => {
239 const controls = resolveThreadQueueRowControls({
240 busy: busyRunId !== null,
241 - canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
241 + // A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
242 + canPromoteToSteer:
243 + (workflow?.canPromoteToSteer ?? false) &&
244 + (run.freshContext !== true || workflow?.promoteSkipsCompaction === true),
245 canSendNow: workflow?.canSendNow ?? false,
246 editBlocked: editBlockedReason !== null,
247 isEditing: editing?.runId === run.id,
apps/mobile/src/features/threads/use-composer-command-menu.test.ts
+19
@@ -94,6 +94,25 @@ describe("mobile slash commands", () => {
94 },
95 );
96
97 + it("offers T3's /clear in place of the provider's, only at the message start", () => {
98 + const claude = {
99 + driver: ProviderDriverKind.make("claudeAgent"),
100 + slashCommands: [{ name: "clear", description: "Clear conversation history" }],
101 + };
102 + const build = (offersFreshSession: boolean, atMessageStart = true) =>
103 + buildComposerSlashCommandItems({
104 + query: "cle",
105 + atMessageStart,
106 + hasThread: true,
107 + allowInteractionMode: true,
108 + offersFreshSession,
109 + selectedProviderStatus: claude,
110 + }).map((item) => item.id);
111 + expect(build(true)).toEqual(["cmd:clear"]);
112 + expect(build(false)).toEqual(["pcmd:clear"]);
113 + expect(build(true, false)).toEqual([]);
114 + });
115 +
116 it("still applies the T3 plan command for supported providers", () => {
117 const items = buildComposerSlashCommandItems({
118 query: "plan",
apps/mobile/src/features/threads/use-composer-command-menu.ts
+24 -1
@@ -104,6 +104,8 @@ export function buildComposerSlashCommandItems(input: {
104 readonly hasThread: boolean;
105 readonly hasCompactableConversation?: boolean;
106 readonly offersUsageLimits?: boolean;
107 + /** T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live. */
108 + readonly offersFreshSession?: boolean;
109 readonly allowInteractionMode: boolean;
110 readonly selectedProviderStatus: Pick<
111 ServerProvider,
@@ -141,10 +143,20 @@ export function buildComposerSlashCommandItems(input: {
143 );
144
145 // Providers expand commands only at the start of a message. T3 commands
144 - // change local state and do not have this restriction.
146 + // change local state and do not have this restriction, except `/clear`.
147 if (!input.atMessageStart) return items;
148 + if (input.offersFreshSession && "clear".includes(query)) {
149 + items.push({
150 + id: "cmd:clear",
151 + type: "slash-command",
152 + command: "clear",
153 + label: "/clear",
154 + description: "Start a fresh session",
155 + });
156 + }
157 for (const command of input.selectedProviderStatus?.slashCommands ?? []) {
158 if (!command.name.toLowerCase().includes(query)) continue;
159 + if (command.name === "clear" && input.offersFreshSession) continue;
160 if (command.name === "compact" && !input.hasCompactableConversation) continue;
161 if (command.name === USAGE_LIMITS_COMMAND.name && input.offersUsageLimits && !input.hasThread) {
162 continue;
@@ -225,6 +237,7 @@ export function useComposerCommandMenu({
237 onChangeDraftMessage,
238 onUpdateInteractionMode,
239 onUsageLimits,
240 + onFreshSession,
241 }: {
242 readonly draftMessage: string;
243 readonly ownerKey: string | null;
@@ -246,6 +259,8 @@ export function useComposerCommandMenu({
259 readonly onChangeDraftMessage: (value: string) => void;
260 readonly onUpdateInteractionMode?: (mode: ProviderInteractionMode) => void;
261 readonly onUsageLimits?: () => void;
262 + /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
263 + readonly onFreshSession?: () => void;
264 }) {
265 const [localSelection, setLocalSelection] = useState(() => ({
266 ownerKey,
@@ -349,6 +364,7 @@ export function useComposerCommandMenu({
364 hasThread,
365 hasCompactableConversation,
366 offersUsageLimits,
367 + offersFreshSession: onFreshSession !== undefined,
368 allowInteractionMode: onUpdateInteractionMode !== undefined,
369 selectedProviderStatus: selectedProviderStatus
370 ? {
@@ -582,6 +598,13 @@ export function useComposerCommandMenu({
598 return;
599 }
600
601 + if (item.type === "slash-command" && item.command === "clear" && onFreshSession) {
602 + const cleared = replaceTextRange(draftMessage, trigger.rangeStart, trigger.rangeEnd, "");
603 + setSelection({ start: cleared.cursor, end: cleared.cursor });
604 + onChangeDraftMessage(cleared.text);
605 + onFreshSession();
606 + return;
607 + }
608 if (
609 item.type === "provider-slash-command" &&
610 item.command.name === USAGE_LIMITS_COMMAND.name &&
apps/mobile/src/state/thread-outbox-model.ts
+3
@@ -57,6 +57,7 @@ export const QueuedThreadMessageSchema = Schema.Struct({
57 modelSelection: Schema.optional(ModelSelection),
58 dispatchMode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
59 compactBeforeSend: Schema.optional(Schema.Boolean),
60 + freshContext: Schema.optional(Schema.Boolean),
61 runtimeMode: Schema.optional(RuntimeMode),
62 interactionMode: Schema.optional(ProviderInteractionMode),
63 creation: Schema.optional(QueuedThreadCreationSchema),
@@ -92,6 +93,8 @@ export interface QueuedThreadMessage {
93 readonly dispatchMode?: ComposerDispatchMode;
94 /** Sends "When you return"'s `/compact` ahead of the message, which queues behind it. */
95 readonly compactBeforeSend?: boolean;
96 + /** Starts a new provider session (`/clear`). */
97 + readonly freshContext?: boolean;
98 readonly creation?: QueuedThreadCreation;
99 readonly createdAt: string;
100 }
apps/mobile/src/state/thread-task-permissions.test.ts
+83 -1
@@ -19,6 +19,7 @@ import {
19 import type { DraftComposerImageAttachment } from "../lib/composerImages";
20 import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
21 import { sendApprovalFeedback } from "@t3tools/client-runtime/state/thread-requests";
22 +import { DateTime } from "effect";
23 import { AsyncResult, type Atom } from "effect/reactivity";
24 import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
25
@@ -34,6 +35,9 @@ const state = vi.hoisted(() => ({
35 projection: null as OrchestrationV2ThreadProjection | null,
36 pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests,
37 enqueue: vi.fn(async () => undefined),
38 + freshPending: false,
39 + compactDue: false,
40 + setFreshPending: vi.fn(),
41 clearDraft: vi.fn(),
42 approve: vi.fn(),
43 answer: vi.fn(),
@@ -54,7 +58,7 @@ const state = vi.hoisted(() => ({
58 runtimeMode: "full-access",
59 interactionMode: "default",
60 runtime: null,
57 - latestRun: null,
61 + latestRun: null as unknown,
62 },
63 }));
64
@@ -70,6 +74,10 @@ vi.mock("react", () => ({
74 ],
75 }));
76 vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
77 +vi.mock("@t3tools/client-runtime/state/context-window", async (importOriginal) => ({
78 + ...(await importOriginal<typeof import("@t3tools/client-runtime/state/context-window")>()),
79 + shouldCompactBeforeSend: () => state.compactDue,
80 +}));
81 vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
82 vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
83 vi.mock("./queued-run-edit", () => ({
@@ -142,6 +150,8 @@ vi.mock("./use-composer-drafts", async () => {
150 composerDraftsAtom: Atom.make({}),
151 composerContextImportsAtom: Atom.make({}),
152 getComposerDraftSnapshot: () => state.draft,
153 + isFreshSessionPending: () => state.freshPending,
154 + setFreshSessionPending: state.setFreshPending,
155 clearComposerDraftContent: state.clearDraft,
156 clearComposerDraft: state.clearDraft,
157 setComposerDraftText: (_key: string, text: string) => {
@@ -181,6 +191,9 @@ beforeEach(() => {
191 state.grantedEnvironments = new Set(["primary"]);
192 state.connectionState = "connected";
193 state.draft = { text: "Keep my draft", attachments: [], modelSelection: undefined };
194 + state.freshPending = false;
195 + state.compactDue = false;
196 + state.thread.latestRun = null;
197 state.projection = null;
198 state.serverConfig = {
199 providers: [{ instanceId: "codex", driver: "codex", enabled: true }],
@@ -254,6 +267,75 @@ describe("mobile task permissions", () => {
267 });
268 });
269
270 + it("keeps an armed fresh session for the message after an approval redirect", async () => {
271 + state.grantedEnvironments.add("secondary");
272 + state.freshPending = true;
273 + const composer = useThreadComposerState();
274 + expect(await composer.onSendMessage(undefined, async () => true)).toBe("message");
275 + expect(state.enqueue).toHaveBeenLastCalledWith(
276 + expect.not.objectContaining({ freshContext: true }),
277 + );
278 + expect(state.setFreshPending).not.toHaveBeenCalled();
279 + expect(await composer.onSendMessage()).toBe("message");
280 + expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true }));
281 + expect(state.setFreshPending).toHaveBeenCalledWith("secondary:thread", false);
282 + });
283 +
284 + it("compacts a stale thread before sending unless a fresh session is armed", async () => {
285 + state.grantedEnvironments.add("secondary");
286 + state.projection = {
287 + thread: {
288 + ...state.thread,
289 + activeProviderThreadId: null,
290 + lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null },
291 + },
292 + runs: [],
293 + attempts: [],
294 + nodes: [],
295 + subagents: [],
296 + providerSessions: [],
297 + providerThreads: [],
298 + providerTurns: [],
299 + runtimeRequests: [],
300 + messages: [],
301 + plans: [],
302 + turnItems: [],
303 + checkpointScopes: [],
304 + checkpoints: [],
305 + contextHandoffs: [],
306 + contextTransfers: [],
307 + visibleTurnItems: [],
308 + updatedAt: DateTime.makeUnsafe(0),
309 + } as unknown as OrchestrationV2ThreadProjection;
310 + state.compactDue = true;
311 + const composer = useThreadComposerState();
312 + await composer.onSendMessage();
313 + expect(state.enqueue).toHaveBeenLastCalledWith(
314 + expect.objectContaining({ compactBeforeSend: true }),
315 + );
316 + state.freshPending = true;
317 + await composer.onSendMessage();
318 + expect(state.enqueue).toHaveBeenLastCalledWith(
319 + expect.not.objectContaining({ compactBeforeSend: true }),
320 + );
321 + expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true }));
322 + });
323 +
324 + it("sends a typed /clear with an approval redirect as that reply's text", async () => {
325 + state.grantedEnvironments.add("secondary");
326 + state.serverConfig = {
327 + ...state.serverConfig,
328 + environment: { capabilities: { freshContext: true } },
329 + } as ServerConfig;
330 + state.thread.latestRun = { runId: "run" };
331 + state.draft = { ...state.draft, text: "/clear" };
332 + const composer = useThreadComposerState();
333 + const beforeDispatch = vi.fn(async () => "responded" as const);
334 + expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
335 + expect(beforeDispatch).toHaveBeenCalledWith("/clear", false);
336 + expect(state.setFreshPending).not.toHaveBeenCalled();
337 + });
338 +
339 it("rechecks a retained send callback before clearing or queueing the draft", async () => {
340 state.grantedEnvironments.add("secondary");
341 const composer = useThreadComposerState();
apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
+1
@@ -151,6 +151,7 @@ vi.mock("./use-composer-drafts", async () => {
151 state.draftText += `\n${input.text}`;
152 }),
153 replaceComposerDraftAttachments: vi.fn(),
154 + setFreshSessionPending: vi.fn(),
155 undoComposerDraftMerge: vi.fn(),
156 updateComposerDraftSettings: vi.fn(),
157 waitForComposerDraftsLoaded: vi.fn(),
apps/mobile/src/state/threadOutboxDelivery.ts
+2
@@ -449,6 +449,7 @@ export async function restoreRejectedQueuedMessage(
449 ...(queuedMessage.modelSelection ? { modelSelection: queuedMessage.modelSelection } : {}),
450 ...(queuedMessage.runtimeMode ? { runtimeMode: queuedMessage.runtimeMode } : {}),
451 ...(queuedMessage.interactionMode ? { interactionMode: queuedMessage.interactionMode } : {}),
452 + ...(queuedMessage.freshContext ? { freshContext: true } : {}),
453 ...(queuedMessage.creation
454 ? {
455 workspaceSelection: {
@@ -933,6 +934,7 @@ export function createThreadOutboxDelivery(): {
934 interactionMode: sendSettings.interactionMode,
935 createdAt: queuedMessage.createdAt,
936 dispatchMode: queuedMessage.dispatchMode ?? "start",
937 + ...(queuedMessage.freshContext ? { freshContext: true } : {}),
938 },
939 });
940 if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true;
apps/mobile/src/state/use-composer-drafts.ts
+31 -4
@@ -403,6 +403,8 @@ export interface ComposerDraft {
403 readonly modelSelection?: ModelSelection;
404 readonly runtimeMode?: RuntimeMode;
405 readonly interactionMode?: ProviderInteractionMode;
406 + /** `/clear` armed this draft: its next message starts a fresh provider session. */
407 + readonly freshContext?: boolean;
408 readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
409 readonly project?: ComposerDraftProject;
410 }
@@ -436,7 +438,12 @@ export interface ComposerDraftWorkspaceSelection {
438
439 export type ComposerDraftSettingsUpdate = Pick<
440 ComposerDraft,
439 - "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection" | "project"
441 + | "modelSelection"
442 + | "runtimeMode"
443 + | "interactionMode"
444 + | "freshContext"
445 + | "workspaceSelection"
446 + | "project"
447 >;
448
449 const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
@@ -468,6 +475,7 @@ const ComposerDraftSchema = Schema.Struct({
475 modelSelection: Schema.optional(ModelSelectionSchema),
476 runtimeMode: Schema.optional(RuntimeModeSchema),
477 interactionMode: Schema.optional(ProviderInteractionModeSchema),
478 + freshContext: Schema.optional(Schema.Boolean),
479 workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
480 project: Schema.optional(ComposerDraftProjectSchema),
481 });
@@ -647,6 +655,7 @@ function isEmptyDraft(draft: ComposerDraft): boolean {
655 draft.modelSelection === undefined &&
656 draft.runtimeMode === undefined &&
657 draft.interactionMode === undefined &&
658 + draft.freshContext !== true &&
659 draft.workspaceSelection === undefined
660 );
661 }
@@ -1532,6 +1541,15 @@ export function updateComposerDraftSettings(
1541 });
1542 }
1543
1544 +export function setFreshSessionPending(draftKey: string, pending: boolean): void {
1545 + if ((getComposerDraftSnapshot(draftKey).freshContext === true) === pending) return;
1546 + updateComposerDraftSettings(draftKey, { freshContext: pending ? true : undefined });
1547 +}
1548 +
1549 +export function isFreshSessionPending(draftKey: string): boolean {
1550 + return getComposerDraftSnapshot(draftKey).freshContext === true;
1551 +}
1552 +
1553 export function subscribeComposerDraftModelReconciliation(input: {
1554 readonly registry: AtomRegistry.AtomRegistry;
1555 readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
@@ -1777,6 +1795,7 @@ export function sameComposerDraftState(a: ComposerDraft, b: ComposerDraft): bool
1795 a.modelSelection === b.modelSelection &&
1796 a.runtimeMode === b.runtimeMode &&
1797 a.interactionMode === b.interactionMode &&
1798 + a.freshContext === b.freshContext &&
1799 a.workspaceSelection === b.workspaceSelection
1800 );
1801 }
@@ -1802,7 +1821,12 @@ export function undoComposerDraftMergeState(
1821 .map((attachment) => attachment.id),
1822 );
1823 const undoSetting = <
1805 - K extends "modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection",
1824 + K extends
1825 + | "modelSelection"
1826 + | "runtimeMode"
1827 + | "interactionMode"
1828 + | "freshContext"
1829 + | "workspaceSelection",
1830 >(
1831 key: K,
1832 ): ComposerDraft[K] => (existing[key] === merged[key] ? snapshot[key] : existing[key]);
@@ -1822,6 +1846,7 @@ export function undoComposerDraftMergeState(
1846 modelSelection: undoSetting("modelSelection"),
1847 runtimeMode: undoSetting("runtimeMode"),
1848 interactionMode: undoSetting("interactionMode"),
1849 + freshContext: undoSetting("freshContext"),
1850 workspaceSelection: undoSetting("workspaceSelection"),
1851 };
1852 return withComposerDraft(current, draftKey, draft);
@@ -2054,7 +2079,7 @@ export const composerDraftUploadSourcesAtom = Atom.make((get): ComposerDraftUplo
2079
2080 type ComposerDraftSettings = Pick<
2081 ComposerDraft,
2057 - "modelSelection" | "runtimeMode" | "interactionMode"
2082 + "modelSelection" | "runtimeMode" | "interactionMode" | "freshContext"
2083 >;
2084 const EMPTY_DRAFT_SETTINGS: ComposerDraftSettings = {};
2085 const composerDraftSettingsAtom = Atom.family((draftKey: string) =>
@@ -2064,13 +2089,15 @@ const composerDraftSettingsAtom = Atom.family((draftKey: string) =>
2089 modelSelection: draft.modelSelection,
2090 runtimeMode: draft.runtimeMode,
2091 interactionMode: draft.interactionMode,
2092 + freshContext: draft.freshContext,
2093 };
2094 }).pipe(
2095 Atom.withEquality(
2096 (a: ComposerDraftSettings, b: ComposerDraftSettings) =>
2097 a.modelSelection === b.modelSelection &&
2098 a.runtimeMode === b.runtimeMode &&
2073 - a.interactionMode === b.interactionMode,
2099 + a.interactionMode === b.interactionMode &&
2100 + a.freshContext === b.freshContext,
2101 ),
2102 ),
2103 );
apps/mobile/src/state/use-thread-composer-state.ts
+23
@@ -72,14 +72,17 @@ import {
72 clearComposerDraftContent,
73 composerContextImportsAtom,
74 getComposerDraftSnapshot,
75 + isFreshSessionPending,
76 mergeComposerDraftContent,
77 removeComposerDraftAttachment,
78 scheduleUnusedComposerAttachmentCleanup,
79 setComposerDraftText,
80 + setFreshSessionPending,
81 updateComposerDraftSettings,
82 useComposerDraft,
83 useComposerDraftSettings,
84 } from "./use-composer-drafts";
85 +import { isClearComposerCommand } from "@t3tools/shared/composerTrigger";
86 import {
87 resolveComposerDispatchMode,
88 type ActiveTurnComposerAction,
@@ -554,6 +557,19 @@ export function useThreadComposerState() {
557 if (text.length === 0 && attachments.length === 0) {
558 return null;
559 }
560 + // A redirect's text answers its approval, so /clear there is that text, not the command.
561 + if (
562 + beforeDispatch === undefined &&
563 + selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.freshContext === true &&
564 + thread.latestRun != null &&
565 + attachments.length === 0 &&
566 + draft.context === undefined &&
567 + isClearComposerCommand(text)
568 + ) {
569 + setFreshSessionPending(threadKey, true);
570 + clearComposerDraftContent(threadKey);
571 + return null;
572 + }
573 // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely.
574 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
575 Dialog.alert(
@@ -672,8 +688,12 @@ export function useThreadComposerState() {
688 ? "queue"
689 : "auto";
690
691 + // A redirect belongs to the approval it answers; the armed session waits for the next message.
692 + const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey);
693 const metadata = makeQueuedMessageMetadata();
694 + // A fresh session drops the context a compaction would summarize.
695 const compactBeforeSend =
696 + !freshContext &&
697 followUpDispatchMode === null &&
698 selectedEnvironmentRuntime?.connectionState === "connected" &&
699 selectedThreadProjection !== null &&
@@ -714,9 +734,11 @@ export function useThreadComposerState() {
734 : followUpDispatchMode === null
735 ? {}
736 : { dispatchMode: followUpDispatchMode }),
737 + ...(freshContext ? { freshContext: true } : {}),
738 createdAt: metadata.createdAt,
739 });
740 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
741 + if (freshContext) setFreshSessionPending(threadKey, false);
742 enqueuePromise.then(
743 () => scheduleUnusedComposerAttachmentCleanup(attachments),
744 (error: unknown) => {
@@ -727,6 +749,7 @@ export function useThreadComposerState() {
749 attachments: [],
750 });
751 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
752 + if (freshContext) setFreshSessionPending(threadKey, true);
753 setThreadComposerError(
754 threadKey,
755 error instanceof Error ? error.message : "Failed to save the queued message.",
apps/server/src/mcp/OrchestratorMcpService.ts
+1
@@ -3133,6 +3133,7 @@ const make = Effect.gen(function* () {
3133 text: input.message,
3134 attachments: [],
3135 mode,
3136 + ...(input.freshContext ? { freshContext: true } : {}),
3137 createdBy: "agent",
3138 creationSource: "mcp",
3139 })
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+15
@@ -521,6 +521,21 @@ it.effect("retains automation and sender attribution while a message waits in th
521 assert.equal(message?.scheduledTaskId, scheduledTaskId);
522 assert.equal(message?.senderThreadId, senderThreadId);
523 assert.equal(message?.text, "Run the audit");
524 + // A fresh send queues instead of steering, so it needs no steerable run.
525 + const fresh = yield* threads.sendToThread({
526 + projectId,
527 + commandId: CommandId.make("command:automation:queued-fresh"),
528 + threadId: launched.threadId,
529 + messageId: MessageId.make("message:automation:queued-fresh"),
530 + text: "Start over",
531 + attachments: [],
532 + mode: "steer",
533 + freshContext: true,
534 + createdBy: "agent",
535 + creationSource: "mcp",
536 + });
537 + assert.equal(fresh.delivery, "queued");
538 + assert.isTrue(fresh.run.freshContext);
539 }).pipe(Effect.provide(harness.layer));
540 });
541
apps/server/src/orchestration-v2/ThreadManagementService.ts
+14 -6
@@ -146,6 +146,8 @@ export interface ThreadManagementSendInput {
146 readonly attachments: ReadonlyArray<ChatAttachment>;
147 readonly modelSelection?: ModelSelection;
148 readonly mode: ThreadManagementSendMode;
149 + /** Start a new provider session; the orchestrator queues it instead of steering. */
150 + readonly freshContext?: boolean;
151 readonly createdBy: OrchestrationV2Actor;
152 readonly creationSource: OrchestrationV2CreationSource;
153 }
@@ -820,26 +822,31 @@ const make = Effect.gen(function* () {
822 });
823 }
824 const steerableRun = latestSteerableRun(target);
825 + // A fresh send never joins a running turn, so it needs none to steer or restart.
826 + const mode =
827 + input.freshContext && (input.mode === "steer" || input.mode === "restart")
828 + ? "queue"
829 + : input.mode;
830 let dispatchMode: Extract<
831 OrchestrationV2Command,
832 { readonly type: "message.dispatch" }
833 >["dispatchMode"];
827 - if (input.mode === "steer" || input.mode === "restart") {
834 + if (mode === "steer" || mode === "restart") {
835 if (steerableRun === undefined) {
836 return yield* new ThreadManagementNoSteerableRunError({
837 threadId: input.threadId,
831 - mode: input.mode,
838 + mode,
839 });
840 }
841 dispatchMode = {
835 - type: input.mode === "steer" ? "steer_active" : "restart_active",
842 + type: mode === "steer" ? "steer_active" : "restart_active",
843 targetRunId: steerableRun.id,
844 };
838 - } else if (input.mode === "auto" && steerableRun !== undefined) {
845 + } else if (mode === "auto" && steerableRun !== undefined) {
846 dispatchMode = { type: "steer_active", targetRunId: steerableRun.id };
847 } else {
848 dispatchMode = {
842 - type: input.mode === "queue" ? "queue_after_active" : "start_immediately",
849 + type: mode === "queue" ? "queue_after_active" : "start_immediately",
850 };
851 }
852
@@ -853,6 +860,7 @@ const make = Effect.gen(function* () {
860 text: input.text,
861 attachments: input.attachments,
862 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
863 + ...(input.freshContext ? { freshContext: true } : {}),
864 dispatchMode,
865 createdBy: input.createdBy,
866 creationSource: input.creationSource,
@@ -888,7 +896,7 @@ const make = Effect.gen(function* () {
896 ? "queued"
897 : turnItem.inputIntent === "turn_start"
898 ? "started"
891 - : input.mode === "restart"
899 + : mode === "restart"
900 ? "restarted"
901 : "steered";
902 return { dispatch: dispatched, projection, message, run, turnItem, delivery };
apps/server/src/provider/agentContextBudget.json
+1 -1
@@ -1,5 +1,5 @@
1 {
2 "claudeSystemAppendBytes": 5133,
3 "codexAdditionalContextBytes": 6863,
4 - "mcpToolListJsonBytes": 47498
4 + "mcpToolListJsonBytes": 47642
5 }
apps/web/src/components/ChatView.logic.test.ts
+14
@@ -1077,6 +1077,7 @@ describe("planComposerTurn", () => {
1077 keepFullHistory: false,
1078 phase: "ready" as const,
1079 dispatchMode: "auto" as const,
1080 + freshContext: false,
1081 };
1082
1083 it("prepares a worktree from the selected branch on a new thread", () => {
@@ -1126,6 +1127,19 @@ describe("planComposerTurn", () => {
1127 shouldQueueBehindActiveRun: false,
1128 baseBranchForWorktree: null,
1129 });
1130 + // A fresh session cannot join the running turn, and a stale one is not compacted first.
1131 + expect(
1132 + planComposerTurn({
1133 + ...running,
1134 + dispatchMode: "steer",
1135 + freshContext: true,
1136 + resumeCompactionTokens: 120_000,
1137 + }),
1138 + ).toMatchObject({
1139 + compactBeforeSend: false,
1140 + turnDispatchMode: "queue",
1141 + shouldQueueBehindActiveRun: true,
1142 + });
1143 });
1144 });
1145
apps/web/src/components/ChatView.logic.ts
+9 -2
@@ -1411,6 +1411,8 @@ export function planComposerTurn(input: {
1411 readonly keepFullHistory: boolean;
1412 readonly phase: SessionPhase;
1413 readonly dispatchMode: ComposerDispatchMode;
1414 + /** The turn starts a new provider session, so it neither compacts first nor steers. */
1415 + readonly freshContext: boolean;
1416 }) {
1417 const isFirstMessage =
1418 !input.sendQueuesBehindSetup && (!input.isServerThread || input.activeMessageCount === 0);
@@ -1420,9 +1422,14 @@ export function planComposerTurn(input: {
1422 // old history. The message queues behind the /compact run, since steering into it is
1423 // rejected.
1424 const compactBeforeSend =
1425 + !input.freshContext &&
1426 input.resumeCompactionTokens !== null &&
1427 !input.keepFullHistory &&
1428 !COMPACT_COMMAND_PATTERN.test(input.messageText);
1429 + const dispatchMode =
1430 + input.freshContext && (input.dispatchMode === "steer" || input.dispatchMode === "restart")
1431 + ? "queue"
1432 + : input.dispatchMode;
1433 return {
1434 // In worktree mode, require an explicit base branch so we don't silently
1435 // fall back to local execution when branch selection is missing.
@@ -1430,11 +1437,11 @@ export function planComposerTurn(input: {
1437 baseBranchForWorktree: shouldCreateWorktree ? input.activeThreadBranch : null,
1438 compactBeforeSend,
1439 turnDispatchMode:
1433 - compactBeforeSend || input.sendQueuesBehindSetup ? ("queue" as const) : input.dispatchMode,
1440 + compactBeforeSend || input.sendQueuesBehindSetup ? ("queue" as const) : dispatchMode,
1441 shouldQueueBehindActiveRun:
1442 compactBeforeSend ||
1443 input.sendQueuesBehindSetup ||
1437 - (input.phase === "running" && input.dispatchMode === "queue"),
1444 + (input.phase === "running" && dispatchMode === "queue"),
1445 };
1446 }
1447
apps/web/src/components/ChatView.tsx
+20
@@ -45,6 +45,8 @@ import { isScratchProject } from "@t3tools/client-runtime/state/projects";
45 import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
46 import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";
47 import { feedbackBannerItem } from "./chat/ComposerFeedback";
48 +import { freshSessionBannerItem } from "./chat/ComposerFreshSession";
49 +import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms";
50 import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";
51 import { useWorktreeSetup } from "./chat/useWorktreeSetup";
52 import { useChatShortcuts } from "./chat/useChatShortcuts";
@@ -2510,8 +2512,15 @@ export default function ChatView(props: ChatViewProps) {
2512 return next;
2513 });
2514 };
2515 + const freshSessionAvailable =
2516 + activeMessageCount > 0 && serverConfig?.environment.capabilities.freshContext === true;
2517 + // While a question or approval owns the composer, its text answers that, not the agent.
2518 + const freshSessionCommandAvailable =
2519 + freshSessionAvailable && activePendingApproval === null && pendingUserInputs.length === 0;
2520 + const freshSessionArmed = useFreshSessionArmed(routeThreadKey);
2521 const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory);
2522 const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory);
2523 + const armFreshSessionStable = useStableCallback(() => armFreshSession(routeThreadKey));
2524 const handleRestoreThreadBranch = () => {
2525 if (!canWriteSourceControl) return;
2526 if (gitStatusQuery.data?.hasWorkingTreeChanges) {
@@ -2602,6 +2611,11 @@ export default function ChatView(props: ChatViewProps) {
2611 const limitRecoveryItems = limitRecoveryBanner === null ? [] : [limitRecoveryBanner];
2612 const usageLimitsItems = usageLimitsBanner === null ? [] : [usageLimitsBanner];
2613 const projectCloneItems = projectCloneBannerItem === null ? [] : [projectCloneBannerItem];
2614 + // An approval's feedback goes to that approval; the armed session waits for the next message.
2615 + const freshSessionItems =
2616 + freshSessionAvailable && freshSessionArmed && activePendingApproval === null
2617 + ? [freshSessionBannerItem(() => disarmFreshSession(routeThreadKey))]
2618 + : [];
2619 if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
2620 return [
2621 ...feedbackBannerItems,
@@ -2609,6 +2623,7 @@ export default function ChatView(props: ChatViewProps) {
2623 ...limitRecoveryItems,
2624 ...usageLimitsItems,
2625 ...projectCloneItems,
2626 + ...freshSessionItems,
2627 ...systemComposerBannerItems,
2628 ];
2629 }
@@ -2618,6 +2633,7 @@ export default function ChatView(props: ChatViewProps) {
2633 ...limitRecoveryItems,
2634 ...usageLimitsItems,
2635 ...projectCloneItems,
2636 + ...freshSessionItems,
2637 ...systemComposerBannerItems,
2638 branchMismatchBannerItem({
2639 mismatchKey: activeBranchMismatchKey,
@@ -2922,6 +2938,7 @@ export default function ChatView(props: ChatViewProps) {
2938 panelAnimationsActive,
2939 panelAnimationDurationMs,
2940 keepFullHistory,
2941 + freshSessionAvailable: freshSessionCommandAvailable,
2942 resumeCompactionTokens,
2943 showPlanFollowUpPrompt,
2944 usageLimitsKey,
@@ -3640,6 +3657,9 @@ export default function ChatView(props: ChatViewProps) {
3657 onToggleKeepFullHistory={toggleKeepFullHistoryStable}
3658 sideChatAvailable={sideChat.available}
3659 sideChatDisabledReason={sideChatDisabledReason}
3660 + onFreshSession={
3661 + freshSessionCommandAvailable ? armFreshSessionStable : undefined
3662 + }
3663 onUsageLimitsCommand={
3664 usageLimitsOffered &&
3665 usageLimitsKey !== null &&
apps/web/src/components/chat/ChatComposer.tsx
+13
@@ -383,6 +383,8 @@ export interface ChatComposerProps {
383 onUsageLimitsCommand?: (() => void) | undefined;
384 sideChatAvailable?: boolean;
385 sideChatDisabledReason?: string | null;
386 + /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
387 + onFreshSession?: (() => void) | undefined;
388 environmentUnavailable: {
389 readonly label: string;
390 readonly connection: EnvironmentConnectionPresentation;
@@ -1151,6 +1153,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1153 planModeUiEnabled,
1154 sideChatAvailable: props.sideChatAvailable === true,
1155 sideChatDisabledReason: props.sideChatDisabledReason ?? null,
1156 + freshSessionAvailable: props.onFreshSession !== undefined,
1157 compactSlashCommandAvailable,
1158 selectedProvider,
1159 selectedProviderSkills,
@@ -1880,6 +1883,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1883 }
1884 return;
1885 }
1886 + if (item.command === "clear") {
1887 + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {
1888 + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),
1889 + });
1890 + if (applied) {
1891 + setComposerHighlightedItemId(null);
1892 + props.onFreshSession?.();
1893 + }
1894 + return;
1895 + }
1896 if (item.command === "side" || item.command === "btw") {
1897 if (props.sideChatDisabledReason) return;
1898 const applied = applyPromptReplacement(
apps/web/src/components/chat/ComposerFreshSession.tsx new
+16
@@ -0,0 +1,16 @@
1 +import { EraserIcon } from "lucide-react";
2 +
3 +import type { ComposerBannerStackItem } from "./ComposerBannerStack";
4 +
5 +/** Shown while `/clear` is armed; dismissing it keeps the current conversation. */
6 +export function freshSessionBannerItem(onUndo: () => void): ComposerBannerStackItem {
7 + return {
8 + id: "fresh-session",
9 + variant: "info",
10 + icon: <EraserIcon />,
11 + title: "Your next message starts a fresh session",
12 + description: "The agent won't see earlier messages in this thread.",
13 + dismissLabel: "Keep the current session",
14 + onDismiss: onUndo,
15 + };
16 +}
apps/web/src/components/chat/QueuedRunsControl.tsx
+13 -4
@@ -113,7 +113,11 @@ export function QueuedRunsControl({
113 const workflow = projection ? deriveThreadQueueWorkflowState(projection) : null;
114 const queued = workflow?.queuedRuns ?? [];
115 const activeRun = workflow?.activeRun ?? null;
116 - const canSend = workflow?.canSendNow === true || workflow?.canPromoteToSteer === true;
116 + // A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
117 + const canSendRun = (freshContext: boolean) =>
118 + workflow?.canSendNow === true ||
119 + (workflow?.canPromoteToSteer === true &&
120 + (!freshContext || workflow.promoteSkipsCompaction === true));
121 const queuedImageUrlById = new Map(
122 queuedImageAttachmentUrls.flatMap((url, index) => {
123 const resource = queuedImageAttachmentResources[index];
@@ -129,6 +133,7 @@ export function QueuedRunsControl({
133 message,
134 runId: run.id,
135 messageId: run.userMessageId,
136 + freshContext: run.freshContext === true,
137 serverIndex,
138 text,
139 // A guest's message keeps the guest's words; the owner can cancel it, not rewrite it.
@@ -148,6 +153,7 @@ export function QueuedRunsControl({
153 message: undefined,
154 runId: null,
155 messageId: null,
156 + freshContext: false,
157 serverIndex: null,
158 text: message.text,
159 editable: true,
@@ -164,7 +170,10 @@ export function QueuedRunsControl({
170 ];
171
172 const sendQueuedMessage = async (queuedRunId: RunId) => {
167 - if (!canSend || steerInFlightRef.current) return;
173 + const freshContext = queued.some(
174 + ({ run }) => run.id === queuedRunId && run.freshContext === true,
175 + );
176 + if (!canSendRun(freshContext) || steerInFlightRef.current) return;
177 steerInFlightRef.current = true;
178 setBusyRunId(queuedRunId);
179 if (workflow?.canSendNow) {
@@ -185,7 +194,7 @@ export function QueuedRunsControl({
194 useImperativeHandle(ref, () => ({
195 steerNext(repeat) {
196 const next = queued[0];
188 - if (!next || !canSend) return false;
197 + if (!next || !canSendRun(next.run.freshContext === true)) return false;
198 if (!repeat && busyRunId === null) void sendQueuedMessage(next.run.id);
199 return true;
200 },
@@ -266,7 +275,7 @@ export function QueuedRunsControl({
275 timestampFormat={props.timestampFormat}
276 onOpenThread={props.onOpenThread}
277 >
269 - {canSend && !isEditing ? (
278 + {canSendRun(item.freshContext) && !isEditing ? (
279 <>
280 <Tooltip>
281 <TooltipTrigger render={<span className="flex shrink-0" />}>
apps/web/src/components/chat/TimelineUserMessageRow.tsx
+2 -1
@@ -38,7 +38,7 @@ import {
38 } from "lucide-react";
39 import { Link as LinkIconNode } from "lucide";
40 import { Button, InlineButton } from "../ui/button";
41 -import { ModelSwitchRow } from "./V2LifecycleRow";
41 +import { FreshSessionRow, ModelSwitchRow } from "./V2LifecycleRow";
42 import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls";
43 import { AttachmentImage } from "../media/AttachmentImage";
44 import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
@@ -252,6 +252,7 @@ export function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "mes
252 const modelSwitch = item?.type === "user_message" ? item.modelSwitch : undefined;
253 return (
254 <>
255 + {item?.type === "user_message" && item.freshContext ? <FreshSessionRow /> : null}
256 {modelSwitch ? (
257 <ModelSwitchRow environmentId={ctx.activeThreadEnvironmentId} modelSwitch={modelSwitch} />
258 ) : null}
apps/web/src/components/chat/V2LifecycleRow.tsx
+6
@@ -43,6 +43,7 @@ import {
43 CircleStopIcon,
44 ArrowRightLeftIcon,
45 ArrowRightIcon,
46 + EraserIcon,
47 GitForkIcon,
48 MessageSquareIcon,
49 } from "lucide-react";
@@ -597,6 +598,11 @@ function EnvironmentHandoffRow({
598 return <HandoffRow {...props} environmentId={environmentId} providers={providers} />;
599 }
600
601 +/** Marks where `/clear` or an automation started a new provider session in this thread. */
602 +export function FreshSessionRow() {
603 + return <TimelineSystemDivider label="New session" icon={EraserIcon} />;
604 +}
605 +
606 /** A same-harness model or effort change. Shows only what changed. */
607 export function ModelSwitchRow(props: {
608 readonly environmentId: EnvironmentId;
apps/web/src/components/chat/composerSlashCommandSearch.ts
+5 -2
@@ -12,7 +12,7 @@ type SlashSearchItem = Extract<
12 { type: "slash-command" | "provider-slash-command" | "skill" }
13 >;
14
15 -/** Provider commands, `/side` and `/btw` work only at the message start. */
15 +/** Provider commands, `/side`, `/btw` and `/clear` work only at the message start. */
16 export function slashCommandItemsForPromptPosition(
17 items: ReadonlyArray<SlashSearchItem>,
18 isAtPromptStart: boolean,
@@ -23,7 +23,10 @@ export function slashCommandItemsForPromptPosition(
23 return items.filter(
24 (item) =>
25 item.type === "skill" ||
26 - (item.type === "slash-command" && item.command !== "side" && item.command !== "btw"),
26 + (item.type === "slash-command" &&
27 + item.command !== "side" &&
28 + item.command !== "btw" &&
29 + item.command !== "clear"),
30 );
31 }
32
apps/web/src/components/chat/freshSessionArms.ts new
+30
@@ -0,0 +1,30 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { Atom } from "effect/reactivity";
3 +
4 +import { appAtomRegistry } from "../../rpc/atomRegistry";
5 +
6 +/** Threads whose next message starts a fresh provider session, keyed by thread, valued by when it was armed. */
7 +const freshSessionArmsAtom = Atom.make<Readonly<Record<string, number>>>({}).pipe(Atom.keepAlive);
8 +
9 +export function armFreshSession(threadKey: string): void {
10 + appAtomRegistry.set(freshSessionArmsAtom, {
11 + ...appAtomRegistry.get(freshSessionArmsAtom),
12 + [threadKey]: Date.now(),
13 + });
14 +}
15 +
16 +/** With `arm`, clears only that arm, so a send never consumes one made while it was in flight. */
17 +export function disarmFreshSession(threadKey: string, arm?: number): void {
18 + const current = appAtomRegistry.get(freshSessionArmsAtom);
19 + if (current[threadKey] === undefined || (arm !== undefined && current[threadKey] !== arm)) return;
20 + const { [threadKey]: _removed, ...rest } = current;
21 + appAtomRegistry.set(freshSessionArmsAtom, rest);
22 +}
23 +
24 +export function readFreshSessionArm(threadKey: string): number | undefined {
25 + return appAtomRegistry.get(freshSessionArmsAtom)[threadKey];
26 +}
27 +
28 +export function useFreshSessionArmed(threadKey: string): boolean {
29 + return useAtomValue(freshSessionArmsAtom)[threadKey] !== undefined;
30 +}
apps/web/src/components/chat/useComposerMenuItems.ts
+17 -1
@@ -66,6 +66,7 @@ export function useComposerMenuItems({
66 planModeUiEnabled,
67 sideChatAvailable,
68 sideChatDisabledReason,
69 + freshSessionAvailable,
70 compactSlashCommandAvailable,
71 selectedProvider,
72 selectedProviderSkills,
@@ -85,6 +86,7 @@ export function useComposerMenuItems({
86 readonly planModeUiEnabled: boolean;
87 readonly sideChatAvailable: boolean;
88 readonly sideChatDisabledReason: string | null;
89 + readonly freshSessionAvailable: boolean;
90 readonly compactSlashCommandAvailable: boolean;
91 readonly selectedProvider: ProviderDriverKind;
92 readonly selectedProviderSkills: ServerProvider["skills"];
@@ -260,6 +262,17 @@ export function useComposerMenuItems({
262 },
263 ] as const)
264 : []),
265 + ...(freshSessionAvailable
266 + ? ([
267 + {
268 + id: "slash:clear",
269 + type: "slash-command",
270 + command: "clear",
271 + label: "/clear",
272 + description: "Start a fresh session; earlier messages stay visible",
273 + },
274 + ] as const)
275 + : []),
276 ] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
277 const slashMenuSkills = getProviderSkillsForSlashMenu(
278 selectedProviderSkills,
@@ -288,8 +301,11 @@ export function useComposerMenuItems({
301 skill.description ??
302 (skill.scope ? `${skill.scope} skill` : ""),
303 }));
304 + // T3's `/clear` replaces the provider's, which would clear a session T3 still treats as live.
305 const visibleProviderSlashCommandItems = providerSlashCommandItems.filter(
292 - (item) => item.command.name !== "compact" || compactSlashCommandAvailable,
306 + (item) =>
307 + (item.command.name !== "compact" || compactSlashCommandAvailable) &&
308 + (item.command.name !== "clear" || !freshSessionAvailable),
309 );
310 const slashCommandItems = slashCommandItemsForPromptPosition(
311 [...builtInSlashCommandItems, ...visibleProviderSlashCommandItems, ...skillItems],
apps/web/src/components/chat/useComposerSend.ts
+27 -8
@@ -1,3 +1,5 @@
1 +import { isClearComposerCommand } from "@t3tools/shared/composerTrigger";
2 +import { armFreshSession, disarmFreshSession, readFreshSessionArm } from "./freshSessionArms";
3 import {
4 mergeDirectPreviewAnnotation,
5 resolveBackgroundDraftWorkspaceOptions,
@@ -207,6 +209,8 @@ interface ComposerSendInput {
209 readonly panelAnimationsActive: boolean;
210 readonly panelAnimationDurationMs: number;
211 readonly keepFullHistory: boolean;
212 + /** `/clear` can arm a fresh session on this thread. */
213 + readonly freshSessionAvailable: boolean;
214 readonly resumeCompactionTokens: number | null;
215 readonly showPlanFollowUpPrompt: boolean;
216 readonly usageLimitsKey: string | null;
@@ -302,6 +306,7 @@ export function useComposerSend(input: ComposerSendInput) {
306 panelAnimationsActive,
307 panelAnimationDurationMs,
308 keepFullHistory,
309 + freshSessionAvailable,
310 resumeCompactionTokens,
311 showPlanFollowUpPrompt,
312 usageLimitsKey,
@@ -716,8 +721,26 @@ export function useComposerSend(input: ComposerSendInput) {
721
722 return;
723 }
724 + const composerHoldsOnlyText =
725 + composerImages.length === 0 &&
726 + composerFiles.length === 0 &&
727 + sendableComposerTerminalContexts.length === 0 &&
728 + composerPreviewAnnotations.length === 0 &&
729 + composerReviewComments.length === 0 &&
730 + composerThreadContexts.length === 0 &&
731 + composerEnvironmentContexts.length === 0;
732 + if (freshSessionAvailable && composerHoldsOnlyText && isClearComposerCommand(trimmed)) {
733 + armFreshSession(routeThreadKey);
734 + promptRef.current = "";
735 + clearComposerDraftContent(composerDraftTarget);
736 + composerRef.current?.resetCursorState();
737 + return;
738 + }
739 + // Read once: an arm made while this send is in flight belongs to the next message.
740 + const freshArm = freshSessionAvailable ? readFreshSessionArm(routeThreadKey) : undefined;
741 if (
742 !directAnnotation &&
743 + freshArm === undefined &&
744 sendInteractionModeEnabled &&
745 showPlanFollowUpPrompt &&
746 activeProposedPlan &&
@@ -798,14 +821,7 @@ export function useComposerSend(input: ComposerSendInput) {
821 return;
822 }
823 const standaloneSlashCommand =
801 - sendInteractionModeEnabled &&
802 - composerImages.length === 0 &&
803 - composerFiles.length === 0 &&
804 - sendableComposerTerminalContexts.length === 0 &&
805 - composerPreviewAnnotations.length === 0 &&
806 - composerReviewComments.length === 0 &&
807 - composerThreadContexts.length === 0 &&
808 - composerEnvironmentContexts.length === 0
824 + sendInteractionModeEnabled && composerHoldsOnlyText
825 ? parseStandaloneComposerSlashCommand(trimmed)
826 : null;
827 if (standaloneSlashCommand && multipleModelSelections === null) {
@@ -881,6 +897,7 @@ export function useComposerSend(input: ComposerSendInput) {
897 keepFullHistory,
898 phase,
899 dispatchMode,
900 + freshContext: freshArm !== undefined,
901 });
902 if (missingWorktreeBaseBranch) {
903 setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
@@ -1364,6 +1381,7 @@ export function useComposerSend(input: ComposerSendInput) {
1381 runtimeMode,
1382 interactionMode: sendInteractionMode,
1383 dispatchMode: turnDispatchMode,
1384 + ...(freshArm === undefined ? {} : { freshContext: true }),
1385 ...(bootstrap ? { bootstrap } : {}),
1386 createdAt: messageCreatedAt,
1387 },
@@ -1397,6 +1415,7 @@ export function useComposerSend(input: ComposerSendInput) {
1415 } else {
1416 turnStartSucceeded = true;
1417 setKeepFullHistory(routeThreadKey, false);
1418 + if (freshArm !== undefined) disarmFreshSession(routeThreadKey, freshArm);
1419 clearUsageLimitsFor(routeThreadKey);
1420 if (turnUsesAttachmentUploads) {
1421 releaseDraftAttachments(composerAttachmentsSnapshot);
apps/web/src/composer-logic.test.ts
+1 -1
@@ -564,7 +564,7 @@ describe("parseSideChatCommand", () => {
564 expect(parseSideChatCommand("/sidebar")).toBeNull();
565 expect(parseSideChatCommand("/btwx")).toBeNull();
566 expect(parseSideChatCommand("ask /side later")).toBeNull();
567 - const items = (["side", "btw", "plan"] as const).map((command) => ({
567 + const items = (["side", "btw", "clear", "plan"] as const).map((command) => ({
568 id: `slash:${command}`,
569 type: "slash-command" as const,
570 command,
apps/web/src/composer-logic.ts
+2 -2
@@ -18,7 +18,7 @@ import {
18 import { resolveShortcutCommand, type ShortcutEventLike } from "./keybindings";
19
20 export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill";
21 -export type ComposerSlashCommand = "model" | "plan" | "default" | "side" | "btw";
21 +export type ComposerSlashCommand = "model" | "plan" | "default" | "side" | "btw" | "clear";
22 export type ComposerSubmissionIntent = "foreground" | "background" | "alternate";
23
24 export interface ComposerTrigger {
@@ -326,7 +326,7 @@ export function parseSideChatCommand(text: string): { prompt: string } | null {
326
327 export function parseStandaloneComposerSlashCommand(
328 text: string,
329 -): Exclude<ComposerSlashCommand, "model" | "side" | "btw"> | null {
329 +): Exclude<ComposerSlashCommand, "model" | "side" | "btw" | "clear"> | null {
330 const match = /^\/(plan|default)\s*$/i.exec(text.trim());
331 if (!match) {
332 return null;
docs/user/composer.md
+6
@@ -264,6 +264,12 @@ Provider commands must start the message to run. T3 Code commands such as
264 Send `/compact` in an existing conversation to reduce context usage when the
265 provider supports it, even with the context meter turned off.
266
267 +Send `/clear` on its own, or pick it from the slash menu, to start a fresh session
268 +in the same thread. Your next message goes to a new provider session that doesn't see the
269 +earlier messages, and the thread marks where it began with **New session**.
270 +Earlier messages and diffs stay in the thread. Dismiss the notice above the
271 +composer to keep the current session instead.
272 +
273 On web and desktop, turn on **Settings → Labs → Legacy → Context
274 window indicator (legacy)** to see context usage. The meter is off by default
275 and appears once the provider reports usage. Open it for usage details and
docs/user/providers-antigravity.md
+1 -1
@@ -88,7 +88,7 @@ its conversation. Reverting a thread or editing and resubmitting an earlier turn
88 is unavailable. Continue with a follow-up message or start a new thread.
89
90 Manual context compaction is unavailable through Antigravity's ACP runtime, even
91 -though its CLI has `/compact`. Start a new thread when you need a fresh context.
91 +though its CLI has `/compact`. Send `/clear` when you need a fresh context.
92
93 ### Skills and attachments
94
evals/mcp-tool-use/cases/orchestration.ndjson
+2 -1
@@ -25,7 +25,7 @@
25 {"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."}
26 {"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."}
27 {"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\": \"pnpm@10.4.0\",\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.'."}
28 -{"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."}
28 +{"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."}
29 {"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."}
30 {"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": ""}
31 {"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 @@
34 {"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."}
35 {"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."}
36 {"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"}}
37 +{"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."}
packages/client-runtime/src/operations/commands.ts
+4
@@ -183,6 +183,8 @@ export interface StartThreadTurnInput extends ThreadCommandInput {
183 readonly bootstrap?: StartThreadBootstrap;
184 readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
185 readonly dispatchMode?: "auto" | "queue" | "steer" | "restart" | "start";
186 + /** Start a new provider session; needs the server's `freshContext` capability. */
187 + readonly freshContext?: boolean;
188 }
189
190 export interface InterruptThreadTurnInput extends ThreadCommandInput {
@@ -752,6 +754,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
754 ...(input.sourceProposedPlan === undefined
755 ? {}
756 : { sourcePlanRef: input.sourceProposedPlan }),
757 + ...(input.freshContext ? { freshContext: true } : {}),
758 dispatchMode: { type: "start_immediately" },
759 });
760 }
@@ -776,6 +779,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
779 ...(input.titleSeed === undefined ? {} : { titleSeed: input.titleSeed }),
780 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
781 ...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
782 + ...(input.freshContext ? { freshContext: true } : {}),
783 ...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}),
784 dispatchMode,
785 });
packages/contracts/src/orchestratorMcp.ts
+6
@@ -503,6 +503,12 @@ export const OrchestratorMcpThreadSendInput = Schema.Struct({
503 threadId: ThreadId,
504 message: OrchestratorMcpPrompt,
505 mode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
506 + freshContext: Schema.optional(
507 + Schema.Boolean.annotate({
508 + description:
509 + "Start a new provider session without the thread's earlier context, like /clear. Never steers.",
510 + }),
511 + ),
512 clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
513 });
514 export type OrchestratorMcpThreadSendInput = typeof OrchestratorMcpThreadSendInput.Type;
packages/shared/src/composerTrigger.ts
+5
@@ -169,3 +169,8 @@ export function replaceTextRange(
169 const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
170 return { text: nextText, cursor: safeStart + replacement.length };
171 }
172 +
173 +/** `/clear` as the whole message arms a fresh session instead of sending. */
174 +export function isClearComposerCommand(text: string): boolean {
175 + return /^\/clear\s*$/i.test(text.trim());
176 +}