feat: MCP apps render and run inline in threads (#16236)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-07 09:44:08 -07:00
1 parent 6ecb82dc42
commit 4d976d1fc2
83 files changed
+4990 -55

No files matched your search

+34 -1
View File
@@ -4606,6 +4606,30 @@ export default function ChatView(props: ChatViewProps) {
},
[composerRef, scheduleComposerFocus],
);
// An MCP App's approved `ui/message`: queued like a typed message, so it
// never steers or interrupts a running turn.
const sendAppMessage = useCallback(
async (text: string) => {
if (!isServerThread || activeThreadId === null) {
throw new Error("Messages from apps need a started thread.");
}
const result = await startThreadTurn({
environmentId,
input: {
threadId: activeThreadId,
message: { messageId: newMessageId(), role: "user", text, attachments: [] },
runtimeMode,
interactionMode,
dispatchMode: "queue",
},
});
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
throw error instanceof Error ? error : new Error("Could not send the app's message.");
}
},
[activeThreadId, environmentId, interactionMode, isServerThread, runtimeMode, startThreadTurn],
);
const editQueuedRunCommand = useAtomCommand(threadEnvironment.editQueuedRun, {
reportFailure: false,
});
@@ -6823,6 +6847,8 @@ export default function ChatView(props: ChatViewProps) {
frame = window.requestAnimationFrame(() => {
frame = window.requestAnimationFrame(() => {
frame = null;
// A full-screen app owns the page; refocusing the composer would close it.
if (document.querySelector("[data-mcp-app-fullscreen]") !== null) return;
if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposer();
});
});
@@ -11280,6 +11306,13 @@ export default function ChatView(props: ChatViewProps) {
!paintOnlyDisplayedTimeline && (isWorking || !latestRunSettled)
}
isCompacting={!paintOnlyDisplayedTimeline && isCompacting}
awaitingUser={
!paintOnlyDisplayedTimeline &&
(activePendingApproval !== null ||
activePendingUserInput !== null ||
// A secret request has no runtime request; the shell carries it.
activeThreadShell?.hasPendingUserInput === true)
}
activeTurnStartedAt={paintOnlyDisplayedTimeline ? null : activeWorkStartedAt}
worktreeSetup={paintOnlyDisplayedTimeline ? null : worktreeSetup}
onCancelWorktreeSetup={onCancelWorktreeSetup}
@@ -11322,7 +11355,7 @@ export default function ChatView(props: ChatViewProps) {
paintOnlyDisplayedTimeline ? noopHeldRevert : onRevertTimelineTurn
}
{...(!paintOnlyDisplayedTimeline
? { onUseArtifactTemplate: useArtifactTemplate }
? { onUseArtifactTemplate: useArtifactTemplate, onSendAppMessage: sendAppMessage }
: {})}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
@@ -0,0 +1,550 @@
import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
import {
makeMcpAppHost,
McpAppHostRefusal,
mcpAppStyleVariables,
mcpResourceBytes,
type McpAppCallToolResult,
type McpAppDisplayMode,
type McpAppHost,
type McpAppHostContext,
} from "@t3tools/client-runtime/mcp-apps";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
clampMcpAppHeight,
MCP_APP_DEFAULT_HEIGHT,
MCP_APP_MAX_HEIGHT,
mcpAppAllowAttribute,
mcpAppFileName,
type McpAppReference,
} from "@t3tools/shared/mcpApp";
import { Minimize2Icon } from "lucide-react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { flushSync } from "react-dom";
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
import { APP_VERSION } from "~/branding";
import { isConfirmDialogActive, requestConfirmDialog } from "~/confirmDialog";
import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
import { Button } from "~/components/ui/button";
import { isElectron } from "~/env";
import { cn } from "~/lib/utils";
import { useTurnItemDetail } from "~/state/queries";
import { mcpAppEnvironment } from "~/state/mcpApps";
import { useAtomCommand } from "~/state/use-atom-command";
const commandFailure = (result: {
readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];
}) => {
const error = squashAtomCommandFailure(result);
return new McpAppHostRefusal(
error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
);
};
/** Full screen shows the box in the top layer, which needs the Popover API. */
/** A cached asset URL with less life than this is minted afresh first. */
const MIN_URL_LIFE_MS = 5 * 60_000;
const fullscreenSupported =
typeof HTMLElement !== "undefined" && "popover" in HTMLElement.prototype;
/** Largest file an app may hand the user through `ui/download-file`. */
const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
/** Saves a file through the browser's own download, which asks where when it is set to. */
function saveBlob(blob: Blob, name: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = name;
link.click();
// Long after the browser has read it: some start the download a task or
// more after the click, and a revoked URL saves nothing.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
/**
* An MCP App inline in the thread: the captured document in an opaque-origin
* frame, speaking the MCP Apps bridge. Its tool calls and resource reads reach
* its own MCP server through the environment; calls to tools the server does
* not mark read-only, chat messages, and downloads ask first. Full screen keeps
* the same frame (and the app's state) and only restyles its box.
*/
export function McpAppFrame(props: {
readonly environmentId: EnvironmentId;
/** The thread that produced the app, which its requests run against. */
readonly threadId: ThreadId;
/** The thread on screen, whose next turn the app's model context informs. */
readonly conversationThreadId: ThreadId;
readonly itemId: TurnItemId;
/** The item's revision, so its stored call is fetched once per version. */
readonly revision: string;
readonly app: McpAppReference;
readonly onSendMessage: ((text: string) => Promise<void>) | undefined;
/** The agent waits on the user, in a panel a full-screen app would cover. */
readonly awaitingUser?: boolean;
/** Told when the app enters or leaves full screen. */
readonly onFullscreenChange?: (fullscreen: boolean) => void;
}) {
const { app } = props;
const theme = useHtmlRenderTheme();
const frameRef = useRef<HTMLIFrameElement>(null);
const boxRef = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(MCP_APP_DEFAULT_HEIGHT);
const [navigatedAway, setNavigatedAway] = useState(false);
const [displayMode, setDisplayMode] = useState<McpAppDisplayMode>("inline");
// The app asked to be closed; the row falls back to its plain tool call.
const [closed, setClosed] = useState(false);
// Counts the app documents this row has shown. Reopening a closed app loads
// a new one, which needs its own host and its own load tracking.
const [documentGeneration, setDocumentGeneration] = useState(0);
useLayoutEffect(() => {
const box = boxRef.current;
if (!box) return;
setWidth(box.clientWidth);
const observer = new ResizeObserver(([entry]) => {
if (entry) setWidth(Math.round(entry.contentRect.width));
});
observer.observe(box);
return () => observer.disconnect();
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Closing and reopening replaces the box.
}, [closed]);
const resource = useMemo(
() => ({
_tag: "attachment" as const,
attachmentId: app.attachmentId,
fileName: mcpAppFileName(app),
mimeType: "text/html",
disposition: "inline" as const,
}),
[app],
);
const asset = useAssetUrlState(props.environmentId, resource);
const refreshAsset = useAssetUrlRefresh(props.environmentId, resource);
// The frame keeps its first URL: a re-minted one would reload the app. A
// cached URL near expiry is minted afresh first, since a frame cannot
// report a failed load. At most one mint per document, so a skewed clock
// cannot mint on every update.
const [src, setSrc] = useState<string | null>(null);
const [mintFailed, setMintFailed] = useState(false);
const minting = useRef(false);
const cachedUrl = asset._tag === "Success" ? asset.url : null;
const cachedExpiresAt = asset._tag === "Success" ? asset.expiresAt : 0;
useEffect(() => {
if (src !== null || cachedUrl === null || minting.current) return;
if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
// oxlint-disable-next-line react/set-state-in-effect -- Adopts the cached URL once it is known to last.
setSrc(cachedUrl);
return;
}
minting.current = true;
void refreshAsset().then(
(url) => (url === null ? setMintFailed(true) : setSrc(url)),
() => setMintFailed(true),
);
}, [src, cachedUrl, cachedExpiresAt, refreshAsset]);
// The wire timeline omits tool input and output; the app needs both.
const detail = useTurnItemDetail({
environmentId: props.environmentId,
threadId: props.threadId,
itemId: props.itemId,
revision: props.revision,
});
const storedItem = detail.data?.item;
const toolCall = useMemo(() => {
if (storedItem?.type !== "dynamic_tool") return undefined;
const output = storedItem.output as { readonly result?: unknown } | undefined;
const result = output?.result as McpAppCallToolResult | undefined;
return { arguments: storedItem.input, result };
}, [storedItem]);
const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
const toolInfo = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
reportFailure: false,
});
// The tool's definition, which the app receives as `toolInfo` at initialize.
const [toolDefinition, setToolDefinition] = useState<unknown>(undefined);
// Read by the host on every message, so it always sees current values
// without being rebuilt (which would drop the app's session).
const live = {
theme,
width,
props,
callTool,
toolInfo,
readResource,
updateModelContext,
displayMode,
toolDefinition,
};
const hostRef = useRef<McpAppHost | null>(null);
const latest = useRef(live);
useEffect(() => {
latest.current = live;
});
useEffect(() => {
const box = boxRef.current;
if (box === null || !fullscreenSupported) return;
const shown = box.matches(":popover-open");
if (displayMode === "fullscreen" && !shown) box.showPopover();
if (displayMode !== "fullscreen" && shown) box.hidePopover();
// Reported only on a change, so an inline row never touches another
// row's pin.
if (displayMode === "fullscreen") {
latest.current.props.onFullscreenChange?.(true);
return () => latest.current.props.onFullscreenChange?.(false);
}
}, [displayMode]);
// The approval or question the agent waits on renders in the page, so a
// full-screen app steps aside for it.
const [stepAsideFor, setStepAsideFor] = useState(props.awaitingUser);
if (stepAsideFor !== props.awaitingUser) {
setStepAsideFor(props.awaitingUser);
if (props.awaitingUser === true) setDisplayMode("inline");
}
// Full screen sits above everything else in the page. Anything that takes
// focus outside it (an approval, the command palette, a dialog) returns the
// app inline so it can be seen; so does Escape pressed outside the app.
// Keys pressed inside the app stay with the app.
useEffect(() => {
if (displayMode !== "fullscreen") return;
const leave = () => setDisplayMode("inline");
const onFocus = (event: FocusEvent) => {
if (event.target instanceof Node && !boxRef.current?.contains(event.target)) leave();
};
const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") leave();
};
const onResize = () => hostRef.current?.updateHostContext();
document.addEventListener("focusin", onFocus);
window.addEventListener("keydown", onKey);
window.addEventListener("resize", onResize);
return () => {
document.removeEventListener("focusin", onFocus);
window.removeEventListener("keydown", onKey);
window.removeEventListener("resize", onResize);
};
}, [displayMode]);
// The definition is read once per app, before the host is built, so the
// initialize response can carry it; a failure only leaves it out.
useEffect(() => {
let cancelled = false;
void latest.current
.toolInfo({
environmentId: props.environmentId,
input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
})
.then((info) => {
if (!cancelled && info._tag === "Success" && info.value.tool !== undefined) {
setToolDefinition(info.value.tool);
}
});
return () => {
cancelled = true;
};
}, [props.environmentId, props.threadId, props.itemId, app.tool]);
// The bridge belongs to the captured document. A frame that navigates keeps
// its window, so a second load stops the app rather than letting a page T3
// never served pose as it. This is not a confidentiality boundary: a frame
// can always navigate itself, so the app could carry anything it read out
// in a URL either way.
// Counted per document: a reopened app is a new document, not a navigation.
const loads = useRef({ generation: 0, count: 0 });
const onFrameLoad = () => {
if (loads.current.generation !== documentGeneration) {
loads.current = { generation: documentGeneration, count: 0 };
}
loads.current.count += 1;
if (loads.current.count > 1) {
hostRef.current?.dispose();
setNavigatedAway(true);
}
};
useEffect(() => {
if (src === null) return;
const hostContext = (): McpAppHostContext => {
const current = latest.current;
return {
theme: current.theme.appearance,
styles: { variables: mcpAppStyleVariables(current.theme.variables) },
displayMode: current.displayMode,
availableDisplayModes: fullscreenSupported ? ["inline", "fullscreen"] : ["inline"],
containerDimensions:
current.displayMode === "fullscreen"
? {
width: frameRef.current?.clientWidth || window.innerWidth,
height: frameRef.current?.clientHeight || window.innerHeight,
}
: { width: current.width, maxHeight: MCP_APP_MAX_HEIGHT },
platform: isElectron ? "desktop" : "web",
locale: navigator.language,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
userAgent: `t3-code/${APP_VERSION}`,
deviceCapabilities: {
touch: window.matchMedia("(pointer: coarse)").matches,
hover: window.matchMedia("(hover: hover)").matches,
},
safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 },
...(current.toolDefinition === undefined
? {}
: { toolInfo: { tool: current.toolDefinition } }),
};
};
// Approvals render in the page, beneath the top layer a full-screen app
// occupies, so the app returns inline before T3 asks.
const ask = async (message: string) => {
flushSync(() => setDisplayMode("inline"));
const approved = await requestConfirmDialog(message);
// No dialog host is mounted, so nobody was asked; say so rather than
// reporting that the user declined.
if (approved === undefined) {
throw new McpAppHostRefusal("T3 could not ask for approval here.");
}
return approved;
};
const target = () => frameRef.current?.contentWindow ?? null;
const scope = () => {
const { environmentId, threadId, itemId } = latest.current.props;
return { environmentId, input: { threadId, itemId } };
};
const host = makeMcpAppHost({
app,
hostVersion: APP_VERSION,
// The document's origin is opaque, so "*" is the only target that reaches it;
// the window reference itself is what scopes delivery to this frame.
post: (message) => target()?.postMessage(message, "*"),
hostContext,
callTool: async ({ name, arguments: args }) => {
const { environmentId, input } = scope();
const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
if (info._tag !== "Success") throw commandFailure(info);
if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
if (!info.value.readOnly) {
const approved = await ask(
`Allow ${app.server} to run ${info.value.title ?? name}?\n${JSON.stringify(args, null, 2)}`,
);
if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
}
const result = await latest.current.callTool({
environmentId,
input: { ...input, name, arguments: args },
});
if (result._tag !== "Success") throw commandFailure(result);
return result.value;
},
readResource: async ({ uri }) => {
const { environmentId, input } = scope();
const result = await latest.current.readResource({
environmentId,
input: { ...input, uri },
});
if (result._tag !== "Success") throw commandFailure(result);
return result.value;
},
openLink: async (url) => {
// Only right after the reader used this frame, as with HTML renders.
if (document.activeElement !== frameRef.current || !navigator.userActivation?.isActive) {
throw new McpAppHostRefusal("Links open only from a click in the app.");
}
window.open(url, "_blank", "noopener,noreferrer");
},
sendMessage: async (text) => {
const send = latest.current.props.onSendMessage;
if (send === undefined) throw new McpAppHostRefusal("Messages are not available here.");
const approved = await ask(`Send this message from ${app.server}?\n${text}`);
if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
await send(text);
},
updateModelContext: async (context) => {
const { environmentId, input } = scope();
const result = await latest.current.updateModelContext({
environmentId,
input: {
...input,
...context,
conversationThreadId: latest.current.props.conversationThreadId,
},
});
if (result._tag !== "Success") throw commandFailure(result);
},
requestDisplayMode: async (mode) => {
// Full screen would cover the approval or question the agent waits
// on, or a confirmation any app is waiting on. Another app already
// full screen keeps the page; two would stack.
const otherFullscreen = document.querySelector("[data-mcp-app-fullscreen]");
if (
mode === "fullscreen" &&
(latest.current.props.awaitingUser === true ||
isConfirmDialogActive() ||
(otherFullscreen !== null && otherFullscreen !== boxRef.current))
) {
return latest.current.displayMode;
}
setDisplayMode(mode);
return mode;
},
downloadFile: async (files) => {
const names = files.map((file) => file.name).join(", ");
const approved = await ask(`Save ${names} from ${app.server}?`);
if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
for (const file of files) {
// A linked file is read from the app's own server, like its other reads.
let bytes: Uint8Array | undefined;
let mimeType = file.mimeType ?? "application/octet-stream";
if (file._tag === "embedded") {
bytes = file.bytes;
} else {
const { environmentId, input } = scope();
const read = await latest.current.readResource({
environmentId,
input: { ...input, uri: file.uri },
});
if (read._tag !== "Success") throw commandFailure(read);
const content = read.value.contents[0];
bytes = mcpResourceBytes(content);
const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
if (typeof declared === "string") mimeType = declared;
}
if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);
if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
throw new McpAppHostRefusal(`${file.name} is too large to save.`);
}
// A copy backed by a plain ArrayBuffer, which Blob requires.
saveBlob(new Blob([bytes.slice()], { type: mimeType }), file.name);
}
},
onRequestTeardown: () => {
if (latest.current.displayMode === "fullscreen") {
setDisplayMode("inline");
return;
}
// The app asked to go, so it gets its teardown before the frame does.
void host.teardown().then(() => setClosed(true));
},
onSizeChanged: (size) => {
// Full screen is a fixed box; what the app reports there would leave
// the inline row its full-screen height on the way back.
if (latest.current.displayMode === "fullscreen") return;
if (size.height !== undefined) setHeight(clampMcpAppHeight(size.height));
},
});
hostRef.current = host;
const receive = (event: MessageEvent) => {
// Only messages from this frame's own window reach its host.
if (event.source !== null && event.source === target()) host.receive(event.data);
};
window.addEventListener("message", receive);
return () => {
window.removeEventListener("message", receive);
// An unmount cannot wait: the request goes out before the frame does,
// which is all a list that recycles rows can offer the app.
void host.teardown();
hostRef.current = null;
};
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- A reopened document needs a new host.
}, [src, app, documentGeneration]);
// The host reads the context through `latest`; these only say when to resend.
useEffect(() => {
hostRef.current?.updateHostContext();
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Context changes trigger a resend.
}, [theme, width, displayMode, toolDefinition]);
// A new document gets a new host, which needs the call again.
useEffect(() => {
if (toolCall !== undefined) hostRef.current?.setToolCall(toolCall);
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each new document needs the call.
}, [toolCall, src, documentGeneration]);
// An app that asked to close keeps the box an inline row had, so the
// timeline does not jump, and says how to bring it back.
if (closed) {
return (
<div className="flex items-center justify-between gap-2 rounded-lg border border-border px-3 py-2 text-muted-foreground text-xs">
<span>The {app.server} app was closed</span>
<Button
size="xs"
variant="ghost"
onClick={() => {
// The first URL's token may have expired: the new document
// takes a fresh one, minted again if it is near expiry.
minting.current = false;
setSrc(null);
setDocumentGeneration((value) => value + 1);
setClosed(false);
}}
>
Show app
</Button>
</div>
);
}
const fullscreen = displayMode === "fullscreen";
return (
// The row keeps its inline height while the app is full screen, so the
// timeline does not jump; the box itself is what goes full screen.
<div style={{ height }}>
<div
ref={boxRef}
// Full screen is the same box shown in the browser's top layer: moving
// the frame to another parent would reload the app, and the timeline's
// rows contain fixed positioning, which the top layer escapes.
{...(fullscreenSupported ? { popover: "manual" as const } : {})}
data-mcp-app-fullscreen={fullscreen ? "" : undefined}
className={cn(
"relative size-full overflow-hidden",
app.prefersBorder === true && !fullscreen && "rounded-lg border border-border",
fullscreen
? "fixed inset-0 m-0 flex h-dvh max-h-none w-dvw max-w-none flex-col border-0 bg-background p-0"
: // A closed popover is hidden; inline, the box is a plain block.
"block! static! m-0 border-0 bg-transparent p-0 text-inherit",
)}
>
{fullscreen ? (
<div className="flex h-10 shrink-0 items-center justify-between border-border border-b px-3 text-sm">
<span className="truncate">{app.server}</span>
<Button
aria-label="Exit full screen"
size="icon-sm"
variant="ghost"
onClick={() => setDisplayMode("inline")}
>
<Minimize2Icon className="size-4" />
</Button>
</div>
) : null}
{navigatedAway ? (
<p className="flex size-full items-center justify-center text-muted-foreground text-xs">
The {app.server} app left its page and was stopped
</p>
) : src !== null ? (
<iframe
ref={frameRef}
src={src}
title={`${app.server} app`}
// Never allow-same-origin: the opaque origin keeps the app out of the session.
sandbox="allow-scripts allow-forms"
allow={mcpAppAllowAttribute(app.permissions)}
onLoad={onFrameLoad}
className={cn("block w-full border-0", fullscreen ? "min-h-0 flex-1" : "h-full")}
style={{ colorScheme: theme.appearance }}
/>
) : asset._tag === "Failure" || mintFailed ? (
<p className="flex size-full items-center justify-center text-muted-foreground text-xs">
Unable to load the {app.server} app
</p>
) : null}
</div>
</div>
);
}
@@ -41,6 +41,8 @@ import {
type OrchestrationV2ProjectedTurnItem,
type RunAttemptId,
RunId,
type ThreadId,
type TurnItemId,
} from "@t3tools/contracts";
import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell";
import {
@@ -50,6 +52,7 @@ import {
} from "@t3tools/shared/t3McpToolPresentation";
import { compactDynamicToolOutput } from "@t3tools/shared/toolOutput";
import { htmlRenderReferencesEqual, type HtmlRenderReference } from "@t3tools/shared/htmlRender";
import { mcpAppReferencesEqual, type McpAppReference } from "@t3tools/shared/mcpApp";
import { dynamicToolTitle } from "@t3tools/shared/toolActivity";
import { formatWorkspaceRelativePath } from "../../filePathDisplay";
import {
@@ -66,7 +69,7 @@ function timelineEntryRunId(entry: TimelineEntry): RunId | null {
if (entry.kind === "proposed-plan") {
return entry.proposedPlan.runId;
}
if (entry.kind === "html-render") return entry.runId;
if (entry.kind === "html-render" || entry.kind === "mcp-app") return entry.runId;
return entry.kind === "work" ? (entry.entry.runId ?? null) : null;
}
@@ -596,6 +599,15 @@ type MessagesTimelineRowContent =
id: string;
createdAt: string;
htmlRender: HtmlRenderReference;
}
| {
kind: "mcp-app";
id: string;
createdAt: string;
sourceThreadId: ThreadId;
itemId: TurnItemId;
revision: string;
mcpApp: McpAppReference;
};
export interface StableMessagesTimelineRowsState {
@@ -720,6 +732,7 @@ function deriveSupersededAttemptFolds(
(entry.kind === "message" && entry.message.role === "user") ||
// A published page stays visible, as it does when its turn folds.
entry.kind === "html-render" ||
entry.kind === "mcp-app" ||
timelineEntryIsPersistentResourceCard(entry) ||
// A steer supersedes the attempt but leaves its children running.
liveSubagentEntryIds.has(entry.id) ||
@@ -1674,6 +1687,19 @@ export function deriveMessagesTimelineRows(input: {
continue;
}
if (timelineEntry.kind === "mcp-app") {
nextRows.push({
kind: "mcp-app",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
sourceThreadId: timelineEntry.sourceThreadId,
itemId: timelineEntry.itemId,
revision: timelineEntry.revision,
mcpApp: timelineEntry.mcpApp,
});
continue;
}
if (timelineEntry.kind === "event") {
const previous = nextRows.at(-1);
if (
@@ -2090,6 +2116,16 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
return a.createdAt === bh.createdAt && htmlRenderReferencesEqual(a.htmlRender, bh.htmlRender);
}
case "mcp-app": {
// Same reason: an equal app keeps its live frame and its state.
const bm = b as typeof a;
return (
a.createdAt === bm.createdAt &&
a.revision === bm.revision &&
mcpAppReferencesEqual(a.mcpApp, bm.mcpApp)
);
}
case "event":
return (
a.projectedItem === (b as typeof a).projectedItem &&
@@ -169,6 +169,7 @@ import {
} from "./SnapShotAttachmentDetails";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { HtmlRenderFrame } from "./HtmlRenderFrame";
import { McpAppFrame } from "./McpAppFrame";
import { ChangedFilesCard } from "./ChangedFilesTree";
import { useFileContextMenuHandler } from "../../fileContextMenu";
import { useProject, useThreadShell } from "../../state/entities";
@@ -312,6 +313,14 @@ interface TimelineRowSharedState {
activeThreadEnvironmentId: EnvironmentId;
onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void;
onUseArtifactTemplate: (template: CodexArtifactTemplate) => void;
/** Sends text an MCP App asked to post, after the user approved it. */
onSendAppMessage: ((text: string) => Promise<void>) | undefined;
/**
* An MCP App row entering or leaving full screen. The row stays rendered
* and the list stops following new output meanwhile, so the app is not
* virtualized away while the reader is using it.
*/
onAppFullscreenChange: (rowId: string, fullscreen: boolean) => void;
onRunShellCommand: ((command: string) => void) | undefined;
onImageExpand: (preview: ExpandedImagePreview) => void;
displayThreadKey?: string;
@@ -345,6 +354,8 @@ interface TimelineRowActivityState {
isCompacting: boolean;
isRevertingCheckpoint: boolean;
activeTurnInProgress: boolean;
/** The agent waits on an approval or an answer from the user. */
awaitingUser: boolean;
isPreparingWorktree: boolean;
latestRunId: RunId | null;
/**
@@ -441,6 +452,8 @@ interface MessagesTimelineProps {
onOpenWorktreeSetupTerminal?: (terminalId: string) => void;
isPreparingWorktree?: boolean;
isCompacting?: boolean;
/** The agent waits on an approval or an answer from the user. */
awaitingUser?: boolean;
/** Thread state shown after the last message, such as a settled or snoozed line. */
footer?: ReactNode;
@@ -468,6 +481,7 @@ interface MessagesTimelineProps {
supportsConversationRollback: boolean;
onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void;
onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
onSendAppMessage?: (text: string) => Promise<void>;
onRunShellCommand?: (command: string) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
@@ -529,6 +543,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onOpenWorktreeSetupTerminal,
isPreparingWorktree = false,
isCompacting = false,
awaitingUser = false,
listRef,
timelineEntries,
latestRun,
@@ -544,6 +559,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
supportsConversationRollback,
onRevertToTurnCount,
onUseArtifactTemplate = NOOP_USE_ARTIFACT_TEMPLATE,
onSendAppMessage,
onRunShellCommand,
isRevertingCheckpoint,
onImageExpand,
@@ -959,7 +975,26 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onManualNavigation,
});
const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
const alwaysRender = citationAlwaysRender ?? restoringAlwaysRender;
const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);
// Only the row that holds the pin can release it.
const onAppFullscreenChange = useCallback((rowId: string, fullscreen: boolean) => {
setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));
}, []);
// Every pin holds at once, so navigating to a citation or restoring a
// position never drops a full-screen app's row. The app is pinned by key,
// which stays right as earlier rows load in.
const alwaysRender = useMemo(() => {
const indices = restoringAlwaysRender?.indices ?? [];
const keys = [
...(citationAlwaysRender?.keys ?? []),
...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),
];
if (indices.length === 0 && keys.length === 0) return undefined;
return {
...(indices.length === 0 ? {} : { indices }),
...(keys.length === 0 ? {} : { keys }),
};
}, [citationAlwaysRender, restoringAlwaysRender, fullscreenAppRowId]);
const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
const [minimapCurrentIndex, setMinimapCurrentIndex] = useState<number | null>(null);
const handleAnchorReady = useCallback(
@@ -1183,6 +1218,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onImageExpand,
onFileOpen,
onUseArtifactTemplate,
onSendAppMessage,
onAppFullscreenChange,
onFileDownload,
openPullRequest,
onOpenTurnDiff,
@@ -1218,6 +1255,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onImageExpand,
onFileOpen,
onUseArtifactTemplate,
onSendAppMessage,
onAppFullscreenChange,
onFileDownload,
openPullRequest,
onOpenTurnDiff,
@@ -1252,10 +1291,12 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isRevertingCheckpoint,
backgroundWorktreeSetup,
activeTurnInProgress,
awaitingUser,
isPreparingWorktree,
latestRunId: latestRun?.runId ?? null,
}),
[
awaitingUser,
compactionAwaitingRow,
backgroundWorktreeSetup,
activeTurnInProgress,
@@ -1375,6 +1416,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
(restoringThreadPosition && rememberedPosition?.atEnd === false) ||
anchoredEndSpace ||
!liveFollowEnabled ||
fullscreenAppRowId !== null ||
disclosureToggleSettling
? false
: isWorking && !prefersReducedMotion && settlingListIdentity === null
@@ -1798,7 +1840,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
row.kind === "worktree-setup" ||
row.kind === "event" ||
row.kind === "attempt-fold" ||
row.kind === "html-render"
row.kind === "html-render" ||
row.kind === "mcp-app"
? "pb-2"
: "pb-4",
(row.kind === "message" && row.message.role === "assistant") ||
@@ -1847,6 +1890,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
{row.kind === "assistant-meta" ? <AssistantMetaTimelineRow row={row} /> : null}
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
{row.kind === "html-render" ? <HtmlRenderTimelineRow row={row} /> : null}
{row.kind === "mcp-app" ? <McpAppTimelineRow row={row} /> : null}
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
{row.kind === "worktree-setup" ? <WorktreeSetupTimelineRow row={row} /> : null}
{row.kind === "event" ? <V2EventTimelineRow row={row} /> : null}
@@ -2736,6 +2780,29 @@ function HtmlRenderTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "htm
);
}
function McpAppTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mcp-app" }> }) {
const ctx = use(TimelineRowCtx);
const { awaitingUser } = use(TimelineRowActivityCtx);
return (
<div className="min-w-0 px-1">
<McpAppFrame
// A recycled row must not keep another app's live document.
key={row.mcpApp.attachmentId}
environmentId={ctx.activeThreadEnvironmentId}
threadId={row.sourceThreadId}
conversationThreadId={ctx.threadRef?.threadId ?? row.sourceThreadId}
itemId={row.itemId}
revision={row.revision}
app={row.mcpApp}
onSendMessage={ctx.onSendAppMessage}
awaitingUser={awaitingUser}
onFullscreenChange={(fullscreen) => ctx.onAppFullscreenChange(row.id, fullscreen)}
/>
</div>
);
}
type V2EventTone = "muted" | "warning" | "danger" | "success";
function v2EventPresentation(item: OrchestrationV2TurnItem): {
+4
View File
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";
import {
completeConfirmDialogClose,
isConfirmDialogActive,
readConfirmDialogState,
registerConfirmDialogHost,
requestConfirmDialog,
@@ -40,6 +41,8 @@ describe("confirm dialog coordinator", () => {
respondToConfirmDialog(true);
await expect(confirmation).resolves.toBe(true);
// Still on screen while it closes, so nothing may cover it yet.
expect(isConfirmDialogActive()).toBe(true);
expect(readConfirmDialogState()).toEqual({
status: "closing",
message: "Delete this thread?",
@@ -48,6 +51,7 @@ describe("confirm dialog coordinator", () => {
completeConfirmDialogClose();
expect(readConfirmDialogState()).toEqual({ status: "idle" });
expect(isConfirmDialogActive()).toBe(false);
unregister();
});
+5
View File
@@ -101,6 +101,11 @@ export function requestConfirmDialog(
return confirmation;
}
/** True while a confirmation is shown, closing, or waiting to be shown. */
export function isConfirmDialogActive(): boolean {
return state.status !== "idle" || activeConfirmation !== null || queuedConfirmations.length > 0;
}
export function respondToConfirmDialog(confirmed: boolean): void {
if (state.status !== "confirming" || !activeConfirmation) return;
+19
View File
@@ -1319,6 +1319,25 @@ describe("HTML renders in the timeline", () => {
]);
});
it("hosts a captured MCP app in place, from any provider's tool", () => {
const mcpApp = {
attachmentId: "render-thread-app-html",
server: "weather",
tool: "get_weather",
resourceUri: "ui://weather/dashboard",
};
const call = renderCall("completed", { t3McpApp: mcpApp, result: { content: [] } });
const entries = turn(
call.type === "dynamic_tool" ? { ...call, toolName: "weather.get_weather" } : call,
);
expect(entries.find((entry) => entry.kind === "mcp-app")).toMatchObject({
id: "render",
itemId: "render",
mcpApp,
});
expect(rowsFor(entries, false)).toEqual(["message", "turn-fold", "mcp-app", "message"]);
});
it("keeps a render visible when its superseded attempt folds", () => {
const attempt: OrchestrationV2RunAttempt = {
id: RunAttemptId.make("attempt-superseded"),
+36 -1
View File
@@ -12,6 +12,8 @@ import {
type ToolActivitySurface,
type ToolActivityIcon,
type ToolActivitySource,
type ThreadId,
type TurnItemId,
} from "@t3tools/contracts";
import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
import {
@@ -21,7 +23,9 @@ import {
formatSearchToolLabel,
} from "@t3tools/shared/toolActivity";
import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
import type { McpAppReference } from "@t3tools/shared/mcpApp";
import { htmlRenderFromToolItem, mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
import {
contextCompactionLabel,
workEntryIndicatesToolFailure,
@@ -140,6 +144,18 @@ export type TimelineEntry = (
readonly runId: RunId | null;
readonly htmlRender: HtmlRenderReference;
}
| {
/** An MCP App a completed tool call captured, hosted where the call happened. */
readonly id: string;
readonly kind: "mcp-app";
readonly createdAt: string;
readonly runId: RunId | null;
/** The thread and item that own the app; a fork's inherited app is its source's. */
readonly sourceThreadId: ThreadId;
readonly itemId: TurnItemId;
readonly revision: string;
readonly mcpApp: McpAppReference;
}
| {
readonly id: string;
readonly kind: "work";
@@ -714,6 +730,25 @@ export function deriveTimelineEntriesFromVisibleTurnItems(
continue;
}
const mcpApp =
item.type === "dynamic_tool" && item.status === "completed"
? mcpAppFromToolItem(item)
: undefined;
if (mcpApp !== undefined) {
entries.push({
id: item.id,
kind: "mcp-app",
createdAt,
runId: item.runId,
sourceThreadId: row.sourceThreadId,
itemId: row.sourceItemId,
revision: turnItemDetailRevision(item),
mcpApp,
...attemptMetadata,
});
continue;
}
if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
entries.push({
id: item.id,
+5
View File
@@ -0,0 +1,5 @@
import { createMcpAppEnvironmentAtoms } from "@t3tools/client-runtime/state/mcp-apps";
import { connectionAtomRuntime } from "../connection/runtime";
export const mcpAppEnvironment = createMcpAppEnvironmentAtoms(connectionAtomRuntime);