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

main
tsx 214 lines 7.53 KB
Raw
1 import type { EnvironmentId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
2 import { useAtomValue } from "@effect/atom-react";
3 import { T, useGT } from "gt-react";
4 import { CheckIcon, CopyIcon, ExternalLinkIcon } from "lucide-react";
5 import { useId, useRef, useState, type KeyboardEvent } from "react";
6
7 import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
8 import { ensureLocalApi } from "../../localApi";
9 import { formatEnvironmentQueryError } from "../../state/query";
10 import { threadEnvironment } from "../../state/threads";
11 import { useAtomCommand } from "../../state/use-atom-command";
12 import { Button, InlineButton } from "../ui/button";
13 import {
14 Dialog,
15 DialogDescription,
16 DialogFooter,
17 DialogHeader,
18 DialogPanel,
19 DialogPopup,
20 DialogTitle,
21 } from "../ui/dialog";
22 import { Input } from "../ui/input";
23 import { toastManager } from "../ui/toast";
24
25 type SignIn =
26 | { readonly phase: "starting" }
27 | { readonly phase: "ready" | "finishing"; readonly url: string }
28 | { readonly phase: "failed"; readonly url: string | null; readonly message: string };
29
30 const stopRowToggle = (event: KeyboardEvent<HTMLElement>) => event.stopPropagation();
31
32 /**
33 * Signs an MCP server in from the notice that says it needs one. The agent
34 * keeps the credential; the user approves in a browser, then pastes back the
35 * address it lands on, which is often a localhost page on another machine.
36 */
37 export function McpSignInAction({
38 environmentId,
39 threadId,
40 providerThreadId,
41 server,
42 noticeAt,
43 }: {
44 readonly environmentId: EnvironmentId;
45 readonly threadId: ThreadId;
46 readonly providerThreadId: ProviderThreadId;
47 readonly server: string;
48 /** When the environment raised the notice, in epoch milliseconds. */
49 readonly noticeAt: number;
50 }) {
51 const gt = useGT();
52 const formId = useId();
53 const allowed = useAtomValue(threadEnvironment.mcpSignInStart.permissionAtom(environmentId));
54 const signedIn = useAtomValue(
55 threadEnvironment.mcpSignedInAtom(environmentId, { threadId, server, noticeAt }),
56 );
57 const start = useAtomCommand(threadEnvironment.mcpSignInStart, { reportFailure: false });
58 const complete = useAtomCommand(threadEnvironment.mcpSignInComplete, { reportFailure: false });
59 const { copyToClipboard, isCopied } = useCopyToClipboard();
60 const [signIn, setSignIn] = useState<SignIn | null>(null);
61 const [callbackUrl, setCallbackUrl] = useState("");
62 // Counts attempts, so a result that lands after a close or a restart changes nothing.
63 const attempt = useRef(0);
64 if (!allowed) return null;
65
66 const input = { threadId, providerThreadId, server };
67 const close = () => {
68 attempt.current += 1;
69 setSignIn(null);
70 };
71 const done = () => {
72 close();
73 toastManager.add({ type: "success", title: gt("Signed in to {server}", { server }) });
74 };
75 const begin = async () => {
76 const current = ++attempt.current;
77 setSignIn({ phase: "starting" });
78 setCallbackUrl("");
79 const result = await start({ environmentId, input });
80 if (current !== attempt.current) return;
81 if (result._tag === "Failure") {
82 setSignIn({ phase: "failed", url: null, message: formatEnvironmentQueryError(result.cause) });
83 } else if (result.value.authorizationUrl === null) {
84 done();
85 } else {
86 setSignIn({ phase: "ready", url: result.value.authorizationUrl });
87 }
88 };
89 const finish = async (url: string) => {
90 if (callbackUrl.trim().length === 0) return;
91 const current = attempt.current;
92 setSignIn({ phase: "finishing", url });
93 const result = await complete({
94 environmentId,
95 input: { ...input, callbackUrl: callbackUrl.trim() },
96 });
97 if (current !== attempt.current) return;
98 if (result._tag === "Failure") {
99 setSignIn({ phase: "failed", url, message: formatEnvironmentQueryError(result.cause) });
100 } else {
101 done();
102 }
103 };
104 const url = signIn !== null && signIn.phase !== "starting" ? signIn.url : null;
105
106 return (
107 <>
108 {signedIn ? (
109 <span className="shrink-0 text-sm text-success-foreground">
110 <T>Signed in</T>
111 </span>
112 ) : (
113 <InlineButton
114 aria-label={gt("Sign in to {server}", { server })}
115 onClick={(event) => {
116 event.stopPropagation();
117 void begin();
118 }}
119 onKeyDown={stopRowToggle}
120 >
121 <T>Sign in</T>
122 </InlineButton>
123 )}
124 <Dialog
125 open={signIn !== null}
126 onOpenChange={(open) => {
127 if (!open) close();
128 }}
129 >
130 <DialogPopup className="max-w-lg">
131 <DialogHeader>
132 <DialogTitle>{gt("Sign in to {server}", { server })}</DialogTitle>
133 <DialogDescription>
134 <T>
135 Approve access in your browser. It then opens a page that may not load: copy that
136 page's address and paste it here.
137 </T>
138 </DialogDescription>
139 </DialogHeader>
140 <DialogPanel>
141 {signIn?.phase === "starting" ? (
142 <p className="text-sm text-muted-foreground">
143 <T>Starting the sign-in…</T>
144 </p>
145 ) : null}
146 {url !== null ? (
147 <form
148 id={formId}
149 className="grid gap-4"
150 onSubmit={(event) => {
151 event.preventDefault();
152 void finish(url);
153 }}
154 >
155 <div className="flex flex-wrap gap-2">
156 <Button
157 variant="outline"
158 size="sm"
159 onClick={() => void ensureLocalApi().shell.openExternal(url)}
160 >
161 <ExternalLinkIcon aria-hidden />
162 <T>Open sign-in page</T>
163 </Button>
164 <Button variant="ghost" size="sm" onClick={() => copyToClipboard(url)}>
165 {isCopied ? <CheckIcon aria-hidden /> : <CopyIcon aria-hidden />}
166 <T>Copy link</T>
167 </Button>
168 </div>
169 <label className="grid gap-1.5 text-sm">
170 <T>Address of the page your browser opened</T>
171 <Input
172 // Browsers can hide `http://`, which the environment adds back.
173 inputMode="url"
174 autoComplete="off"
175 spellCheck={false}
176 value={callbackUrl}
177 maxLength={16_384}
178 disabled={signIn?.phase === "finishing"}
179 onChange={(event) => setCallbackUrl(event.target.value)}
180 />
181 </label>
182 </form>
183 ) : null}
184 {signIn?.phase === "failed" ? (
185 <p role="alert" className="mt-3 text-sm text-destructive-foreground">
186 {signIn.message}
187 </p>
188 ) : null}
189 </DialogPanel>
190 <DialogFooter variant="bare">
191 <Button variant="outline" onClick={close}>
192 <T>Cancel</T>
193 </Button>
194 {url === null && signIn?.phase === "failed" ? (
195 <Button onClick={() => void begin()}>
196 <T>Try again</T>
197 </Button>
198 ) : (
199 <Button
200 type="submit"
201 form={formId}
202 disabled={
203 url === null || signIn?.phase === "finishing" || callbackUrl.trim().length === 0
204 }
205 >
206 <T>Finish sign-in</T>
207 </Button>
208 )}
209 </DialogFooter>
210 </DialogPopup>
211 </Dialog>
212 </>
213 );
214 }