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

+10
View File
@@ -51,6 +51,7 @@ import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet";
import { ThreadAgentsSheet } from "./features/threads/ThreadAgentsSheet";
import { ThreadQueueSheet } from "./features/threads/ThreadQueueControl";
import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen";
import { McpAppFullscreenScreen } from "./features/threads/McpAppFullscreenScreen";
import { ConnectionsRouteScreen } from "./features/connection/ConnectionsRouteScreen";
import { ConnectionsNewRouteScreen } from "./features/connection/ConnectionsNewRouteScreen";
import { HomeRouteScreen } from "./features/home/HomeRouteScreen";
@@ -747,6 +748,15 @@ const RootStackConfig = createNativeStackNavigator({
linking: `${THREAD_LINKING_PREFIX}/files/:path*`,
options: SOLID_HEADER_OPTIONS,
}),
ThreadMcpApp: createNativeStackScreen({
screen: McpAppFullscreenScreen,
linking: `${THREAD_LINKING_PREFIX}/apps/:itemId`,
options: {
presentation: "fullScreenModal",
headerShown: false,
gestureEnabled: false,
},
}),
ThreadAttachment: createNativeStackScreen({
screen: AttachmentFileScreen,
linking: `${THREAD_LINKING_PREFIX}/attachments/:attachmentId`,
@@ -0,0 +1,168 @@
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { SymbolView } from "../../components/AppSymbol";
import { orchestrationEnvironment } from "../../state/orchestration";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { useThreadShell, useThreadShells } from "../../state/entities";
import { useEnvironmentQuery } from "../../state/query";
import { ThreadMcpApp } from "./McpAppWebView";
type McpAppFullscreenScreenProps = StaticScreenProps<{
readonly environmentId: string;
readonly threadId: string;
readonly conversationThreadId?: string;
readonly itemId: string;
readonly revision?: string;
}>;
/**
* The thread an app's messages go to. A link only names it, so it counts only
* when it is the app's own thread or a fork of it; anything else falls back to
* the app's thread.
*/
function useConversationThreadId(
environmentId: EnvironmentId,
threadId: ThreadId,
requested: string | undefined,
): ThreadId {
const shells = useThreadShells();
return useMemo(
() =>
requested !== undefined && descendsFrom(shells, environmentId, requested, threadId)
? ThreadId.make(requested)
: threadId,
[shells, environmentId, threadId, requested],
);
}
/** True when `threadId` is `ancestorId` or one of its forks, at any depth. */
function descendsFrom(
shells: ReadonlyArray<EnvironmentThreadShell>,
environmentId: EnvironmentId,
threadId: string,
ancestorId: ThreadId,
): boolean {
const parents = new Map(
shells
.filter((shell) => shell.environmentId === environmentId)
// Only forks continue a conversation; a subagent is its own.
.filter((shell) => shell.lineage.relationshipToParent === "fork")
.map((shell) => [shell.id as string, shell.lineage.parentThreadId]),
);
let current: string | null | undefined = threadId;
for (let depth = 0; depth < 64 && current != null; depth += 1) {
if (current === ancestorId) return true;
current = parents.get(current);
}
return false;
}
/**
* An MCP App full screen (`ui/request-display-mode`), in a modal over the
* thread. It is its own view of the app; closing it returns to the row. The
* app is read from its stored tool call, never from the route, so a link can
* only open an app that call really produced.
*/
export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
// A plain goBack pops whatever is on top, so it only runs while this modal
// is: an exit that lands while another screen covers it (after a teardown
// wait) waits for the modal to be on top again, rather than popping that
// screen or being lost.
const focused = useIsFocused();
const [exitRequested, setExitRequested] = useState(false);
const onClose = useCallback(() => {
if (navigation.isFocused()) navigation.goBack();
else setExitRequested(true);
}, [navigation]);
const [size, setSize] = useState({ width: 0, height: 0 });
const params = route.params;
const environmentId = EnvironmentId.make(params.environmentId);
const threadId = ThreadId.make(params.threadId);
const itemId = TurnItemId.make(params.itemId);
const conversationThreadId = useConversationThreadId(
environmentId,
threadId,
params.conversationThreadId,
);
const detail = useEnvironmentQuery(
orchestrationEnvironment.turnItem({
environmentId,
input: {
threadId,
itemId,
...(params.revision === undefined ? {} : { revision: params.revision }),
},
}),
);
const item = detail.data?.item;
// One reference per app: the item is a new object on every refetch (a
// reconnect, for one), and a new reference would rebuild the app's host.
const derived = item?.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
const [app, setApp] = useState(derived);
if (derived?.attachmentId !== app?.attachmentId) setApp(derived);
// The approval or question the agent waits on renders on the thread this
// modal covers, so the app steps aside for it.
const conversation = useThreadShell(scopeThreadRef(environmentId, conversationThreadId));
const awaitingUser =
conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
useEffect(() => {
if ((awaitingUser || exitRequested) && focused) navigation.goBack();
}, [awaitingUser, exitRequested, focused, navigation]);
return (
<View className="flex-1 bg-background" style={{ paddingTop: insets.top }}>
<View className="h-11 flex-row items-center justify-between px-3">
<Text className="text-base font-semibold text-foreground" numberOfLines={1}>
{app?.server ?? "App"}
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Exit full screen"
hitSlop={8}
onPress={onClose}
>
<SymbolView name="xmark" size={18} tintColor="gray" />
</Pressable>
</View>
<View
className="flex-1"
style={{ paddingBottom: insets.bottom }}
onLayout={(event) =>
setSize({
width: Math.round(event.nativeEvent.layout.width),
height: Math.round(event.nativeEvent.layout.height - insets.bottom),
})
}
>
{app === undefined ? (
detail.data === undefined ? null : (
<Text className="m-6 text-sm text-foreground-muted">This app cannot be shown.</Text>
)
) : size.width > 0 ? (
<ThreadMcpApp
environmentId={environmentId}
threadId={threadId}
conversationThreadId={conversationThreadId}
itemId={itemId}
revision={params.revision ?? (item == null ? "" : turnItemDetailRevision(item))}
app={app}
width={size.width}
height={size.height}
displayMode="fullscreen"
onExitFullscreen={onClose}
/>
) : null}
</View>
</View>
);
}
@@ -0,0 +1,611 @@
import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
import {
makeMcpAppHost,
McpAppHostRefusal,
mcpAppStyleVariables,
mcpResourceBytes,
type McpAppCallToolResult,
type McpAppHost,
type McpAppHostContext,
} from "@t3tools/client-runtime/mcp-apps";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { CommandId, MessageId } from "@t3tools/contracts";
import {
mcpAppAllowAttribute,
mcpAppFileName,
mcpAppReferencesEqual,
type McpAppReference,
} from "@t3tools/shared/mcpApp";
import * as Predicate from "effect/Predicate";
import Constants from "expo-constants";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Alert, Platform, Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { WebView, type WebViewMessageEvent } from "react-native-webview";
import { AppText as Text } from "../../components/AppText";
import { shareGeneratedAttachment } from "../../lib/attachmentDownload";
import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { uuidv4 } from "../../lib/uuid";
import { useAssetUrlState } from "../../state/assets";
import { useThreadShell } from "../../state/entities";
import { mcpAppEnvironment } from "../../state/mcpApps";
import { orchestrationEnvironment } from "../../state/orchestration";
import { useEnvironmentQuery } from "../../state/query";
import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
import { useAtomCommand } from "../../state/use-atom-command";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
/** The feed reserves a fixed box for an app; a taller app scrolls inside it. */
const MCP_APP_ROW_HEIGHT = 420;
const ROW_BOTTOM_MARGIN = 8;
export function mcpAppRowHeight() {
return MCP_APP_ROW_HEIGHT + ROW_BOTTOM_MARGIN;
}
// The WebView loads a tiny outer page that hosts the app in a real
// opaque-origin iframe, as web does, so the app's `window.parent` and the
// `event.source` of host replies are a real window, which the MCP Apps SDK
// requires. The outer page only relays: app → React Native, and host
// replies (injected as `__t3McpAppReceive(...)`) → app.
//
// Android exposes `ReactNativeWebView` to every frame, so a frame nested in
// the app could post to React Native directly. The outer page therefore wraps
// what it relays with a secret only it holds, and React Native drops anything
// else. The bridge belongs to the captured document: once the app frame loads
// a second time (it navigated itself), the outer page stops relaying and says
// so, rather than letting a page T3 never served pose as the app. 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.
function outerDocument(src: string, allow: string, secret: string) {
const attribute = (value: string) =>
value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
return `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">
<style>html,body{margin:0;height:100%;background:transparent}iframe{border:0;display:block;width:100%;height:100%}</style></head>
<body><iframe id="app" sandbox="allow-scripts allow-forms" allow="${attribute(allow)}"></iframe>
<script>(function(){var frame=document.getElementById("app"),secret=${JSON.stringify(secret)},loads=0,live=true;
var send=function(m){window.ReactNativeWebView.postMessage(JSON.stringify({secret:secret,message:m}));};
frame.addEventListener("load",function(){loads+=1;if(loads>1&&live){live=false;send({t3:"navigated"});}});
window.addEventListener("message",function(e){if(live&&e.source===frame.contentWindow)send(e.data);});
window.__t3McpAppReceive=function(m){live&&frame.contentWindow&&frame.contentWindow.postMessage(m,"*");};
frame.src=${JSON.stringify(src).replace(/</g, "\\u003c")};})();</script></body></html>`;
}
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.",
);
};
const confirm = (title: string, message: string, action: string) =>
new Promise<boolean>((resolve) => {
Alert.alert(
title,
message,
[
{ text: "Cancel", style: "cancel", onPress: () => resolve(false) },
{ text: action, onPress: () => resolve(true) },
],
// Android dismisses an open alert when the next one shows; a dismissed
// request is declined rather than left holding an in-flight slot.
{ cancelable: true, onDismiss: () => resolve(false) },
);
});
/** Largest file an app may hand the user through `ui/download-file`. */
const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
/**
* A captured MCP App, hosted in a WebView over the MCP Apps bridge: inline as
* a fixed row of the thread feed, or full screen in its own modal screen. A
* WebView cannot move between the two without reloading, so each is its own
* view of the app: the inline one is torn down before full screen opens, and
* comes back when it closes.
*/
export function ThreadMcpApp(props: {
readonly environmentId: EnvironmentId;
/** The thread that produced the app, which its requests run against. */
readonly threadId: ThreadId;
/** The thread on screen, which approved app messages are sent to. */
readonly conversationThreadId: ThreadId;
readonly itemId: TurnItemId;
readonly revision: string;
readonly app: McpAppReference;
readonly width: number;
/** Full screen fills its screen; inline is the feed's fixed row. */
readonly displayMode?: "inline" | "fullscreen";
/** Full screen only: leaves it, back to the inline row. */
readonly onExitFullscreen?: () => void;
/** Full screen only: the screen's height, which the app is told it fills. */
readonly height?: number;
}) {
// One reference per app: a new object with the same content (a refetch, a
// rerender) must not rebuild the host of a document that is already live.
const [app, setApp] = useState(props.app);
if (!mcpAppReferencesEqual(app, props.app)) setApp(props.app);
const fullscreen = props.displayMode === "fullscreen";
const navigation = useNavigation();
const insets = useSafeAreaInsets();
// The app asked to be closed; the row falls back to a note that brings it back.
const [closed, setClosed] = useState(false);
// Full screen is a separate view of the app, so the inline one steps aside
// (and is torn down) while it is open, and comes back when the thread is
// shown again.
const [presentedFullscreen, setPresentedFullscreen] = useState(false);
// Counts the documents this row has shown on purpose (back from full screen,
// or reopened after closing); each gets its own view and host.
const [documentKey, setDocumentKeyState] = useState(0);
const { themeId, themeAppearance, themeVariables, systemColorsActive } =
useAppearancePreferences();
const theme = useMemo(
() =>
mobileHtmlRenderTheme({
themeId,
appearance: themeAppearance,
variables: themeVariables,
systemColors: systemColorsActive,
platform: Platform.OS,
}),
[themeId, themeAppearance, themeVariables, systemColorsActive],
);
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);
// The view keeps its first URL: a re-minted one would reload the app.
const [uri, setUri] = useState<string | null>(null);
if (uri === null && asset._tag === "Success") setUri(asset.url);
const [loaded, setLoaded] = useState(false);
const [navigatedAway, setNavigatedAway] = useState(false);
// Bumped when the OS reclaims the web process: a fresh view, document and
// host, so the reloaded app is initialized and replayed again. Once only, so
// an app that keeps crashing its process is not reloaded forever.
const [generation, setGeneration] = useState(0);
const [crashed, setCrashed] = useState(false);
const restart = () => {
if (generation > 0) {
setCrashed(true);
return;
}
setLoaded(false);
// The first URL's token may have expired by now; the asset query keeps
// a refreshed one, which this new view can load.
if (asset._tag === "Success") setUri(asset.url);
setGeneration(1);
};
// Minted per view, so only this view's outer page can speak for its app.
const [secret] = useState(uuidv4);
// A new document starts loading, is not yet one that navigated away, and
// loads the asset query's current URL: the first one's token may be gone.
const setDocumentKey = (next: (value: number) => number) => {
setLoaded(false);
setNavigatedAway(false);
if (asset._tag === "Success") setUri(asset.url);
setDocumentKeyState(next);
};
// Back from full screen: the thread shows a fresh inline view of the app.
// The listener reads the latest helper, whose URL comes from this render.
const openNewDocument = useRef(setDocumentKey);
useEffect(() => {
openNewDocument.current = setDocumentKey;
});
useEffect(() => {
if (!presentedFullscreen) return;
return navigation.addListener("focus", () => {
openNewDocument.current((value) => value + 1);
setPresentedFullscreen(false);
});
}, [navigation, presentedFullscreen]);
// The feed omits tool input and output; the app needs both.
const detail = useEnvironmentQuery(
orchestrationEnvironment.turnItem({
environmentId: props.environmentId,
input: { 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;
return {
arguments: storedItem.input,
result: output?.result as McpAppCallToolResult | undefined,
};
}, [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).
// The approval or question the agent waits on renders on this thread, and a
// full-screen app would cover it.
const conversation = useThreadShell(
scopeThreadRef(props.environmentId, props.conversationThreadId),
);
const awaitingUser =
conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
const live = {
awaitingUser,
theme,
props,
callTool,
toolInfo,
readResource,
updateModelContext,
insets,
toolDefinition,
navigation,
};
const latest = useRef(live);
useEffect(() => {
latest.current = live;
});
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]);
const webView = useRef<WebView<object>>(null);
const hostRef = useRef<McpAppHost | null>(null);
// One host per loaded document.
useEffect(() => {
if (uri === null) return;
const scope = () => {
const { environmentId, threadId, itemId } = latest.current.props;
return { environmentId, input: { threadId, itemId } };
};
const hostContext = (): McpAppHostContext => {
const current = latest.current;
const isFullscreen = current.props.displayMode === "fullscreen";
return {
theme: current.theme.appearance,
styles: { variables: mcpAppStyleVariables(current.theme.variables) },
displayMode: isFullscreen ? "fullscreen" : "inline",
availableDisplayModes: ["inline", "fullscreen"],
// Both are fixed boxes, so the app is told its exact size.
containerDimensions: {
width: current.props.width,
height: isFullscreen ? (current.props.height ?? MCP_APP_ROW_HEIGHT) : MCP_APP_ROW_HEIGHT,
},
platform: "mobile",
locale: Intl.DateTimeFormat().resolvedOptions().locale,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
userAgent: `t3-code/${Constants.expoConfig?.version ?? "0.0.0"}`,
deviceCapabilities: { touch: true, hover: false },
// The full-screen modal keeps the top and bottom insets for its
// header and the home indicator; only the sides reach the app.
safeAreaInsets: isFullscreen
? { top: 0, right: current.insets.right, bottom: 0, left: current.insets.left }
: { top: 0, right: 0, bottom: 0, left: 0 },
...(current.toolDefinition === undefined
? {}
: { toolInfo: { tool: current.toolDefinition } }),
};
};
const next = makeMcpAppHost({
app,
hostVersion: Constants.expoConfig?.version ?? "0.0.0",
post: (message) =>
webView.current?.injectJavaScript(
`window.__t3McpAppReceive&&window.__t3McpAppReceive(${JSON.stringify(message)});true;`,
),
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 &&
!(await confirm(
`Allow ${app.server} to run ${info.value.title ?? name}?`,
JSON.stringify(args, null, 2),
"Allow",
))
) {
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: resourceUri }) => {
const { environmentId, input } = scope();
const result = await latest.current.readResource({
environmentId,
input: { ...input, uri: resourceUri },
});
if (result._tag !== "Success") throw commandFailure(result);
return result.value;
},
openLink: async (url) => {
// A WebView cannot tell whether the reader just tapped the app, so it
// asks, rather than letting an app leave T3 on a timer.
if (!(await confirm(`Open a link from ${app.server}?`, url, "Open"))) {
throw new McpAppHostRefusal("Declined by the user.");
}
if (!(await tryOpenExternalUrl(url, "mcp-app"))) {
throw new McpAppHostRefusal("The link could not be opened.");
}
},
sendMessage: async (text) => {
if (!(await confirm(`Send this message from ${app.server}?`, text, "Send"))) {
throw new McpAppHostRefusal("Declined by the user.");
}
// Through the outbox like a typed message, so it survives a dropped
// connection; the thread's own settings fill in when it sends.
await enqueueThreadOutboxMessage({
environmentId: latest.current.props.environmentId,
threadId: latest.current.props.conversationThreadId,
messageId: MessageId.make(uuidv4()),
commandId: CommandId.make(uuidv4()),
text,
attachments: [],
dispatchMode: "queue",
createdAt: new Date().toISOString(),
});
},
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) => {
const current = latest.current.props;
// Full screen would cover the approval or question the agent waits
// on, or a screen the user moved to.
if (
mode === "fullscreen" &&
(latest.current.awaitingUser || !latest.current.navigation.isFocused())
) {
return current.displayMode ?? "inline";
}
if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
// The inline view is torn down by the switch (this row unmounts
// while the modal covers it); the modal opens a fresh view.
// The inline view steps aside for the modal; it gets its teardown first.
await hostRef.current?.teardown();
// The wait may have let an approval arrive, or the user moved to
// another screen; either way the view reloads inline.
if (latest.current.awaitingUser || !latest.current.navigation.isFocused()) {
openNewDocument.current((value) => value + 1);
return "inline";
}
setPresentedFullscreen(true);
latest.current.navigation.navigate("ThreadMcpApp", {
environmentId: String(current.environmentId),
threadId: String(current.threadId),
conversationThreadId: String(current.conversationThreadId),
itemId: String(current.itemId),
revision: current.revision,
});
return "fullscreen";
}
if (mode === "inline" && current.displayMode === "fullscreen") {
await hostRef.current?.teardown();
current.onExitFullscreen?.();
return "inline";
}
return current.displayMode ?? "inline";
},
downloadFile: async (files) => {
const names = files.map((file) => file.name).join(", ");
if (!(await confirm(`Save a file from ${app.server}?`, names, "Save"))) {
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.`);
}
const shared = await shareGeneratedAttachment({
bytes,
attachment: { name: file.name, mimeType },
signal: new AbortController().signal,
});
if (!shared) throw new McpAppHostRefusal("Sharing is not available on this device.");
}
},
onRequestTeardown: () => {
const current = latest.current.props;
if (current.displayMode === "fullscreen") {
void hostRef.current?.teardown().then(() => current.onExitFullscreen?.());
} else {
void hostRef.current?.teardown().then(() => setClosed(true));
}
},
// Both modes are fixed boxes, so the app's own height only decides
// whether it scrolls inside one.
onSizeChanged: () => undefined,
});
hostRef.current = next;
return () => {
// An unmount cannot wait: the request goes out before the view does.
void next.teardown();
hostRef.current = null;
};
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- A restarted view needs a new host.
}, [uri, app, generation, documentKey]);
// 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, props.width, props.height, insets, 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, uri, generation, documentKey]);
const source = useMemo(
() =>
uri === null
? null
: { html: outerDocument(uri, mcpAppAllowAttribute(app.permissions), secret) },
[uri, app.permissions, secret],
);
if (presentedFullscreen) {
return (
<View
style={{ height: MCP_APP_ROW_HEIGHT, marginBottom: ROW_BOTTOM_MARGIN }}
className="items-center justify-center rounded-lg border border-border"
>
<Text className="text-sm text-foreground-muted">
The {app.server} app is open full screen
</Text>
</View>
);
}
if (closed) {
return (
<View
style={{ height: MCP_APP_ROW_HEIGHT, marginBottom: ROW_BOTTOM_MARGIN }}
className="items-center justify-center gap-2 rounded-lg border border-border"
>
<Text className="text-sm text-foreground-muted">The {app.server} app was closed</Text>
<Pressable
accessibilityRole="button"
onPress={() => {
setDocumentKey((value) => value + 1);
setClosed(false);
}}
>
<Text className="text-sm text-foreground">Show app</Text>
</Pressable>
</View>
);
}
return (
<View
style={
fullscreen ? { flex: 1 } : { height: MCP_APP_ROW_HEIGHT, marginBottom: ROW_BOTTOM_MARGIN }
}
>
{navigatedAway ? (
<View className="flex-1 items-center justify-center">
<Text className="text-sm text-foreground-muted">
The {app.server} app left its page and was stopped
</Text>
</View>
) : uri !== null && !crashed ? (
<WebView<object>
key={`${documentKey}:${generation}`}
ref={webView}
onContentProcessDidTerminate={restart}
onRenderProcessGone={restart}
source={source!}
accessibilityLabel={`${app.server} app`}
style={{ flex: 1, backgroundColor: "transparent" }}
nestedScrollEnabled
originWhitelist={["*"]}
// Only the outer page loads at the top; the app opens links through
// the bridge. Android reports every navigation as top-frame, frames
// the app nests included, so it has no gate to apply: there the
// outer page never navigates, and the app frame's sandbox already
// forbids top navigation and popups.
onShouldStartLoadWithRequest={(request) =>
Platform.OS === "android" ||
request.isTopFrame === false ||
request.url === "about:blank"
}
setSupportMultipleWindows={false}
onLoadEnd={() => setLoaded(true)}
// The outer page is inline HTML, so these report a broken view, not
// an app page; the row shows the failure instead of a blank box.
onError={() => setCrashed(true)}
onHttpError={() => setCrashed(true)}
onMessage={(event: WebViewMessageEvent) => {
let envelope: unknown;
try {
envelope = JSON.parse(event.nativeEvent.data);
} catch {
return; // Not JSON: not a bridge message.
}
if (!Predicate.isObject(envelope) || envelope.secret !== secret) return;
const message = envelope.message;
if (Predicate.isObject(message) && message.t3 === "navigated") {
hostRef.current?.dispose();
setNavigatedAway(true);
return;
}
hostRef.current?.receive(message);
}}
/>
) : asset._tag === "Failure" || crashed ? (
<View className="flex-1 items-center justify-center">
<Text className="text-sm text-foreground-muted">Unable to load the {app.server} app</Text>
</View>
) : null}
{uri !== null && !loaded && !crashed && !navigatedAway ? (
<View pointerEvents="none" className="absolute inset-0 items-center justify-center">
<ActivityIndicator />
</View>
) : null}
</View>
);
}
@@ -188,6 +188,7 @@ import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
import { resolveThreadFeedFixedItemSize } from "./thread-feed-item-size";
import { htmlRenderFrameHeight } from "@t3tools/shared/htmlRender";
import { htmlRenderRowHeight, ThreadHtmlRender } from "./HtmlRenderWebView";
import { mcpAppRowHeight, ThreadMcpApp } from "./McpAppWebView";
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import {
assetEnvironment,
@@ -1597,6 +1598,20 @@ function renderFeedEntry(
);
}
if (entry.type === "mcp-app") {
return (
<ThreadMcpApp
environmentId={props.environmentId}
threadId={entry.sourceThreadId}
conversationThreadId={props.threadId}
itemId={entry.itemId}
revision={entry.revision}
app={entry.app}
width={props.contentWidth}
/>
);
}
if (entry.type === "work-toggle") {
return (
<ThreadWorkGroupToggle
@@ -2914,6 +2929,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
if (entry.type === "html-render") {
return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth));
}
if (entry.type === "mcp-app") return mcpAppRowHeight();
if (workRowSizing.fixedRowHeight === undefined) {
return undefined;
}
+23
View File
@@ -274,3 +274,26 @@ export async function shareLocalAttachment(input: {
cached.preview.dispose();
}
}
/**
* Shares bytes made on this device (an MCP App's download) through the same
* cache and share sheet. False when the share sheet could not be shown.
*/
export async function shareGeneratedAttachment(input: {
readonly bytes: Uint8Array;
readonly attachment: AttachmentFileMetadata;
readonly signal: AbortSignal;
}): Promise<boolean> {
// An unavailable share sheet is a refusal for the caller, not a failure.
const sharing = await availableSharing(input.signal).catch(() => null);
if (sharing === null) return false;
const cached = await createCachedAttachmentFile(input.attachment);
try {
if (input.signal.aborted) return false;
cached.file.write(input.bytes);
await cached.preview.share(input.signal);
return true;
} finally {
cached.preview.dispose();
}
}
+1
View File
@@ -7,6 +7,7 @@ const ExternalUrlTarget = Schema.Literals([
"pull-request",
"provider-auth",
"html-render",
"mcp-app",
]);
export type ExternalUrlTarget = typeof ExternalUrlTarget.Type;
@@ -2511,3 +2511,35 @@ describe("html renders", () => {
}
});
});
describe("MCP apps", () => {
const app = {
attachmentId: "attachment-app",
server: "weather",
tool: "get_weather",
resourceUri: "ui://weather/dashboard",
};
const appCall = (status: OrchestrationV2TurnItem["status"]): OrchestrationV2TurnItem => ({
...base("item-app", "2026-06-20T00:00:02.500Z", 2),
status,
type: "dynamic_tool",
toolName: "weather.get_weather",
input: { city: "Oslo" },
output: { t3McpApp: app, result: { content: [] } },
});
const feed = (status: OrchestrationV2TurnItem["status"]) =>
buildThreadFeed([
projected(userMessage(), 0),
projected(appCall(status), 1),
projected(assistantMessage("2026-06-20T00:00:04.000Z"), 2),
]);
it("hosts a completed app in place of its tool row, owned by its source item", () => {
const entry = feed("completed").find((candidate) => candidate.type === "mcp-app");
expect(entry).toMatchObject({ type: "mcp-app", app, itemId: "item-app", runId });
});
it("keeps a running app call an ordinary work row", () => {
expect(feed("running").some((candidate) => candidate.type === "mcp-app")).toBe(false);
});
});
+44 -3
View File
@@ -8,6 +8,7 @@ import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subage
import { isLiveSubagentTurnItem } from "@t3tools/client-runtime/state/subagentRuntime";
import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
import {
turnItemDetailRevision,
turnItemHasDetail,
turnItemNeedsDetailFetch,
} from "@t3tools/client-runtime/work-log/item-detail";
@@ -48,6 +49,7 @@ import type {
OrchestrationV2UserMessageInputIntent,
RunAttemptId,
ScheduledTaskId,
TurnItemId,
} from "@t3tools/contracts";
import { RunId, ThreadId } from "@t3tools/contracts";
import {
@@ -59,7 +61,12 @@ import {
} from "@t3tools/shared/toolActivity";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
import { compactDynamicToolOutput, htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
import type { McpAppReference } from "@t3tools/shared/mcpApp";
import {
compactDynamicToolOutput,
htmlRenderFromToolItem,
mcpAppFromToolItem,
} from "@t3tools/shared/toolOutput";
import * as DateTime from "effect/DateTime";
export type PendingApproval = ThreadPendingApproval;
@@ -165,12 +172,24 @@ type RawThreadFeedEntry =
readonly createdAt: string;
readonly runId: RunId | null;
readonly render: HtmlRenderReference;
}
| {
/** An MCP App a completed tool call captured, hosted in place of its work row. */
readonly type: "mcp-app";
readonly id: string;
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 app: McpAppReference;
};
export type ThreadFeedEntry = ThreadFeedEntryContent & { readonly continuesWorkLog?: boolean };
type ThreadFeedEntryContent =
| Extract<RawThreadFeedEntry, { type: "message" | "html-render" }>
| Extract<RawThreadFeedEntry, { type: "message" | "html-render" | "mcp-app" }>
| {
readonly type: "activity-group";
readonly id: string;
@@ -1049,7 +1068,9 @@ function deriveThreadFeedRunFolds(
const runId =
entry.type === "message" && entry.message.role === "assistant"
? (entry.message.runId ?? runlessKey)
: entry.type === "activity-group" || entry.type === "html-render"
: entry.type === "activity-group" ||
entry.type === "html-render" ||
entry.type === "mcp-app"
? (entry.runId ?? runlessKey)
: null;
if (!runId) continue;
@@ -1102,6 +1123,7 @@ function deriveThreadFeedRunFolds(
entry.id !== firstAssistantId &&
entry.id !== terminalAssistantId &&
entry.type !== "html-render" &&
entry.type !== "mcp-app" &&
!(
entry.type === "activity-group" &&
entry.activities.some(
@@ -1750,6 +1772,25 @@ export function buildThreadFeed(
entries.push(entry);
continue;
}
const app =
item.type === "dynamic_tool" && item.status === "completed"
? mcpAppFromToolItem(item)
: undefined;
if (app) {
const entry: RawThreadFeedEntry = {
type: "mcp-app",
id: `mcp-app:${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
createdAt,
runId: item.runId,
sourceThreadId: row.sourceThreadId,
itemId: row.sourceItemId,
revision: turnItemDetailRevision(item),
app,
};
projectedEntriesCache.set(row, { attemptId, entry });
entries.push(entry);
continue;
}
if (item.type === "user_message" || item.type === "assistant_message") {
const updatedAt = DateTime.formatIso(item.updatedAt);
const entry: RawThreadFeedEntry = {
+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);
@@ -72,6 +72,7 @@ const CODEX_REPLAY_PLAN_MODE_DEVELOPER_INSTRUCTIONS =
const CODEX_CLIENT_CAPABILITIES = {
experimentalApi: true,
optOutNotificationMethods: ["turn/diff/updated"],
extensions: { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] } },
} as const;
const CODEX_REPLAY_DEFAULT_MODEL = "gpt-6-luna";
const CODEX_REPLAY_MODEL_OVERRIDE = readArgValue("--model") ?? process.env.T3_CODEX_REPLAY_MODEL;
+20
View File
@@ -243,4 +243,24 @@ describe("threadHtmlRenderAttachmentIds", () => {
]),
).toEqual([own]);
});
it("includes captured MCP App documents from any tool", () => {
const app = createAttachmentId("thread-a", "html")!;
expect(
threadHtmlRenderAttachmentIds("thread-a", [
{
toolName: "weather.get_weather",
output: {
t3McpApp: {
attachmentId: app,
server: "weather",
tool: "get_weather",
resourceUri: "ui://weather/dashboard",
},
result: { content: [] },
},
},
]),
).toEqual([app]);
});
});
+6 -4
View File
@@ -4,7 +4,7 @@ import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import type { ChatAttachment } from "@t3tools/contracts";
import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
import { htmlRenderFromToolItem, mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
import {
normalizeAttachmentRelativePath,
@@ -116,8 +116,9 @@ export function parseThreadSegmentFromAttachmentId(attachmentId: string): string
}
/**
* Attachments a thread's `html_render` tool calls published. Only ids minted
* for this thread count, so deleting a fork never removes its source's pages.
* Attachments a thread's tool calls published: `html_render` pages and
* captured MCP App documents. Only ids minted for this thread count, so
* deleting a fork never removes its source's pages.
*/
export function threadHtmlRenderAttachmentIds(
threadId: string,
@@ -126,7 +127,8 @@ export function threadHtmlRenderAttachmentIds(
const segment = toSafeThreadAttachmentSegment(threadId);
if (segment === null) return [];
return Array.from(items).flatMap((item) => {
const attachmentId = htmlRenderFromToolItem(item)?.attachmentId;
const attachmentId =
htmlRenderFromToolItem(item)?.attachmentId ?? mcpAppFromToolItem(item)?.attachmentId;
return attachmentId !== undefined &&
parseThreadSegmentFromAttachmentId(attachmentId) === segment
? [attachmentId]
+5
View File
@@ -155,6 +155,11 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
[WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
[WS_METHODS.providerUploadFeedback]: AuthOrchestrationOperateScope,
// An app's tool calls can change things on its server, like a user action.
[WS_METHODS.mcpAppsCallTool]: AuthOrchestrationOperateScope,
[WS_METHODS.mcpAppsToolInfo]: AuthOrchestrationReadScope,
[WS_METHODS.mcpAppsReadResource]: AuthOrchestrationReadScope,
[WS_METHODS.mcpAppsUpdateModelContext]: AuthOrchestrationOperateScope,
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeWorktreeSetup]: AuthOrchestrationReadScope,
[WS_METHODS.worktreeSetupCancel]: AuthOrchestrationOperateScope,
@@ -0,0 +1,68 @@
import { ThreadId, TurnItemId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/sql/SqlClient";
import { runMigrations } from "../persistence/Migrations.ts";
import * as McpAppModelContext from "./McpAppModelContext.ts";
const database = NodeSqliteClient.layer({ filename: ":memory:" });
const layer = it.layer(
Layer.merge(database, McpAppModelContext.layer.pipe(Layer.provide(database))),
);
const threadId = ThreadId.make("thread-context");
const forkId = ThreadId.make("thread-context-fork");
/** An app's tool call in the projection, in a run with the given status. */
const insertAppItem = (itemId: string, runId: string, runStatus: string) =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
INSERT INTO orchestration_v2_projection_runs
(run_id, thread_id, ordinal, provider, status, requested_at, payload_json)
VALUES (${runId}, ${threadId}, ${runId.length}, 'codex', ${runStatus}, '2026-01-01', '{}')
`;
yield* sql`
INSERT INTO orchestration_v2_projection_turn_items
(turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json)
VALUES (${itemId}, ${threadId}, ${runId}, 0, 'dynamic_tool', 'completed', '2026-01-01', '{}')
`;
});
layer("McpAppModelContext", (it) => {
it.effect("sends only apps still in the thread's history, including a fork's", () =>
Effect.gen(function* () {
yield* runMigrations();
const store = yield* McpAppModelContext.McpAppModelContext;
yield* insertAppItem("item-kept", "run-a", "completed");
yield* insertAppItem("item-rolled-back", "run-bb", "rolled_back");
const set = (thread: ThreadId, itemId: string, text: string) =>
store.set({
threadId: thread,
itemId: TurnItemId.make(itemId),
server: "todos",
tool: "list_todos",
text,
});
yield* set(threadId, "item-kept", "kept");
yield* set(threadId, "item-rolled-back", "from a rolled-back run");
yield* set(threadId, "item-deleted", "from an item that is gone");
// A fork showing the source thread's app keeps its own context, even
// after the source rolls that app's run back.
yield* set(forkId, "item-kept", "from the fork");
yield* set(forkId, "item-rolled-back", "inherited before the rollback");
const texts = (thread: ThreadId) =>
store.forThread(thread).pipe(Effect.map((entries) => entries.map((entry) => entry.text)));
assert.deepEqual(yield* texts(threadId), ["kept"]);
assert.deepEqual(yield* texts(forkId), ["from the fork", "inherited before the rollback"]);
// Clearing removes the app's context.
yield* set(threadId, "item-kept", "");
assert.deepEqual(yield* texts(threadId), []);
}),
);
});
@@ -0,0 +1,105 @@
import type { ThreadId, TurnItemId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
/** Largest context one app may keep for the agent, in UTF-8 bytes. */
export const MCP_APP_MODEL_CONTEXT_MAX_BYTES = 16 * 1024;
export class McpAppModelContextError extends Schema.TaggedError<McpAppModelContextError>()(
"McpAppModelContextError",
{ cause: Schema.optional(Schema.Defect()) },
) {}
export interface McpAppModelContextEntry {
readonly itemId: string;
readonly server: string;
readonly tool: string;
readonly text: string;
}
/**
* What each MCP App told the agent through `ui/update-model-context`. The spec
* replaces an app's context on every update, so there is one entry per app (its
* tool call); the thread's next turn carries the entries to the provider.
*/
export class McpAppModelContext extends Context.Service<
McpAppModelContext,
{
/** Replaces the app's context; empty text removes it. */
readonly set: (input: {
readonly threadId: ThreadId;
readonly itemId: TurnItemId;
readonly server: string;
readonly tool: string;
readonly text: string;
}) => Effect.Effect<void, McpAppModelContextError>;
readonly forThread: (
threadId: ThreadId,
) => Effect.Effect<ReadonlyArray<McpAppModelContextEntry>, McpAppModelContextError>;
}
>()("t3/mcpApps/McpAppModelContext") {}
export const layer = Layer.effect(
McpAppModelContext,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const fail = (cause: unknown) => new McpAppModelContextError({ cause });
const set = Effect.fn("McpAppModelContext.set")(function* (input: {
readonly threadId: ThreadId;
readonly itemId: TurnItemId;
readonly server: string;
readonly tool: string;
readonly text: string;
}) {
if (input.text.trim() === "") {
yield* sql`
DELETE FROM mcp_app_model_context
WHERE thread_id = ${input.threadId} AND item_id = ${input.itemId}
`.pipe(Effect.mapError(fail));
return;
}
const updatedAt = DateTime.formatIso(yield* DateTime.now);
yield* sql`
INSERT INTO mcp_app_model_context (thread_id, item_id, server, tool, text, updated_at)
VALUES (${input.threadId}, ${input.itemId}, ${input.server}, ${input.tool}, ${input.text}, ${updatedAt})
ON CONFLICT(thread_id, item_id) DO UPDATE SET text = excluded.text, updated_at = excluded.updated_at
`.pipe(Effect.mapError(fail));
});
const forThread = Effect.fn("McpAppModelContext.forThread")(function* (threadId: ThreadId) {
// Only apps still in the thread's history count: an app whose item is
// gone, or whose run this thread rolled back, stops informing the agent.
// The item can live in a thread this one was forked from, so it is
// matched by id alone; that thread rolling the run back later leaves the
// fork's copy in place.
return yield* sql<McpAppModelContextEntry>`
SELECT context.item_id AS "itemId", context.server, context.tool, context.text
FROM mcp_app_model_context AS context
JOIN orchestration_v2_projection_turn_items AS item
ON item.turn_item_id = context.item_id
LEFT JOIN orchestration_v2_projection_runs AS run
ON run.run_id = item.run_id
WHERE context.thread_id = ${threadId}
AND (
run.status IS NULL
OR run.status <> 'rolled_back'
OR run.thread_id <> context.thread_id
)
ORDER BY context.updated_at, context.item_id
`.pipe(Effect.mapError(fail));
});
return McpAppModelContext.of({ set, forThread });
}),
);
/** No app context: for code paths and tests with no MCP Apps. */
export const layerEmpty = Layer.succeed(
McpAppModelContext,
McpAppModelContext.of({ set: () => Effect.void, forThread: () => Effect.succeed([]) }),
);
@@ -0,0 +1,284 @@
import {
ProviderSessionId,
ProviderThreadId,
ThreadId,
TurnItemId,
type McpAppRequestError,
type OrchestrationV2ProviderThread,
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import type {
ProviderAdapterV2McpApps,
ProviderAdapterV2SessionRuntime,
} from "../orchestration-v2/ProviderAdapter.ts";
import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as McpAppModelContext from "./McpAppModelContext.ts";
import * as McpAppRequests from "./McpAppRequests.ts";
const threadId = ThreadId.make("thread-app");
const itemId = TurnItemId.make("item-app");
const providerThreadId = ProviderThreadId.make("provider-thread-app");
const providerSessionId = ProviderSessionId.make("provider-session-app");
const forkId = ThreadId.make("thread-fork");
const unrelatedId = ThreadId.make("thread-unrelated");
// A chain of forks deeper than any fixed walk limit: deep-70 → … → deep-1 → app.
const deepForkId = (depth: number) => ThreadId.make(`thread-deep-${depth}`);
const deepParent = (id: ThreadId): ThreadId | null => {
const match = /^thread-deep-(\d+)$/.exec(id);
if (match === null) return null;
const depth = Number(match[1]);
return depth === 1 ? threadId : deepForkId(depth - 1);
};
const appItem = (output: unknown): OrchestrationV2TurnItem => ({
id: itemId,
threadId,
runId: null,
nodeId: null,
providerThreadId,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "completed",
title: null,
startedAt: null,
completedAt: null,
updatedAt: DateTime.makeUnsafe(0),
type: "dynamic_tool",
toolName: "weather.get_weather",
input: {},
output,
});
const app = {
attachmentId: "thread-app-00000000-0000-0000-0000-000000000000-html",
server: "weather",
tool: "get_weather",
resourceUri: "ui://weather/dashboard",
};
/** Each app's stored context, keyed by item, as the real store keeps it. */
const storedContext = new Map<string, string>();
function makeLayer(input: {
readonly item: OrchestrationV2TurnItem | null;
readonly mcpApps?: ProviderAdapterV2McpApps;
readonly live?: boolean;
}) {
return McpAppRequests.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(McpAppModelContext.McpAppModelContext)({
set: (entry) =>
Effect.sync(() => {
const key = `${entry.threadId}/${entry.itemId}`;
if (entry.text.trim() === "") storedContext.delete(key);
else storedContext.set(key, entry.text);
}),
}),
Layer.mock(Orchestrator.OrchestratorV2)({
getTurnItem: () => Effect.succeed(input.item),
}),
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadRecords: (id: ThreadId) =>
Effect.succeed({
// A fork of the app's thread, and an unrelated thread.
thread: {
lineage:
deepParent(id) !== null
? {
parentThreadId: deepParent(id),
relationshipToParent: "fork",
rootThreadId: threadId,
}
: id === forkId
? {
parentThreadId: threadId,
relationshipToParent: "fork",
rootThreadId: threadId,
}
: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
},
providerThreads: [
{ id: providerThreadId, providerSessionId } as OrchestrationV2ProviderThread,
],
} as never),
}),
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
get: () =>
Effect.succeed(
input.live === false
? Option.none()
: Option.some(
(input.mcpApps === undefined
? {}
: { mcpApps: input.mcpApps }) as ProviderAdapterV2SessionRuntime,
),
),
}),
),
),
);
}
const reason = <A, R>(effect: Effect.Effect<A, McpAppRequestError, R>) =>
effect.pipe(
Effect.flip,
Effect.map((error) => error.reason),
);
describe("McpAppRequests", () => {
const calls: Array<{ server: string; tool: string }> = [];
const mcpApps: ProviderAdapterV2McpApps = {
listTools: () =>
Effect.succeed([
{ name: "refresh", annotations: { readOnlyHint: true } },
{ name: "model_only", _meta: { ui: { visibility: ["model"] } } },
]),
callTool: (input) =>
Effect.sync(() => {
calls.push({ server: input.server, tool: input.tool });
return { content: [{ type: "text", text: "ok" }] };
}),
readResource: () => Effect.succeed({ contents: [] }),
};
it.effect("calls tools on the app's own server and reports their read-only hint", () =>
Effect.gen(function* () {
const requests = yield* McpAppRequests.McpAppRequests;
const result = yield* requests.callTool({
threadId,
itemId,
name: "refresh",
arguments: {},
});
assert.deepEqual(result, { content: [{ type: "text", text: "ok" }] });
assert.deepEqual(calls.at(-1), { server: "weather", tool: "refresh" });
assert.deepEqual(yield* requests.toolInfo({ threadId, itemId, name: "refresh" }), {
callable: true,
readOnly: true,
tool: { name: "refresh", annotations: { readOnlyHint: true } },
});
}).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps }))),
);
it.effect("refuses tools hidden from apps or missing from the server", () =>
Effect.gen(function* () {
const requests = yield* McpAppRequests.McpAppRequests;
const before = calls.length;
for (const name of ["model_only", "unknown"]) {
assert.equal(
yield* reason(requests.callTool({ threadId, itemId, name, arguments: {} })),
"tool-not-callable",
);
}
assert.equal(calls.length, before);
}).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps }))),
);
it.effect("keeps each app's latest model context, without a live session", () =>
Effect.gen(function* () {
const requests = yield* McpAppRequests.McpAppRequests;
const own = { threadId, itemId, conversationThreadId: threadId };
// The app's text is stored as sent, whitespace included.
yield* requests.updateModelContext({
...own,
content: [{ type: "text", text: " indented value " }],
});
assert.equal(storedContext.get(`${threadId}/${itemId}`), " indented value ");
// An update replaces the app's context rather than adding to it.
yield* requests.updateModelContext({
...own,
content: [{ type: "text", text: "Filtered to overdue" }],
structuredContent: { filter: "overdue" },
});
assert.equal(
storedContext.get(`${threadId}/${itemId}`),
'Filtered to overdue\n{"filter":"overdue"}',
);
assert.equal(
yield* reason(
requests.updateModelContext({ ...own, content: [{ type: "image", data: "x" }] }),
),
"unsupported-content",
);
// The cap is in UTF-8 bytes: 6,000 three-byte characters exceed 16 KiB.
assert.equal(
yield* reason(
requests.updateModelContext({
...own,
content: [{ type: "text", text: "表".repeat(6000) }],
}),
),
"request-failed",
);
yield* requests.updateModelContext(own);
assert.isFalse(storedContext.has(`${threadId}/${itemId}`));
}).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), live: false }))),
);
it.effect("stores a fork's model context under the fork, and refuses unrelated threads", () =>
Effect.gen(function* () {
const requests = yield* McpAppRequests.McpAppRequests;
const content = [{ type: "text", text: "Seen from the fork" }];
yield* requests.updateModelContext({
threadId,
itemId,
conversationThreadId: forkId,
content,
});
assert.equal(storedContext.get(`${forkId}/${itemId}`), "Seen from the fork");
assert.isFalse(storedContext.has(`${threadId}/${itemId}`));
assert.equal(
yield* reason(
requests.updateModelContext({
threadId,
itemId,
conversationThreadId: unrelatedId,
content,
}),
),
"not-an-app",
);
// However many forks deep, a descendant still counts.
yield* requests.updateModelContext({
threadId,
itemId,
conversationThreadId: deepForkId(70),
content,
});
assert.isTrue(storedContext.has(`${deepForkId(70)}/${itemId}`));
}).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), live: false }))),
);
it.effect("reports why a request cannot run", () =>
Effect.gen(function* () {
const run = (layer: ReturnType<typeof makeLayer>) =>
Effect.gen(function* () {
const requests = yield* McpAppRequests.McpAppRequests;
return yield* reason(requests.readResource({ threadId, itemId, uri: "ui://weather/x" }));
}).pipe(Effect.provide(layer));
assert.equal(
yield* run(makeLayer({ item: appItem({ result: "plain" }), mcpApps })),
"not-an-app",
);
assert.equal(
yield* run(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps, live: false })),
"session-stopped",
);
assert.equal(
yield* run(makeLayer({ item: appItem({ t3McpApp: app }) })),
"provider-unsupported",
);
}),
);
});
+240
View File
@@ -0,0 +1,240 @@
import {
McpAppRequestError,
type McpAppCallToolInput,
type McpAppCallToolResult,
type McpAppReadResourceInput,
type McpAppReadResourceResult,
type McpAppToolInfo,
type McpAppToolInfoInput,
type McpAppUpdateModelContextInput,
type OrchestrationV2AppThread,
type ThreadId,
type TurnItemId,
} from "@t3tools/contracts";
import { mcpAppToolCallableByApp, type McpAppReference } from "@t3tools/shared/mcpApp";
import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as Schema from "effect/Schema";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import type {
ProviderAdapterV2McpApps,
ProviderAdapterV2McpTool,
} from "../orchestration-v2/ProviderAdapter.ts";
import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as McpAppModelContext from "./McpAppModelContext.ts";
/**
* Requests an MCP App makes of its own MCP server. The app is resolved from the
* tool call that produced it, so it reaches only that server, and each request
* runs through the thread's live provider session, whose MCP client owns the
* connection and its credentials. A stopped session is reported, never
* started: an app view must not spend a provider turn.
*/
export class McpAppRequests extends Context.Service<
McpAppRequests,
{
readonly callTool: (
input: McpAppCallToolInput,
) => Effect.Effect<McpAppCallToolResult, McpAppRequestError>;
readonly toolInfo: (
input: McpAppToolInfoInput,
) => Effect.Effect<McpAppToolInfo, McpAppRequestError>;
readonly readResource: (
input: McpAppReadResourceInput,
) => Effect.Effect<McpAppReadResourceResult, McpAppRequestError>;
readonly updateModelContext: (
input: McpAppUpdateModelContextInput,
) => Effect.Effect<void, McpAppRequestError>;
}
>()("t3/mcpApps/McpAppRequests") {}
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const utf8 = new TextEncoder();
const readOnlyHint = (tool: ProviderAdapterV2McpTool) =>
Predicate.isObject(tool.annotations) && tool.annotations.readOnlyHint === true;
const toolTitle = (tool: ProviderAdapterV2McpTool) =>
Predicate.isObject(tool.annotations) && typeof tool.annotations.title === "string"
? tool.annotations.title
: undefined;
const make = Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const threadManagement = yield* ThreadManagementService.ThreadManagementService;
const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
const modelContext = yield* McpAppModelContext.McpAppModelContext;
const fail = (threadId: ThreadId, reason: McpAppRequestError["reason"], cause?: unknown) =>
new McpAppRequestError({ threadId, reason, ...(cause === undefined ? {} : { cause }) });
/** The app a tool call produced, read from the stored item. */
const resolveApp = Effect.fn("McpAppRequests.resolveApp")(function* (input: {
readonly threadId: ThreadId;
readonly itemId: TurnItemId;
}) {
// The stored item, not the wire projection, so the reference is intact.
const item = yield* orchestrator
.getTurnItem({ threadId: input.threadId, itemId: input.itemId })
.pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
const app: McpAppReference | undefined =
item?.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
if (item === null || app === undefined || item.providerThreadId === null) {
return yield* fail(input.threadId, "not-an-app");
}
return { app, providerThreadId: item.providerThreadId };
});
/** The app, its provider thread, and the live session's MCP Apps operations. */
const resolve = Effect.fn("McpAppRequests.resolve")(function* (input: {
readonly threadId: ThreadId;
readonly itemId: TurnItemId;
}) {
const { app, providerThreadId } = yield* resolveApp(input);
const projection = yield* threadManagement
.getThreadRecords(input.threadId, ["providerThreads"])
.pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === providerThreadId,
);
if (providerThread?.providerSessionId == null) {
return yield* fail(input.threadId, "session-stopped");
}
const runtime = Option.getOrUndefined(
yield* providerSessions
.get(providerThread.providerSessionId)
.pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause))),
);
if (runtime === undefined) return yield* fail(input.threadId, "session-stopped");
const mcpApps: ProviderAdapterV2McpApps | undefined = runtime.mcpApps;
if (mcpApps === undefined) return yield* fail(input.threadId, "provider-unsupported");
return { app, providerThread, mcpApps };
});
const findTool = Effect.fn("McpAppRequests.findTool")(function* (
threadId: ThreadId,
resolved: Effect.Success<ReturnType<typeof resolve>>,
name: string,
) {
const tools = yield* resolved.mcpApps
.listTools({ providerThread: resolved.providerThread, server: resolved.app.server })
.pipe(Effect.mapError((cause) => fail(threadId, "request-failed", cause)));
return tools.find((tool) => tool.name === name);
});
const toolInfo = Effect.fn("McpAppRequests.toolInfo")(function* (input: McpAppToolInfoInput) {
const resolved = yield* resolve(input);
const tool = yield* findTool(input.threadId, resolved, input.name);
const title = tool === undefined ? undefined : toolTitle(tool);
return {
callable: tool !== undefined && mcpAppToolCallableByApp(tool._meta),
readOnly: tool !== undefined && readOnlyHint(tool),
...(title === undefined ? {} : { title }),
...(tool === undefined ? {} : { tool }),
} satisfies McpAppToolInfo;
});
const callTool = Effect.fn("McpAppRequests.callTool")(function* (input: McpAppCallToolInput) {
const resolved = yield* resolve(input);
// The spec forbids apps calling tools hidden from them; checked here too,
// since a client's own check is only a courtesy to its user.
const tool = yield* findTool(input.threadId, resolved, input.name);
if (tool === undefined || !mcpAppToolCallableByApp(tool._meta)) {
return yield* fail(input.threadId, "tool-not-callable");
}
return yield* resolved.mcpApps
.callTool({
providerThread: resolved.providerThread,
server: resolved.app.server,
tool: input.name,
arguments: input.arguments,
})
.pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
});
const readResource = Effect.fn("McpAppRequests.readResource")(function* (
input: McpAppReadResourceInput,
) {
const resolved = yield* resolve(input);
return yield* resolved.mcpApps
.readResource({
providerThread: resolved.providerThread,
server: resolved.app.server,
uri: input.uri,
})
.pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
});
// Context is state for the agent's next turn, so it needs the app but not a
// live session. Text blocks are kept as written and structured content as
// JSON; other content kinds are not declared by the host.
/** Whether `threadId` is `ancestorId` or forked from it, however many forks deep. */
const descendsFrom = Effect.fn("McpAppRequests.descendsFrom")(function* (
threadId: ThreadId,
ancestorId: ThreadId,
) {
// Walks fork links until the chain ends; a thread seen twice means a
// corrupt cycle, which proves nothing.
const seen = new Set<ThreadId>();
let current: ThreadId | null = threadId;
while (current !== null && !seen.has(current)) {
if (current === ancestorId) return true;
seen.add(current);
const records: { readonly thread: OrchestrationV2AppThread } = yield* threadManagement
.getThreadRecords(current, [])
.pipe(Effect.mapError((cause) => fail(threadId, "request-failed", cause)));
const { lineage } = records.thread;
current = lineage.relationshipToParent === "fork" ? lineage.parentThreadId : null;
}
return false;
});
const updateModelContext = Effect.fn("McpAppRequests.updateModelContext")(function* (
input: McpAppUpdateModelContextInput,
) {
const { app } = yield* resolveApp(input);
// Context belongs to the conversation on screen, which only shows this app
// when it is the app's own thread or one forked from it.
if (!(yield* descendsFrom(input.conversationThreadId, input.threadId))) {
return yield* fail(input.threadId, "not-an-app");
}
const texts: Array<string> = [];
for (const block of input.content ?? []) {
if (!Predicate.isObject(block) || block.type !== "text" || typeof block.text !== "string") {
return yield* fail(input.threadId, "unsupported-content");
}
texts.push(block.text);
}
if (input.structuredContent !== undefined) {
texts.push(encodeJson(input.structuredContent));
}
// Kept as sent; blank text clears the app's context in the store.
const text = texts.join("\n");
if (utf8.encode(text).byteLength > McpAppModelContext.MCP_APP_MODEL_CONTEXT_MAX_BYTES) {
return yield* fail(
input.threadId,
"request-failed",
new Error("Model context is too large."),
);
}
yield* modelContext
.set({
threadId: input.conversationThreadId,
itemId: input.itemId,
server: app.server,
tool: app.tool,
text,
})
.pipe(Effect.mapError((cause) => fail(input.threadId, "request-failed", cause)));
});
return McpAppRequests.of({ callTool, toolInfo, readResource, updateModelContext });
});
export const layer = Layer.effect(McpAppRequests, make);
+108
View File
@@ -0,0 +1,108 @@
import type { ThreadId } from "@t3tools/contracts";
import {
injectMcpAppCsp,
MCP_APP_MAX_HTML_BYTES,
MCP_APP_MIME_TYPE,
MCP_APP_RESOURCE_SCHEME,
readMcpAppCsp,
readMcpAppPermissions,
type McpAppReference,
} from "@t3tools/shared/mcpApp";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Predicate from "effect/Predicate";
import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
import { createAttachmentId } from "../attachmentStore.ts";
const encoder = new TextEncoder();
/**
* The HTML document in a `resources/read` result, with the `_meta.ui` the
* resource declared. Only `text/html;profile=mcp-app` content counts; a blob is
* base64 per MCP. A null document is one too large to store.
*/
function readMcpAppDocument(
contents: ReadonlyArray<unknown>,
uri: string,
): { readonly html: string | null; readonly meta: unknown } | undefined {
for (const content of contents) {
if (!Predicate.isObject(content)) continue;
if (content.uri !== undefined && content.uri !== uri) continue;
const mimeType = typeof content.mimeType === "string" ? content.mimeType : "";
if (mimeType.replace(/\s+/g, "").toLowerCase() !== MCP_APP_MIME_TYPE) continue;
// Sizes are checked before decoding, so an oversized resource is
// refused without first being copied: a string's UTF-8 form is at least
// its length, and base64 decodes to three quarters of its own.
const html =
typeof content.text === "string"
? content.text.length > MCP_APP_MAX_HTML_BYTES
? null
: content.text
: typeof content.blob === "string"
? content.blob.length > Math.ceil(MCP_APP_MAX_HTML_BYTES / 3) * 4
? null
: Buffer.from(content.blob, "base64").toString("utf8")
: undefined;
if (html === null) return { html: null, meta: undefined };
if (html === undefined || html.trim() === "") continue;
const meta = Predicate.isObject(content._meta) ? content._meta.ui : undefined;
return { html, meta };
}
return undefined;
}
/**
* Stores an app's document as a thread attachment and returns the reference
* clients host it from. Saving a snapshot keeps the app viewable after the
* provider exits; interaction still goes through a live provider session.
* Undefined when the resource is not an MCP App document or is too large.
*/
export const snapshotMcpApp = Effect.fn("McpAppSnapshot.snapshot")(function* (input: {
readonly attachmentsDir: string;
readonly threadId: ThreadId;
readonly server: string;
readonly tool: string;
readonly resourceUri: string;
readonly contents: ReadonlyArray<unknown>;
}) {
if (!input.resourceUri.startsWith(MCP_APP_RESOURCE_SCHEME)) return undefined;
const document = readMcpAppDocument(input.contents, input.resourceUri);
if (document === undefined) return undefined;
if (document.html === null || encoder.encode(document.html).byteLength > MCP_APP_MAX_HTML_BYTES) {
yield* Effect.logWarning("MCP app document exceeds the size limit.", {
server: input.server,
resourceUri: input.resourceUri,
});
return undefined;
}
// The `-html` suffix makes the asset route serve it as a sandboxed document.
const attachmentId = createAttachmentId(input.threadId, "html");
const filePath =
attachmentId === null
? null
: resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${attachmentId}.html`,
});
if (attachmentId === null || filePath === null) return undefined;
const html = document.html;
const ui = Predicate.isObject(document.meta) ? document.meta : {};
const csp = readMcpAppCsp(ui.csp);
const fileSystem = yield* FileSystem.FileSystem;
// Only the returned reference lets thread deletion find the document, so a
// write that fails or is interrupted removes it.
yield* fileSystem
.writeFileString(filePath, injectMcpAppCsp(html, csp))
.pipe(Effect.onError(() => fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore)));
const permissions = readMcpAppPermissions(ui.permissions);
return {
attachmentId,
server: input.server,
tool: input.tool,
resourceUri: input.resourceUri,
...(csp === undefined ? {} : { csp }),
...(permissions === undefined ? {} : { permissions }),
...(typeof ui.prefersBorder === "boolean" ? { prefersBorder: ui.prefersBorder } : {}),
} satisfies McpAppReference;
});
@@ -142,6 +142,10 @@ const RPC_AGGREGATES = {
[WS_METHODS.attachmentsCreateUploadUrl]: "workspace",
[WS_METHODS.attachmentsDelete]: "workspace",
[WS_METHODS.providerUploadFeedback]: "provider",
[WS_METHODS.mcpAppsCallTool]: "provider",
[WS_METHODS.mcpAppsToolInfo]: "provider",
[WS_METHODS.mcpAppsUpdateModelContext]: "provider",
[WS_METHODS.mcpAppsReadResource]: "provider",
[WS_METHODS.subscribeVcsStatus]: "vcs",
[WS_METHODS.subscribeWorktreeSetup]: "vcs",
[WS_METHODS.worktreeSetupCancel]: "vcs",
@@ -18,6 +18,7 @@ import {
type OrchestrationV2AppThread,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
type OrchestrationV2TurnItem,
ProjectId,
ProviderInstanceId,
ProviderSessionId,
@@ -40,6 +41,8 @@ import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Predicate from "effect/Predicate";
import * as FileSystem from "effect/FileSystem";
import { MCP_APP_OUTPUT_KEY, readMcpAppReference } from "@t3tools/shared/mcpApp";
import { resolveAttachmentPathById } from "../../attachmentStore.ts";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
@@ -463,6 +466,38 @@ describe("CodexAdapterV2 runtime policy", () => {
}),
);
it.effect("sends MCP app model context as untrusted Codex context", () =>
Effect.gen(function* () {
const policy = { runtimeMode: "full-access", interactionMode: "default", cwd: null } as const;
const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };
const appContext = [{ key: "mcp_app_todos_list_todos_item-1", text: "Filtered to overdue" }];
const alone = yield* CodexAdapterV2.buildCodexTurnStartParams({
nativeThreadId: "native-app-context",
codexInput: [{ type: "text", text: "what's on my list?" }],
runtimePolicy: policy,
modelSelection,
appContext,
});
assert.deepEqual(alone.additionalContext, {
"mcp_app_todos_list_todos_item-1": { kind: "untrusted", value: "Filtered to overdue" },
});
// Alongside T3's own context, both are kept.
const withT3 = yield* CodexAdapterV2.buildCodexTurnStartParams({
nativeThreadId: "native-app-context",
codexInput: [{ type: "text", text: "what's on my list?" }],
runtimePolicy: policy,
modelSelection,
hasT3Mcp: true,
appContext,
});
assert.deepEqual(withT3.additionalContext?.["mcp_app_todos_list_todos_item-1"], {
kind: "untrusted",
value: "Filtered to overdue",
});
assert.isDefined(withT3.additionalContext?.["t3_code_runtime"]);
}),
);
it.effect("adds default-mode developer instructions when the T3 MCP server is attached", () =>
Effect.gen(function* () {
const params = yield* CodexAdapterV2.buildCodexTurnStartParams({
@@ -1548,6 +1583,9 @@ function codexReplayPreamble(input: {
capabilities: {
experimentalApi: true,
optOutNotificationMethods: ["turn/diff/updated"],
extensions: {
"io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] },
},
},
},
},
@@ -1972,6 +2010,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
runtime,
providerThread,
threadId,
serverConfig,
events,
continuationRequests,
terminalEvents,
@@ -2113,6 +2152,9 @@ describe("CodexAdapterV2 post-settle continuation", () => {
capabilities: {
experimentalApi: true,
optOutNotificationMethods: ["turn/diff/updated"],
extensions: {
"io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] },
},
},
},
]);
@@ -6305,6 +6347,253 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
const MCP_APP_SCENARIO = "codex-mcp-app-capture";
const MCP_APP_NATIVE_THREAD = "native-codex-mcp-app-thread";
const MCP_APP_NATIVE_TURN = "native-codex-mcp-app-turn";
const MCP_APP_ITEM = "mcp-weather-call";
const MCP_APP_PROMPT = "Show the weather in Oslo.";
const MCP_APP_RESOURCE = "ui://weather/dashboard";
const MCP_APP_HTML = "<!doctype html><html><body><p>Weather</p><script>1</script></body></html>";
const mcpAppToolItem = (status: "inProgress" | "completed") => ({
type: "mcpToolCall",
id: MCP_APP_ITEM,
server: "weather",
tool: "get_weather",
status,
arguments: { city: "Oslo" },
mcpAppResourceUri: MCP_APP_RESOURCE,
...(status === "completed"
? { result: { content: [{ type: "text", text: "Sunny" }], structuredContent: { temp: 21 } } }
: {}),
});
const mcpAppTranscript = makeCodexReplayTranscript({
scenario: MCP_APP_SCENARIO,
entries: [
...codexReplayPreamble({
nativeThreadId: MCP_APP_NATIVE_THREAD,
nativeTurnId: MCP_APP_NATIVE_TURN,
prompt: MCP_APP_PROMPT,
}),
{
type: "emit_inbound",
label: "item/started/app-tool",
frame: {
method: "item/started",
params: {
item: mcpAppToolItem("inProgress"),
threadId: MCP_APP_NATIVE_THREAD,
turnId: MCP_APP_NATIVE_TURN,
startedAtMs: 1782622440500,
},
},
},
{
type: "emit_inbound",
label: "item/completed/app-tool",
frame: {
method: "item/completed",
params: {
item: mcpAppToolItem("completed"),
threadId: MCP_APP_NATIVE_THREAD,
turnId: MCP_APP_NATIVE_TURN,
completedAtMs: 1782622441500,
},
},
},
{
type: "emit_inbound",
label: "turn/completed",
frame: {
method: "turn/completed",
params: {
threadId: MCP_APP_NATIVE_THREAD,
turn: makeCodexReplayTurn({ id: MCP_APP_NATIVE_TURN, status: "completed" }),
},
},
},
{
type: "expect_outbound",
label: "mcpServer/resource/read",
frame: {
id: 4,
method: "mcpServer/resource/read",
params: { threadId: MCP_APP_NATIVE_THREAD, server: "weather", uri: MCP_APP_RESOURCE },
},
},
{
type: "emit_inbound",
label: "mcpServer/resource/read",
frame: {
id: 4,
result: {
contents: [
{
uri: MCP_APP_RESOURCE,
mimeType: "text/html;profile=mcp-app",
text: MCP_APP_HTML,
_meta: { ui: { csp: { connectDomains: ["https://api.weather.test"] } } },
},
],
},
},
},
],
});
it.effect("captures an MCP app's resource and holds the turn open until it lands", () =>
Effect.scoped(
Effect.gen(function* () {
const appCaptured = yield* Deferred.make<OrchestrationV2TurnItem>();
const harness = yield* makeCodexReplayHarness(mcpAppTranscript, (event) =>
event.type === "turn_item.updated" &&
event.turnItem.type === "dynamic_tool" &&
event.turnItem.status === "completed"
? Deferred.succeed(appCaptured, event.turnItem)
: Effect.void,
);
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeCodexTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-codex-mcp-app"),
text: MCP_APP_PROMPT,
}),
);
const item = yield* Deferred.await(appCaptured);
assert.equal(harness.terminalEvents()[0]?.status, "completed");
// The completed tool row is emitted once, with the app, never as a bare row first.
const completedRows = harness.events.filter(
(event) =>
event.type === "turn_item.updated" &&
event.turnItem.type === "dynamic_tool" &&
event.turnItem.status === "completed",
);
assert.lengthOf(completedRows, 1);
assert.equal(item.type, "dynamic_tool");
const output = item.type === "dynamic_tool" ? (item.output as Record<string, unknown>) : {};
const reference = readMcpAppReference(output[MCP_APP_OUTPUT_KEY]);
assert.deepEqual(
{ ...reference, attachmentId: undefined },
{
attachmentId: undefined,
server: "weather",
tool: "get_weather",
resourceUri: MCP_APP_RESOURCE,
csp: { connectDomains: ["https://api.weather.test"] },
},
);
assert.deepEqual(output.result, {
content: [{ type: "text", text: "Sunny" }],
structuredContent: { temp: 21 },
});
const fileSystem = yield* FileSystem.FileSystem;
const stored = yield* fileSystem.readFileString(
resolveAttachmentPathById({
attachmentsDir: harness.serverConfig.attachmentsDir,
attachmentId: reference!.attachmentId,
})!,
);
// Stored with the app's declared policy ahead of its scripts.
assert.include(stored, "connect-src https://api.weather.test");
assert.isBelow(stored.indexOf("Content-Security-Policy"), stored.indexOf("<script>"));
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
),
);
// The turn fails while the app's resource read is still outstanding (Codex
// never answers it), so the capture must be cancelled and its tool row
// settled before the terminal event closes ingestion.
const failedMcpAppTranscript = makeCodexReplayTranscript({
scenario: "codex-mcp-app-capture-failed-turn",
entries: [
...codexReplayPreamble({
nativeThreadId: MCP_APP_NATIVE_THREAD,
nativeTurnId: MCP_APP_NATIVE_TURN,
prompt: MCP_APP_PROMPT,
}),
{
type: "emit_inbound",
label: "item/completed/app-tool",
frame: {
method: "item/completed",
params: {
item: mcpAppToolItem("completed"),
threadId: MCP_APP_NATIVE_THREAD,
turnId: MCP_APP_NATIVE_TURN,
completedAtMs: 1782622441500,
},
},
},
{
type: "expect_outbound",
label: "mcpServer/resource/read",
frame: {
id: 4,
method: "mcpServer/resource/read",
params: { threadId: MCP_APP_NATIVE_THREAD, server: "weather", uri: MCP_APP_RESOURCE },
},
},
{
type: "emit_inbound",
label: "turn/completed",
frame: {
method: "turn/completed",
params: {
threadId: MCP_APP_NATIVE_THREAD,
turn: {
...makeCodexReplayTurn({ id: MCP_APP_NATIVE_TURN, status: "failed" }),
error: { message: "provider failed mid-capture" },
},
},
},
},
],
});
it.effect("settles a pending MCP app capture before a failed turn's terminal event", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeCodexReplayHarness(failedMcpAppTranscript);
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeCodexTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-codex-mcp-app-failed"),
text: MCP_APP_PROMPT,
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed terminal");
assert.equal(harness.terminalEvents()[0]?.status, "failed");
const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal");
const rows = harness.events.flatMap((event, index) =>
event.type === "turn_item.updated" &&
event.turnItem.type === "dynamic_tool" &&
event.turnItem.status === "completed"
? [{ index, turnItem: event.turnItem }]
: [],
);
// Settled once, as a plain tool row, ahead of the terminal event.
assert.lengthOf(rows, 1);
assert.isBelow(rows[0]!.index, terminalIndex);
const output = rows[0]!.turnItem.type === "dynamic_tool" ? rows[0]!.turnItem.output : null;
assert.isUndefined((output as Record<string, unknown> | null)?.[MCP_APP_OUTPUT_KEY]);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
),
);
const ORPHAN_WAIT_SCENARIO = "codex-orphaned-dynamic-tool";
const ORPHAN_WAIT_NATIVE_THREAD = "native-codex-orphan-wait-thread";
const ORPHAN_WAIT_NATIVE_TURN = "native-codex-orphan-wait-turn";
@@ -65,11 +65,13 @@ import type {
import * as CodexClient from "effect-codex-app-server/client";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexSchema from "effect-codex-app-server/schema";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -82,7 +84,7 @@ import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachmentStore.ts";
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "../../pathExpansion.ts";
@@ -107,6 +109,13 @@ import { ProviderEventLoggers } from "../../provider/ProviderEventLoggers.ts";
import { codexAppServerArgs, resolveCodexLaunchArgs } from "../../provider/codexLaunchArgs.ts";
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import {
MCP_APP_EXTENSION_ID,
MCP_APP_MIME_TYPE,
MCP_APP_OUTPUT_KEY,
MCP_APP_RESOURCE_SCHEME,
} from "@t3tools/shared/mcpApp";
import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriver,
@@ -146,6 +155,7 @@ import {
type ProviderAdapterV2ForkThreadInput,
type ProviderAdapterV2RollbackThreadInput,
type ProviderAdapterV2RuntimePolicy,
type ProviderAdapterV2McpApps,
type ProviderAdapterV2SessionRuntime,
type ProviderAdapterV2InterruptInput,
type ProviderAdapterV2SteerInput,
@@ -232,6 +242,9 @@ const decodeCodexBackgroundTerminalsListResponse = Schema.decodeUnknownEffect(
const CODEX_CLIENT_CAPABILITIES = {
experimentalApi: true,
optOutNotificationMethods: ["turn/diff/updated"],
// Declares MCP Apps support (SEP-1724 extension negotiation), so servers
// attach their UI resources and Codex reports them on tool call items.
extensions: { [MCP_APP_EXTENSION_ID]: { mimeTypes: [MCP_APP_MIME_TYPE] } },
} as const;
export const CodexProviderCapabilitiesV2 = {
@@ -471,6 +484,17 @@ function codexMcpToolOutput(
: { error: item.error.message, result: resultOutput };
}
// Reading an app's resource is one MCP round trip; a server that hangs must not
// hold the item (and the run's ingestion) open.
const MCP_APP_CAPTURE_TIMEOUT = "20 seconds";
/** The UI resource a completed Codex MCP tool call names, under any field Codex reports it in. */
function codexMcpAppResourceUri(item: CodexDynamicToolItem): string | undefined {
if (item.type !== "mcpToolCall") return undefined;
const uri = item.mcpAppUi?.resourceUri ?? item.mcpAppResourceUri ?? item.appContext?.resourceUri;
return typeof uri === "string" && uri.startsWith(MCP_APP_RESOURCE_SCHEME) ? uri : undefined;
}
function codexDynamicToolOutput(
item: Extract<CodexDynamicToolItem, { readonly type: "dynamicToolCall" }>,
): unknown | undefined {
@@ -707,6 +731,8 @@ export function buildCodexTurnStartParams(input: {
readonly deviceToolsAvailable?: boolean;
/** ChatGPT token sharing does not accept service tiers. */
readonly omitServiceTier?: boolean;
/** What the thread's MCP Apps want the agent to know (`ui/update-model-context`). */
readonly appContext?: ProviderAdapterV2TurnInput["appContext"];
}) {
return Effect.gen(function* () {
const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);
@@ -732,7 +758,16 @@ export function buildCodexTurnStartParams(input: {
input.hasT3Mcp !== true
? undefined
: buildCodexDeveloperInstructions(input.runtimePolicy.interactionMode);
const additionalContext =
// An app's context is text an MCP server wrote, so it goes in as untrusted
// context: Codex renders it as quoted user-side input, never as developer
// instructions. Codex resends it only when it changes.
const appContext = Object.fromEntries(
(input.appContext ?? []).map((entry) => [
entry.key,
{ kind: "untrusted" as const, value: entry.text },
]),
);
const t3Context =
input.hasT3Mcp === true
? buildCodexAdditionalContext(
{ model: input.modelSelection.model, reasoningEffort: effort ?? "medium" },
@@ -742,6 +777,10 @@ export function buildCodexTurnStartParams(input: {
},
)
: undefined;
const additionalContext =
t3Context === undefined && Object.keys(appContext).length === 0
? undefined
: { ...t3Context, ...appContext };
const collaborationMode: CodexSchema.ClientRequest__CollaborationMode | undefined =
input.runtimePolicy.interactionMode !== "plan" && developerInstructions === undefined
? undefined
@@ -1688,11 +1727,26 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
if (!context) return;
yield* client.request("thread/inject_items", {
threadId,
items: Object.entries(context).map(([key, entry]) => ({
type: "message",
role: "developer",
content: [{ type: "input_text", text: `<${key}>${entry.value}</${key}>` }],
})),
// Restored as Codex sent them: application context as developer
// input, untrusted context as quoted user-side input.
items: Object.entries(context).map(([key, entry]) =>
entry.kind === "untrusted"
? {
type: "message",
role: "user",
content: [
{
type: "input_text",
text: `<external_${key}>${entry.value}</external_${key}>`,
},
],
}
: {
type: "message",
role: "developer",
content: [{ type: "input_text", text: `<${key}>${entry.value}</${key}>` }],
},
),
});
}).pipe(
Effect.timeout("10 seconds"),
@@ -2037,6 +2091,33 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return [remaining.size === 0, updated] as const;
});
// MCP app captures still reading their resource, by native turn and
// item. Each counts as retained background work, so the turn's context
// and the run's ingestion stay open until its app lands on the item.
// A turn that ends badly cancels its captures and settles their items
// itself (terminalizeMcpAppCaptures).
interface PendingMcpAppCapture {
readonly item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>;
readonly fiber: Fiber.Fiber<void>;
}
const pendingMcpAppCaptures = yield* Ref.make(
new Map<string, ReadonlyMap<string, PendingMcpAppCapture>>(),
);
/** Removes a capture; true when this call removed it (each settles once). */
const takePendingMcpAppCapture = (nativeTurnId: string, nativeItemId: string) =>
Ref.modify(pendingMcpAppCaptures, (current) => {
const captures = current.get(nativeTurnId);
if (captures === undefined || !captures.has(nativeItemId)) {
return [false, current] as const;
}
const remaining = new Map(captures);
remaining.delete(nativeItemId);
const updated = new Map(current);
if (remaining.size === 0) updated.delete(nativeTurnId);
else updated.set(nativeTurnId, remaining);
return [true, updated] as const;
});
const trackRunningDynamicTool = (nativeTurnId: string, item: CodexDynamicToolItem) =>
Ref.update(runningDynamicToolsByTurn, (current) => {
const updated = new Map(current);
@@ -2069,6 +2150,9 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
if (commands !== undefined && commands.size > 0) {
return true;
}
if ((yield* Ref.get(pendingMcpAppCaptures)).has(nativeTurnId)) {
return true;
}
const tools = (yield* Ref.get(runningDynamicToolsByTurn)).get(nativeTurnId);
if (tools === undefined) {
return false;
@@ -3555,6 +3639,157 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return { node, turnItem };
});
/**
* Completes an MCP tool call whose tool names a UI resource: reads the
* resource through Codex's MCP client, stores it, and records the app
* in the item's output. The item stays running until then, which keeps
* the run's event ingestion open past turn/completed; it runs off the
* notification reader so a slow server cannot stall other events.
*/
const captureMcpApp = (
context: ActiveCodexTurnContext,
nativeTurnId: string,
item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>,
resourceUri: string,
) =>
Effect.gen(function* () {
// Registered before it can run, so a turn ending right away sees it.
const started = yield* Deferred.make<void>();
const fiber = yield* Deferred.await(started).pipe(
Effect.andThen(captureMcpAppItem(context, nativeTurnId, item, resourceUri)),
Effect.forkIn(scope, { startImmediately: true }),
);
yield* Ref.update(pendingMcpAppCaptures, (current) => {
const updated = new Map(current);
updated.set(
nativeTurnId,
new Map(current.get(nativeTurnId) ?? []).set(item.id, { item, fiber }),
);
return updated;
});
yield* Deferred.succeed(started, undefined);
});
const captureMcpAppItem = (
context: ActiveCodexTurnContext,
nativeTurnId: string,
item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>,
resourceUri: string,
) =>
// Only reading and storing the document can be cancelled; a write
// cut short removes its file. Once a document is stored, the capture
// either lands it on the item or, when its turn already settled the
// item, removes it, so no stored app goes unreferenced.
Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
const reference =
item.status === "completed" && item.result != null && item.error == null
? yield* restore(
getNativeThreadId(context.providerThread).pipe(
Effect.flatMap((threadId) =>
client.request("mcpServer/resource/read", {
threadId,
server: item.server,
uri: resourceUri,
}),
),
Effect.timeout(MCP_APP_CAPTURE_TIMEOUT),
Effect.flatMap((response) =>
snapshotMcpApp({
attachmentsDir: serverConfig.attachmentsDir,
threadId: context.projectionThreadId,
server: item.server,
tool: item.tool,
resourceUri,
contents: response.contents,
}),
),
Effect.provideService(FileSystem.FileSystem, fileSystem),
// Every failure and defect becomes a plain tool row,
// so a crashed read never holds the turn open; only
// interruption, the turn cancelling the capture, ends
// the fiber here. Nothing typed is left for orDie.
Effect.catchCauseIf(
(cause) => !Cause.hasInterruptsOnly(cause),
(cause) =>
Effect.logWarning(
"Failed to capture an MCP app; showing a plain tool row.",
{ server: item.server, tool: item.tool, resourceUri, cause },
).pipe(Effect.as(undefined)),
),
Effect.orDie,
),
)
: undefined;
const artifacts = yield* buildDynamicToolArtifacts(context, item);
// Cleared before the final emit: ingestion re-checks pending work
// after each event, and must see this capture done by then. A turn
// that already ended badly took the capture and settled its item.
if (!(yield* takePendingMcpAppCapture(nativeTurnId, item.id))) {
if (reference !== undefined) {
const filePath = resolveAttachmentPathById({
attachmentsDir: serverConfig.attachmentsDir,
attachmentId: reference.attachmentId,
});
if (filePath !== null) {
yield* fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore);
}
}
return;
}
const turnItem =
reference === undefined || artifacts.turnItem.type !== "dynamic_tool"
? artifacts.turnItem
: {
...artifacts.turnItem,
// The full CallToolResult the app replays, beside the app.
output: { [MCP_APP_OUTPUT_KEY]: reference, result: item.result },
};
yield* emitProviderEvent({
type: "node.updated",
driver: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CODEX_PROVIDER,
turnItem,
});
// Only a turn that already ended is released; an active one
// still needs its final-answer bookkeeping.
if ((yield* Ref.get(settledTurns)).has(nativeTurnId)) {
yield* releaseSettledTurnIfIdle(nativeTurnId);
}
}),
);
/**
* Settles the items of app captures still running when their turn is
* interrupted or fails: the capture is cancelled and its tool call is
* reported as it completed, without the app, before the turn's
* terminal event closes ingestion.
*/
const terminalizeMcpAppCaptures = (context: ActiveCodexTurnContext, nativeTurnId: string) =>
Effect.gen(function* () {
const captures = (yield* Ref.get(pendingMcpAppCaptures)).get(nativeTurnId);
if (captures === undefined) return;
for (const { item, fiber } of captures.values()) {
if (!(yield* takePendingMcpAppCapture(nativeTurnId, item.id))) continue;
yield* Fiber.interrupt(fiber);
const artifacts = yield* buildDynamicToolArtifacts(context, item);
yield* emitProviderEvent({
type: "node.updated",
driver: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
}
});
const buildProposedPlanArtifacts = (input: {
readonly context: ActiveCodexTurnContext;
readonly nativeItemId: string;
@@ -4531,6 +4766,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
if (payload.item.type === "mcpToolCall" || payload.item.type === "dynamicToolCall") {
yield* clearRunningDynamicTool(payload.turnId, payload.item.id);
const appResourceUri = codexMcpAppResourceUri(payload.item);
if (appResourceUri !== undefined && payload.item.type === "mcpToolCall") {
yield* captureMcpApp(context, payload.turnId, payload.item, appResourceUri);
return;
}
const artifacts = yield* buildDynamicToolArtifacts(context, payload.item);
yield* emitProviderEvent({
type: "node.updated",
@@ -5563,6 +5803,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
input.status,
input.completedAt,
);
yield* terminalizeMcpAppCaptures(input.context, input.nativeTurnId);
}
const dynamicToolStatus: "cancelled" | "interrupted" | "failed" =
input.status === "interrupted" || input.status === "failed"
@@ -5601,6 +5842,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
updated.set(input.nativeTurnId, input.context);
return updated;
});
// Background work that finished between the check above and
// the turn being recorded as settled saw no settled turn to
// release, so it is re-checked once recorded.
yield* releaseSettledTurnIfIdle(input.nativeTurnId);
}
yield* Ref.update(activeTurns, (current) => {
const updated = new Map(current);
@@ -5874,6 +6119,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
browserToolsAvailable: mcpSession?.browserToolsAvailable ?? true,
deviceToolsAvailable: mcpSession?.capabilities?.has("device") ?? false,
omitServiceTier: adapterOptions.resolveRuntime !== undefined,
...(turnInput.appContext === undefined ? {} : { appContext: turnInput.appContext }),
});
yield* Ref.update(pendingRootTurns, (current) => {
const updated = new Map(current);
@@ -6022,6 +6268,64 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
),
);
// MCP Apps reach their server through Codex's own MCP client, so any
// server the user configured for Codex works without T3 connecting to it.
const mcpAppsError = (detail: string) => (cause: unknown) =>
new ProviderAdapterProtocolError({ driver: CODEX_PROVIDER, detail, payload: cause });
const mcpApps: ProviderAdapterV2McpApps = {
listTools: (toolsInput) =>
Effect.gen(function* () {
const threadId = yield* getNativeThreadId(toolsInput.providerThread);
const response = yield* ensureInitialized.pipe(
Effect.andThen(
client.request("mcpServerStatus/list", {
threadId,
serverName: toolsInput.server,
detail: "toolsAndAuthOnly",
}),
),
);
const server = response.data.find((entry) => entry.name === toolsInput.server);
return Object.values(server?.tools ?? {});
}).pipe(Effect.mapError(mcpAppsError("Failed to list Codex MCP tools."))),
callTool: (callInput) =>
Effect.gen(function* () {
const threadId = yield* getNativeThreadId(callInput.providerThread);
const response = yield* ensureInitialized.pipe(
Effect.andThen(
client.request("mcpServer/tool/call", {
threadId,
server: callInput.server,
tool: callInput.tool,
arguments: callInput.arguments as Schema.Json,
}),
),
);
return {
content: response.content,
...(response.structuredContent === undefined
? {}
: { structuredContent: response.structuredContent }),
...(response.isError === true ? { isError: true } : {}),
...(response._meta === undefined ? {} : { _meta: response._meta }),
};
}).pipe(Effect.mapError(mcpAppsError("Codex MCP tool call failed."))),
readResource: (readInput) =>
Effect.gen(function* () {
const threadId = yield* getNativeThreadId(readInput.providerThread);
const response = yield* ensureInitialized.pipe(
Effect.andThen(
client.request("mcpServer/resource/read", {
threadId,
server: readInput.server,
uri: readInput.uri,
}),
),
);
return { contents: response.contents };
}).pipe(Effect.mapError(mcpAppsError("Codex MCP resource read failed."))),
};
const runtime: ProviderAdapterV2SessionRuntime = {
instanceId: adapterOptions.instanceId,
driver: CODEX_PROVIDER,
@@ -6044,6 +6348,9 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return true;
}
}
if ((yield* Ref.get(pendingMcpAppCaptures)).size > 0) {
return true;
}
for (const subagent of (yield* Ref.get(subagentThreads)).values()) {
if (subagent.task.status === "running") {
return true;
@@ -6669,6 +6976,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
completedAt,
true,
);
yield* terminalizeMcpAppCaptures(context, context.nativeTurnId);
yield* Ref.update(runningCommandItemsByTurn, (current) => {
const updated = new Map(current);
updated.delete(context.nativeTurnId);
@@ -6765,6 +7073,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
}),
),
),
mcpApps,
readThreadSnapshot: (threadInput) =>
Effect.gen(function* () {
const threadId = yield* getNativeThreadId(threadInput.providerThread);
@@ -70,6 +70,7 @@ import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
import type * as Statement from "effect/sql/Statement";
import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp";
import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts";
import {
isThreadHistoryUserTurn,
@@ -4603,13 +4604,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
json_each(message.payload_json, '$.attachments') AS attachment
WHERE message.thread_id = ${threadId}
`,
// Pages published by html_render live in the attachment store too.
// Pages published by html_render, and captured MCP App documents,
// live in the attachment store too.
sql<{ payload_json: string }>`
SELECT payload_json
FROM orchestration_v2_projection_turn_items
WHERE thread_id = ${threadId}
AND type = 'dynamic_tool'
AND payload_json LIKE '%htmlRender%'
AND (payload_json LIKE '%htmlRender%' OR payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`})
`,
]).pipe(
Effect.map(([messages, renders]) => [
@@ -408,6 +408,12 @@ export interface ProviderAdapterV2TurnInput {
readonly message: ProviderAdapterV2TurnMessage;
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
/**
* What the thread's MCP Apps want the agent to know (`ui/update-model-context`),
* latest per app, keyed stably per app. Adapters that host apps deliver it as
* application context; others never receive any.
*/
readonly appContext?: ReadonlyArray<{ readonly key: string; readonly text: string }>;
}
export interface ProviderAdapterV2SteerInput {
@@ -483,6 +489,39 @@ export interface ProviderAdapterV2HistoricalContext {
readonly context: string;
}
/** An MCP tool as the provider's MCP client lists it. */
export interface ProviderAdapterV2McpTool {
readonly name: string;
readonly _meta?: unknown;
readonly annotations?: unknown;
}
/** MCP `CallToolResult` / `ReadResourceResult` shapes, passed through unchanged. */
export interface ProviderAdapterV2McpCallToolResult {
readonly content: ReadonlyArray<unknown>;
readonly structuredContent?: unknown;
readonly isError?: boolean;
readonly _meta?: unknown;
}
export interface ProviderAdapterV2McpApps {
readonly listTools: (input: {
readonly providerThread: OrchestrationV2ProviderThread;
readonly server: string;
}) => Effect.Effect<ReadonlyArray<ProviderAdapterV2McpTool>, ProviderAdapterV2Error>;
readonly callTool: (input: {
readonly providerThread: OrchestrationV2ProviderThread;
readonly server: string;
readonly tool: string;
readonly arguments: Record<string, unknown>;
}) => Effect.Effect<ProviderAdapterV2McpCallToolResult, ProviderAdapterV2Error>;
readonly readResource: (input: {
readonly providerThread: OrchestrationV2ProviderThread;
readonly server: string;
readonly uri: string;
}) => Effect.Effect<{ readonly contents: ReadonlyArray<unknown> }, ProviderAdapterV2Error>;
}
export interface ProviderAdapterV2SessionRuntime {
readonly instanceId: ProviderInstanceId;
readonly driver: ProviderDriverKind;
@@ -572,6 +611,12 @@ export interface ProviderAdapterV2SessionRuntime {
readonly providerThread: OrchestrationV2ProviderThread;
readonly reason?: string;
}) => Effect.Effect<{ readonly feedbackId: string }, ProviderAdapterV2Error>;
/**
* MCP Apps host operations through the provider's own MCP client, for
* drivers whose protocol exposes them (Codex). Absent means apps from this
* provider are not interactive and their tool calls stay plain tool rows.
*/
readonly mcpApps?: ProviderAdapterV2McpApps;
readonly rollbackThread: (
input: ProviderAdapterV2RollbackThreadInput,
) => Effect.Effect<ProviderAdapterV2ThreadSnapshot, ProviderAdapterV2Error>;
@@ -49,9 +49,11 @@ import {
type ProviderAdapterV2Error,
type ProviderAdapterV2Event,
type ProviderAdapterV2SessionRuntime,
type ProviderAdapterV2TurnInput,
} from "./ProviderAdapter.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
import * as RunExecutionService from "./RunExecutionService.ts";
import * as RunFinalizationService from "./RunFinalizationService.ts";
@@ -60,6 +62,7 @@ const driver = ProviderDriverKind.make("codex");
const layerRunExecutionTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
Layer.mock(EventSink.EventSinkV2)({}),
IdAllocator.layer,
@@ -591,6 +594,90 @@ it.effect("rechecks run ownership immediately before calling the provider", () =
}).pipe(Effect.provide(layerRunExecutionTest)),
);
it.effect("passes the thread's MCP app context to the provider under a safe key", () =>
Effect.gen(function* () {
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
const started = yield* Deferred.make<ProviderAdapterV2TurnInput>();
const threadId = ThreadId.make("thread:run-execution-app-context");
const providerInstanceId = ProviderInstanceId.make("codex");
const attemptId = RunAttemptId.make("attempt:run-execution-app-context");
const session = {
events: Stream.never,
startTurn: (input: ProviderAdapterV2TurnInput) => Deferred.succeed(started, input),
} as unknown as ProviderAdapterV2SessionRuntime;
yield* runExecution.startRootRun({
commandId: CommandId.make("command:run-execution-app-context"),
appThread: { id: threadId } as OrchestrationV2AppThread,
providerSessionId: ProviderSessionId.make("session:run-execution-app-context"),
session,
run: {
id: RunId.make("run:run-execution-app-context"),
threadId,
ordinal: 1,
providerInstanceId,
} as OrchestrationV2Run,
rootNode: {
id: NodeId.make("node:run-execution-app-context"),
} as OrchestrationV2ExecutionNode,
checkpointScope: {
id: CheckpointScopeId.make("checkpoint-scope:run-execution-app-context"),
} as OrchestrationV2CheckpointScope,
providerThread: {
id: ProviderThreadId.make("provider-thread:run-execution-app-context"),
driver,
} as OrchestrationV2ProviderThread,
attempt: { id: attemptId, providerTurnId: null } as OrchestrationV2RunAttempt,
attemptId,
providerTurnOrdinal: 1,
message: {
messageId: MessageId.make("message:run-execution-app-context"),
text: "What is on my list?",
attachments: [],
createdBy: "user",
creationSource: "web",
},
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: process.cwd() },
});
const input = yield* Deferred.await(started);
// Item ids carry colons, and server names are free text; neither reaches the key.
assert.deepEqual(input.appContext, [
{ key: "mcp_app_turn-item_provider_codex_native-item_call-1", text: "2 overdue" },
]);
}).pipe(
Effect.provide(
RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(McpAppModelContext.McpAppModelContext)({
forThread: () =>
Effect.succeed([
{
itemId: "turn-item:provider:codex:native-item:call-1",
server: "my tools>",
tool: "list",
text: "2 overdue",
},
]),
}),
Layer.mock(CheckpointService.CheckpointServiceV2)({
captureBaseline: () => Effect.void,
}),
Layer.mock(EventSink.EventSinkV2)({}),
IdAllocator.layer,
Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({
ingestNormalized: () => Effect.succeed([]),
}),
ServerSettings.layerTest(),
),
),
),
),
),
);
it.effect("fails the run when its ownership check cannot be read before calling the provider", () =>
Effect.gen(function* () {
const guardCalls = yield* Ref.make(0);
@@ -603,6 +690,7 @@ it.effect("fails the run when its ownership check cannot be read before calling
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
Layer.mock(EventSink.EventSinkV2)({
writeIfRunCurrent: (input) =>
@@ -876,6 +964,7 @@ it.effect("starts the provider when checkpoint baseline capture fails", () =>
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({
captureBaseline: () =>
Effect.fail(
@@ -993,6 +1082,7 @@ it.effect.each(["failure", "interruption", "stale-attempt", "start-guard"] as co
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({
captureBaseline: () =>
scenario === "start-guard" ? Effect.void : Effect.die("not reached"),
@@ -1163,6 +1253,7 @@ it.effect("keeps ingesting owned child events after the root turn terminalizes",
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
Layer.mock(EventSink.EventSinkV2)({
write: () => Effect.succeed([]),
@@ -1588,6 +1679,7 @@ it.effect(
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({
captureBaseline: () => Effect.void,
}),
@@ -1805,6 +1897,7 @@ it.effect("drops late root provider-thread writes from a superseded attempt", ()
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
Layer.mock(EventSink.EventSinkV2)({
write: () => Effect.succeed([]),
@@ -2009,6 +2102,7 @@ it.effect(
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({
captureBaseline: () => Effect.void,
}),
@@ -2180,6 +2274,7 @@ it.effect(
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({
captureBaseline: () => Effect.void,
}),
@@ -2349,6 +2444,7 @@ it.effect(
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({
captureBaseline: () => Effect.void,
}),
@@ -2722,6 +2818,7 @@ it.effect(
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({
captureBaseline: () => Effect.void,
}),
@@ -3444,6 +3541,7 @@ function captureRootRunTermination(input: {
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
Layer.mock(EventSink.EventSinkV2)({
write: (payload) =>
@@ -3922,6 +4020,7 @@ function runBackgroundItemScenario(
const layerTest = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
Layer.mock(EventSink.EventSinkV2)({
write: () => Effect.succeed([]),
@@ -36,6 +36,7 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as CheckpointService from "./CheckpointService.ts";
import * as EventSink from "./EventSink.ts";
@@ -544,6 +545,7 @@ export const layer: Layer.Layer<
| IdAllocator.IdAllocatorV2
| ProviderEventIngestor.ProviderEventIngestorV2
| ServerSettings.ServerSettingsService
| McpAppModelContext.McpAppModelContext
> = Layer.effect(
RunExecutionServiceV2,
Effect.gen(function* () {
@@ -552,6 +554,7 @@ export const layer: Layer.Layer<
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const mcpAppModelContext = yield* McpAppModelContext.McpAppModelContext;
const finalizationObserver = yield* RunFinalizationService.RunFinalizationObserver;
const writeFinalRunEvents = (input: {
@@ -1352,6 +1355,23 @@ export const layer: Layer.Layer<
// its already-issued MCP credential valid even when the agent goes
// a long time between browser-tool calls.
yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
// A context read that fails costs the agent the apps' notes for
// this turn, not the turn itself.
const appContext = (yield* mcpAppModelContext
.forThread(input.run.threadId)
.pipe(
Effect.catch((cause) =>
Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe(
Effect.as([]),
),
),
)).map((entry) => ({
// The item id alone is unique and needs no escaping; server and
// tool names are free text that would break the tag Codex wraps
// the context in.
key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`,
text: entry.text,
}));
const turnInput = {
appThread: input.appThread,
threadId: input.run.threadId,
@@ -1372,6 +1392,7 @@ export const layer: Layer.Layer<
message: input.message,
modelSelection: input.modelSelection,
runtimePolicy: input.runtimePolicy,
...(appContext.length === 0 ? {} : { appContext }),
};
const compact =
input.message.attachments.length === 0 &&
@@ -3,6 +3,8 @@ import * as Scheduler from "../scheduling/Scheduler.ts";
import * as Layer from "effect/Layer";
import * as OrchestrationCommandReceipts from "../persistence/OrchestrationCommandReceipts.ts";
import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
import * as McpAppRequests from "../mcpApps/McpAppRequests.ts";
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
@@ -141,6 +143,7 @@ const layerProviderAuthServiceProvided = ProviderAuthService.layer.pipe(
const layerRunExecutionServiceProvided = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layer,
layerCheckpointServiceProvided,
layerEventSinkProvided,
IdAllocator.layer,
@@ -314,8 +317,20 @@ const layerProviderRuntimeRecoveryProvided = ProviderRuntimeRecoveryService.laye
),
);
const layerMcpAppRequestsProvided = McpAppRequests.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layer,
layerOrchestratorProvided,
layerThreadManagementProvided,
layerProviderSessionManagerProvided,
),
),
);
export const layer = Layer.mergeAll(
layerOrchestratorProvided,
layerMcpAppRequestsProvided,
layerThreadManagementProvided,
layerEffectWorkerProvided,
layerProviderSessionManagerProvided,
@@ -44,6 +44,7 @@ import * as ProviderSwitchService from "../ProviderSwitchService.ts";
import * as ProviderTurnControlService from "../ProviderTurnControlService.ts";
import * as ProviderTurnStartService from "../ProviderTurnStartService.ts";
import * as ProviderTurnStartServiceTestkit from "../ProviderTurnStartService.testkit.ts";
import * as McpAppModelContext from "../../mcpApps/McpAppModelContext.ts";
import * as RunExecutionService from "../RunExecutionService.ts";
import * as RunFinalizationService from "../RunFinalizationService.ts";
import * as ThreadTitleRegenerationService from "../ThreadTitleRegenerationService.ts";
@@ -355,6 +356,7 @@ export function layerWithRegistry<Error>(
const layerRunExecutionServiceProvided = RunExecutionService.layer.pipe(
Layer.provide(
Layer.mergeAll(
McpAppModelContext.layerEmpty,
layerCheckpointServiceProvided,
layerEventSinkProvided,
IdAllocator.layer,
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.120.0","scenario":"delegated_task_status","metadata":{"source":"constructed-codex-app-server-replay-fixture","fileName":"codex_transcript.ndjson","normalization":"Provider-valid frames were composed into a deterministic multi-turn lifecycle; native IDs and timestamps were normalized.","description":"An active parent delegates a child, interrupts a running follow-up, and lets queued work complete."}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.120.0 (Mac OS 26.4.1; arm64) dumb (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"macos"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"parent.thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true}}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"message_steering","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"message_steering.ndjson","description":"One active turn receives an immediate turn/steer request.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"multi_turn","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"multi_turn.ndjson","description":"One thread with two sequential user turns.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"plan_questions","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"plan_questions.ndjson","description":"One plan-mode turn that asks a structured clarifying question.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"proposed_plan","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"proposed_plan.ndjson","description":"One plan-mode turn that emits a proposed plan document.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"provider_thread_resume","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"provider_thread_resume.ndjson","description":"One provider-native thread is started, completed, then resumed by thread id in a fresh app-server session.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -32,7 +32,7 @@
{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","status":{"type":"idle"}},"emittedAtMs":1790295635342}}
{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd","turn":{"id":"01a0d5ef-637e-7ba2-bf9a-5534a6f98a83","items":[{"type":"agentMessage","id":"msg_0b6c69e800b2ec4c016ab5be52efd887d092b6695452f82b22","text":"provider thread resume fixture first turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295630,"completedAt":1790295635,"durationMs":4607}},"emittedAtMs":1790295635342}}
{"type":"runtime_exit","status":"success"}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/resume","frame":{"id":2,"method":"thread/resume","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","excludeTurns":true,"model":"gpt-6-luna","threadId":"01a0d5ef-62bd-7c20-861b-0528ff7d86bd"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"queued_turn","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"queued_turn.ndjson","description":"A second user turn queued behind an active turn starts after it completes.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"simple","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"simple.ndjson","description":"One thread and one turn with a deterministic text-only response.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"subagent","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"subagent.ndjson","description":"One root turn that asks Codex to spawn two collab agents.","model":"gpt-5.6-luna","recorderThreadConfigKeys":["skills.include_instructions"]}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"skills.include_instructions":false},"cwd":"<workspace>","model":"gpt-5.6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"subagent_continue","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"subagent_continue.ndjson","description":"A root turn spawns one native Codex subagent, then a later root turn resumes and messages the same child thread.","model":"gpt-5.6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-5.6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"subagent_v2","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"subagent_v2.ndjson","description":"One root turn on a multi-agent v2 model that spawns one native subagent and waits for it.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"subagent_v2_approval","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"subagent_v2_approval.ndjson","description":"One root turn in approval-required mode whose multi-agent v2 subagent runs a command that needs approval.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/tmp/codex-subagent-approval-rec/codex-home","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"subagent_v2_nested","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"subagent_v2_nested.ndjson","description":"One root turn on a multi-agent v2 model whose subagent spawns a subagent that spawns a leaf.","model":"gpt-6-luna","recorderThreadConfigKeys":["agents.max_depth"]}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"agents.max_depth":3},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"subagent_v2_nested_approval","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"subagent_v2_nested_approval.ndjson","description":"One root turn in approval-required mode whose multi-agent v2 subagent spawns a subagent that runs a command that needs approval.","model":"gpt-6-luna","recorderThreadConfigKeys":["agents.max_depth"]}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.cache/codex-nested-approval-rec/codex-home","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"agents.max_depth":2},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.120.0","scenario":"thread_fork_native","metadata":{"source":"hand-authored-replay","description":"One completed source turn, a native thread/fork, and the first target fork turn.","normalization":"The thread/fork expected request gains lastTurnId (inclusive native boundary) to match the V2 adapter's native-boundary fork."}}
{"type":"expect_outbound","label":"initialize/source","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize/source","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize/source","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.120.0","codexHome":"/tmp/codex","platformFamily":"unix","platformOs":"macos"}}}
{"type":"expect_outbound","label":"initialized/source","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start/source","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true}}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"thread_fork_native_continue","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"thread_fork_native_continue.ndjson","description":"One source marker turn, a native thread fork, a fork-local marker turn, and a recall turn that requires both contexts.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.124.0-alpha.3","scenario":"thread_fork_native_prior_turn","metadata":{"source":"codex-app-server-live-probe-normalized-for-orchestrator-replay","description":"Two completed source turns, a native thread/fork through the first source turn, and a fork turn that only sees the first turn.","sourceThreadId":"019dd6ba-2681-7bf0-b051-141b0cbcbb27","forkThreadId":"019dd6ba-47b7-7092-8688-9cf7fe5f6498","firstTurnId":"019dd6ba-268b-7f82-8f4c-9fde0edcfd55","secondTurnId":"019dd6ba-416d-7902-95cf-d4179c3f4738","repeatTurnId":"019dd6ba-47eb-7041-ad45-5abe752c28c9","normalization":"Native frames are live. Initialize frames are normalized to the T3 adapter client info, and a fork-session initialize was inserted to match orchestrator provider-session lifecycle. The thread/fork expected request gains lastTurnId (the first source turn, inclusive), the emitted fork response now contains only turns through that boundary, and the thread/rollback pair was removed to match the V2 adapter's native-boundary fork."}}
{"type":"expect_outbound","label":"initialize/source","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize/source","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize/source","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.124.0-alpha.3","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"macos"}}}
{"type":"expect_outbound","label":"initialized/source","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true}}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"thread_fork_native_siblings","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"thread_fork_native_siblings.ndjson","description":"One source marker turn and two independent native forks that each recall the source plus only their own fork marker.","model":"gpt-6-sol"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-sol"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"thread_merge_back_continue","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"thread_merge_back_continue.ndjson","description":"A source thread consumes one fork-delta handoff and later recalls source and transferred context.","model":"gpt-6-sol"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-sol"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"thread_merge_back_siblings","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"thread_merge_back_siblings.ndjson","description":"Two sibling fork deltas are merged sequentially into one source provider thread and recalled together.","model":"gpt-6-sol"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-sol"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"thread_rollback","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"thread_rollback.ndjson","description":"One thread completes two turns, rolls back the most recent turn, then starts another turn.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"thread_rollback_after_restart","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"thread_rollback_after_restart.ndjson","description":"One thread completes two turns, the app-server restarts, then the thread rolls back its latest turn and starts another turn.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/tmp/bughunt-codex/codex-home","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -45,7 +45,7 @@
{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","status":{"type":"idle"}},"emittedAtMs":1790404934811}}
{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a","turn":{"id":"01a0dc73-2dc4-7911-a448-c66b9bf3318b","items":[{"type":"agentMessage","id":"msg_0f3ce1c685f16088016ab769447c6087d08bd0018d724b5401","text":"rollback fixture second turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790404931,"completedAt":1790404934,"durationMs":3756}},"emittedAtMs":1790404934811}}
{"type":"runtime_exit","status":"success"}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/tmp/bughunt-codex/codex-home","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/read","frame":{"id":2,"method":"thread/read","params":{"includeTurns":false,"threadId":"01a0dc73-1bb4-74f1-977f-2fc39b8aaa6a"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"thread_rollback_to_stopped_turn","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"thread_rollback_to_stopped_turn.ndjson","description":"One completed turn, one turn stopped mid-tool, one completed turn, thread/revert back to the stopped turn, then a post-rollback turn.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"todo_list","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"todo_list.ndjson","description":"One turn that asks Codex to emit progress through update_plan.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"tool_call_read_only_on_request","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"tool_call_read_only_on_request.ndjson","description":"Write a small fixture file with read-only full filesystem visibility and on-request approvals.","model":"gpt-6-sol"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-sol"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"tool_call_restricted_granular","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"tool_call_restricted_granular.ndjson","description":"Write a small fixture file with restricted read access and granular approval flags enabled.","model":"gpt-5.6-terra"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-5.6-terra"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"tool_call_workspace_never","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"tool_call_workspace_never.ndjson","description":"Write a small fixture file with workspace-write sandbox policy and never approvals.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"turn_interrupt","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"turn_interrupt.ndjson","description":"One active turn is interrupted before it finishes naturally.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"turn_interrupt_mid_tool","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"turn_interrupt_mid_tool.ndjson","description":"One active turn is interrupted after Codex has already executed a local command.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -1,5 +1,5 @@
{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"web_search","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"web_search.ndjson","description":"One turn with a native Codex webSearch item that should become normalized progress.","model":"gpt-6-luna"}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"]},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true},"cwd":"<workspace>","model":"gpt-6-luna"}}}
@@ -72,6 +72,7 @@ import Migration0055 from "./Migrations/055_OrchestrationV2.ts";
import Migration0056 from "./Migrations/056_RemoveRedundantProjectionIndexes.ts";
import Migration0057 from "./Migrations/057_ScheduledTaskWebhooks.ts";
import Migration0058 from "./Migrations/058_WebhookRelayDeliveries.ts";
import Migration0059 from "./Migrations/059_McpAppModelContext.ts";
/**
* Migration loader with all migrations defined inline.
@@ -144,6 +145,7 @@ export const migrationEntries = [
[56, "RemoveRedundantProjectionIndexes", Migration0056],
[57, "ScheduledTaskWebhooks", Migration0057],
[58, "WebhookRelayDeliveries", Migration0058],
[59, "McpAppModelContext", Migration0059],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -13,7 +13,7 @@ layer("055_OrchestrationV2", (it) => {
Effect.sync(() => {
assert.deepStrictEqual(
migrationEntries.map(([id]) => id),
Array.from({ length: 58 }, (_, index) => index + 1),
Array.from({ length: 59 }, (_, index) => index + 1),
);
}),
);
@@ -30,6 +30,7 @@ layer("055_OrchestrationV2", (it) => {
[56, "RemoveRedundantProjectionIndexes"],
[57, "ScheduledTaskWebhooks"],
[58, "WebhookRelayDeliveries"],
[59, "McpAppModelContext"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
@@ -54,6 +55,7 @@ layer("055_OrchestrationV2", (it) => {
{ migration_id: 56, name: "RemoveRedundantProjectionIndexes" },
{ migration_id: 57, name: "ScheduledTaskWebhooks" },
{ migration_id: 58, name: "WebhookRelayDeliveries" },
{ migration_id: 59, name: "McpAppModelContext" },
]);
const tables = yield* sql<{ readonly name: string }>`
@@ -0,0 +1,21 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
// The latest context each MCP App gave the agent (`ui/update-model-context`),
// one row per app, replaced on every update and sent with the thread's next
// turn.
yield* sql`
CREATE TABLE IF NOT EXISTS mcp_app_model_context (
thread_id TEXT NOT NULL,
item_id TEXT NOT NULL,
server TEXT NOT NULL,
tool TEXT NOT NULL,
text TEXT NOT NULL,
updated_at TEXT NOT NULL,
PRIMARY KEY (thread_id, item_id)
)
`;
});
@@ -39,6 +39,7 @@ describe("V2 preview upgrade", () => {
[56, "RemoveRedundantProjectionIndexes"],
[57, "ScheduledTaskWebhooks"],
[58, "WebhookRelayDeliveries"],
[59, "McpAppModelContext"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -120,6 +121,7 @@ describe("V2 preview upgrade", () => {
[56, "RemoveRedundantProjectionIndexes"],
[57, "ScheduledTaskWebhooks"],
[58, "WebhookRelayDeliveries"],
[59, "McpAppModelContext"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
+6
View File
@@ -116,6 +116,7 @@ import * as EnvironmentTheme from "./environmentTheme.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as ThreadManagementService from "./orchestration-v2/ThreadManagementService.ts";
import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";
import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts";
import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts";
@@ -1203,6 +1204,7 @@ const layerWsRpc = (
const threadSearch = yield* ThreadSearch.ThreadSearch;
const providerSessionsV2 = yield* ProviderSessionManager.ProviderSessionManagerV2;
const mcpAppRequests = yield* McpAppRequests.McpAppRequests;
const analytics = yield* AnalyticsService.AnalyticsService;
// Client-origin attribution (#7774): every thread/turn the connecting
// client starts is credited to its surface + app version. Best-effort:
@@ -2226,6 +2228,10 @@ const layerWsRpc = (
}
return { providers };
}),
[WS_METHODS.mcpAppsCallTool]: (input) => mcpAppRequests.callTool(input),
[WS_METHODS.mcpAppsToolInfo]: (input) => mcpAppRequests.toolInfo(input),
[WS_METHODS.mcpAppsUpdateModelContext]: (input) => mcpAppRequests.updateModelContext(input),
[WS_METHODS.mcpAppsReadResource]: (input) => mcpAppRequests.readResource(input),
[WS_METHODS.providerUploadFeedback]: (input) =>
Effect.gen(function* () {
const projection = yield* threadManagement.getThreadRecords(input.threadId, [
+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);