The best way to control Claude Code, Codex and more from any computer or phone
refactor(mobile): stream and MCP webviews tie their work to the view's lifetime (#25226)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 22:19 UTC
c66f13ce97d6e02e495f0ed8c7cb8a91f16dc303
10 files changed
+480
-376
apps/mobile/src/features/browser/PreviewStreamWebView.tsx
+41
-40
@@ -12,7 +12,6 @@ import {
12
} from "@t3tools/client-runtime/preview/server-browser-stream";
13
import type { EnvironmentId, PreviewStreamHostSetup } from "@t3tools/contracts";
14
import {
15
- useEffect,
15
useEffectEvent,
16
useImperativeHandle,
17
useLayoutEffect,
@@ -52,11 +51,13 @@ export interface PreviewPictureInPictureState {
51
type NativeStreamBridge = {
52
readonly ref?: Ref<PreviewStreamRef>;
53
readonly onUnauthorized: () => void;
54
+ /** Asks for fresh access after a refusal, once `delayMs` has passed. */
55
+ readonly onRefused: (delayMs: number) => void;
56
readonly onGone?: () => void;
57
readonly onViewport?: (viewport: { readonly width: number; readonly height: number }) => void;
58
readonly onControl?: (control: PreviewStreamControl | null) => void;
59
readonly onPictureInPicture?: (state: PreviewPictureInPictureState, detail?: string) => void;
59
- /** True while frames show, so commands reach the page. Pass a stable function. */
60
+ /** True while frames show, so commands reach the page. */
61
readonly onStreamingChange?: (streaming: boolean) => void;
62
readonly compact?: boolean;
63
readonly pdfUri?: string | null;
@@ -113,14 +114,21 @@ const MAX_REFUSALS = 3;
114
115
export function PreviewStreamWebView(
116
props: Omit<PreviewStreamConfiguration, "access"> &
116
- Omit<NativeStreamBridge, "onUnauthorized"> & {
117
+ Omit<NativeStreamBridge, "onUnauthorized" | "onRefused"> & {
118
readonly environmentId: EnvironmentId;
119
readonly paused?: boolean;
120
},
121
) {
121
- const { access, error, refresh } = usePreviewStreamAccess(props.environmentId);
122
+ const { access, error, refresh, retryAfter } = usePreviewStreamAccess(props.environmentId);
123
if (access && !props.paused) {
123
- return <AuthorizedPreviewStream {...props} access={access} onUnauthorized={refresh} />;
124
+ return (
125
+ <AuthorizedPreviewStream
126
+ {...props}
127
+ access={access}
128
+ onUnauthorized={refresh}
129
+ onRefused={retryAfter}
130
+ />
131
+ );
132
}
133
return (
134
<View
@@ -165,13 +173,6 @@ function AuthorizedPreviewStream({
173
}
174
const processRetried = useRef(false);
175
const unauthorized = useRef(0);
168
- const refreshTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
169
- useEffect(
170
- () => () => {
171
- if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);
172
- },
173
- [],
174
- );
176
const configuration = JSON.stringify({
177
access: props.access,
178
threadId: props.threadId,
@@ -188,14 +189,7 @@ function AuthorizedPreviewStream({
189
onUnauthorized={() => {
190
const refusals = ++unauthorized.current;
191
if (refusals >= MAX_REFUSALS) return false;
191
- if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);
192
- refreshTimer.current = setTimeout(
193
- () => {
194
- refreshTimer.current = null;
195
- props.onUnauthorized();
196
- },
197
- refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1),
198
- );
192
+ props.onRefused(refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1));
193
return true;
194
}}
195
onRetry={() => {
@@ -232,7 +226,7 @@ function PreviewStreamDocumentView({
226
onRetry,
227
onStreaming,
228
onRecoverProcess,
235
-}: Omit<NativeStreamBridge, "onUnauthorized"> & {
229
+}: Omit<NativeStreamBridge, "onUnauthorized" | "onRefused"> & {
230
readonly configuration: string;
231
readonly background: string;
232
readonly onUnauthorized: () => boolean;
@@ -241,13 +235,13 @@ function PreviewStreamDocumentView({
235
readonly onRecoverProcess: () => boolean;
236
}) {
237
const webView = useRef<WebView<object>>(null);
244
- const active = useRef(true);
238
+ const active = useRef(false);
239
const failed = useRef(false);
240
+ const bootstrapTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
241
const [status, setStatus] = useState<"connecting" | "streaming" | "error">("connecting");
242
const [error, setError] = useState<string | null>(null);
243
const [gone, setGone] = useState(false);
244
const [hostSetup, setHostSetup] = useState<PreviewStreamHostSetup | null>(null);
250
- const [started, setStarted] = useState(false);
245
const [control, setControl] = useState<PreviewStreamControl | null>(null);
246
const dialogRef = useRef<PreviewStreamControl["dialog"]>(null);
247
const [promptText, setPromptText] = useState("");
@@ -263,7 +257,6 @@ function PreviewStreamDocumentView({
257
),
258
);
259
};
266
- const controlChanged = useEffectEvent((next: PreviewStreamControl | null) => onControl?.(next));
260
const command = (input: PreviewStreamInput) =>
261
webView.current?.injectJavaScript(
262
`window.T3PreviewStream?.command(${JSON.stringify(input)}); true;`,
@@ -277,9 +270,15 @@ function PreviewStreamDocumentView({
270
},
271
() => Dialog.alert("Could not read the clipboard"),
272
);
273
+ const clearBootstrapTimer = () => {
274
+ if (bootstrapTimer.current === null) return;
275
+ clearTimeout(bootstrapTimer.current);
276
+ bootstrapTimer.current = null;
277
+ };
278
const fail = (message: string) => {
279
if (!active.current || failed.current) return;
280
failed.current = true;
281
+ clearBootstrapTimer();
282
webView.current?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
283
onStreamingChange?.(false);
284
setControl(null);
@@ -291,11 +290,23 @@ function PreviewStreamDocumentView({
290
const bootstrapTimedOut = useEffectEvent(() =>
291
fail("Browser viewer could not start. Reconnect to try again."),
292
);
294
- useEffect(() => {
295
- if (started) return;
296
- const timer = setTimeout(bootstrapTimedOut, 15_000);
297
- return () => clearTimeout(timer);
298
- }, [started]);
293
+ const streamEnded = useEffectEvent(() => {
294
+ onStreamingChange?.(false);
295
+ onControl?.(null);
296
+ });
297
+ // The stream lives exactly as long as this view.
298
+ useLayoutEffect(() => {
299
+ active.current = true;
300
+ const view = webView.current;
301
+ bootstrapTimer.current = setTimeout(bootstrapTimedOut, 15_000);
302
+ return () => {
303
+ if (bootstrapTimer.current !== null) clearTimeout(bootstrapTimer.current);
304
+ bootstrapTimer.current = null;
305
+ active.current = false;
306
+ view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
307
+ streamEnded();
308
+ };
309
+ }, []);
310
const source = useMemo(
311
() => ({
312
html: previewStreamDocument(configuration, previewStreamScript),
@@ -309,16 +320,6 @@ function PreviewStreamDocumentView({
320
togglePictureInPicture: () =>
321
webView.current?.injectJavaScript("window.T3PreviewStream?.pictureInPicture(); true;"),
322
}));
312
- useLayoutEffect(() => {
313
- active.current = true;
314
- const view = webView.current;
315
- return () => {
316
- active.current = false;
317
- view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
318
- };
319
- }, []);
320
- useEffect(() => () => onStreamingChange?.(false), [onStreamingChange]);
321
- useEffect(() => () => controlChanged(null), []);
323
const processTerminated = () => {
324
if (!active.current || failed.current) return;
325
if (!onRecoverProcess()) fail("Browser viewer stopped. Reconnect to try again.");
@@ -407,7 +408,7 @@ function PreviewStreamDocumentView({
408
onPictureInPicture?.(message, message.detail);
409
return;
410
case "status":
410
- setStarted(true);
411
+ clearBootstrapTimer();
412
if (message.status === "error") {
413
fail(message.detail ?? "Browser stream failed.");
414
return;
apps/mobile/src/features/browser/ThreadBrowserFloat.tsx
+24
-15
@@ -2,7 +2,7 @@ import { useIsFocused } from "@react-navigation/native";
2
import type { EnvironmentId, PreviewSessionSnapshot, ThreadId } from "@t3tools/contracts";
3
import { previewPdfAssetUrl } from "@t3tools/shared/preview";
4
import * as Option from "effect/Option";
5
-import { useCallback, useEffect, useRef, useState } from "react";
5
+import { useCallback, useState } from "react";
6
import { Pressable, View } from "react-native";
7
import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
8
@@ -26,21 +26,30 @@ export function ThreadBrowserFloat(props: {
26
readonly onOpen: (tabId: string) => void;
27
}) {
28
const [tabId, setTabId] = useState<string | null>(null);
29
- const known = useRef<ReadonlyMap<string, string | undefined> | null>(null);
30
- useEffect(() => {
31
- if (!props.loaded) return;
32
- const previous = known.current;
33
- known.current = new Map(props.tabs.map((tab) => [tab.tabId, tab.revealRequest?.id]));
34
- if (previous === null) return;
35
- const opened = props.tabs.findLast(
36
- (tab) =>
37
- tab.reveal === true &&
38
- (tab.revealRequest
39
- ? previous.get(tab.tabId) !== tab.revealRequest.id
40
- : !previous.has(tab.tabId)),
41
- );
29
+ // The reveal requests already seen, so only a tab revealed after the first
30
+ // list pops the player.
31
+ const [seen, setSeen] = useState<{
32
+ readonly tabs: ReadonlyArray<PreviewSessionSnapshot>;
33
+ readonly reveals: ReadonlyMap<string, string | undefined>;
34
+ } | null>(null);
35
+ if (props.loaded && seen?.tabs !== props.tabs) {
36
+ setSeen({
37
+ tabs: props.tabs,
38
+ reveals: new Map(props.tabs.map((tab) => [tab.tabId, tab.revealRequest?.id])),
39
+ });
40
+ const previous = seen?.reveals;
41
+ const opened =
42
+ previous === undefined
43
+ ? undefined
44
+ : props.tabs.findLast(
45
+ (tab) =>
46
+ tab.reveal === true &&
47
+ (tab.revealRequest
48
+ ? previous.get(tab.tabId) !== tab.revealRequest.id
49
+ : !previous.has(tab.tabId)),
50
+ );
51
if (opened !== undefined) setTabId(opened.tabId);
43
- }, [props.loaded, props.tabs]);
52
+ }
53
const focused = useIsFocused();
54
const foreground = useAppForeground();
55
const tab = props.tabs.find((entry) => entry.tabId === tabId) ?? null;
apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx
+10
-15
@@ -9,7 +9,7 @@ import {
9
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
10
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
11
import * as Cause from "effect/Cause";
12
-import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
12
+import { useEffect, useRef, useState, type RefObject } from "react";
13
import * as Haptics from "expo-haptics";
14
import { Accelerometer } from "expo-sensors";
15
import { Pressable, StatusBar, View } from "react-native";
@@ -31,7 +31,8 @@ import { useAppForeground } from "../../lib/appState";
31
import { useHardwareBack } from "../../lib/backHandler";
32
import { deriveBottomControlInsets } from "../../lib/reserved-regions";
33
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
34
-import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
34
+import { uuidv4 } from "../../lib/uuid";
35
+import { deviceEnvironment, useDeviceHubAccess } from "../../state/device";
36
import { useEnvironmentQuery } from "../../state/query";
37
import { useAtomCommand } from "../../state/use-atom-command";
38
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
@@ -102,13 +103,10 @@ export function DevicePreviewScreen({
103
const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
104
const previews = threadDevicePreviews(state.data, threadId);
105
const preview = selectedThreadDevicePreview(previews, selectedKey);
105
- const onInputConnected = useCallback(
106
- async (connected: boolean) => {
107
- setInputConnected(connected);
108
- if (connected && !embedded) setControlsVisible(false);
109
- },
110
- [embedded],
111
- );
106
+ const onInputConnected = async (connected: boolean) => {
107
+ setInputConnected(connected);
108
+ if (connected && !embedded) setControlsVisible(false);
109
+ };
110
useEffect(() => {
111
if (focused && state.data !== null && previews.length === 0) onClose();
112
}, [focused, state.data, previews.length, onClose]);
@@ -401,12 +399,9 @@ function OpenDevicePreview({
399
}) {
400
const { session } = preview;
401
const { themeVariables } = useAppearancePreferences();
404
- const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId);
405
- const onUnauthorized = async () => refreshDeviceHubAccess(environmentId);
406
- useEffect(() => {
407
- refreshDeviceHubAccess(environmentId);
408
- return () => void onInputConnected(false);
409
- }, [environmentId, onInputConnected]);
402
+ const [viewer] = useState(uuidv4);
403
+ const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId, viewer);
404
+ const onUnauthorized = async () => refresh();
405
return access ? (
406
<DeviceStreamWebView
407
ref={streamRef}
apps/mobile/src/features/devices/DeviceStreamWebView.tsx
+24
-19
@@ -1,7 +1,6 @@
1
import { Button } from "../../components/ui/Button";
2
import deviceStreamScript from "@t3tools/mobile-device-stream";
3
import {
4
- useEffect,
4
useEffectEvent,
5
useImperativeHandle,
6
useLayoutEffect,
@@ -95,14 +94,20 @@ function DeviceStreamDocumentView({
94
readonly onRecoverProcess: () => boolean;
95
}) {
96
const webView = useRef<WebView<object>>(null);
98
- const active = useRef(true);
97
+ const active = useRef(false);
98
const failed = useRef(false);
99
+ const bootstrapTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
100
const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
101
const [error, setError] = useState<string | null>(null);
102
- const [started, setStarted] = useState(false);
102
+ const clearBootstrapTimer = () => {
103
+ if (bootstrapTimer.current === null) return;
104
+ clearTimeout(bootstrapTimer.current);
105
+ bootstrapTimer.current = null;
106
+ };
107
const fail = (message: string) => {
108
if (!active.current || failed.current) return;
109
failed.current = true;
110
+ clearBootstrapTimer();
111
void onInputConnected(false);
112
webView.current?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
113
setError(message);
@@ -111,11 +116,21 @@ function DeviceStreamDocumentView({
116
const bootstrapTimedOut = useEffectEvent(() =>
117
fail("Device viewer could not start. Reconnect to try again."),
118
);
114
- useEffect(() => {
115
- if (started) return;
116
- const timer = setTimeout(bootstrapTimedOut, 15_000);
117
- return () => clearTimeout(timer);
118
- }, [started]);
119
+ const resetInput = useEffectEvent(() => void onInputConnected(false));
120
+ // The stream lives exactly as long as this view.
121
+ useLayoutEffect(() => {
122
+ active.current = true;
123
+ resetInput();
124
+ const view = webView.current;
125
+ bootstrapTimer.current = setTimeout(bootstrapTimedOut, 15_000);
126
+ return () => {
127
+ if (bootstrapTimer.current !== null) clearTimeout(bootstrapTimer.current);
128
+ bootstrapTimer.current = null;
129
+ active.current = false;
130
+ view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
131
+ resetInput();
132
+ };
133
+ }, []);
134
const source = {
135
html: deviceStreamDocument(configuration, deviceStreamScript),
136
baseUrl,
@@ -131,16 +146,6 @@ function DeviceStreamDocumentView({
146
appSwitcher: () => command("appSwitcher"),
147
rotate: () => command("rotate"),
148
}));
134
- const resetInput = useEffectEvent(() => void onInputConnected(false));
135
- useLayoutEffect(() => {
136
- active.current = true;
137
- resetInput();
138
- const view = webView.current;
139
- return () => {
140
- active.current = false;
141
- view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
142
- };
143
- }, []);
149
const processTerminated = () => {
150
if (!active.current || failed.current) return;
151
void onInputConnected(false);
@@ -173,7 +178,7 @@ function DeviceStreamDocumentView({
178
else if (message?.type === "input") void onInputConnected(message.connected);
179
else if (message?.type === "retry") onRetry();
180
else if (message?.type === "status") {
176
- setStarted(true);
181
+ clearBootstrapTimer();
182
if (message.status === "error") fail(message.detail ?? "Device stream failed.");
183
else {
184
setStatus(message.status);
apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx
+17
-8
@@ -3,7 +3,7 @@ import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
3
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4
import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
5
import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
6
-import { useCallback, useEffect, useMemo, useState } from "react";
6
+import { useEffect, useMemo, useRef, useState } from "react";
7
import { Pressable, View } from "react-native";
8
import { useSafeAreaInsets } from "react-native-safe-area-context";
9
@@ -64,11 +64,19 @@ export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) {
64
const insets = useSafeAreaInsets();
65
// Wait for focus before goBack; an exit under another screen must not pop that screen.
66
const focused = useIsFocused();
67
- const [exitRequested, setExitRequested] = useState(false);
68
- const onClose = useCallback(() => {
69
- if (navigation.isFocused()) navigation.goBack();
70
- else setExitRequested(true);
71
- }, [navigation]);
67
+ const exitPending = useRef(false);
68
+ const onClose = () => {
69
+ if (navigation.isFocused()) {
70
+ navigation.goBack();
71
+ return;
72
+ }
73
+ if (exitPending.current) return;
74
+ exitPending.current = true;
75
+ const unsubscribe = navigation.addListener("focus", () => {
76
+ unsubscribe();
77
+ navigation.goBack();
78
+ });
79
+ };
80
const [size, setSize] = useState({ width: 0, height: 0 });
81
const params = route.params;
82
const environmentId = EnvironmentId.make(params.environmentId);
@@ -97,9 +105,10 @@ export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) {
105
const conversation = useThreadShell(scopeThreadRef(environmentId, conversationThreadId));
106
const awaitingUser =
107
conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
108
+ // A request for the user is server state with no local handler to react in.
109
useEffect(() => {
101
- if ((awaitingUser || exitRequested) && focused) navigation.goBack();
102
- }, [awaitingUser, exitRequested, focused, navigation]);
110
+ if (awaitingUser && focused && !exitPending.current) navigation.goBack();
111
+ }, [awaitingUser, focused, navigation]);
112
113
return (
114
<View className="flex-1 bg-screen" style={{ paddingTop: insets.top }}>
apps/mobile/src/features/threads/McpAppWebView.tsx
+287
-256
@@ -21,9 +21,10 @@ import {
21
type McpAppReference,
22
} from "@t3tools/shared/mcpApp";
23
import * as Predicate from "effect/Predicate";
24
+import { AsyncResult } from "effect/reactivity";
25
import Constants from "expo-constants";
26
import { useNavigation } from "@react-navigation/native";
26
-import { useEffect, useMemo, useRef, useState } from "react";
27
+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
28
import { Platform, View } from "react-native";
29
import { useSafeAreaInsets } from "react-native-safe-area-context";
30
import { WebView, type WebViewMessageEvent } from "react-native-webview";
@@ -34,6 +35,7 @@ import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme";
35
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
36
import { uuidv4 } from "../../lib/uuid";
37
import { useAssetUrlState } from "../../state/assets";
38
+import { appAtomRegistry } from "../../state/atom-registry";
39
import { useThreadShell } from "../../state/entities";
40
import { mcpAppEnvironment } from "../../state/mcpApps";
41
import { orchestrationEnvironment } from "../../state/orchestration";
@@ -88,6 +90,18 @@ const confirm = (title: string, message: string, action: string) =>
90
91
const MAX_DOWNLOAD_BYTES = 25 * 1024 * 1024;
92
93
+// The feed omits tool input and output; the app needs both.
94
+function storedToolCall(
95
+ item: { readonly type: string; readonly input?: unknown; readonly output?: unknown } | null,
96
+) {
97
+ if (item?.type !== "dynamic_tool") return undefined;
98
+ const output = item.output as { readonly result?: unknown } | undefined;
99
+ return {
100
+ arguments: item.input,
101
+ result: output?.result as McpAppCallToolResult | undefined,
102
+ };
103
+}
104
+
105
/** WebViews reload when moved; tear down inline before opening fullscreen and recreate it on return. */
106
export function ThreadMcpApp(props: {
107
readonly environmentId: EnvironmentId;
@@ -101,19 +115,29 @@ export function ThreadMcpApp(props: {
115
readonly onExitFullscreen?: () => void;
116
readonly height?: number;
117
}) {
104
- // Equal app content must retain its reference to preserve the live document host.
118
const [height, setHeight] = useState(MCP_APP_INLINE_MAX_HEIGHT);
119
+ const [documentKey, setDocumentKeyState] = useState(0);
120
+ // The view keeps its first URL: a re-minted one would reload the app.
121
+ const [uri, setUri] = useState<string | null>(null);
122
+ const [loaded, setLoaded] = useState(false);
123
+ const [navigatedAway, setNavigatedAway] = useState(false);
124
+ // Equal app content must retain its reference to preserve the live document host.
125
+ // A different app needs a new document even when its asset URL is unchanged,
126
+ // so the WebView key moves on with the document key, not only the URL.
127
const [app, setApp] = useState(props.app);
128
if (!mcpAppReferencesEqual(app, props.app)) {
129
setApp(props.app);
130
setHeight(MCP_APP_INLINE_MAX_HEIGHT);
131
+ setUri(null);
132
+ setLoaded(false);
133
+ setNavigatedAway(false);
134
+ setDocumentKeyState((value) => value + 1);
135
}
136
const fullscreen = props.displayMode === "fullscreen";
137
const navigation = useNavigation();
138
const insets = useSafeAreaInsets();
139
const [closed, setClosed] = useState(false);
140
const [presentedFullscreen, setPresentedFullscreen] = useState(false);
116
- const [documentKey, setDocumentKeyState] = useState(0);
141
142
const { themeId, themeAppearance, themeVariables, systemColorsActive } =
143
useAppearancePreferences();
@@ -140,11 +164,7 @@ export function ThreadMcpApp(props: {
164
[app],
165
);
166
const asset = useAssetUrlState(props.environmentId, resource);
143
- // The view keeps its first URL: a re-minted one would reload the app.
144
- const [uri, setUri] = useState<string | null>(null);
167
if (uri === null && asset._tag === "Success") setUri(asset.url);
146
- const [loaded, setLoaded] = useState(false);
147
- const [navigatedAway, setNavigatedAway] = useState(false);
168
const [generation, setGeneration] = useState(0);
169
const [crashed, setCrashed] = useState(false);
170
const restart = () => {
@@ -159,49 +179,41 @@ export function ThreadMcpApp(props: {
179
setGeneration(1);
180
};
181
const [secret] = useState(uuidv4);
162
- const setDocumentKey = (next: (value: number) => number) => {
182
+ const reopenDocument = () => {
183
setLoaded(false);
184
setHeight(MCP_APP_INLINE_MAX_HEIGHT);
185
setNavigatedAway(false);
186
if (asset._tag === "Success") setUri(asset.url);
167
- setDocumentKeyState(next);
187
+ setDocumentKeyState((value) => value + 1);
188
};
169
- const openNewDocument = useRef(setDocumentKey);
170
- useEffect(() => {
171
- openNewDocument.current = setDocumentKey;
189
+ const returnedFromFullscreen = useEffectEvent(() => {
190
+ reopenDocument();
191
+ setPresentedFullscreen(false);
192
});
193
+ // oxlint-disable-next-line t3code/react-effect-budget -- Navigation focus is outside React; listen only while the app is presented full screen, and stop on unmount.
194
useEffect(() => {
195
if (!presentedFullscreen) return;
175
- return navigation.addListener("focus", () => {
176
- openNewDocument.current((value) => value + 1);
177
- setPresentedFullscreen(false);
178
- });
196
+ return navigation.addListener("focus", () => returnedFromFullscreen());
197
}, [navigation, presentedFullscreen]);
198
181
- // The feed omits tool input and output; the app needs both.
182
- const detail = useEnvironmentQuery(
183
- orchestrationEnvironment.turnItem({
199
+ const detailAtom = orchestrationEnvironment.turnItem({
200
+ environmentId: props.environmentId,
201
+ input: { threadId: props.threadId, itemId: props.itemId, revision: props.revision },
202
+ });
203
+ const toolInfo = useEnvironmentQuery(
204
+ mcpAppEnvironment.toolInfoQuery({
205
environmentId: props.environmentId,
185
- input: { threadId: props.threadId, itemId: props.itemId, revision: props.revision },
206
+ input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
207
}),
208
);
188
- const storedItem = detail.data?.item;
189
- const toolCall = useMemo(() => {
190
- if (storedItem?.type !== "dynamic_tool") return undefined;
191
- const output = storedItem.output as { readonly result?: unknown } | undefined;
192
- return {
193
- arguments: storedItem.input,
194
- result: output?.result as McpAppCallToolResult | undefined,
195
- };
196
- }, [storedItem]);
209
+ const toolDefinition = toolInfo.data?.tool;
210
211
const callTool = useAtomCommand(mcpAppEnvironment.callTool, { reportFailure: false });
199
- const toolInfo = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
212
+ const toolInfoCommand = useAtomCommand(mcpAppEnvironment.toolInfo, { reportFailure: false });
213
const readResource = useAtomCommand(mcpAppEnvironment.readResource, { reportFailure: false });
214
const updateModelContext = useAtomCommand(mcpAppEnvironment.updateModelContext, {
215
reportFailure: false,
216
});
204
- const [toolDefinition, setToolDefinition] = useState<unknown>(undefined);
217
// Read current context per message without rebuilding the host and losing its session.
218
const conversation = useThreadShell(
219
scopeThreadRef(props.environmentId, props.conversationThreadId),
@@ -212,8 +224,9 @@ export function ThreadMcpApp(props: {
224
awaitingUser,
225
theme,
226
props,
227
+ asset,
228
callTool,
216
- toolInfo,
229
+ toolInfo: toolInfoCommand,
230
readResource,
231
updateModelContext,
232
insets,
@@ -221,237 +234,255 @@ export function ThreadMcpApp(props: {
234
navigation,
235
};
236
const latest = useRef(live);
237
+ // The attached WebView owns its host; state lets the tool-call effect pair
238
+ // a host only with an atom from a render after that host existed.
239
+ const [host, setHost] = useState<McpAppHost | null>(null);
240
useEffect(() => {
241
+ const previous = latest.current;
242
latest.current = live;
243
+ // Building the context is not free, so resend only when one of its inputs changed.
244
+ if (
245
+ previous.theme !== live.theme ||
246
+ previous.insets !== live.insets ||
247
+ previous.toolDefinition !== live.toolDefinition ||
248
+ previous.props.width !== live.props.width ||
249
+ previous.props.height !== live.props.height ||
250
+ previous.props.displayMode !== live.props.displayMode
251
+ ) {
252
+ host?.updateHostContext();
253
+ }
254
});
255
+ // The host sends the call once the app initializes, so a stored item that
256
+ // lands late still reaches it. A completed call can arrive under a new
257
+ // revision, which is a new atom, so the host follows the current one.
258
+ // oxlint-disable-next-line t3code/react-effect-budget -- subscribes the MCP host to the current tool call
259
useEffect(() => {
228
- let cancelled = false;
229
- void latest.current
230
- .toolInfo({
231
- environmentId: props.environmentId,
232
- input: { threadId: props.threadId, itemId: props.itemId, name: app.tool },
233
- })
234
- .then((info) => {
235
- if (!cancelled && info._tag === "Success" && info.value.tool !== undefined) {
236
- setToolDefinition(info.value.tool);
237
- }
238
- });
239
- return () => {
240
- cancelled = true;
241
- };
242
- }, [props.environmentId, props.threadId, props.itemId, app.tool]);
243
- const webView = useRef<WebView<object>>(null);
244
- const hostRef = useRef<McpAppHost | null>(null);
260
+ if (host === null) return;
261
+ return appAtomRegistry.subscribe(
262
+ detailAtom,
263
+ (result) => {
264
+ const call = AsyncResult.isSuccess(result) ? storedToolCall(result.value.item) : undefined;
265
+ if (call !== undefined) host.setToolCall(call);
266
+ },
267
+ { immediate: true },
268
+ );
269
+ }, [host, detailAtom]);
270
const userActive = useRef(false);
271
247
- useEffect(() => {
248
- if (uri === null) return;
249
- const scope = () => {
250
- const { environmentId, threadId, itemId } = latest.current.props;
251
- return { environmentId, input: { threadId, itemId } };
252
- };
253
- const hostContext = (): McpAppHostContext => {
254
- const current = latest.current;
255
- const isFullscreen = current.props.displayMode === "fullscreen";
256
- return {
257
- theme: current.theme.appearance,
258
- styles: { variables: mcpAppStyleVariables(current.theme.variables) },
259
- displayMode: isFullscreen ? "fullscreen" : "inline",
260
- availableDisplayModes: ["inline", "fullscreen"],
261
- containerDimensions: isFullscreen
262
- ? {
263
- width: current.props.width,
264
- height: current.props.height ?? MCP_APP_INLINE_MAX_HEIGHT,
265
- }
266
- : { width: current.props.width, maxHeight: MCP_APP_INLINE_MAX_HEIGHT },
267
- platform: "mobile",
268
- locale: Intl.DateTimeFormat().resolvedOptions().locale,
269
- timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
270
- userAgent: `t3-code/${Constants.expoConfig?.version ?? "0.0.0"}`,
271
- deviceCapabilities: { touch: true, hover: false },
272
- safeAreaInsets: isFullscreen
273
- ? { top: 0, right: current.insets.right, bottom: 0, left: current.insets.left }
274
- : { top: 0, right: 0, bottom: 0, left: 0 },
275
- ...(current.toolDefinition === undefined
276
- ? {}
277
- : { toolInfo: { tool: current.toolDefinition } }),
272
+ // Each WebView document gets its own host: the view is keyed by document,
273
+ // restart generation and URL, and a changed app re-attaches this callback.
274
+ // Any other identity change would tear the host down, so per-render values
275
+ // are read through `latest`, never captured.
276
+ const attachWebView = useCallback(
277
+ (view: WebView<object> | null) => {
278
+ if (view === null) return;
279
+ const reloadInline = () => {
280
+ setLoaded(false);
281
+ setHeight(MCP_APP_INLINE_MAX_HEIGHT);
282
+ setNavigatedAway(false);
283
+ const current = latest.current.asset;
284
+ if (current._tag === "Success") setUri(current.url);
285
+ setDocumentKeyState((value) => value + 1);
286
};
279
- };
280
- const next = makeMcpAppHost({
281
- app,
282
- hostVersion: Constants.expoConfig?.version ?? "0.0.0",
283
- post: (message) =>
284
- webView.current?.injectJavaScript(
285
- `window.__t3McpAppReceive&&window.__t3McpAppReceive(${JSON.stringify(message)});true;`,
286
- ),
287
- hostContext,
288
- callTool: async ({ name, arguments: args }) => {
289
- const { environmentId, input } = scope();
290
- const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
291
- if (info._tag !== "Success") throw commandFailure(info);
292
- if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
293
- if (
294
- !info.value.readOnly &&
295
- !(await confirm(
296
- `Allow ${app.server} to run ${info.value.title ?? name}?`,
297
- JSON.stringify(args, null, 2),
298
- "Allow",
299
- ))
300
- ) {
301
- throw new McpAppHostRefusal("Declined by the user.");
302
- }
303
- const result = await latest.current.callTool({
304
- environmentId,
305
- input: { ...input, name, arguments: args },
306
- });
307
- if (result._tag !== "Success") throw commandFailure(result);
308
- return result.value;
309
- },
310
- readResource: async ({ uri: resourceUri }) => {
311
- const { environmentId, input } = scope();
312
- const result = await latest.current.readResource({
313
- environmentId,
314
- input: { ...input, uri: resourceUri },
315
- });
316
- if (result._tag !== "Success") throw commandFailure(result);
317
- return result.value;
318
- },
319
- openLink: async (url) => {
320
- // WebViews cannot prove user activation; confirm links to prevent timer-driven navigation out of T3.
321
- if (!(await confirm(`Open a link from ${app.server}?`, url, "Open"))) {
322
- throw new McpAppHostRefusal("Declined by the user.");
323
- }
324
- if (!(await tryOpenExternalUrl(url, "mcp-app"))) {
325
- throw new McpAppHostRefusal("The link could not be opened.");
326
- }
327
- },
328
- sendMessage: async (text) => {
329
- if (!(await confirm(`Send this message from ${app.server}?`, text, "Send"))) {
330
- throw new McpAppHostRefusal("Declined by the user.");
331
- }
332
- await enqueueThreadOutboxMessage({
333
- environmentId: latest.current.props.environmentId,
334
- threadId: latest.current.props.conversationThreadId,
335
- messageId: MessageId.make(uuidv4()),
336
- commandId: CommandId.make(uuidv4()),
337
- text,
338
- attachments: [],
339
- dispatchMode: "queue",
340
- createdAt: new Date().toISOString(),
341
- });
342
- },
343
- updateModelContext: async (context) => {
344
- const { environmentId, input } = scope();
345
- const result = await latest.current.updateModelContext({
346
- environmentId,
347
- input: {
348
- ...input,
349
- ...context,
350
- conversationThreadId: latest.current.props.conversationThreadId,
351
- },
352
- });
353
- if (result._tag !== "Success") throw commandFailure(result);
354
- },
355
- requestDisplayMode: async (mode) => {
356
- const current = latest.current.props;
357
- // receive dispatches synchronously; read activation before awaiting teardown.
358
- if (
359
- mode === "fullscreen" &&
360
- (!userActive.current ||
361
- latest.current.awaitingUser ||
362
- !latest.current.navigation.isFocused())
363
- ) {
364
- return current.displayMode ?? "inline";
365
- }
366
- if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
367
- await hostRef.current?.teardown();
368
- // Approval arrival or navigation during the wait requires reloading inline.
369
- if (latest.current.awaitingUser || !latest.current.navigation.isFocused()) {
370
- openNewDocument.current((value) => value + 1);
371
- return "inline";
287
+ const scope = () => {
288
+ const { environmentId, threadId, itemId } = latest.current.props;
289
+ return { environmentId, input: { threadId, itemId } };
290
+ };
291
+ const hostContext = (): McpAppHostContext => {
292
+ const current = latest.current;
293
+ const isFullscreen = current.props.displayMode === "fullscreen";
294
+ return {
295
+ theme: current.theme.appearance,
296
+ styles: { variables: mcpAppStyleVariables(current.theme.variables) },
297
+ displayMode: isFullscreen ? "fullscreen" : "inline",
298
+ availableDisplayModes: ["inline", "fullscreen"],
299
+ containerDimensions: isFullscreen
300
+ ? {
301
+ width: current.props.width,
302
+ height: current.props.height ?? MCP_APP_INLINE_MAX_HEIGHT,
303
+ }
304
+ : { width: current.props.width, maxHeight: MCP_APP_INLINE_MAX_HEIGHT },
305
+ platform: "mobile",
306
+ locale: Intl.DateTimeFormat().resolvedOptions().locale,
307
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
308
+ userAgent: `t3-code/${Constants.expoConfig?.version ?? "0.0.0"}`,
309
+ deviceCapabilities: { touch: true, hover: false },
310
+ safeAreaInsets: isFullscreen
311
+ ? { top: 0, right: current.insets.right, bottom: 0, left: current.insets.left }
312
+ : { top: 0, right: 0, bottom: 0, left: 0 },
313
+ ...(current.toolDefinition === undefined
314
+ ? {}
315
+ : { toolInfo: { tool: current.toolDefinition } }),
316
+ };
317
+ };
318
+ const documentHost: McpAppHost = makeMcpAppHost({
319
+ app,
320
+ hostVersion: Constants.expoConfig?.version ?? "0.0.0",
321
+ post: (message) =>
322
+ view.injectJavaScript(
323
+ `window.__t3McpAppReceive&&window.__t3McpAppReceive(${JSON.stringify(message)});true;`,
324
+ ),
325
+ hostContext,
326
+ callTool: async ({ name, arguments: args }) => {
327
+ const { environmentId, input } = scope();
328
+ const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
329
+ if (info._tag !== "Success") throw commandFailure(info);
330
+ if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
331
+ if (
332
+ !info.value.readOnly &&
333
+ !(await confirm(
334
+ `Allow ${app.server} to run ${info.value.title ?? name}?`,
335
+ JSON.stringify(args, null, 2),
336
+ "Allow",
337
+ ))
338
+ ) {
339
+ throw new McpAppHostRefusal("Declined by the user.");
340
}
373
- setPresentedFullscreen(true);
374
- latest.current.navigation.navigate("ThreadMcpApp", {
375
- environmentId: String(current.environmentId),
376
- threadId: String(current.threadId),
377
- conversationThreadId: String(current.conversationThreadId),
378
- itemId: String(current.itemId),
379
- revision: current.revision,
341
+ const result = await latest.current.callTool({
342
+ environmentId,
343
+ input: { ...input, name, arguments: args },
344
});
381
- return "fullscreen";
382
- }
383
- if (mode === "inline" && current.displayMode === "fullscreen") {
384
- await hostRef.current?.teardown();
385
- current.onExitFullscreen?.();
386
- return "inline";
387
- }
388
- return current.displayMode ?? "inline";
389
- },
390
- downloadFile: async (files) => {
391
- const names = files.map((file) => file.name).join(", ");
392
- if (!(await confirm(`Save a file from ${app.server}?`, names, "Save"))) {
393
- throw new McpAppHostRefusal("Declined by the user.");
394
- }
395
- for (const file of files) {
396
- let bytes: Uint8Array | undefined;
397
- let mimeType = file.mimeType ?? "application/octet-stream";
398
- if (file._tag === "embedded") {
399
- bytes = file.bytes;
400
- } else {
401
- const { environmentId, input } = scope();
402
- const read = await latest.current.readResource({
403
- environmentId,
404
- input: { ...input, uri: file.uri },
405
- });
406
- if (read._tag !== "Success") throw commandFailure(read);
407
- const content = read.value.contents[0];
408
- bytes = mcpResourceBytes(content);
409
- const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
410
- if (typeof declared === "string") mimeType = declared;
345
+ if (result._tag !== "Success") throw commandFailure(result);
346
+ return result.value;
347
+ },
348
+ readResource: async ({ uri: resourceUri }) => {
349
+ const { environmentId, input } = scope();
350
+ const result = await latest.current.readResource({
351
+ environmentId,
352
+ input: { ...input, uri: resourceUri },
353
+ });
354
+ if (result._tag !== "Success") throw commandFailure(result);
355
+ return result.value;
356
+ },
357
+ openLink: async (url) => {
358
+ // WebViews cannot prove user activation; confirm links to prevent timer-driven navigation out of T3.
359
+ if (!(await confirm(`Open a link from ${app.server}?`, url, "Open"))) {
360
+ throw new McpAppHostRefusal("Declined by the user.");
361
}
412
- if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);
413
- if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
414
- throw new McpAppHostRefusal(`${file.name} is too large to save.`);
362
+ if (!(await tryOpenExternalUrl(url, "mcp-app"))) {
363
+ throw new McpAppHostRefusal("The link could not be opened.");
364
}
416
- const shared = await shareGeneratedAttachment({
417
- bytes,
418
- attachment: { name: file.name, mimeType },
419
- signal: new AbortController().signal,
365
+ },
366
+ sendMessage: async (text) => {
367
+ if (!(await confirm(`Send this message from ${app.server}?`, text, "Send"))) {
368
+ throw new McpAppHostRefusal("Declined by the user.");
369
+ }
370
+ await enqueueThreadOutboxMessage({
371
+ environmentId: latest.current.props.environmentId,
372
+ threadId: latest.current.props.conversationThreadId,
373
+ messageId: MessageId.make(uuidv4()),
374
+ commandId: CommandId.make(uuidv4()),
375
+ text,
376
+ attachments: [],
377
+ dispatchMode: "queue",
378
+ createdAt: new Date().toISOString(),
379
});
421
- if (!shared) throw new McpAppHostRefusal("Sharing is not available on this device.");
422
- }
423
- },
424
- onRequestTeardown: () => {
425
- const current = latest.current.props;
426
- if (current.displayMode === "fullscreen") {
427
- void hostRef.current?.teardown().then(() => current.onExitFullscreen?.());
428
- } else {
429
- void hostRef.current?.teardown().then(() => setClosed(true));
430
- }
431
- },
432
- onSizeChanged: (size) => {
433
- if (latest.current.props.displayMode === "fullscreen") return;
434
- const nextHeight = mcpAppInlineHeight(size.height);
435
- if (nextHeight !== undefined) setHeight(nextHeight);
436
- },
437
- });
438
- hostRef.current = next;
439
- return () => {
440
- // An unmount cannot wait: the request goes out before the view does.
441
- void next.teardown();
442
- hostRef.current = null;
443
- };
444
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A restarted view needs a new host.
445
- }, [uri, app, generation, documentKey]);
446
-
447
- useEffect(() => {
448
- hostRef.current?.updateHostContext();
449
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Context changes trigger a resend.
450
- }, [theme, props.width, props.height, insets, toolDefinition]);
451
- useEffect(() => {
452
- if (toolCall !== undefined) hostRef.current?.setToolCall(toolCall);
453
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each new document needs the call.
454
- }, [toolCall, uri, generation, documentKey]);
380
+ },
381
+ updateModelContext: async (context) => {
382
+ const { environmentId, input } = scope();
383
+ const result = await latest.current.updateModelContext({
384
+ environmentId,
385
+ input: {
386
+ ...input,
387
+ ...context,
388
+ conversationThreadId: latest.current.props.conversationThreadId,
389
+ },
390
+ });
391
+ if (result._tag !== "Success") throw commandFailure(result);
392
+ },
393
+ requestDisplayMode: async (mode) => {
394
+ const current = latest.current.props;
395
+ // receive dispatches synchronously; read activation before awaiting teardown.
396
+ if (
397
+ mode === "fullscreen" &&
398
+ (!userActive.current ||
399
+ latest.current.awaitingUser ||
400
+ !latest.current.navigation.isFocused())
401
+ ) {
402
+ return current.displayMode ?? "inline";
403
+ }
404
+ if (mode === "fullscreen" && current.displayMode !== "fullscreen") {
405
+ await documentHost.teardown();
406
+ // Approval arrival or navigation during the wait requires reloading inline.
407
+ const navigation = latest.current.navigation;
408
+ if (latest.current.awaitingUser || !navigation.isFocused()) {
409
+ reloadInline();
410
+ return "inline";
411
+ }
412
+ setPresentedFullscreen(true);
413
+ navigation.navigate("ThreadMcpApp", {
414
+ environmentId: String(current.environmentId),
415
+ threadId: String(current.threadId),
416
+ conversationThreadId: String(current.conversationThreadId),
417
+ itemId: String(current.itemId),
418
+ revision: current.revision,
419
+ });
420
+ return "fullscreen";
421
+ }
422
+ if (mode === "inline" && current.displayMode === "fullscreen") {
423
+ await documentHost.teardown();
424
+ current.onExitFullscreen?.();
425
+ return "inline";
426
+ }
427
+ return current.displayMode ?? "inline";
428
+ },
429
+ downloadFile: async (files) => {
430
+ const names = files.map((file) => file.name).join(", ");
431
+ if (!(await confirm(`Save a file from ${app.server}?`, names, "Save"))) {
432
+ throw new McpAppHostRefusal("Declined by the user.");
433
+ }
434
+ for (const file of files) {
435
+ let bytes: Uint8Array | undefined;
436
+ let mimeType = file.mimeType ?? "application/octet-stream";
437
+ if (file._tag === "embedded") {
438
+ bytes = file.bytes;
439
+ } else {
440
+ const { environmentId, input } = scope();
441
+ const read = await latest.current.readResource({
442
+ environmentId,
443
+ input: { ...input, uri: file.uri },
444
+ });
445
+ if (read._tag !== "Success") throw commandFailure(read);
446
+ const content = read.value.contents[0];
447
+ bytes = mcpResourceBytes(content);
448
+ const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
449
+ if (typeof declared === "string") mimeType = declared;
450
+ }
451
+ if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);
452
+ if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
453
+ throw new McpAppHostRefusal(`${file.name} is too large to save.`);
454
+ }
455
+ const shared = await shareGeneratedAttachment({
456
+ bytes,
457
+ attachment: { name: file.name, mimeType },
458
+ signal: new AbortController().signal,
459
+ });
460
+ if (!shared) throw new McpAppHostRefusal("Sharing is not available on this device.");
461
+ }
462
+ },
463
+ onRequestTeardown: () => {
464
+ const current = latest.current.props;
465
+ if (current.displayMode === "fullscreen") {
466
+ void documentHost.teardown().then(() => current.onExitFullscreen?.());
467
+ } else {
468
+ void documentHost.teardown().then(() => setClosed(true));
469
+ }
470
+ },
471
+ onSizeChanged: (size) => {
472
+ if (latest.current.props.displayMode === "fullscreen") return;
473
+ const nextHeight = mcpAppInlineHeight(size.height);
474
+ if (nextHeight !== undefined) setHeight(nextHeight);
475
+ },
476
+ });
477
+ setHost(documentHost);
478
+ return () => {
479
+ // An unmount cannot wait: the request goes out before the view does.
480
+ void documentHost.teardown();
481
+ setHost((current) => (current === documentHost ? null : current));
482
+ };
483
+ },
484
+ [app],
485
+ );
486
487
const source = useMemo(
488
() =>
@@ -486,7 +517,7 @@ export function ThreadMcpApp(props: {
517
label="Show app"
518
tone="secondary"
519
onPress={() => {
489
- setDocumentKey((value) => value + 1);
520
+ reopenDocument();
521
setClosed(false);
522
}}
523
/>
@@ -505,8 +536,8 @@ export function ThreadMcpApp(props: {
536
</View>
537
) : uri !== null && !crashed ? (
538
<WebView<object>
508
- key={`${documentKey}:${generation}`}
509
- ref={webView}
539
+ key={`${documentKey}:${generation}:${uri}`}
540
+ ref={attachWebView}
541
onContentProcessDidTerminate={restart}
542
onRenderProcessGone={restart}
543
source={source!}
@@ -534,12 +565,12 @@ export function ThreadMcpApp(props: {
565
if (!Predicate.isObject(envelope) || envelope.secret !== secret) return;
566
const message = envelope.message;
567
if (Predicate.isObject(message) && message.t3 === "navigated") {
537
- hostRef.current?.dispose();
568
+ host?.dispose();
569
setNavigatedAway(true);
570
return;
571
}
572
userActive.current = envelope.active === true;
542
- hostRef.current?.receive(message);
573
+ host?.receive(message);
574
userActive.current = false;
575
}}
576
/>
apps/mobile/src/state/device.ts
+17
-17
@@ -7,32 +7,32 @@ import { Atom } from "effect/reactivity";
7
import { useMemo } from "react";
8
9
import { connectionAtomRuntime } from "../connection/runtime";
10
-import { appAtomRegistry } from "./atom-registry";
10
import { useEnvironmentQuery } from "./query";
11
import { environmentSession, usePreparedConnection } from "./session";
12
13
export const deviceEnvironment = createDeviceEnvironmentAtoms(connectionAtomRuntime);
14
15
+// Hub tickets are single use, so each viewer resolves its own access: a new
16
+// viewer (a reload, a device switch, a return to the screen) never reuses a
17
+// ticket an earlier connection already spent.
18
const deviceHubAccessAtom = Atom.family((environmentId: EnvironmentId) =>
17
- connectionAtomRuntime
18
- .atom((get) => {
19
- const prepared = Option.getOrNull(
20
- get(environmentSession.preparedConnectionValueAtom(environmentId)),
21
- );
22
- return prepared === null
23
- ? Effect.never
24
- : resolveDeviceHubAccess({ prepared, hubBasePath: "/api/device-hub" });
25
- })
26
- .pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`mobile-device-hub-access:${environmentId}`)),
19
+ Atom.family((_viewer: string) =>
20
+ connectionAtomRuntime
21
+ .atom((get) => {
22
+ const prepared = Option.getOrNull(
23
+ get(environmentSession.preparedConnectionValueAtom(environmentId)),
24
+ );
25
+ return prepared === null
26
+ ? Effect.never
27
+ : resolveDeviceHubAccess({ prepared, hubBasePath: "/api/device-hub" });
28
+ })
29
+ .pipe(Atom.withLabel(`mobile-device-hub-access:${environmentId}`)),
30
+ ),
31
);
32
29
-export function refreshDeviceHubAccess(environmentId: EnvironmentId) {
30
- appAtomRegistry.refresh(deviceHubAccessAtom(environmentId));
31
-}
32
-
33
-export function useDeviceHubAccess(environmentId: EnvironmentId, hostId: string) {
33
+export function useDeviceHubAccess(environmentId: EnvironmentId, hostId: string, viewer: string) {
34
const prepared = usePreparedConnection(environmentId);
35
- const query = useEnvironmentQuery(deviceHubAccessAtom(environmentId));
35
+ const query = useEnvironmentQuery(deviceHubAccessAtom(environmentId)(viewer));
36
const access = useMemo(
37
() =>
38
query.data && query.error === null && Option.isSome(prepared)
apps/mobile/src/state/preview.ts
+23
-4
@@ -16,6 +16,7 @@ import { AsyncResult, Atom } from "effect/reactivity";
16
import { useMemo } from "react";
17
18
import { connectionAtomRuntime } from "../connection/runtime";
19
+import { appAtomRegistry } from "./atom-registry";
20
import { useEnvironmentQuery } from "./query";
21
import { environmentSession, usePreparedConnection } from "./session";
22
@@ -142,22 +143,40 @@ export function useThreadServerBrowserTabs(input: {
143
return { tabs: sessions, loaded: tabs.listed };
144
}
145
146
+// The earliest time the next access request may go out.
147
+const previewStreamNotBeforeAtom = Atom.family((environmentId: EnvironmentId) =>
148
+ Atom.make(0).pipe(Atom.withLabel(`mobile-preview-stream-retry:${environmentId}`)),
149
+);
150
+
151
const previewStreamAccessAtom = Atom.family((environmentId: EnvironmentId) =>
152
connectionAtomRuntime
153
.atom((get) => {
154
const prepared = Option.getOrNull(
155
get(environmentSession.preparedConnectionValueAtom(environmentId)),
156
);
151
- return prepared === null
152
- ? Effect.never
153
- : resolveDeviceHubAccess({ prepared, hubBasePath: PREVIEW_STREAM_BASE_PATH });
157
+ const notBefore = get(previewStreamNotBeforeAtom(environmentId));
158
+ if (prepared === null) return Effect.never;
159
+ const resolve = resolveDeviceHubAccess({ prepared, hubBasePath: PREVIEW_STREAM_BASE_PATH });
160
+ // A recompute interrupts the wait, so only the newest retry resolves.
161
+ const wait = notBefore - Date.now();
162
+ return wait > 0 ? Effect.andThen(Effect.sleep(wait), resolve) : resolve;
163
})
164
.pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`mobile-preview-stream-access:${environmentId}`)),
165
);
166
167
+/** Resolves fresh stream access once `delayMs` has passed. */
168
+function retryPreviewStreamAccess(environmentId: EnvironmentId, delayMs: number) {
169
+ appAtomRegistry.set(previewStreamNotBeforeAtom(environmentId), Date.now() + delayMs);
170
+}
171
+
172
export function usePreviewStreamAccess(environmentId: EnvironmentId) {
173
const prepared = usePreparedConnection(environmentId);
174
const query = useEnvironmentQuery(previewStreamAccessAtom(environmentId));
175
const access = query.data && query.error === null && Option.isSome(prepared) ? query.data : null;
162
- return { access, error: query.error, refresh: query.refresh };
176
+ return {
177
+ access,
178
+ error: query.error,
179
+ refresh: query.refresh,
180
+ retryAfter: (delayMs: number) => retryPreviewStreamAccess(environmentId, delayMs),
181
+ };
182
}
packages/client-runtime/src/mcpApps/host.test.ts
+27
@@ -130,6 +130,33 @@ describe("makeMcpAppHost", () => {
130
expect(sent.find((m) => m.id === 2)?.result).toEqual({ content: [] });
131
});
132
133
+ it("sends a later result for a call that had none, without repeating its input", () => {
134
+ const { host, sent } = setup();
135
+ initialize(host);
136
+ sent.length = 0;
137
+ host.setToolCall({ arguments: { city: "Oslo" }, result: undefined });
138
+ host.setToolCall({
139
+ arguments: { city: "Oslo" },
140
+ result: { content: [{ type: "text", text: "Sunny" }] },
141
+ });
142
+ host.setToolCall({
143
+ arguments: { city: "Bergen" },
144
+ result: { content: [{ type: "text", text: "Rain" }] },
145
+ });
146
+ expect(sent).toEqual([
147
+ {
148
+ jsonrpc: "2.0",
149
+ method: "ui/notifications/tool-input",
150
+ params: { arguments: { city: "Oslo" } },
151
+ },
152
+ {
153
+ jsonrpc: "2.0",
154
+ method: "ui/notifications/tool-result",
155
+ params: { content: [{ type: "text", text: "Sunny" }] },
156
+ },
157
+ ]);
158
+ });
159
+
160
it("accepts ui/message as one text block or the SDK's block array", async () => {
161
const messages: Array<string> = [];
162
const { host, sent } = setup({ sendMessage: async (text) => void messages.push(text) });
packages/client-runtime/src/mcpApps/host.ts
+10
-2
@@ -405,8 +405,16 @@ export function makeMcpAppHost(options: McpAppHostOptions): McpAppHost {
405
else handleNotification(method, params);
406
},
407
setToolCall: (call) => {
408
- toolCall ??= call;
409
- sendToolCall();
408
+ // A running call has no result yet; only its completion may replace it.
409
+ if (toolCall === undefined || !toolCallSent) {
410
+ if (toolCall?.result === undefined) toolCall = call;
411
+ sendToolCall();
412
+ return;
413
+ }
414
+ if (toolCall.result !== undefined || call.result === undefined) return;
415
+ // The app already has this call's input; it only needs the result.
416
+ toolCall = { arguments: toolCall.arguments, result: call.result };
417
+ notify("ui/notifications/tool-result", normalizeMcpAppToolResult(call.result));
418
},
419
updateHostContext: () => {
420
// The spec forbids messages before the app finishes initializing; it