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

main
tsx 221 lines 6.99 KB
Raw
1 import { useAuth, useClerk } from "@clerk/react";
2 import { useAtomValue } from "@effect/atom-react";
3 import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
4 import {
5 type ConnectMcpApprovalCall,
6 ConnectMcpApprovalUnavailableError,
7 } from "@t3tools/client-runtime/state/connectMcpApproval";
8 import { type AuthMcpApprovalDetails, EnvironmentId } from "@t3tools/contracts";
9 import * as Result from "effect/Result";
10 import * as Schema from "effect/Schema";
11 import { msg, T, useGT } from "gt-react";
12 import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
13
14 import { m } from "../../i18n/messages";
15
16 import { isElectron } from "../../env";
17 import { runConnectMcpApproval } from "../../state/connectMcpApproval";
18 import { resolveClerkSignInProps } from "../clerk/authRedirect";
19 import { retryClerkLoad, useClerkLoadFailed } from "../clerk/clerkLoadFailure";
20 import { Button } from "../ui/button";
21 import { Spinner } from "../ui/spinner";
22 import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
23 import {
24 type McpApprovalAnswer,
25 type McpApprovalTransport,
26 McpConsent,
27 readAuthorizationRequest,
28 } from "./ConnectAgentSurface";
29
30 const isUnavailable = Schema.is(ConnectMcpApprovalUnavailableError);
31
32 function readEnvironmentId(): EnvironmentId | null {
33 const value = new URL(window.location.href).searchParams.get("environment");
34 return value ? EnvironmentId.make(value) : null;
35 }
36
37 /** Sends each call with the owner's T3 Connect session and remembers where the environment is. */
38 function connectTransport(
39 environmentId: EnvironmentId,
40 onEnvironment: (environment: { readonly url: string; readonly label: string }) => void,
41 ): McpApprovalTransport {
42 const send = async (
43 call: ConnectMcpApprovalCall,
44 ): Promise<McpApprovalAnswer<AuthMcpApprovalDetails>> => {
45 const result = await runConnectMcpApproval(environmentId, call);
46 if (Result.isFailure(result)) {
47 return {
48 kind: "error",
49 message: isUnavailable(result.failure)
50 ? result.failure.message
51 : m(msg("Could not reach this environment. Try again.")),
52 };
53 }
54 onEnvironment({
55 url: result.success.environmentUrl,
56 label: result.success.environmentLabel,
57 });
58 const { answer } = result.success;
59 switch (answer.kind) {
60 case "details":
61 return { kind: "ok", value: answer.details };
62 case "redirect":
63 return { kind: "redirect", url: answer.url };
64 case "refused":
65 return { kind: "error", message: answer.message };
66 }
67 };
68 return {
69 load: (authorization) => send({ kind: "approval", payload: authorization }),
70 decide: (authorization, decision) =>
71 send({ kind: "decision", payload: { authorization, decision } }),
72 };
73 }
74
75 /**
76 * The consent screen for an agent sign-in on a T3 Connect environment: the owner signs in to
77 * T3 Connect here and approves with that session, so no sign-in code is needed.
78 */
79 export function ApproveAgentSurface() {
80 const gt = useGT();
81 const [environmentId] = useState(readEnvironmentId);
82 const [authorization] = useState(readAuthorizationRequest);
83 // Another site could frame this page and steer a click onto Approve.
84 const [framed] = useState(() => window.top !== window.self);
85 const [environment, setEnvironment] = useState<{
86 readonly url: string;
87 readonly label: string;
88 } | null>(null);
89 const [transport] = useState(() =>
90 environmentId === null ? null : connectTransport(environmentId, setEnvironment),
91 );
92 const clerk = useClerk();
93 const { isLoaded, isSignedIn } = useAuth();
94 const loadFailed = useClerkLoadFailed();
95 const session = useAtomValue(managedRelaySessionAtom);
96 const signInOpened = useRef(false);
97
98 const openSignIn = () =>
99 clerk.openSignIn(resolveClerkSignInProps(window.location.href, isElectron));
100 const openSignInOnLoad = useEffectEvent(openSignIn);
101
102 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens Clerk sign-in once Clerk has loaded and nobody is signed in
103 useEffect(() => {
104 if (!isLoaded || isSignedIn || signInOpened.current || framed) return;
105 signInOpened.current = true;
106 openSignInOnLoad();
107 }, [framed, isLoaded, isSignedIn]);
108
109 if (environmentId === null || transport === null) {
110 return (
111 <Message
112 title={gt("This sign-in link is incomplete")}
113 description={gt("Close this page and start the sign-in again from your agent.")}
114 />
115 );
116 }
117
118 if (framed) {
119 return (
120 <Message
121 title={gt("Open this page in its own window")}
122 description={gt("For your safety, agent sign-ins cannot be approved inside another site.")}
123 />
124 );
125 }
126
127 if (loadFailed) {
128 return (
129 <Message
130 title={gt("Could not load sign-in")}
131 description={gt("T3 Connect sign-in did not load. Check your connection, then try again.")}
132 >
133 <div className="mt-6">
134 <Button type="button" onClick={retryClerkLoad}>
135 <T>Retry sign-in</T>
136 </Button>
137 </div>
138 </Message>
139 );
140 }
141
142 if (!isLoaded || (isSignedIn && session === null)) {
143 return (
144 <StandalonePage>
145 <StandalonePageHeader
146 context={gt("Agent sign-in")}
147 title={gt("Connecting to T3 Connect")}
148 description={gt("One moment while your account loads.")}
149 />
150 <Spinner className="mt-6" size="lg" tone="muted" />
151 </StandalonePage>
152 );
153 }
154
155 if (!isSignedIn) {
156 return (
157 <Message
158 title={gt("Sign in to approve")}
159 description={gt("Sign in to T3 Connect with the account this environment is linked to.")}
160 >
161 <div className="mt-6">
162 <Button type="button" onClick={openSignIn}>
163 <T>Sign in</T>
164 </Button>
165 </div>
166 </Message>
167 );
168 }
169
170 const search = new URLSearchParams(window.location.search);
171 search.delete("environment");
172 return (
173 <McpConsent
174 authorization={authorization}
175 transport={transport}
176 requireLevelChoice
177 environmentLabel={environment?.label}
178 footer={
179 <div className="mt-6 flex flex-wrap gap-2">
180 {environment ? (
181 <Button
182 size="sm"
183 variant="link"
184 render={
185 <a href={`${new URL("/connect-agent", environment.url).toString()}?${search}`} />
186 }
187 >
188 <T>Use a sign-in code instead</T>
189 </Button>
190 ) : null}
191 <Button
192 size="sm"
193 variant="link"
194 onClick={() => void clerk.signOut({ redirectUrl: window.location.href })}
195 type="button"
196 >
197 <T>Use another account</T>
198 </Button>
199 </div>
200 }
201 />
202 );
203 }
204
205 function Message({
206 title,
207 description,
208 children,
209 }: {
210 readonly title: string;
211 readonly description: string;
212 readonly children?: ReactNode;
213 }) {
214 const gt = useGT();
215 return (
216 <StandalonePage>
217 <StandalonePageHeader context={gt("Agent sign-in")} title={title} description={description} />
218 {children}
219 </StandalonePage>
220 );
221 }