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

main
tsx 332 lines 9.85 KB
Raw
1 import { Alert, AlertDescription } from "../ui/alert";
2 import type { AuthSessionState } from "@t3tools/contracts";
3 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4 import { msg, T, useGT, useMessages, Var } from "gt-react";
5 import React, { startTransition, useEffect, useEffectEvent, useRef, useState } from "react";
6
7 import { connectPairing } from "../../connection/onboarding";
8 import {
9 peekPairingTokenFromUrl,
10 stripPairingTokenFromUrl,
11 submitServerAuthCredential,
12 } from "../../environments/primary";
13 import { readHostedPairingRequest } from "../../hostedPairing";
14 import { Button } from "../ui/button";
15 import { Input } from "../ui/input";
16 import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
17 import { useAtomCommand } from "../../state/use-atom-command";
18 import { m, type MessageResolver } from "../../i18n/messages";
19
20 export function PairingPendingSurface() {
21 const gt = useGT();
22 return (
23 <StandalonePage>
24 <StandalonePageHeader
25 title={gt("Pairing with this environment")}
26 description={gt("Validating the pairing link and preparing your session.")}
27 />
28 </StandalonePage>
29 );
30 }
31
32 export function PairingRouteSurface({
33 auth,
34 initialErrorMessage,
35 onAuthenticated,
36 }: {
37 auth: AuthSessionState["auth"];
38 initialErrorMessage?: string;
39 onAuthenticated: () => void;
40 }) {
41 const gt = useGT();
42 const messages = useMessages();
43 const [autoPairToken] = useState(peekPairingTokenFromUrl);
44 const [credential, setCredential] = useState(autoPairToken ?? "");
45 const [errorMessage, setErrorMessage] = useState(initialErrorMessage ?? "");
46 const [isSubmitting, setIsSubmitting] = useState(false);
47 const autoSubmitAttemptedRef = useRef(false);
48
49 const submitCredential = async (nextCredential: string) => {
50 setIsSubmitting(true);
51 setErrorMessage("");
52
53 const submitError = await submitServerAuthCredential(nextCredential).then(
54 () => null,
55 (error) => errorMessageFromUnknown(error),
56 );
57
58 setIsSubmitting(false);
59
60 if (submitError) {
61 setErrorMessage(submitError);
62 return;
63 }
64
65 startTransition(() => {
66 onAuthenticated();
67 });
68 };
69
70 const handleSubmit = async (event?: React.SubmitEvent<HTMLFormElement>) => {
71 event?.preventDefault();
72 await submitCredential(credential);
73 };
74
75 const autoSubmit = useEffectEvent((token: string) => {
76 void submitCredential(token);
77 });
78
79 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- strips the pairing token from the URL and submits it once when the route carries one
80 useEffect(() => {
81 if (!autoPairToken || autoSubmitAttemptedRef.current) {
82 return;
83 }
84
85 autoSubmitAttemptedRef.current = true;
86 stripPairingTokenFromUrl();
87 autoSubmit(autoPairToken);
88 }, [autoPairToken]);
89
90 return (
91 <StandalonePage>
92 <StandalonePageHeader
93 title={gt("Pair with this environment")}
94 description={describeAuthGate(auth.bootstrapMethods, messages)}
95 />
96
97 <form className="mt-6 space-y-4" onSubmit={(event) => void handleSubmit(event)}>
98 <div className="space-y-2">
99 <label className="text-sm font-medium" htmlFor="pairing-token">
100 <T>Pairing token</T>
101 </label>
102 <Input
103 id="pairing-token"
104 autoCapitalize="none"
105 autoComplete="off"
106 autoCorrect="off"
107 disabled={isSubmitting}
108 nativeInput
109 onChange={(event) => setCredential(event.currentTarget.value)}
110 placeholder={gt("Paste a one-time token or pairing secret")}
111 spellCheck={false}
112 value={credential}
113 />
114 </div>
115
116 {errorMessage ? (
117 <Alert variant="error">
118 <AlertDescription>{errorMessage}</AlertDescription>
119 </Alert>
120 ) : null}
121
122 <div className="flex flex-wrap gap-2">
123 <Button disabled={isSubmitting} size="sm" type="submit">
124 {isSubmitting ? gt("Pairing...") : gt("Continue")}
125 </Button>
126 <Button
127 disabled={isSubmitting}
128 onClick={() => window.location.reload()}
129 size="sm"
130 variant="outline"
131 >
132 <T>Reload app</T>
133 </Button>
134 </div>
135 </form>
136
137 <div className="mt-6 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
138 {describeSupportedMethods(auth.bootstrapMethods, messages)}
139 </div>
140 </StandalonePage>
141 );
142 }
143
144 export function HostedPairingRouteSurface() {
145 const connectPairingEnvironment = useAtomCommand(connectPairing, {
146 reportFailure: false,
147 });
148 const [request] = useState(readHostedPairingRequest);
149 const gt = useGT();
150 const [status, setStatus] = useState<"pairing" | "paired" | "error">(
151 request ? "pairing" : "error",
152 );
153 const [message, setMessage] = useState(() =>
154 request
155 ? m(msg("Connecting to this backend."))
156 : m(msg("This pairing link is missing its backend host or token.")),
157 );
158 const [canRetry, setCanRetry] = useState(false);
159 const submitAttemptedRef = useRef(false);
160 const tokenSubmittedRef = useRef(false);
161
162 const submitHostedPairingRequest = async () => {
163 if (!request) {
164 setStatus("error");
165 setMessage(gt("This pairing link is missing its backend host or token."));
166 setCanRetry(false);
167 return;
168 }
169
170 if (tokenSubmittedRef.current) {
171 setStatus("error");
172 setMessage(
173 gt("This one-time pairing token was already submitted. Request a new pairing link."),
174 );
175 setCanRetry(false);
176 return;
177 }
178
179 setStatus("pairing");
180 setMessage(gt("Connecting to this backend."));
181 setCanRetry(false);
182 tokenSubmittedRef.current = true;
183
184 const result = await connectPairingEnvironment({
185 host: request.host,
186 pairingCode: request.token,
187 });
188 if (result._tag === "Success") {
189 setStatus("paired");
190 setMessage(
191 request.label
192 ? gt("{environment} is saved in this browser.", { environment: request.label })
193 : gt("The environment is saved in this browser."),
194 );
195 return;
196 }
197
198 tokenSubmittedRef.current = false;
199 setStatus("error");
200 setCanRetry(true);
201 setMessage(
202 gt(
203 "{error} If the backend accepted this one-time token, request a new pairing link before retrying.",
204 { error: errorMessageFromUnknown(squashAtomCommandFailure(result)) },
205 ),
206 );
207 };
208
209 const submitOnMount = useEffectEvent(() => {
210 void submitHostedPairingRequest();
211 });
212
213 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- strips the pairing token from the URL and submits the hosted pairing request once on mount
214 useEffect(() => {
215 if (submitAttemptedRef.current) {
216 return;
217 }
218 submitAttemptedRef.current = true;
219
220 stripPairingTokenFromUrl();
221 submitOnMount();
222 }, []);
223
224 return (
225 <StandalonePage>
226 <StandalonePageHeader
227 title={
228 status === "paired"
229 ? gt("Backend paired")
230 : status === "error"
231 ? gt("Pairing failed")
232 : gt("Pairing backend")
233 }
234 description={message}
235 />
236
237 {request ? (
238 <div className="mt-5 rounded-lg border border-border/70 bg-background/55 px-3 py-3 text-xs leading-relaxed text-muted-foreground">
239 <T>
240 Host:{" "}
241 <span className="font-mono text-foreground/80">
242 <Var>{request.host}</Var>
243 </span>
244 </T>
245 </div>
246 ) : null}
247
248 {status === "error" ? (
249 <Alert variant="error" className="mt-5">
250 <AlertDescription>
251 <T>
252 Verify the backend is reachable from this browser, supports CORS for hosted clients,
253 and is served over HTTPS when opening this page from HTTPS.
254 </T>
255 </AlertDescription>
256 </Alert>
257 ) : null}
258
259 <div className="mt-6 flex flex-wrap gap-2">
260 {status === "pairing" ? (
261 <Button disabled size="sm">
262 <T>Pairing...</T>
263 </Button>
264 ) : canRetry ? (
265 <Button size="sm" onClick={() => void submitHostedPairingRequest()}>
266 <T>Try again</T>
267 </Button>
268 ) : null}
269 {status === "paired" ? (
270 <Button size="sm" variant="outline" onClick={() => (window.location.href = "/")}>
271 <T>Open app</T>
272 </Button>
273 ) : null}
274 </div>
275 </StandalonePage>
276 );
277 }
278
279 function errorMessageFromUnknown(error: unknown): string {
280 if (error instanceof Error && error.message.trim().length > 0) {
281 return error.message;
282 }
283
284 if (typeof error === "string" && error.trim().length > 0) {
285 return error;
286 }
287
288 return m(msg("Authentication failed."));
289 }
290
291 function describeAuthGate(
292 bootstrapMethods: ReadonlyArray<string>,
293 resolve: MessageResolver,
294 ): string {
295 if (bootstrapMethods.includes("desktop-bootstrap")) {
296 return resolve(
297 msg("This environment expects a trusted pairing credential before the app can connect."),
298 );
299 }
300
301 return resolve(msg("Enter a pairing token to start a session with this environment."));
302 }
303
304 function describeSupportedMethods(
305 bootstrapMethods: ReadonlyArray<string>,
306 resolve: MessageResolver,
307 ): string {
308 if (
309 bootstrapMethods.includes("desktop-bootstrap") &&
310 bootstrapMethods.includes("one-time-token")
311 ) {
312 return resolve(
313 msg(
314 "Desktop-managed pairing and one-time pairing tokens are both accepted for this environment.",
315 ),
316 );
317 }
318
319 if (bootstrapMethods.includes("desktop-bootstrap")) {
320 return resolve(
321 msg(
322 "This environment is desktop-managed. Open it from the desktop app or paste a bootstrap credential if one was issued explicitly.",
323 ),
324 );
325 }
326
327 return resolve(
328 msg(
329 "This environment accepts one-time pairing tokens. Pairing links can open this page directly, or you can paste the token here.",
330 ),
331 );
332 }