@devries-cameron20 / t3code-1 / commits / aab388ddb1
Fork 0

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

fix(server): Claude can show the user mid-turn text in full (#36384)

Julius Marminge committed Nov 13, 2026 at 13:16 UTC aab388ddb1f739ff264ab956a62145ffb016cae6
22 files changed +297 -12
apps/mobile/src/features/threads/ThreadFeed.tsx
+18
@@ -1748,6 +1748,24 @@ function renderFeedEntry(
1748 );
1749 }
1750
1751 + if (entry.type === "sent-message") {
1752 + return (
1753 + <View className="mb-1 px-1">
1754 + <MarkdownImageAvailableWidthContext value={props.markdownContentWidth}>
1755 + <AssistantMarkdownContent
1756 + markdown={entry.text}
1757 + environmentId={props.environmentId}
1758 + markdownStyles={markdownStyles.assistant}
1759 + linkHandlers={props.markdownLinkHandlers}
1760 + onUseArtifactTemplate={props.onUseArtifactTemplate}
1761 + renderImage={props.renderMarkdownImage}
1762 + skills={props.skills}
1763 + />
1764 + </MarkdownImageAvailableWidthContext>
1765 + </View>
1766 + );
1767 + }
1768 +
1769 if (entry.type === "viewed-images") {
1770 const thumbnailWidth = Math.floor((props.contentWidth - VIEWED_IMAGE_GAP) / 2);
1771 return (
apps/mobile/src/lib/threadActivity.ts
+31 -2
@@ -73,6 +73,7 @@ import type { McpAppReference } from "@t3tools/shared/mcpApp";
73 import {
74 compactDynamicToolOutput,
75 htmlRenderFromToolItem,
76 + sentMessageFromToolItem,
77 mcpAppFromToolItem,
78 } from "@t3tools/shared/toolOutput";
79 import * as DateTime from "effect/DateTime";
@@ -182,6 +183,13 @@ type RawThreadFeedEntry =
183 readonly runId: RunId | null;
184 readonly render: HtmlRenderReference;
185 }
186 + | {
187 + readonly type: "sent-message";
188 + readonly id: string;
189 + readonly createdAt: string;
190 + readonly runId: RunId | null;
191 + readonly text: string;
192 + }
193 | {
194 readonly type: "mcp-app";
195 readonly id: string;
@@ -200,7 +208,7 @@ export type ThreadFeedEntry = ThreadFeedEntryContent & {
208 };
209
210 type ThreadFeedEntryContent =
203 - | Extract<RawThreadFeedEntry, { type: "message" | "html-render" | "mcp-app" }>
211 + | Extract<RawThreadFeedEntry, { type: "message" | "html-render" | "sent-message" | "mcp-app" }>
212 | {
213 readonly type: "activity-group";
214 readonly id: string;
@@ -1098,7 +1106,10 @@ function feedEntryFoldRunId(entry: ThreadFeedEntry, runlessKey: RunId | null): R
1106 if (entry.type === "message") {
1107 return entry.message.role === "assistant" ? (entry.message.runId ?? runlessKey) : null;
1108 }
1101 - return entry.type === "activity-group" || entry.type === "html-render" || entry.type === "mcp-app"
1109 + return entry.type === "activity-group" ||
1110 + entry.type === "html-render" ||
1111 + entry.type === "sent-message" ||
1112 + entry.type === "mcp-app"
1113 ? (entry.runId ?? runlessKey)
1114 : null;
1115 }
@@ -1227,6 +1238,7 @@ function deriveThreadFeedRunFolds(
1238 entry.id !== terminalAssistantId &&
1239 !(entry.type === "message" && retainedAnswerIds.has(entry.message.id)) &&
1240 entry.type !== "html-render" &&
1241 + entry.type !== "sent-message" &&
1242 entry.type !== "mcp-app" &&
1243 entry.id !== visibleCompactionId &&
1244 !(
@@ -2429,6 +2441,23 @@ export function buildThreadFeed(
2441 entryRows.push(index);
2442 continue;
2443 }
2444 + const sentMessage =
2445 + item.type === "dynamic_tool" && item.status === "completed"
2446 + ? sentMessageFromToolItem(item)
2447 + : undefined;
2448 + if (sentMessage !== undefined) {
2449 + const entry: RawThreadFeedEntry = {
2450 + type: "sent-message",
2451 + id: `sent-message:${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
2452 + createdAt,
2453 + runId: item.runId,
2454 + text: sentMessage,
2455 + };
2456 + projectedEntriesCache.set(row, { attemptId, entries: [entry] });
2457 + entries.push(entry);
2458 + entryRows.push(index);
2459 + continue;
2460 + }
2461 if (item.type === "user_message" || item.type === "assistant_message") {
2462 const updatedAt = DateTime.formatIso(item.updatedAt);
2463 const entry: RawThreadFeedEntry = {
apps/server/src/mcp/McpHttpServer.ts
+5
@@ -84,6 +84,8 @@ import {
84 DeviceStandardToolkit,
85 } from "./toolkits/device/tools.ts";
86 import * as HtmlHandlers from "./toolkits/html/handlers.ts";
87 +import { MessageToolkit } from "./toolkits/message/tools.ts";
88 +import * as MessageHandlers from "./toolkits/message/handlers.ts";
89 import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts";
90 import { requestUrl } from "../requestUrl.ts";
91
@@ -1239,6 +1241,8 @@ export const layerOrchestratorToolkit = toolkitRegistration(
1241
1242 export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
1243
1244 +const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer);
1245 +
1246 const layerWorktreeToolkitRegistration = toolkitRegistration(
1247 WorktreeToolkit,
1248 WorktreeHandlers.layer,
@@ -1324,6 +1328,7 @@ export const layerTools = Layer.mergeAll(
1328 layerPullRequestsToolkit,
1329 layerDeviceToolkit,
1330 layerHtmlToolkit,
1331 + layerMessageToolkit,
1332 );
1333
1334 const layerToolExposure = Layer.effect(
apps/server/src/mcp/toolkits/message/handlers.ts new
+15
@@ -0,0 +1,15 @@
1 +import * as Effect from "effect/Effect";
2 +
3 +import * as McpToolAccess from "../../McpToolAccess.ts";
4 +import { MessageToolkit } from "./tools.ts";
5 +
6 +const handlers = {
7 + send_to_user: McpToolAccess.actsAsCaller((input) =>
8 + Effect.succeed({
9 + sentMessage: input.message,
10 + message: "Shown to the user. Don't repeat it.",
11 + }),
12 + ),
13 +} satisfies McpToolAccess.Handlers<typeof MessageToolkit.tools>;
14 +
15 +export const layer = McpToolAccess.toLayer(MessageToolkit, handlers);
apps/server/src/mcp/toolkits/message/tools.ts new
+39
@@ -0,0 +1,39 @@
1 +import { OrchestratorMcpFailure } from "@t3tools/contracts";
2 +import { SEND_TO_USER_MAX_LENGTH, SEND_TO_USER_TOOL_NAME } from "@t3tools/shared/toolOutput";
3 +import * as Schema from "effect/Schema";
4 +import { Tool, Toolkit } from "effect/ai";
5 +
6 +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
7 +import * as McpInvocationContext from "../../McpInvocationContext.ts";
8 +
9 +// Claude 5.1+ returns text written before a tool call only as a short summary; tool input arrives intact.
10 +// It affects only the caller's thread, so read-only sandboxes and plan mode may use it.
11 +const SendToUserTool = Tool.make(SEND_TO_USER_TOOL_NAME, {
12 + description:
13 + "Show the user a Markdown message in this thread, exactly as written, before your turn ends. Use it for content the user must read in full mid-turn, such as a draft, a code block, or what a question you are about to ask refers to. Don't repeat it in your reply.",
14 + parameters: Schema.Struct({
15 + message: Schema.String.check(
16 + Schema.isMinLength(1),
17 + Schema.isMaxLength(SEND_TO_USER_MAX_LENGTH),
18 + ).annotate({ description: "Markdown, shown verbatim." }),
19 + }),
20 + success: Schema.Struct({
21 + sentMessage: Schema.String,
22 + message: Schema.String,
23 + }),
24 + failure: OrchestratorMcpFailure,
25 + failureMode: "return",
26 + dependencies: [
27 + McpInvocationContext.McpInvocationContext,
28 + ThreadManagementService.ThreadManagementService,
29 + ],
30 +})
31 + .annotate(Tool.Title, "Send a message to the user")
32 + .annotate(Tool.Readonly, true)
33 + .annotate(Tool.Destructive, false)
34 + .annotate(Tool.Idempotent, false)
35 + .annotate(Tool.OpenWorld, false)
36 + // Claude Code defers MCP tools behind ToolSearch; Anthropic says to declare this from the first request.
37 + .annotate(Tool.Meta, { "anthropic/alwaysLoad": true });
38 +
39 +export const MessageToolkit = Toolkit.make(SendToUserTool);
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+2
@@ -90,6 +90,7 @@ import { T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH } from "@t3tools/prov
90 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
91 import { PreviewControlsToolkit } from "../../mcp/toolkits/previewControls/tools.ts";
92 import { HtmlToolkit } from "../../mcp/toolkits/html/tools.ts";
93 +import { MessageToolkit } from "../../mcp/toolkits/message/tools.ts";
94 import { EnvironmentToolkit } from "../../mcp/toolkits/environment/tools.ts";
95 import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts";
96 import { WorktreeToolkit } from "../../mcp/toolkits/worktree/tools.ts";
@@ -663,6 +664,7 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
664 ...Object.values(EnvironmentToolkit.tools),
665 ...Object.values(PreviewControlsToolkit.tools),
666 ...Object.values(HtmlToolkit.tools),
667 + ...Object.values(MessageToolkit.tools),
668 ]
669 .filter((tool) => Context.get(tool.annotations, Tool.Readonly))
670 .map((tool) => `mcp__t3-code__${tool.name}`)
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+10
@@ -1965,6 +1965,14 @@ const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = `
1965 To wait for a background command or Monitor you started (tests, a build), call \`t3_background_wait\` with its task ID before you end your turn. Do not mark work you leave running, or PRs. T3 MCP tools are deferred: load one with ToolSearch before you call it.
1966 `;
1967
1968 +// Claude 5.1+ returns text written before a tool call as a progress update, which the API
1969 +// returns only as a summary.
1970 +const CLAUDE_SEND_TO_USER_INSTRUCTIONS = `
1971 +### Text the user must read mid-turn
1972 +
1973 +Text you write before a tool call may reach the user only as a one-line summary. When the user must read something in full before your turn ends, such as a draft, a code block, or what a question you're about to ask refers to, send it with \`send_to_user\`. Put everything else in your final reply.
1974 +`;
1975 +
1976 // Native subagents start from their task, not this session's system prompt.
1977 const subagentDeviceInstructions: HookCallback = () =>
1978 Promise.resolve({
@@ -2143,6 +2151,7 @@ export function makeClaudeQueryOptions(input: {
2151 ? ""
2152 : T3_CODE_ORCHESTRATION_INSTRUCTIONS +
2153 CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS +
2154 + CLAUDE_SEND_TO_USER_INSTRUCTIONS +
2155 (deviceInstructions
2156 ? `\n${T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH}\n`
2157 : "")),
@@ -2263,6 +2272,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
2272 "mcp__t3-code__t3_environment_links",
2273 "mcp__t3-code__html_preview",
2274 "mcp__t3-code__html_render",
2275 + "mcp__t3-code__send_to_user",
2276 ];
2277
2278 // T3 waits can block for an hour; exceed Claude's default 60 s timeout.
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+9 -2
@@ -4333,9 +4333,16 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
4333 workCursor = page.nextCursor;
4334 }
4335 assert.strictEqual(workIds.size, 999);
4336 - for (const toolName of ["t3-code.delegate_task", "mcp__t3_code__delegate_task"]) {
4336 + for (const [toolName, output] of [
4337 + ["t3-code.delegate_task", null],
4338 + ["mcp__t3_code__delegate_task", null],
4339 + ["mcp__t3-code__send_to_user", null],
4340 + // OpenCode Code Mode reports a nested send_to_user call as one `execute` item.
4341 + ["execute", JSON.stringify({ sentMessage: "Draft" })],
4342 + ] as const) {
4343 yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool',
4338 - payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', ${toolName})
4344 + payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', ${toolName},
4345 + '$.output', ${output})
4346 WHERE thread_id = ${threadId} AND ordinal = 2`;
4347 const window = yield* projectionStore.getThreadSnapshotWindow(threadId, {
4348 rowLimit: sqlPageLimit,
apps/server/src/orchestration-v2/ProjectionStore.ts
+3 -1
@@ -2128,7 +2128,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
2128 const inlineWorkOutput = sql`item.type = 'dynamic_tool' AND (
2129 item.payload_json LIKE '%htmlRender%' OR item.payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`}
2130 OR item.payload_json LIKE '%"viewedImagePath"%'
2131 - OR item.payload_json LIKE '%"toolName":"%delegate_task"%')`;
2131 + OR item.payload_json LIKE '%"toolName":"%delegate_task"%'
2132 + OR item.payload_json LIKE '%"toolName":"%send_to_user"%'
2133 + OR item.payload_json LIKE '%sentMessage%')`;
2134
2135 // SQLite uses the partial conversation index of migration 082 only for this exact predicate.
2136 const CONVERSATION_INDEX_EXCLUDED_TYPES = sql.literal(
apps/server/src/provider/AgentContextBudget.test.ts
+5 -2
@@ -116,13 +116,16 @@ const layerAdvertisedTools = McpHttpServer.layerTools.pipe(
116 );
117
118 // Claude Code loads these tools up front instead of behind ToolSearch, outside this budget.
119 -it.effect("only request_secret asks Claude Code to load it up front", () =>
119 +it.effect("only request_secret and send_to_user ask Claude Code to load them up front", () =>
120 Effect.gen(function* () {
121 const mcp = yield* McpServer.McpServer;
122 const alwaysLoad = mcp.tools
123 .filter(({ tool }) => tool._meta?.["anthropic/alwaysLoad"] !== undefined)
124 .map(({ tool }) => [tool.name, tool._meta]);
125 - expect(alwaysLoad).toEqual([["request_secret", { "anthropic/alwaysLoad": true }]]);
125 + expect(alwaysLoad).toEqual([
126 + ["request_secret", { "anthropic/alwaysLoad": true }],
127 + ["send_to_user", { "anthropic/alwaysLoad": true }],
128 + ]);
129 }).pipe(Effect.provide(layerAdvertisedTools)),
130 );
131
apps/server/src/provider/agentContextBudget.json
+2 -2
@@ -1,5 +1,5 @@
1 {
2 - "claudeSystemAppendBytes": 5594,
2 + "claudeSystemAppendBytes": 5930,
3 "codexAdditionalContextBytes": 7324,
4 - "mcpToolListJsonBytes": 48094
4 + "mcpToolListJsonBytes": 48566
5 }
apps/web/src/components/chat/MessagesTimeline.logic.ts
+25 -1
@@ -82,7 +82,9 @@ export function timelineEntryRunId(entry: TimelineEntry): RunId | null {
82 if (entry.kind === "proposed-plan") {
83 return entry.proposedPlan.runId;
84 }
85 - if (entry.kind === "html-render" || entry.kind === "mcp-app") return entry.runId;
85 + if (entry.kind === "html-render" || entry.kind === "mcp-app" || entry.kind === "sent-message") {
86 + return entry.runId;
87 + }
88 return entry.kind === "work" ? (entry.entry.runId ?? null) : null;
89 }
90
@@ -634,6 +636,12 @@ type MessagesTimelineRowContent =
636 createdAt: string;
637 htmlRender: HtmlRenderReference;
638 }
639 + | {
640 + kind: "sent-message";
641 + id: string;
642 + createdAt: string;
643 + text: string;
644 + }
645 | {
646 kind: "mcp-app";
647 id: string;
@@ -817,6 +825,7 @@ function deriveSupersededAttemptFolds(
825 (entry.kind === "event" && entry.projectedItem.item.type === "handoff") ||
826 entry.kind === "html-render" ||
827 entry.kind === "mcp-app" ||
828 + entry.kind === "sent-message" ||
829 timelineEntryIsPersistentResourceCard(entry) ||
830 liveSubagentEntryIds.has(entry.id) ||
831 (entry.kind === "work" && entry.entry.itemType === "system_notice")
@@ -2126,6 +2135,16 @@ export function deriveMessagesTimelineRows(input: {
2135 continue;
2136 }
2137
2138 + if (timelineEntry.kind === "sent-message") {
2139 + nextRows.push({
2140 + kind: "sent-message",
2141 + id: timelineEntry.id,
2142 + createdAt: timelineEntry.createdAt,
2143 + text: timelineEntry.text,
2144 + });
2145 + continue;
2146 + }
2147 +
2148 if (timelineEntry.kind === "mcp-app") {
2149 nextRows.push({
2150 kind: "mcp-app",
@@ -2720,6 +2739,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
2739 return a.createdAt === bh.createdAt && htmlRenderReferencesEqual(a.htmlRender, bh.htmlRender);
2740 }
2741
2742 + case "sent-message": {
2743 + const bs = b as typeof a;
2744 + return a.createdAt === bs.createdAt && a.text === bs.text;
2745 + }
2746 +
2747 case "mcp-app": {
2748 const bm = b as typeof a;
2749 return (
apps/web/src/components/chat/MessagesTimeline.tsx
+3
@@ -126,6 +126,7 @@ import {
126 AssistantMetaTimelineRow,
127 ProposedPlanTimelineRow,
128 HtmlRenderTimelineRow,
129 + SentMessageTimelineRow,
130 McpAppTimelineRow,
131 } from "./TimelineAssistantRows";
132 import { V2EventTimelineRow } from "./TimelineV2EventRow";
@@ -1626,6 +1627,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
1627 row.kind === "event" ||
1628 row.kind === "attempt-fold" ||
1629 row.kind === "html-render" ||
1630 + row.kind === "sent-message" ||
1631 row.kind === "mcp-app" ||
1632 row.kind === "viewed-images"
1633 ? "pb-2"
@@ -1676,6 +1678,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
1678 {row.kind === "assistant-meta" ? <AssistantMetaTimelineRow row={row} /> : null}
1679 {row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
1680 {row.kind === "html-render" ? <HtmlRenderTimelineRow row={row} /> : null}
1681 + {row.kind === "sent-message" ? <SentMessageTimelineRow row={row} /> : null}
1682 {row.kind === "viewed-images" ? <ViewedImagesTimelineRow row={row} /> : null}
1683 {row.kind === "mcp-app" ? <McpAppTimelineRow row={row} /> : null}
1684 {row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
apps/web/src/components/chat/TimelineAssistantRows.tsx
+26
@@ -96,6 +96,32 @@ export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind
96 );
97 }
98
99 +/** Text an agent sent with `send_to_user`, shown as its own words. */
100 +export function SentMessageTimelineRow({
101 + row,
102 +}: {
103 + row: Extract<TimelineRow, { kind: "sent-message" }>;
104 +}) {
105 + const ctx = use(TimelineRowCtx);
106 +
107 + return (
108 + <div className="min-w-0 px-1 py-0.5">
109 + <MessageAuthorHeading>T3 Code</MessageAuthorHeading>
110 + <ChatMarkdown
111 + text={row.text}
112 + cwd={ctx.markdownCwd}
113 + threadRef={ctx.threadRef ?? undefined}
114 + lineBreaks={shouldPreserveAssistantLineBreaks(row.text)}
115 + skills={ctx.skills}
116 + headingLevelOffset={MESSAGE_HEADING_LEVEL}
117 + onUseArtifactTemplate={ctx.onUseArtifactTemplate}
118 + onRunShellCommand={ctx.onRunShellCommand}
119 + onImageExpand={ctx.onImageExpand}
120 + />
121 + </div>
122 + );
123 +}
124 +
125 function AssistantForkButton({
126 projectedItem,
127 }: {
apps/web/src/session-logic.test.ts
+23
@@ -1391,6 +1391,29 @@ describe("HTML renders in the timeline", () => {
1391 ]);
1392 });
1393
1394 + it("shows a sent message in place through the turn fold, and only once sent", () => {
1395 + const sentMessage = "Draft reply:\n\n> Thanks, Thursday works.";
1396 + const send = (
1397 + status: OrchestrationV2TurnItem["status"],
1398 + output?: unknown,
1399 + ): OrchestrationV2TurnItem => ({
1400 + ...base("render", 2),
1401 + status,
1402 + type: "dynamic_tool",
1403 + toolName: "mcp__t3-code__send_to_user",
1404 + input: { message: sentMessage },
1405 + ...(output === undefined ? {} : { output }),
1406 + });
1407 + const entries = turn(send("completed", { structuredContent: { sentMessage }, content: [] }));
1408 + expect(entries.find((entry) => entry.kind === "sent-message")).toMatchObject({
1409 + id: "render",
1410 + runId,
1411 + text: sentMessage,
1412 + });
1413 + expect(rowsFor(entries, false)).toEqual(["message", "turn-fold", "sent-message", "message"]);
1414 + expect(turn(send("running")).some((entry) => entry.kind === "sent-message")).toBe(false);
1415 + });
1416 +
1417 it("hosts a captured MCP app after its tool row, from any provider's tool", () => {
1418 const mcpApp = {
1419 attachmentId: "render-thread-app-html",
apps/web/src/session-logic.ts
+28 -1
@@ -25,7 +25,11 @@ import {
25 import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
26 import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
27 import type { McpAppReference } from "@t3tools/shared/mcpApp";
28 -import { htmlRenderFromToolItem, mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
28 +import {
29 + htmlRenderFromToolItem,
30 + mcpAppFromToolItem,
31 + sentMessageFromToolItem,
32 +} from "@t3tools/shared/toolOutput";
33 import {
34 contextCompactionLabel,
35 workEntryIndicatesToolFailure,
@@ -123,6 +127,13 @@ export type TimelineEntry = (
127 readonly runId: RunId | null;
128 readonly htmlRender: HtmlRenderReference;
129 }
130 + | {
131 + readonly id: string;
132 + readonly kind: "sent-message";
133 + readonly createdAt: string;
134 + readonly runId: RunId | null;
135 + readonly text: string;
136 + }
137 | {
138 readonly id: string;
139 readonly kind: "mcp-app";
@@ -652,6 +663,22 @@ export function deriveTimelineEntriesFromVisibleTurnItems(
663 continue;
664 }
665
666 + const sentMessage =
667 + item.type === "dynamic_tool" && item.status === "completed"
668 + ? sentMessageFromToolItem(item)
669 + : undefined;
670 + if (sentMessage !== undefined) {
671 + entries.push({
672 + id: item.id,
673 + kind: "sent-message",
674 + createdAt,
675 + runId: item.runId,
676 + text: sentMessage,
677 + ...attemptMetadata,
678 + });
679 + continue;
680 + }
681 +
682 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
683 entries.push({
684 id: item.id,
evals/mcp-tool-use/cases/mid-turn-messages.ndjson new
+4
@@ -0,0 +1,4 @@
1 +{"id": "draft-before-question-sent-in-full", "area": "mid-turn-messages", "kind": "bad", "pattern": "draft written before AskUserQuestion reaches the user only as a progress-update summary", "experience": "The agent drafted an email reply, then opened a question card about it. Claude returned the draft as a progress update before the tool call, so the user saw a one-line summary and answered a card about a draft they never read.", "rule": "Text the user must read in full before the turn ends goes through send_to_user.", "privacy": "commit-safe", "source": {"issue": "#32877"}, "setup": {"role": "top", "world": {"files": {"inbox/acme-renewal.txt": "From: Dana Ortiz <dana@acme.example>\nSubject: Renewal for Acme Analytics\n\nHi,\n\nOur annual Acme Analytics contract renews on December 1. The price goes from $18,000 to $21,600. Before I sign, can you confirm whether the SSO add-on is still included and whether we can move the renewal date to January 15?\n\nThanks,\nDana\n"}}, "mocks": {"AskUserQuestion": "The user chose: Send it as written."}}, "prompt": "Draft a reply to the email in inbox/acme-renewal.txt. Sign it 'Morgan'. Show me the whole draft, then ask me with a question card whether to send it as written or make it shorter.", "expect": {"calls": [{"tool": "send_to_user", "args": {"message": "~Morgan"}}, {"tool": "AskUserQuestion"}], "order": ["send_to_user", "AskUserQuestion"]}, "notes": "The question card's own text would also arrive in full, but it is a short question, not a place for a whole draft."}
2 +{"id": "control-draft-as-final-reply", "area": "mid-turn-messages", "kind": "control", "pattern": "a draft with no question after it belongs in the final reply", "experience": "Final messages always arrive in full, so a draft that ends the turn needs no send_to_user.", "rule": "Put everything else in your final reply.", "privacy": "commit-safe", "source": {"issue": "#32877"}, "setup": {"role": "top", "world": {"files": {"inbox/acme-renewal.txt": "From: Dana Ortiz <dana@acme.example>\nSubject: Renewal for Acme Analytics\n\nHi,\n\nOur annual Acme Analytics contract renews on December 1. The price goes from $18,000 to $21,600. Before I sign, can you confirm whether the SSO add-on is still included and whether we can move the renewal date to January 15?\n\nThanks,\nDana\n"}}}, "prompt": "Draft a reply to the email in inbox/acme-renewal.txt. Sign it 'Morgan'.", "expect": {"notCalls": ["send_to_user"], "finalTextMust": ["Morgan"]}, "notes": ""}
3 +{"id": "control-progress-updates-stay-text", "area": "mid-turn-messages", "kind": "control", "pattern": "ordinary multi-step work: progress notes are not send_to_user content", "experience": "Status notes between tool calls are what progress updates are for; sending each through send_to_user would flood the thread.", "rule": "send_to_user is for content the user must read in full mid-turn.", "privacy": "commit-safe", "source": {"issue": "#32877"}, "setup": {"role": "top", "world": {"files": {"src/price.ts": "export function renewalPrice(base: number, upliftPercent: number) {\n return base + base * upliftPercent;\n}\n", "src/price.test.ts": "import { expect, it } from \"vitest\";\nimport { renewalPrice } from \"./price\";\n\nit(\"applies a 20% uplift\", () => {\n expect(renewalPrice(18_000, 20)).toBe(21_600);\n});\n"}}}, "prompt": "src/price.test.ts fails. Find out why and fix it.", "expect": {"notCalls": ["send_to_user"]}, "notes": ""}
4 +{"id": "answer-before-bookkeeping-call", "area": "mid-turn-messages", "kind": "bad", "pattern": "answer written before a closing bookkeeping tool call; the turn ends on a short note", "experience": "The agent answered the question, ran one more command its project rules ask for at the end of a turn, then wrote two short sentences. The answer came back as a progress update and reached the user as a summary folded under the turn.", "rule": "Text before a tool call may reach the user only as a summary; put the answer in the final reply or send_to_user.", "privacy": "commit-safe", "source": {"issue": "#32877"}, "setup": {"role": "top", "world": {"files": {"scripts/log-question.sh": "#!/bin/sh\necho \"$(date -u +%FT%TZ) $1\" >> .questions.log\n", "src/server/config.ts": "export const config = {\n port: Number(process.env.PORT ?? 4817),\n host: process.env.HOST ?? \"127.0.0.1\",\n};\n"}}, "shellMocks": [{"match": "log-question", "output": ""}], "context": "Contents of /home/user/acme/AGENTS.md (project instructions, checked into the codebase):\n\n# Acme app\n\nAfter you answer a question, run `./scripts/log-question.sh <one-word topic>` so we can track what people ask about."}, "prompt": "Which port and host does the dev server listen on by default, and how do I change them?", "expect": {"shellMust": ["log-question"], "finalTextMust": ["4817", "PORT"]}, "notes": "Passes when the full answer ends the turn. An answer sent with send_to_user and a final reply without it fails, since a plain answer belongs in the final reply."}
evals/mcp-tool-use/run.ts
+2
@@ -56,6 +56,7 @@ import { AttachmentToolkit } from "../../apps/server/src/mcp/toolkits/attachment
56 import { DeviceToolkit } from "../../apps/server/src/mcp/toolkits/device/tools.ts";
57 import { EnvironmentToolkit } from "../../apps/server/src/mcp/toolkits/environment/tools.ts";
58 import { HtmlToolkit } from "../../apps/server/src/mcp/toolkits/html/tools.ts";
59 +import { MessageToolkit } from "../../apps/server/src/mcp/toolkits/message/tools.ts";
60 import { OrchestratorToolkit } from "../../apps/server/src/mcp/toolkits/orchestrator/tools.ts";
61 import { PreviewToolkit } from "../../apps/server/src/mcp/toolkits/preview/tools.ts";
62 import { PreviewControlsToolkit } from "../../apps/server/src/mcp/toolkits/previewControls/tools.ts";
@@ -456,6 +457,7 @@ const t3SourceTools: ReadonlyArray<Tool.Any> = [
457 PreviewToolkit,
458 DeviceToolkit,
459 HtmlToolkit,
460 + MessageToolkit,
461 ].flatMap((toolkit): ReadonlyArray<Tool.Any> => Object.values(toolkit.tools));
462 // McpHttpServer decodes arguments with each tool's JSON codec, which drops undeclared keys.
463 const t3InputDecoders = new Map(
packages/client-runtime/src/t3ToolSummary.ts
+3
@@ -472,6 +472,9 @@ export function summarizeT3ToolCalls(
472 case "html-render":
473 label = phrase("Rendered", "render", quantity(selected.length, "HTML page"));
474 break;
475 + case "send-to-user":
476 + label = phrase("Sent", "send", quantity(selected.length, "message"));
477 + break;
478 case "capabilities":
479 label = phrase("Checked", "check", `orchestration capabilities ${times}`);
480 break;
packages/shared/src/t3McpToolPresentation.ts
+3 -1
@@ -68,7 +68,8 @@ export type T3McpToolSummaryAction =
68 | "browser"
69 | "device"
70 | "html-preview"
71 - | "html-render";
71 + | "html-render"
72 + | "send-to-user";
73
74 export interface T3McpToolDefinition {
75 readonly displayName: string;
@@ -372,6 +373,7 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
373 t3_thread_send_attachments: tool(["Send", "Sending", "Sent", "attachments"], "attachment-send"),
374 html_preview: tool(["Preview", "Previewing", "Previewed", "an HTML page"], "html-preview"),
375 html_render: tool(["Render", "Rendering", "Rendered", "an HTML page"], "html-render"),
376 + send_to_user: tool(["Send", "Sending", "Sent", "a message"], "send-to-user"),
377 };
378
379 export const T3_MCP_TOOL_NAMES: ReadonlySet<string> = new Set(Object.keys(T3_MCP_TOOLS));
packages/shared/src/toolOutput.test.ts
+14
@@ -4,6 +4,8 @@ import {
4 compactDynamicToolOutput,
5 MAX_TOOL_OUTPUT_IMAGES,
6 mcpToolResultOutput,
7 + SEND_TO_USER_MAX_LENGTH,
8 + sentMessageFromToolItem,
9 toolOutputImages,
10 toolOutputIndicatesFailure,
11 } from "./toolOutput.ts";
@@ -23,6 +25,18 @@ describe("compactDynamicToolOutput", () => {
25 }
26 });
27
28 + it("keeps a send_to_user message up to its limit, even in 3-byte characters", () => {
29 + const longest = "界".repeat(SEND_TO_USER_MAX_LENGTH);
30 + for (const sentMessage of ["Draft:\n\n> Hi Sam,", longest]) {
31 + const json = JSON.stringify({ sentMessage, message: "Shown to the user." });
32 + expect(compactDynamicToolOutput([{ type: "text", text: json }])).toEqual({ sentMessage });
33 + }
34 + expect(compactDynamicToolOutput({ sentMessage: `${longest}界` })).toBeUndefined();
35 + // OpenCode 2 Code Mode reports a script's nested send_to_user call as one `execute` item.
36 + const output = JSON.stringify({ sentMessage: "Draft", message: "Shown to the user." });
37 + expect(sentMessageFromToolItem({ toolName: "execute", output })).toBe("Draft");
38 + });
39 +
40 it("keeps nested thread identity and scalar task IDs without result bodies", () => {
41 const output = {
42 thread: { threadId: "thread-1", messages: ["Private message"] },
packages/shared/src/toolOutput.ts
+27
@@ -17,6 +17,10 @@ import {
17 } from "./mcpApp.ts";
18 import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
19
20 +export const SEND_TO_USER_TOOL_NAME = "send_to_user";
21 +// 4,000 UTF-16 units stay inside MAX_PARSED_BYTES even as 3-byte characters.
22 +export const SEND_TO_USER_MAX_LENGTH = 4_000;
23 +
24 const MAX_PARSED_BYTES = 16_384;
25 const MAX_METADATA_BYTES = 8_192;
26 const MAX_ID_LENGTH = 256;
@@ -50,6 +54,7 @@ interface CompactToolOutput {
54 threads?: Array<{ threadId?: string; status?: "rolled_back" }>;
55 linkedCount?: number;
56 unlinkedCount?: number;
57 + sentMessage?: string;
58 }
59
60 function readResult(value: unknown, budget: ResultReadBudget, depth = 0): ResultEnvelope {
@@ -134,6 +139,13 @@ export function compactDynamicToolOutput(value: unknown): CompactToolOutput | un
139 const count = data[key];
140 if (typeof count === "number" && Number.isSafeInteger(count)) output[key] = count;
141 }
142 + if (
143 + typeof data.sentMessage === "string" &&
144 + data.sentMessage.trim() !== "" &&
145 + data.sentMessage.length <= SEND_TO_USER_MAX_LENGTH
146 + ) {
147 + output.sentMessage = data.sentMessage;
148 + }
149 const htmlRender = readHtmlRenderReference(data.htmlRender);
150 if (htmlRender !== undefined) output.htmlRender = htmlRender;
151 const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]);
@@ -204,6 +216,21 @@ export function htmlRenderFromToolItem(item: {
216 return output?.isError ? undefined : output?.htmlRender;
217 }
218
219 +/** The text `send_to_user` showed the user, which clients render as the agent's own words. */
220 +export function sentMessageFromToolItem(item: {
221 + readonly toolName: string | null | undefined;
222 + readonly output?: unknown;
223 +}): string | undefined {
224 + if (
225 + item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
226 + resolveT3McpToolId(item.toolName) !== SEND_TO_USER_TOOL_NAME
227 + ) {
228 + return undefined;
229 + }
230 + const output = compactDynamicToolOutput(item.output);
231 + return output?.isError ? undefined : output?.sentMessage;
232 +}
233 +
234 /** The thread-owned file `preview_recording_stop` stored for the agent. */
235 export function previewRecordingIdFromToolItem(item: {
236 readonly toolName: string | null | undefined;