The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 186 lines 6.42 KB
Raw
1 import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
2 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 { T, useGT } from "gt-react-native";
7 import { useEffect, useRef, useState } from "react";
8 import { View } from "react-native";
9 import { useSafeAreaInsets } from "react-native-safe-area-context";
10
11 import { AppText as Text } from "../../components/ui/AppText";
12 import { AppBar } from "../../components/ui/AppBar";
13 import { orchestrationEnvironment } from "../../state/orchestration";
14 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
15 import { useThreadShell, useThreadShells } from "../../state/entities";
16 import { useEnvironmentQuery } from "../../state/query";
17 import { ThreadMcpApp } from "./McpAppWebView";
18
19 type McpAppFullscreenScreenProps = StaticScreenProps<{
20 readonly environmentId: string;
21 readonly threadId: string;
22 readonly conversationThreadId?: string;
23 readonly itemId: string;
24 readonly revision?: string;
25 }>;
26
27 function useConversationThreadId(
28 environmentId: EnvironmentId,
29 threadId: ThreadId,
30 requested: string | undefined,
31 ): ThreadId {
32 const shells = useThreadShells();
33 return requested !== undefined && descendsFrom(shells, environmentId, requested, threadId)
34 ? ThreadId.make(requested)
35 : threadId;
36 }
37
38 function descendsFrom(
39 shells: ReadonlyArray<EnvironmentThreadShell>,
40 environmentId: EnvironmentId,
41 threadId: string,
42 ancestorId: ThreadId,
43 ): boolean {
44 const parents = new Map(
45 shells
46 .filter((shell) => shell.environmentId === environmentId)
47 .filter((shell) => shell.lineage.relationshipToParent === "fork")
48 .map((shell) => [shell.id as string, shell.lineage.parentThreadId]),
49 );
50 let current: string | null | undefined = threadId;
51 for (let depth = 0; depth < 64 && current != null; depth += 1) {
52 if (current === ancestorId) return true;
53 current = parents.get(current);
54 }
55 return false;
56 }
57
58 /** Resolve apps from stored tool calls so links cannot supply apps the call never produced. */
59 export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) {
60 const gt = useGT();
61 const navigation = useNavigation();
62 const { environmentId, threadId, itemId } = route.params;
63 if (!environmentId?.trim() || !threadId?.trim() || !itemId?.trim()) {
64 return (
65 <View className="flex-1 bg-screen">
66 <AppBar
67 title={gt("App")}
68 onClose={() => navigation.goBack()}
69 closeAccessibilityLabel={gt("Exit full screen")}
70 />
71 <Text className="m-6 text-sm text-foreground-muted">
72 <T>This app cannot be shown.</T>
73 </Text>
74 </View>
75 );
76 }
77 return (
78 <McpAppFullscreen
79 params={route.params}
80 environmentId={EnvironmentId.make(environmentId)}
81 threadId={ThreadId.make(threadId)}
82 itemId={TurnItemId.make(itemId)}
83 />
84 );
85 }
86
87 function McpAppFullscreen({
88 params,
89 environmentId,
90 threadId,
91 itemId,
92 }: {
93 readonly params: McpAppFullscreenScreenProps["route"]["params"];
94 readonly environmentId: EnvironmentId;
95 readonly threadId: ThreadId;
96 readonly itemId: TurnItemId;
97 }) {
98 const gt = useGT();
99 const navigation = useNavigation();
100 const insets = useSafeAreaInsets();
101 // Wait for focus before goBack; an exit under another screen must not pop that screen.
102 const focused = useIsFocused();
103 const exitPending = useRef(false);
104 const onClose = () => {
105 if (navigation.isFocused()) {
106 navigation.goBack();
107 return;
108 }
109 if (exitPending.current) return;
110 exitPending.current = true;
111 const unsubscribe = navigation.addListener("focus", () => {
112 unsubscribe();
113 navigation.goBack();
114 });
115 };
116 const [size, setSize] = useState({ width: 0, height: 0 });
117 const conversationThreadId = useConversationThreadId(
118 environmentId,
119 threadId,
120 params.conversationThreadId,
121 );
122 const detail = useEnvironmentQuery(
123 orchestrationEnvironment.turnItem({
124 environmentId,
125 input: {
126 threadId,
127 itemId,
128 ...(params.revision === undefined ? {} : { revision: params.revision }),
129 },
130 }),
131 );
132 const item = detail.data?.item;
133 // Keep one reference per app; refetches must not rebuild the host.
134 const derived = item?.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
135 const [app, setApp] = useState(derived);
136 if (derived?.attachmentId !== app?.attachmentId) setApp(derived);
137 const conversation = useThreadShell(scopeThreadRef(environmentId, conversationThreadId));
138 const awaitingUser =
139 conversation?.hasPendingApprovals === true || conversation?.hasPendingUserInput === true;
140 // A request for the user is server state with no local handler to react in.
141 // 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
142 useEffect(() => {
143 if (awaitingUser && focused && !exitPending.current) navigation.goBack();
144 }, [awaitingUser, focused, navigation]);
145
146 return (
147 <View className="flex-1 bg-screen">
148 <AppBar
149 title={app?.server ?? gt("App")}
150 onClose={onClose}
151 closeAccessibilityLabel={gt("Exit full screen")}
152 />
153 <View
154 className="flex-1"
155 style={{ paddingBottom: insets.bottom }}
156 onLayout={(event) =>
157 setSize({
158 width: Math.round(event.nativeEvent.layout.width),
159 height: Math.round(event.nativeEvent.layout.height - insets.bottom),
160 })
161 }
162 >
163 {app === undefined ? (
164 detail.data === undefined ? null : (
165 <Text className="m-6 text-sm text-foreground-muted">
166 <T>This app cannot be shown.</T>
167 </Text>
168 )
169 ) : size.width > 0 ? (
170 <ThreadMcpApp
171 environmentId={environmentId}
172 threadId={threadId}
173 conversationThreadId={conversationThreadId}
174 itemId={itemId}
175 revision={params.revision ?? (item == null ? "" : turnItemDetailRevision(item))}
176 app={app}
177 width={size.width}
178 height={size.height}
179 displayMode="fullscreen"
180 onExitFullscreen={onClose}
181 />
182 ) : null}
183 </View>
184 </View>
185 );
186 }