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

main
tsx 175 lines 5.88 KB
Raw
1 import type { EnvironmentId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import {
4 type AtomCommandResult,
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7 } from "@t3tools/client-runtime/state/runtime";
8 import * as Haptics from "expo-haptics";
9 import { msg, T, useGT, useMessages } from "gt-react-native";
10 import { useRef, useState } from "react";
11 import { ScrollView } from "react-native";
12 import { useSafeAreaInsets } from "react-native-safe-area-context";
13
14 import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
15 import { Button } from "../../components/ui/Button";
16 import { Sheet } from "../../components/ui/Sheet";
17 import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
18 import { threadEnvironment } from "../../state/threads";
19 import { useAtomCommand } from "../../state/use-atom-command";
20
21 export interface McpSignInTarget {
22 readonly threadId: ThreadId;
23 readonly providerThreadId: ProviderThreadId;
24 readonly server: string;
25 }
26
27 /**
28 * Signs an agent's MCP server in from the notice that says it needs one. The
29 * agent keeps the credential; the user approves in a browser, then pastes back
30 * the address it lands on, which is often a localhost page on another machine.
31 */
32 export function McpSignInSheet(props: {
33 readonly environmentId: EnvironmentId;
34 readonly target: McpSignInTarget;
35 readonly onClose: () => void;
36 }) {
37 const gt = useGT();
38 const m = useMessages();
39 const insets = useSafeAreaInsets();
40 const { server } = props.target;
41 const start = useAtomCommand(threadEnvironment.mcpSignInStart, {
42 label: "start MCP sign-in",
43 reportFailure: false,
44 reportDefect: false,
45 });
46 const complete = useAtomCommand(threadEnvironment.mcpSignInComplete, {
47 label: "finish MCP sign-in",
48 reportFailure: false,
49 reportDefect: false,
50 });
51 const [url, setUrl] = useState<string | null>(null);
52 const [callbackUrl, setCallbackUrl] = useState("");
53 const [busy, setBusy] = useState(false);
54 const [error, setError] = useState<string | null>(null);
55 // A result that lands after the sheet closed must not open a browser or report anything.
56 const closed = useRef(false);
57 const close = () => {
58 closed.current = true;
59 props.onClose();
60 };
61
62 const failed = (result: AtomCommandResult<unknown, unknown> & { readonly _tag: "Failure" }) => {
63 if (isAtomCommandInterrupted(result)) return;
64 setError(
65 errorDisplayMessage(squashAtomCommandFailure(result), m) ??
66 m(msg("The sign-in couldn't continue. Try again.")),
67 );
68 };
69 // The command marks the server signed in for the thread, which every notice about it shows.
70 const signedIn = () => {
71 void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
72 close();
73 };
74 const openSignInPage = async () => {
75 setBusy(true);
76 setError(null);
77 let page = url;
78 if (page === null) {
79 const result = await start({ environmentId: props.environmentId, input: props.target });
80 if (closed.current) return;
81 if (result._tag === "Failure") {
82 setBusy(false);
83 failed(result);
84 return;
85 }
86 if (result.value.authorizationUrl === null) {
87 setBusy(false);
88 signedIn();
89 return;
90 }
91 page = result.value.authorizationUrl;
92 setUrl(page);
93 }
94 setBusy(false);
95 if (!(await tryOpenExternalUrl(page, "provider-auth"))) {
96 setError(gt("Could not open the sign-in page."));
97 }
98 };
99 const finish = async () => {
100 const pasted = callbackUrl.trim();
101 if (pasted.length === 0) return;
102 setBusy(true);
103 setError(null);
104 const result = await complete({
105 environmentId: props.environmentId,
106 input: { ...props.target, callbackUrl: pasted },
107 });
108 if (closed.current) return;
109 setBusy(false);
110 if (result._tag === "Success") signedIn();
111 else failed(result);
112 };
113
114 return (
115 <Sheet title={gt("Sign in to {server}", { server })} onClose={close}>
116 <ScrollView
117 className="flex-1 bg-sheet-solid"
118 contentInsetAdjustmentBehavior="automatic"
119 contentContainerClassName="gap-5 p-5"
120 contentContainerStyle={{ paddingBottom: insets.bottom + 20 }}
121 keyboardShouldPersistTaps="handled"
122 >
123 <Text className="font-sans text-sm leading-5 text-foreground-muted">
124 <T>
125 Approve access in your browser. It then opens a page that may not load: copy that page's
126 address and paste it here.
127 </T>
128 </Text>
129 <Button
130 label={gt("Open sign-in page")}
131 icon="globe"
132 tone="secondary"
133 disabled={busy}
134 onPress={() => void openSignInPage()}
135 fullWidth
136 />
137 {url !== null ? (
138 <TextInput
139 accessibilityLabel={gt("Address of the page your browser opened")}
140 placeholder="http://127.0.0.1:…/callback?code=…"
141 value={callbackUrl}
142 onChangeText={setCallbackUrl}
143 editable={!busy}
144 autoCorrect={false}
145 autoCapitalize="none"
146 keyboardType="url"
147 spellCheck={false}
148 returnKeyType="done"
149 onSubmitEditing={() => void finish()}
150 />
151 ) : null}
152 {error !== null ? (
153 <Text
154 accessibilityRole="alert"
155 accessibilityLiveRegion="polite"
156 className="font-sans text-sm text-danger-foreground"
157 >
158 {error}
159 </Text>
160 ) : null}
161 {url !== null ? (
162 <Button
163 label={gt("Finish sign-in")}
164 tone="primary"
165 loading={busy}
166 disabled={busy || callbackUrl.trim().length === 0}
167 onPress={() => void finish()}
168 fullWidth
169 />
170 ) : null}
171 <Button label={gt("Cancel")} tone="secondary" onPress={close} fullWidth />
172 </ScrollView>
173 </Sheet>
174 );
175 }