Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpAppFullscreenScreen.tsx

157 lines5.9 KB

1import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
2import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
3import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
5import { mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
6import { useCallback, useEffect, useMemo, useState } from "react";
7import { Pressable, View } from "react-native";
8import { useSafeAreaInsets } from "react-native-safe-area-context";
9​
10import { AppText as Text } from "../../components/ui/AppText";
11import { SymbolView } from "../../components/ui/AppSymbol";
12import { orchestrationEnvironment } from "../../state/orchestration";
13import { scopeThreadRef } from "@t3tools/client-runtime/environment";
14import { useThreadShell, useThreadShells } from "../../state/entities";
15import { useEnvironmentQuery } from "../../state/query";
16import { ThreadMcpApp } from "./McpAppWebView";
17​
18type McpAppFullscreenScreenProps = StaticScreenProps<{
19 readonly environmentId: string;
20 readonly threadId: string;
21 readonly conversationThreadId?: string;
22 readonly itemId: string;
23 readonly revision?: string;
24}>;
25​
26function useConversationThreadId(
27 environmentId: EnvironmentId,
28 threadId: ThreadId,
29 requested: string | undefined,
30): ThreadId {
31 const shells = useThreadShells();
32 return useMemo(
33 () =>
34 requested !== undefined && descendsFrom(shells, environmentId, requested, threadId)
35 ? ThreadId.make(requested)
36 : threadId,
37 [shells, environmentId, threadId, requested],
38 );
40​
41function descendsFrom(
42 shells: ReadonlyArray<EnvironmentThreadShell>,
43 environmentId: EnvironmentId,
44 threadId: string,
45 ancestorId: ThreadId,
46): boolean {
47 const parents = new Map(
48 shells
49 .filter((shell) => shell.environmentId === environmentId)
50 .filter((shell) => shell.lineage.relationshipToParent === "fork")
51 .map((shell) => [shell.id as string, shell.lineage.parentThreadId]),
52 );
53 let current: string | null | undefined = threadId;
54 for (let depth = 0; depth < 64 && current != null; depth += 1) {
55 if (current === ancestorId) return true;
56 current = parents.get(current);
57 }
58 return false;
60​
61/**
62 * The app is read from its stored tool call, never from the route, so a link
63 * can only open an app that call really produced.
64 */
65export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) {
66 const navigation = useNavigation();
67 const insets = useSafeAreaInsets();
68 // A plain goBack pops whatever is on top, so it only runs while this modal
69 // is: an exit that lands while another screen covers it (after a teardown
70 // wait) waits for the modal to be on top again, rather than popping that
71 // screen or being lost.
72 const focused = useIsFocused();
73 const [exitRequested, setExitRequested] = useState(false);
74 const onClose = useCallback(() => {
75 if (navigation.isFocused()) navigation.goBack();
76 else setExitRequested(true);
77 }, [navigation]);
78 const [size, setSize] = useState({ width: 0, height: 0 });
79 const params = route.params;
80 const environmentId = EnvironmentId.make(params.environmentId);
81 const threadId = ThreadId.make(params.threadId);
82 const itemId = TurnItemId.make(params.itemId);
83 const conversationThreadId = useConversationThreadId(
84 environmentId,
85 threadId,
86 params.conversationThreadId,
87 );
88 const detail = useEnvironmentQuery(
89 orchestrationEnvironment.turnItem({
90 environmentId,
91 input: {
92 threadId,
93 itemId,
94 ...(params.revision === undefined ? {} : { revision: params.revision }),
95 },
96 }),
97 );
98 const item = detail.data?.item;
99 // One reference per app: the item is a new object on every refetch (a
100 // reconnect, for one), and a new reference would rebuild the app's host.
101 const derived = item?.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
102 const [app, setApp] = useState(derived);
103 if (derived?.attachmentId !== app?.attachmentId) setApp(derived);
104 const conversation = useThreadShell(scopeThreadRef(environmentId, conversationThreadId));
105 const awaitingUser =
106 conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
107 useEffect(() => {
108 if ((awaitingUser || exitRequested) && focused) navigation.goBack();
109 }, [awaitingUser, exitRequested, focused, navigation]);
110​
111 return (
112 <View className="flex-1 bg-screen" style={{ paddingTop: insets.top }}>
113 <View className="h-11 flex-row items-center justify-between px-3">
114 <Text className="text-base font-semibold text-foreground" numberOfLines={1}>
115 {app?.server ?? "App"}
116 </Text>
117 <Pressable
118 accessibilityRole="button"
119 accessibilityLabel="Exit full screen"
120 hitSlop={8}
121 onPress={onClose}
122 >
123 <SymbolView name="xmark" size={18} tintColor="gray" />
124 </Pressable>
125 </View>
126 <View
127 className="flex-1"
128 style={{ paddingBottom: insets.bottom }}
129 onLayout={(event) =>
130 setSize({
131 width: Math.round(event.nativeEvent.layout.width),
132 height: Math.round(event.nativeEvent.layout.height - insets.bottom),
133 })
134 }
135 >
136 {app === undefined ? (
137 detail.data === undefined ? null : (
138 <Text className="m-6 text-sm text-foreground-muted">This app cannot be shown.</Text>
139 )
140 ) : size.width > 0 ? (
141 <ThreadMcpApp
142 environmentId={environmentId}
143 threadId={threadId}
144 conversationThreadId={conversationThreadId}
145 itemId={itemId}
146 revision={params.revision ?? (item == null ? "" : turnItemDetailRevision(item))}
147 app={app}
148 width={size.width}
149 height={size.height}
150 displayMode="fullscreen"
151 onExitFullscreen={onClose}
152 />
153 ) : null}
154 </View>
155 </View>
156 );