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

ApproveAgentSurface.tsx

199 lines6.3 KB

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