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

McpAppFullscreenScreen.tsx

156 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 { useEffect, useRef, 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 requested !== undefined && descendsFrom(shells, environmentId, requested, threadId)
33 ? ThreadId.make(requested)
34 : threadId;
36​
37function descendsFrom(
38 shells: ReadonlyArray<EnvironmentThreadShell>,
39 environmentId: EnvironmentId,
40 threadId: string,
41 ancestorId: ThreadId,
42): boolean {
43 const parents = new Map(
44 shells
45 .filter((shell) => shell.environmentId === environmentId)
46 .filter((shell) => shell.lineage.relationshipToParent === "fork")
47 .map((shell) => [shell.id as string, shell.lineage.parentThreadId]),
48 );
49 let current: string | null | undefined = threadId;
50 for (let depth = 0; depth < 64 && current != null; depth += 1) {
51 if (current === ancestorId) return true;
52 current = parents.get(current);
53 }
54 return false;
56​
57/** Resolve apps from stored tool calls so links cannot supply apps the call never produced. */
58export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) {
59 const navigation = useNavigation();
60 const insets = useSafeAreaInsets();
61 // Wait for focus before goBack; an exit under another screen must not pop that screen.
62 const focused = useIsFocused();
63 const exitPending = useRef(false);
64 const onClose = () => {
65 if (navigation.isFocused()) {
66 navigation.goBack();
67 return;
68 }
69 if (exitPending.current) return;
70 exitPending.current = true;
71 const unsubscribe = navigation.addListener("focus", () => {
72 unsubscribe();
73 navigation.goBack();
74 });
75 };
76 const [size, setSize] = useState({ width: 0, height: 0 });
77 const params = route.params;
78 const environmentId = EnvironmentId.make(params.environmentId);
79 const threadId = ThreadId.make(params.threadId);
80 const itemId = TurnItemId.make(params.itemId);
81 const conversationThreadId = useConversationThreadId(
82 environmentId,
83 threadId,
84 params.conversationThreadId,
85 );
86 const detail = useEnvironmentQuery(
87 orchestrationEnvironment.turnItem({
88 environmentId,
89 input: {
90 threadId,
91 itemId,
92 ...(params.revision === undefined ? {} : { revision: params.revision }),
93 },
94 }),
95 );
96 const item = detail.data?.item;
97 // Keep one reference per app; refetches must not rebuild the host.
98 const derived = item?.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
99 const [app, setApp] = useState(derived);
100 if (derived?.attachmentId !== app?.attachmentId) setApp(derived);
101 const conversation = useThreadShell(scopeThreadRef(environmentId, conversationThreadId));
102 const awaitingUser =
103 conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
104 // A request for the user is server state with no local handler to react in.
105 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the focused screen through the navigator when the server asks the user for input or approval
106 useEffect(() => {
107 if (awaitingUser && focused && !exitPending.current) navigation.goBack();
108 }, [awaitingUser, focused, navigation]);
109​
110 return (
111 <View className="flex-1 bg-screen" style={{ paddingTop: insets.top }}>
112 <View className="h-11 flex-row items-center justify-between px-3">
113 <Text className="text-base font-semibold text-foreground" numberOfLines={1}>
114 {app?.server ?? "App"}
115 </Text>
116 <Pressable
117 accessibilityRole="button"
118 accessibilityLabel="Exit full screen"
119 hitSlop={8}
120 onPress={onClose}
121 >
122 <SymbolView name="xmark" size={18} tintColor="gray" />
123 </Pressable>
124 </View>
125 <View
126 className="flex-1"
127 style={{ paddingBottom: insets.bottom }}
128 onLayout={(event) =>
129 setSize({
130 width: Math.round(event.nativeEvent.layout.width),
131 height: Math.round(event.nativeEvent.layout.height - insets.bottom),
132 })
133 }
134 >
135 {app === undefined ? (
136 detail.data === undefined ? null : (
137 <Text className="m-6 text-sm text-foreground-muted">This app cannot be shown.</Text>
138 )
139 ) : size.width > 0 ? (
140 <ThreadMcpApp
141 environmentId={environmentId}
142 threadId={threadId}
143 conversationThreadId={conversationThreadId}
144 itemId={itemId}
145 revision={params.revision ?? (item == null ? "" : turnItemDetailRevision(item))}
146 app={app}
147 width={size.width}
148 height={size.height}
149 displayMode="fullscreen"
150 onExitFullscreen={onClose}
151 />
152 ) : null}
153 </View>
154 </View>
155 );