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

main
tsx 936 lines 33.1 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { useAuth } from "@clerk/react";
3 import { useAtomValue } from "@effect/atom-react";
4 import {
5 managedCapabilityDenial,
6 managedRuntimeModeDenial,
7 } from "@t3tools/client-runtime/contract-labels";
8 import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request";
9 import {
10 AuthAccessWriteScope,
11 AuthMcpClientAccess,
12 AuthRelayReadScope,
13 type EnvironmentConnectReachability,
14 type EnvironmentId,
15 mcpClientScopes,
16 sessionGrantsScope,
17 } from "@t3tools/contracts";
18 import { useNavigate } from "@tanstack/react-router";
19 import { CheckIcon, CopyIcon } from "lucide-react";
20 import * as Option from "effect/Option";
21 import { Atom } from "effect/reactivity";
22 import * as Result from "effect/Result";
23 import { msg, T, useGT, useMessages, Var } from "gt-react";
24 import { m } from "~/i18n/messages";
25 import { type ReactNode, useEffect, useEffectEvent, useState } from "react";
26
27 import { checkReachability, readLinkState } from "~/cloud/linkEnvironmentAtoms";
28 import { isManagedTunnelActive } from "~/cloud/t3ConnectState";
29 import { hasCloudPublicConfig } from "~/cloud/publicConfig";
30 import { readCachedCloudLinkState } from "~/cloud/cloudLinkState";
31 import { useCloudLinkController } from "~/cloud/useCloudLinkController";
32 import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
33 import { isElectron } from "~/env";
34 import { useT3ConnectTurnOn } from "~/cloud/useT3ConnectTurnOn";
35 import {
36 namedClipboardTarget,
37 useCopyToClipboard,
38 writeTextToClipboard,
39 } from "~/hooks/useCopyToClipboard";
40 import { useNowSecond } from "~/hooks/useNowSecond";
41 import { readLocalApi } from "~/localApi";
42 import { appAtomRegistry } from "~/rpc/atomRegistry";
43 import {
44 type EnvironmentPresentation,
45 useEnvironmentIdentities,
46 usePrimaryEnvironmentId,
47 } from "~/state/environments";
48 import { useManagedPolicy } from "~/state/managedPolicy";
49 import { mintMcpApprovalCodeOn } from "~/state/peerPairingCode";
50 import { peerLinkEnvironment } from "~/state/peerLinks";
51 import { useEnvironmentQuery } from "~/state/query";
52 import { relayEnvironmentDiscovery } from "~/state/relay";
53 import { useEnvironmentScope, useEnvironmentSessionState } from "~/state/session";
54 import { useAtomCommand } from "~/state/use-atom-command";
55 import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
56 import { CommandBlock } from "../CommandBlock";
57 import { AccessOption, accessConfig } from "../auth/ConnectAgentSurface";
58 import { useAccessEnvironment } from "../settings/useAccessEnvironment";
59 import { Button } from "../ui/button";
60 import { Dialog } from "../ui/dialog";
61 import { RadioGroup } from "../ui/radio-group";
62 import { Spinner } from "../ui/spinner";
63 import { toastManager } from "../ui/toast";
64 import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
65 import { afterFailedCheck, resolveMcpGate } from "./mcpGate";
66 import { MCP_APPS, type McpApp, mcpHandoffAction, OTHER_MCP_APP_STEPS } from "./mcpApps";
67
68 const requestAtom = Atom.make<{ readonly environmentId: EnvironmentId | null } | null>(null).pipe(
69 Atom.keepAlive,
70 Atom.withLabel("mcp:use-in-another-app"),
71 );
72
73 /** Opens the wizard for `environmentId`, or for the one Sharing & access picks when null. */
74 export function openUseInAnotherApp(environmentId: EnvironmentId | null): void {
75 appAtomRegistry.set(requestAtom, { environmentId });
76 }
77
78 const close = () => appAtomRegistry.set(requestAtom, null);
79
80 /** Hosted once at the root, so Cmd-K and Settings can open it from anywhere. */
81 export function UseInAnotherAppDialogHost() {
82 const request = useAtomValue(requestAtom);
83 return request === null ? null : <UseInAnotherAppDialog requested={request.environmentId} />;
84 }
85
86 function UseInAnotherAppDialog({ requested }: { readonly requested: EnvironmentId | null }) {
87 const { environment, label } = useAccessEnvironment(requested);
88 const gt = useGT();
89 const title = `${gt("Use T3 Code in another app (MCP)")} · ${label ?? "T3 Code"}`;
90 return (
91 <Dialog open onOpenChange={(open) => (open ? undefined : close())}>
92 <WizardPopup>
93 {environment !== null && hasCloudPublicConfig() ? (
94 <Wizard key={environment.environmentId} environment={environment} title={title} />
95 ) : (
96 <>
97 <WizardHeader title={title} />
98 <WizardPanel>
99 <GateMessage
100 title={
101 environment === null
102 ? gt("Connect to an environment first.")
103 : gt("T3 Connect is not available in this build.")
104 }
105 />
106 </WizardPanel>
107 </>
108 )}
109 </WizardPopup>
110 </Dialog>
111 );
112 }
113
114 const STEPS = [
115 msg("App", { $context: "wizard step: choose the app" }),
116 msg("Access", { $context: "wizard step: choose the access level" }),
117 msg("Connect", { $context: "wizard step: connect the app" }),
118 ] as const;
119 const HOSTED_APPROVAL_STEPS = [STEPS[0], STEPS[2]] as const;
120 type Step = 0 | 1 | 2;
121 type Choice = McpApp | "other";
122
123 function Wizard({
124 environment,
125 title,
126 }: {
127 readonly environment: EnvironmentPresentation;
128 readonly title: string;
129 }) {
130 const gt = useGT();
131 const m = useMessages();
132 const gate = useGate(environment);
133 const levels = useGrantableLevels(environment);
134 const [step, setStep] = useState<Step>(0);
135 const [choice, setChoice] = useState<Choice | null>(null);
136 const [picked, setPicked] = useState<AuthMcpClientAccess | null>(null);
137 const access = picked ?? DEFAULT_LEVELS.find((level) => levels.get(level) === undefined) ?? null;
138 const open = gate.gate.kind === "open";
139 // The level is picked on the sign-in page, so the wizard neither asks for it nor needs a code.
140 const hostedApproval =
141 environment.serverConfig?.environment.capabilities.mcpHostedApproval === true;
142 const steps = hostedApproval ? HOSTED_APPROVAL_STEPS : STEPS;
143 const shownStep = hostedApproval && step === 2 ? 1 : step;
144 const next = () => setStep(step === 0 ? (hostedApproval ? 2 : 1) : 2);
145 const levelsHeading =
146 choice === null || choice === "other"
147 ? gt("What can the app do?")
148 : gt("What can {app} do?", { app: choice.name });
149 return (
150 <>
151 <WizardHeader title={title}>
152 {open ? (
153 <WizardSteps
154 steps={steps.map((label) => m(label))}
155 currentStep={shownStep}
156 isStepDisabled={(index) => index > shownStep}
157 onStepChange={(index) => setStep(hostedApproval && index === 1 ? 2 : (index as Step))}
158 />
159 ) : null}
160 </WizardHeader>
161 <WizardPanel>
162 {gate.gate.kind !== "open" ? (
163 <GateScreen environment={environment} gate={gate} />
164 ) : step === 0 ? (
165 <AppStep choice={choice} onChoose={setChoice} />
166 ) : step === 1 ? (
167 <section className="space-y-3">
168 <h3 className="text-sm font-medium">{levelsHeading}</h3>
169 <RadioGroup
170 aria-label={levelsHeading}
171 value={access}
172 onValueChange={(value) => setPicked(value as AuthMcpClientAccess)}
173 >
174 {AuthMcpClientAccess.literals.map((level) => (
175 <AccessOption
176 key={level}
177 access={level}
178 selected={level === access}
179 disabledReason={levels.get(level)}
180 description={
181 level === "full-access"
182 ? gt("Runs commands and edits files without asking")
183 : null
184 }
185 />
186 ))}
187 </RadioGroup>
188 </section>
189 ) : choice !== null && (hostedApproval || access !== null) ? (
190 <ConnectStep
191 environment={environment}
192 mcpUrl={gate.gate.mcpUrl}
193 choice={choice}
194 access={hostedApproval ? null : access}
195 />
196 ) : null}
197 </WizardPanel>
198 {open ? (
199 <WizardFooter
200 leading={step === 2 ? <ManageAccessButton environment={environment} /> : undefined}
201 >
202 {step === 1 ? (
203 <Button variant="outline" onClick={() => setStep(0)}>
204 <T>Back</T>
205 </Button>
206 ) : null}
207 {step === 2 ? (
208 <Button onClick={close}>
209 <T>Done</T>
210 </Button>
211 ) : (
212 <Button disabled={step === 0 ? choice === null : access === null} onClick={next}>
213 <T>Next</T>
214 </Button>
215 )}
216 </WizardFooter>
217 ) : null}
218 </>
219 );
220 }
221
222 /** The level the Access step starts at: Auto, else the next one down that can be granted. */
223 const DEFAULT_LEVELS: readonly AuthMcpClientAccess[] = [
224 "auto",
225 "auto-accept-edits",
226 "approval-required",
227 "read-only",
228 ];
229
230 /** Why each level cannot be granted on this environment; absent when it can. */
231 function useGrantableLevels(environment: EnvironmentPresentation) {
232 const environmentId = environment.environmentId;
233 const session = useEnvironmentSessionState(environmentId).data;
234 const canMint = useEnvironmentScope(environmentId, AuthAccessWriteScope);
235 const policy = useManagedPolicy(environmentId);
236 const gt = useGT();
237 const messages = useMessages();
238 // The server refuses codes for any level when its policy keeps remote clients out.
239 const remoteDenial = managedCapabilityDenial(policy, "remoteClients", messages);
240 return new Map(
241 AuthMcpClientAccess.literals.flatMap((level) => {
242 const reason =
243 remoteDenial ??
244 (!canMint
245 ? gt("This device needs the Manage access permission on {environment}.", {
246 environment: environment.label,
247 })
248 : session === null ||
249 !mcpClientScopes(level).every((scope) => sessionGrantsScope(session, scope))
250 ? gt("This device cannot grant this on {environment}.", {
251 environment: environment.label,
252 })
253 : level === "read-only"
254 ? undefined
255 : managedRuntimeModeDenial(policy, level, messages));
256 return reason === undefined ? [] : [[level, reason] as const];
257 }),
258 );
259 }
260
261 function useGate(environment: EnvironmentPresentation) {
262 const environmentId = environment.environmentId;
263 const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
264 const controller = useCloudLinkController(environmentId);
265 const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);
266 const thisMachine =
267 environmentId === usePrimaryEnvironmentId() ||
268 isDesktopLocalConnectionTarget(environment.entry.target);
269 const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);
270 const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, {
271 reportFailure: false,
272 });
273 const runCheck = useAtomCommand(checkReachability, { reportFailure: false });
274 const readState = useAtomCommand(readLinkState, { reportFailure: false });
275 const m = useMessages();
276 // The gate opens on a check it ran, or on a newer one the link state reports. A failed run
277 // counts only server checks newer than `since` (see afterFailedCheck); null waits for a retry.
278 const [check, setCheck] = useState<
279 | "idle"
280 | "running"
281 | { readonly result: EnvironmentConnectReachability | null; readonly since: string | null }
282 >("idle");
283 const [connecting, setConnecting] = useState(false);
284 const linkState = controller.linkState.data;
285 const reported = linkState?.reachability;
286 const serverConfig = environment.serverConfig;
287 const connected = environment.connection.phase === "connected";
288 const relayEntry = discovery.environments.get(environmentId);
289 const gate = resolveMcpGate(
290 {
291 signedIn: isSignedIn,
292 connected,
293 approvalCodes:
294 serverConfig === null
295 ? undefined
296 : serverConfig.environment.capabilities.mcpApprovalCodes === true,
297 canReadRelay,
298 linkState,
299 linkStateError: controller.linkState.error,
300 thisMachine,
301 relay:
302 !discovery.refreshing && (discovery.offline || Option.isSome(discovery.error))
303 ? { status: "failed" }
304 : discovery.listed
305 ? {
306 status: "listed",
307 endpoint: relayEntry?.environment.endpoint,
308 availability: relayEntry?.availability,
309 }
310 : { status: "loading" },
311 reachability:
312 typeof check === "string"
313 ? "checking"
314 : reported !== undefined && check.since !== null && reported.checkedAt > check.since
315 ? reported
316 : check.result,
317 },
318 m,
319 );
320 const runReachabilityCheck = async () => {
321 setCheck("running");
322 // A saved machine's address comes from T3 Connect's list, which can be stale.
323 if (!thisMachine) void refreshDiscovery();
324 const prior = readCachedCloudLinkState({ environmentId });
325 const result = await runCheck({ target: { environmentId } });
326 controller.linkState.refresh();
327 if (result._tag === "Success") {
328 setCheck({ result: result.value, since: result.value.checkedAt });
329 return;
330 }
331 const latest = await readState({ target: { environmentId } });
332 setCheck(afterFailedCheck(prior, latest._tag === "Success" ? latest.value : null));
333 };
334 const turnOn = async () => {
335 setConnecting(true);
336 const ok = await controller.reconcileCloudState({
337 managedTunnel: true,
338 publish: controller.publishAgentActivity,
339 });
340 if (!ok) setConnecting(false);
341 };
342 // A cached link state can name a tunnel on a disconnected machine; checking it would fail and
343 // spend the one automatic check.
344 const canCheck = connected && linkState !== null && isManagedTunnelActive(linkState, undefined);
345 const checkOnce = useEffectEvent(() => {
346 if (check === "idle") void runReachabilityCheck();
347 });
348 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the server to check its tunnel once one exists
349 useEffect(() => {
350 if (canCheck) queueMicrotask(checkOnce);
351 }, [canCheck]);
352 // T3 Connect lists machines only once something asks, and a saved machine's gate reads that list.
353 const discoverIfUnasked = useEffectEvent(() => {
354 if (!thisMachine && !discovery.listed && !discovery.refreshing) void refreshDiscovery();
355 });
356 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks T3 Connect for its machine list once the wizard opens signed in
357 useEffect(() => {
358 if (isSignedIn) discoverIfUnasked();
359 }, [isSignedIn]);
360 const waiting = gate.kind === "offline" || (connecting && gate.kind === "turn-on");
361 const refreshLinkState = useEffectEvent(() => controller.linkState.refresh());
362 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls the server's link state while the tunnel starts; the server has no push for it
363 useEffect(() => {
364 if (!waiting) return;
365 const interval = window.setInterval(() => refreshLinkState(), 5_000);
366 return () => window.clearInterval(interval);
367 }, [waiting]);
368 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- stops showing Connecting once a started tunnel has had time to come up
369 useEffect(() => {
370 if (!connecting) return;
371 const timeout = window.setTimeout(() => setConnecting(false), 90_000);
372 return () => window.clearTimeout(timeout);
373 }, [connecting]);
374 return {
375 gate,
376 connecting: connecting && gate.kind !== "open",
377 check: runReachabilityCheck,
378 // A disconnected machine cannot be checked; its list entry says when it is back.
379 refreshList: () => void refreshDiscovery(),
380 turnOn,
381 operationError: controller.operationError,
382 tunnelLimit: controller.tunnelLimit,
383 };
384 }
385
386 type Gate = ReturnType<typeof useGate>;
387
388 function GateScreen({
389 environment,
390 gate: { gate, connecting, check, refreshList, turnOn, operationError, tunnelLimit },
391 }: {
392 readonly environment: EnvironmentPresentation;
393 readonly gate: Gate;
394 }) {
395 const name = environment.label;
396 const gt = useGT();
397 const turnOnHere = useT3ConnectTurnOn(environment.environmentId);
398 const { openAuthPrompt } = useT3ConnectAuthPrompt();
399 const retry = (onClick: () => void) => (
400 <Button variant="outline" onClick={onClick}>
401 <T>Check again</T>
402 </Button>
403 );
404 const offlineTitle = gt("{environment}''s T3 Connect is offline", { environment: name });
405 const cannotCheckTitle = gt("Can't check T3 Connect on {environment}", { environment: name });
406 const checkAgain = retry(() => void check());
407 switch (gate.kind) {
408 case "checking":
409 return (
410 <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground">
411 <Spinner size="sm" tone="muted" />
412 <T>Checking T3 Connect…</T>
413 </p>
414 );
415 case "sign-in":
416 return (
417 <GateMessage
418 title={gt("Sign in to T3 Connect")}
419 lines={[
420 gt(
421 "Apps like Poke and Claude run in the cloud. They need a public address to reach {environment}.",
422 { environment: name },
423 ),
424 gt("T3 Connect gives {environment} that address. Each app still needs your approval.", {
425 environment: name,
426 }),
427 ]}
428 >
429 {/* Clerk's sign-in is its own modal, so this dialog closes first. */}
430 <Button
431 onClick={() => {
432 close();
433 openAuthPrompt();
434 }}
435 >
436 <T>Sign in to T3 Connect</T>
437 </Button>
438 </GateMessage>
439 );
440 case "disconnected":
441 return gate.relay === null ? (
442 <GateMessage title={gt("Connect to {environment} first.", { environment: name })} />
443 ) : (
444 <GateMessage title={gate.relay === "offline" ? offlineTitle : cannotCheckTitle}>
445 {retry(refreshList)}
446 </GateMessage>
447 );
448 case "update":
449 return <GateMessage title={gt("Update T3 Code on {environment}", { environment: name })} />;
450 case "no-relay-read":
451 return (
452 <GateMessage
453 title={cannotCheckTitle}
454 lines={[
455 gt("This device needs the View relay permission on {environment}.", {
456 environment: name,
457 }),
458 ]}
459 />
460 );
461 case "error":
462 return (
463 <GateMessage title={cannotCheckTitle} lines={[gate.message]}>
464 {checkAgain}
465 </GateMessage>
466 );
467 case "turn-on":
468 case "offline": {
469 if (gate.kind === "offline" && !connecting) {
470 const reachability = gate.reachability;
471 return (
472 <GateMessage
473 title={reachability ? offlineTitle : cannotCheckTitle}
474 lines={
475 reachability ? [reachability.reason, gt("Fix: {fix}", { fix: reachability.fix })] : []
476 }
477 >
478 {checkAgain}
479 </GateMessage>
480 );
481 }
482 return (
483 <GateMessage
484 title={gt("Turn on T3 Connect for {environment}", { environment: name })}
485 lines={[
486 gt("{environment} gets a public https address, with no router setup.", {
487 environment: name,
488 }),
489 gt("Only apps you approve can use it. You can turn it off in Settings."),
490 ]}
491 >
492 {turnOnHere.kind === "here" ? (
493 <div className="space-y-2">
494 <Button disabled={connecting} onClick={() => void turnOn()}>
495 {connecting ? gt("Connecting…") : gt("Turn on")}
496 </Button>
497 {operationError ? (
498 <p className="text-xs text-destructive-foreground">{operationError}</p>
499 ) : null}
500 {tunnelLimit !== null ? (
501 <>
502 <p className="text-sm text-destructive-foreground">
503 <T>Your T3 Connect account is out of tunnels.</T>
504 </p>
505 <ManageAccessButton environment={environment} label={gt("Manage tunnels")} />
506 </>
507 ) : null}
508 </div>
509 ) : turnOnHere.kind === "policy" ? (
510 <p className="text-sm text-muted-foreground">{turnOnHere.reason}</p>
511 ) : (
512 <div className="space-y-2 text-sm">
513 <CommandBlock command="t3 connect link" />
514 <p>
515 <T>
516 Restart T3 Code on <Var>{name}</Var>.
517 </T>
518 </p>
519 {checkAgain}
520 </div>
521 )}
522 </GateMessage>
523 );
524 }
525 case "open":
526 return null;
527 }
528 }
529
530 function GateMessage({
531 title,
532 lines = [],
533 children,
534 }: {
535 readonly title: string;
536 readonly lines?: readonly string[];
537 readonly children?: ReactNode;
538 }) {
539 return (
540 <section className="space-y-3">
541 <h3 className="text-base font-medium">{title}</h3>
542 {lines.length > 0 ? (
543 <div className="space-y-1 text-sm text-muted-foreground">
544 {lines.map((line) => (
545 <p key={line}>{line}</p>
546 ))}
547 </div>
548 ) : null}
549 {children}
550 </section>
551 );
552 }
553
554 function AppStep({
555 choice,
556 onChoose,
557 }: {
558 readonly choice: Choice | null;
559 readonly onChoose: (choice: Choice) => void;
560 }) {
561 return (
562 <section className="space-y-3">
563 <h3 className="text-sm font-medium">
564 <T>Which app?</T>
565 </h3>
566 <div className="grid grid-cols-3 gap-2 sm:grid-cols-4">
567 {MCP_APPS.filter((app) => !app.hidden).map((app) => (
568 <button
569 key={app.id}
570 type="button"
571 aria-pressed={choice === app}
572 onClick={() => onChoose(app)}
573 className="flex min-w-0 flex-col items-center gap-2 rounded-lg border border-transparent px-1 py-3 outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring aria-pressed:border-primary aria-pressed:bg-primary/8"
574 >
575 <img
576 src={app.logo}
577 alt=""
578 className="size-10 rounded-lg ring-1 ring-black/10 dark:ring-white/12"
579 />
580 <span className="max-w-full truncate whitespace-nowrap text-xs font-medium">
581 {app.name}
582 </span>
583 </button>
584 ))}
585 </div>
586 <button
587 type="button"
588 aria-pressed={choice === "other"}
589 onClick={() => onChoose("other")}
590 className="w-full rounded-lg border border-border px-3 py-2.5 text-sm font-medium outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring aria-pressed:border-primary aria-pressed:bg-primary/8"
591 >
592 <T>Something else…</T>
593 </button>
594 </section>
595 );
596 }
597
598 function ConnectStep({
599 environment,
600 mcpUrl,
601 choice,
602 access,
603 }: {
604 readonly environment: EnvironmentPresentation;
605 readonly mcpUrl: string;
606 readonly choice: Choice;
607 /** Null when the sign-in page asks for the level, so no code is needed. */
608 readonly access: AuthMcpClientAccess | null;
609 }) {
610 const [anotherWay, setAnotherWay] = useState(choice === "other");
611 const gt = useGT();
612 const m = useMessages();
613 const app = choice === "other" ? null : choice;
614 const code =
615 access === null ? (
616 <p className="text-sm text-muted-foreground">
617 {app === null
618 ? gt(
619 "When the app opens the sign-in page, choose what it may do and approve with your T3 Connect account.",
620 )
621 : gt(
622 "When {app} opens the sign-in page, choose what it may do and approve with your T3 Connect account.",
623 { app: app.name },
624 )}
625 </p>
626 ) : (
627 <ApprovalCode
628 key={access}
629 environmentId={environment.environmentId}
630 name={environment.label}
631 access={access}
632 />
633 );
634 if (anotherWay || app === null) {
635 const message = app?.handoff.kind === "copy-message" ? app.handoff.message(mcpUrl) : null;
636 return (
637 <section className="space-y-4">
638 <CopyRow label={gt("URL")} value={mcpUrl} />
639 {message ? (
640 <CopyRow label={gt("Message", { $context: "message to send" })} value={message} />
641 ) : null}
642 <ol className="list-decimal space-y-1 ps-5 text-sm">
643 {(app?.steps ?? OTHER_MCP_APP_STEPS).map((step) => (
644 <li key={step}>{m(step)}</li>
645 ))}
646 </ol>
647 {app === null ? (
648 <p className="text-xs text-muted-foreground">
649 <T>Apps that require their own client ID cannot connect.</T>
650 </p>
651 ) : app.docs ? (
652 <TextButton onClick={() => openLink(app.docs ?? "")}>
653 {gt("{app} help", { app: app.name })}
654 </TextButton>
655 ) : null}
656 {code}
657 {app === null ? null : (
658 <TextButton onClick={() => setAnotherWay(false)}>
659 {app.handoff.kind === "commands" ? gt("Back to commands") : gt("Back to one click")}
660 </TextButton>
661 )}
662 <LinkedLine environment={environment} access={access} />
663 </section>
664 );
665 }
666 return (
667 <section className="space-y-4">
668 <PrimaryAction app={app} mcpUrl={mcpUrl} />
669 <CopyRow label={gt("URL")} value={mcpUrl} />
670 {code}
671 <TextButton onClick={() => setAnotherWay(true)}>
672 <T>Set up another way</T>
673 </TextButton>
674 <LinkedLine environment={environment} access={access} />
675 </section>
676 );
677 }
678
679 function TextButton({
680 onClick,
681 children,
682 }: {
683 readonly onClick: () => void;
684 readonly children: ReactNode;
685 }) {
686 return (
687 <button
688 type="button"
689 onClick={onClick}
690 className="block text-sm font-medium underline-offset-4 outline-none hover:underline focus-visible:underline"
691 >
692 {children}
693 </button>
694 );
695 }
696
697 function openLink(url: string) {
698 void readLocalApi()
699 ?.shell.openExternal(url)
700 .catch((error: unknown) =>
701 toastManager.add({
702 type: "error",
703 title: m(msg("Could not open the link")),
704 description: thrownErrorMessage(error, m) ?? url,
705 }),
706 );
707 }
708
709 function PrimaryAction({ app, mcpUrl }: { readonly app: McpApp; readonly mcpUrl: string }) {
710 const gt = useGT();
711 const m = useMessages();
712 const action = mcpHandoffAction(app, mcpUrl, m);
713 const note = app.note ? <p className="text-xs text-muted-foreground">{m(app.note)}</p> : null;
714 if (action === null) {
715 return (
716 <div className="space-y-2">
717 {app.handoff.kind === "commands"
718 ? app.handoff
719 .commands(mcpUrl)
720 .map((command) => <CommandBlock key={command} command={command} />)
721 : null}
722 <p className="text-xs text-muted-foreground">
723 {gt("Run these where {app} runs.", { app: app.name })}
724 </p>
725 {note}
726 </div>
727 );
728 }
729 const { copy, link, appLink } = action;
730 // The desktop app reports a link nothing opens and falls back; a browser cannot tell, and
731 // opens an app link in place (a new tab for it would stay blank), so its toast keeps the web.
732 const openApp = () => {
733 if (appLink === null) return openLink(link);
734 if (!isElectron) return window.location.assign(appLink);
735 void readLocalApi()
736 ?.shell.openExternal(appLink)
737 .catch(() => openLink(link));
738 };
739 const handOff = async () => {
740 if (copy !== null) {
741 // The app opens only once the copy lands, so it never gets an older clipboard.
742 const copied = await writeTextToClipboard(copy.text, namedClipboardTarget(copy.title)).catch(
743 () => false,
744 );
745 if (!copied) {
746 toastManager.add({
747 type: "error",
748 title: gt("Could not copy"),
749 description: gt("Use Set up another way."),
750 });
751 return;
752 }
753 toastManager.add({
754 type: "success",
755 title: copy.title,
756 // A browser can block an open that follows the copy, and no platform reliably reports an
757 // app link nothing handles (Linux says it opened), so these keep a way through.
758 ...(isElectron && appLink === null
759 ? {}
760 : {
761 actionProps: {
762 children:
763 appLink === null
764 ? gt("Open {app}", { app: app.name })
765 : gt("Get {app}", { app: app.name }),
766 onClick: () => openLink(link),
767 },
768 }),
769 });
770 }
771 openApp();
772 };
773 return (
774 <div className="space-y-2">
775 <Button className="w-full" onClick={() => void handOff()}>
776 {action.label}
777 </Button>
778 {note}
779 </div>
780 );
781 }
782
783 /** "Get code" mints on click; the code is never copied or sent anywhere by itself. */
784 function ApprovalCode({
785 environmentId,
786 name,
787 access,
788 }: {
789 readonly environmentId: EnvironmentId;
790 readonly name: string;
791 readonly access: AuthMcpClientAccess;
792 }) {
793 const [code, setCode] = useState<{
794 readonly credential: string;
795 readonly expiresAt: number;
796 } | null>(null);
797 const gt = useGT();
798 const m = useMessages();
799 const [pending, setPending] = useState(false);
800 const [error, setError] = useState<string | null>(null);
801 const now = useNowSecond();
802 const live = code !== null && now < code.expiresAt;
803 const mint = async () => {
804 setPending(true);
805 setError(null);
806 const result = await mintMcpApprovalCodeOn(environmentId, access);
807 setPending(false);
808 if (Result.isSuccess(result)) {
809 setCode({
810 credential: result.success.credential,
811 expiresAt: result.success.expiresAt.epochMilliseconds,
812 });
813 } else {
814 setError(gt("Could not get a code from {environment}. Try again.", { environment: name }));
815 }
816 };
817 const left = code === null ? 0 : Math.max(0, Math.floor((code.expiresAt - now) / 1000));
818 return (
819 <div className="space-y-1.5">
820 <div className="flex flex-wrap items-center justify-between gap-2">
821 <span className="text-sm">
822 <T>
823 Code to approve{" "}
824 <span className="font-medium">
825 <Var>{m(accessConfig[access].label)}</Var>
826 </span>
827 </T>
828 </span>
829 {live ? null : (
830 <Button size="sm" variant="outline" disabled={pending} onClick={() => void mint()}>
831 {pending ? gt("Getting code…") : code === null ? gt("Get code") : gt("New code")}
832 </Button>
833 )}
834 </div>
835 {code !== null ? (
836 live ? (
837 <>
838 <CopyRow label={gt("Code", { $context: "approval code" })} value={code.credential} />
839 <p className="text-xs text-muted-foreground">
840 {gt("Expires {time} · one use", {
841 time: `${Math.floor(left / 60)}:${String(left % 60).padStart(2, "0")}`,
842 })}
843 </p>
844 </>
845 ) : (
846 <p className="text-xs text-muted-foreground">
847 <T>The code expired.</T>
848 </p>
849 )
850 ) : null}
851 {error ? <p className="text-xs text-destructive-foreground">{error}</p> : null}
852 </div>
853 );
854 }
855
856 function CopyRow({ label, value }: { readonly label: string; readonly value: string }) {
857 const { copyToClipboard, isCopied } = useCopyToClipboard({
858 timeout: 1500,
859 target: namedClipboardTarget(label),
860 });
861 const gt = useGT();
862 return (
863 <div className="flex min-w-0 items-center gap-2 rounded-lg border border-border bg-muted/50 px-3 py-2">
864 <span className="shrink-0 text-xs text-muted-foreground">{label}</span>
865 <span className="min-w-0 flex-1 truncate font-mono text-sm">{value}</span>
866 <Button
867 size="icon-xs"
868 variant="ghost"
869 aria-label={gt("Copy {label}", { label })}
870 onClick={() => copyToClipboard(value, undefined)}
871 >
872 {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
873 </Button>
874 </div>
875 );
876 }
877
878 const levelRank = (level: AuthMcpClientAccess) => AuthMcpClientAccess.literals.indexOf(level);
879
880 /** Machines this environment links to, at the level a call forwarded there gets. */
881 function LinkedLine({
882 environment,
883 access,
884 }: {
885 readonly environment: EnvironmentPresentation;
886 /** Null when the level is picked later; each link then shows its own. */
887 readonly access: AuthMcpClientAccess | null;
888 }) {
889 const offered = offersLinkedEnvironments(environment.serverConfig);
890 const links = useEnvironmentQuery(
891 offered
892 ? peerLinkEnvironment.list({ environmentId: environment.environmentId, input: {} })
893 : null,
894 ).data?.links;
895 const identities = useEnvironmentIdentities();
896 const gt = useGT();
897 const m = useMessages();
898 if (!offered || links === undefined || links.length === 0) return null;
899 const named = links.map((link) => {
900 const name =
901 identities.find((identity) => identity.environmentId === link.environmentId)?.label ??
902 link.label;
903 // A forwarded call keeps the lower of the app's level and the link's own.
904 const level =
905 access === null || levelRank(link.access) < levelRank(access) ? link.access : access;
906 return `${name} · ${link.status === "expired" ? gt("Expired") : m(accessConfig[level].label)}`;
907 });
908 return (
909 <p className="text-xs text-muted-foreground">
910 {gt("Linked: {environments}", { environments: named.join(", ") })}
911 </p>
912 );
913 }
914
915 /** Opens Sharing & access on this environment, where its clients and T3 Connect tunnels live. */
916 function ManageAccessButton({
917 environment,
918 label,
919 }: {
920 readonly environment: EnvironmentPresentation;
921 readonly label?: string;
922 }) {
923 const navigate = useNavigate();
924 const gt = useGT();
925 return (
926 <Button
927 variant="ghost"
928 onClick={() => {
929 close();
930 void navigate({ to: "/settings/access", search: { machine: environment.environmentId } });
931 }}
932 >
933 {label ?? gt("Manage access")}
934 </Button>
935 );
936 }