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

UseInAnotherAppDialog.tsx

910 lines32.4 KB

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