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

UseInAnotherAppDialog.tsx

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