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

main
tsx 293 lines 10.6 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { m } from "~/i18n/messages";
3 import type { EnvironmentId, SourceControlSignInPrompt } from "@t3tools/contracts";
4 import {
5 readHostCredentialSettings,
6 type SourceControlAppSignIn,
7 type SourceControlDefinition,
8 } from "@t3tools/client-runtime/source-control-clients";
9 import { useAtomValue } from "@effect/atom-react";
10 import * as Cause from "effect/Cause";
11 import { msg, T, useGT, Var } from "gt-react";
12 import { CheckIcon, ExternalLinkIcon, CopyIcon } from "lucide-react";
13 import { useState, type ReactNode } from "react";
14
15 import { T3AppIcon } from "~/components/T3AppIcon";
16 import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
17 import { useEnvironmentSettings } from "../../hooks/useSettings";
18 import { cn } from "../../lib/utils";
19 import { serverEnvironment } from "../../state/server";
20 import { sourceControlEnvironment } from "../../state/sourceControl";
21 import { useAtomCommand } from "../../state/use-atom-command";
22 import { Button, InlineButton } from "../ui/button";
23 import { Spinner } from "../ui/spinner";
24 import { RedactedSensitiveText } from "./RedactedSensitiveText";
25
26 type SignInState =
27 | { readonly status: "idle" }
28 | { readonly status: "starting" }
29 | { readonly status: "waiting"; readonly prompt: SourceControlSignInPrompt }
30 | { readonly status: "failed"; readonly message: string };
31
32 const failureMessage = (cause: Cause.Cause<unknown>) => {
33 const error = Cause.squash(cause);
34 return error instanceof Error ? (thrownErrorMessage(error, m) ?? error.message) : String(error);
35 };
36
37 const expiryTime = (expiresAt: number) =>
38 new Date(expiresAt).toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
39
40 function ExternalLink(props: { readonly href: string; readonly children: ReactNode }) {
41 return (
42 <InlineButton render={<a href={props.href} target="_blank" rel="noreferrer noopener" />}>
43 {props.children}
44 <ExternalLinkIcon aria-hidden className="size-3" />
45 </InlineButton>
46 );
47 }
48
49 function AppMark(props: { readonly signedIn: boolean }) {
50 return (
51 <div className="relative size-10 shrink-0">
52 <T3AppIcon className="size-full" />
53 {props.signedIn ? (
54 <span className="absolute -right-1 -bottom-1 grid size-4 place-items-center rounded-full bg-success text-white ring-2 ring-card">
55 <CheckIcon aria-hidden className="size-2.5" strokeWidth={3} />
56 </span>
57 ) : null}
58 </div>
59 );
60 }
61
62 /** The device code, one cell per character, as GitHub prints it. */
63 function DeviceCode(props: { readonly code: string }) {
64 return (
65 <div className="flex items-center gap-1 font-mono text-lg font-medium">
66 <span className="sr-only">{props.code}</span>
67 {Array.from(props.code, (char, index) =>
68 char === "-" ? (
69 <span key={index} aria-hidden className="px-0.5 text-muted-foreground">
70 –
71 </span>
72 ) : (
73 <span
74 key={index}
75 aria-hidden
76 className="grid h-10 w-8 place-items-center rounded-md border border-border bg-background shadow-xs"
77 >
78 {char}
79 </span>
80 ),
81 )}
82 </div>
83 );
84 }
85
86 export function SourceControlAppSignInSettings({
87 environmentId,
88 definition,
89 appSignIn,
90 account,
91 onChanged,
92 }: {
93 readonly environmentId: EnvironmentId;
94 readonly definition: SourceControlDefinition;
95 readonly appSignIn: SourceControlAppSignIn;
96 /** The login discovery reports, which is the signed-in account when no token overrides it. */
97 readonly account: string | null;
98 readonly onChanged: () => void;
99 }) {
100 const gt = useGT();
101 const host = appSignIn.hosts[0] ?? "";
102 const { signIns, tokens } = useEnvironmentSettings(environmentId, (settings) =>
103 readHostCredentialSettings(settings, definition.kind),
104 );
105 const signedIn = (signIns[host] ?? "").length > 0;
106 const token = tokens[host];
107 // A token read from a secret provider overrides the sign-in like a saved one.
108 const tokenOverrides = typeof token === "string" ? token.length > 0 : token !== undefined;
109 const canSignIn = useAtomValue(
110 sourceControlEnvironment.startSignIn.permissionAtom(environmentId),
111 );
112 const start = useAtomCommand(sourceControlEnvironment.startSignIn, { reportFailure: false });
113 const wait = useAtomCommand(sourceControlEnvironment.waitForSignIn, { reportFailure: false });
114 const cancel = useAtomCommand(sourceControlEnvironment.cancelSignIn, { reportFailure: false });
115 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
116 label: `sign out of ${appSignIn.appName}`,
117 });
118 const { copyToClipboard, isCopied } = useCopyToClipboard({
119 timeout: 1500,
120 target: {
121 target: "sign-in code",
122 unavailableMessage: msg("Clipboard API is unavailable while copying sign-in code."),
123 failureMessage: msg("Failed to copy sign-in code to the clipboard."),
124 },
125 });
126 const [state, setState] = useState<SignInState>({ status: "idle" });
127
128 const signIn = async () => {
129 setState({ status: "starting" });
130 const input = { provider: definition.kind, host };
131 const started = await start({ environmentId, input });
132 if (started._tag !== "Success") {
133 setState({ status: "failed", message: failureMessage(started.cause) });
134 return;
135 }
136 const prompt = started.value;
137 setState({ status: "waiting", prompt });
138 const finished = await wait({ environmentId, input });
139 // A newer attempt, a cancel, or a sign-out owns the state by now.
140 setState((current) => {
141 if (current.status !== "waiting" || current.prompt !== prompt) return current;
142 return finished._tag === "Success"
143 ? { status: "idle" }
144 : { status: "failed", message: failureMessage(finished.cause) };
145 });
146 if (finished._tag === "Success") onChanged();
147 };
148
149 const signOut = async () => {
150 setState({ status: "idle" });
151 const result = await updateSettings({
152 environmentId,
153 // Send the whole map; other hosts' redaction markers preserve their sessions.
154 input: {
155 patch: {
156 sourceControlHosts: { [definition.kind]: { signIns: { ...signIns, [host]: "" } } },
157 },
158 },
159 });
160 if (result._tag === "Success") onChanged();
161 };
162
163 const waiting = !signedIn && state.status === "waiting" ? state.prompt : null;
164
165 let subtitle: ReactNode;
166 let action: ReactNode;
167 if (signedIn) {
168 subtitle =
169 account !== null && !tokenOverrides ? (
170 <span className="flex min-w-0 items-center gap-1">
171 <T>
172 Signed in as
173 <RedactedSensitiveText
174 value={account}
175 ariaLabel={gt("Signed-in GitHub account")}
176 revealTooltip={gt("Show account")}
177 hideTooltip={gt("Hide account")}
178 />
179 </T>
180 </span>
181 ) : tokenOverrides ? (
182 gt("Signed in, but the token saved below is used while it can be read.")
183 ) : (
184 gt("Signed in")
185 );
186 action = (
187 <Button size="xs" variant="outline" disabled={!canSignIn} onClick={() => void signOut()}>
188 <T>Sign out</T>
189 </Button>
190 );
191 } else if (waiting !== null) {
192 subtitle = gt("Approve the app on GitHub to finish signing in.");
193 action = (
194 <Button
195 size="xs"
196 variant="ghost"
197 onClick={() => {
198 setState({ status: "idle" });
199 void cancel({ environmentId, input: { provider: definition.kind, host } });
200 }}
201 >
202 <T>Cancel</T>
203 </Button>
204 );
205 } else {
206 subtitle = gt("A far higher GitHub API rate limit than a personal token or gh login.");
207 action = (
208 <Button
209 size="xs"
210 disabled={!canSignIn || state.status === "starting"}
211 onClick={() => void signIn()}
212 >
213 {state.status === "starting" ? <Spinner /> : null}
214 {state.status === "failed" ? gt("Try again") : gt("Sign in with GitHub")}
215 </Button>
216 );
217 }
218
219 return (
220 <div
221 className={cn(
222 "overflow-hidden rounded-xl border bg-card",
223 state.status === "failed" && !signedIn ? "border-destructive/40" : "border-border",
224 )}
225 >
226 <div className="flex items-center gap-3 p-3">
227 <AppMark signedIn={signedIn} />
228 <div className="min-w-0 flex-1 space-y-0.5">
229 <p className="text-sm font-medium text-foreground">{appSignIn.appName}</p>
230 <div className="text-xs text-muted-foreground">{subtitle}</div>
231 </div>
232 <div className="shrink-0">{action}</div>
233 </div>
234
235 {waiting !== null ? (
236 <div className="grid gap-4 border-t border-border bg-muted/40 px-3 py-4 sm:grid-cols-[auto_1fr] sm:items-center sm:gap-6">
237 <div className="flex items-center gap-2">
238 <DeviceCode code={waiting.userCode} />
239 <Button
240 size="icon-xs"
241 variant="ghost"
242 aria-label={gt("Copy code")}
243 onClick={() => copyToClipboard(waiting.userCode, undefined)}
244 >
245 {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
246 </Button>
247 </div>
248 <div className="grid gap-2 sm:justify-items-end">
249 <Button
250 size="sm"
251 render={
252 <a href={waiting.verificationUri} target="_blank" rel="noreferrer noopener" />
253 }
254 onClick={() => copyToClipboard(waiting.userCode, undefined)}
255 >
256 <T>Copy code & open GitHub</T>
257 <ExternalLinkIcon aria-hidden className="size-3.5" />
258 </Button>
259 <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
260 <span aria-hidden className="size-1.5 rounded-full bg-warning" />
261 <T>
262 Waiting for approval · code expires at <Var>{expiryTime(waiting.expiresAt)}</Var>
263 </T>
264 </p>
265 </div>
266 </div>
267 ) : null}
268
269 {signedIn ? (
270 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
271 <span className="min-w-0 flex-1">
272 <T>Reaches repositories in accounts and organizations that installed the app.</T>
273 </span>
274 <ExternalLink href={appSignIn.installUrl}>
275 <T>Install on an organization</T>
276 </ExternalLink>
277 <ExternalLink href={appSignIn.revokeUrl}>
278 <T>Manage on GitHub</T>
279 </ExternalLink>
280 </div>
281 ) : null}
282
283 {state.status === "failed" && !signedIn ? (
284 <p
285 role="alert"
286 className="border-t border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive"
287 >
288 {state.message}
289 </p>
290 ) : null}
291 </div>
292 );
293 }