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

UseInAnotherAppDialog.tsx

844 lines30.4 KB

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