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

LinkedEnvironmentsSettings.tsx

699 lines26.9 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 linkBackBlockLabel,
4 linkBatchFailureLabel,
5 linkWithMintedCode,
6} from "@t3tools/client-runtime/link-batch";
7import { ANOTHER_ADDRESS, linkRequestFailureMessage } from "@t3tools/client-runtime/link-request";
8import {
9 AuthAccessWriteScope,
10 type AuthMcpClientAccess,
11 type EnvironmentId,
12 type PeerLinkSummary,
13} from "@t3tools/contracts";
14import {
15 isAtomCommandInterrupted,
16 squashAtomCommandFailure,
17} from "@t3tools/client-runtime/state/runtime";
18import { peerLinkHealth, type PeerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
19import * as DateTime from "effect/DateTime";
20import * as Option from "effect/Option";
21import * as Result from "effect/Result";
22import { PlusIcon } from "lucide-react";
23import { T, useGT, useMessages, Var } from "gt-react";
24import { type ReactNode, useId, useRef, useState } from "react";
25​
26import { requestConfirmDialog } from "~/confirmDialog";
27import { useEnvironment } from "~/state/environments";
28import { mintPairingCodeOn } from "~/state/peerPairingCode";
29import {
30 peerLinkEnvironment,
31 useLinkableMachines,
32 useLinkBackOffers,
33 useLinkThroughRoutes,
34} from "~/state/peerLinks";
35import { useEnvironments } from "~/state/environments";
36import { useEnvironmentQuery } from "~/state/query";
37import { useEnvironmentScope, usePreparedConnection } from "~/state/session";
38import { useAtomCommand } from "~/state/use-atom-command";
39import { accessConfig } from "../auth/ConnectAgentSurface";
40import { ConnectionStatusDot } from "../ConnectionStatusDot";
41import { Button } from "../ui/button";
42import { Checkbox } from "../ui/checkbox";
43import {
44 Dialog,
45 DialogClose,
46 DialogDescription,
47 DialogFooter,
48 DialogHeader,
49 DialogPanel,
50 DialogPopup,
51 DialogTitle,
52 DialogTrigger,
53} from "../ui/dialog";
54import { Input } from "../ui/input";
55import { stackedThreadToast, toastManager } from "../ui/toast";
56import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
57import { LinkAccessPicker } from "./LinkAccessPicker";
58import { LinkAddressWarning, LinkMachineSelect } from "./LinkMachineSelect";
59import { LinkSeveralEnvironmentsAction } from "./LinkSeveralEnvironments";
60import { SettingsRow, SettingsSection } from "./settingsLayout";
61import { useLiveRefresh } from "../../hooks/useLiveRefresh";
62import { m as resolveMessage } from "../../i18n/messages";
63import { useNowMinute } from "../../hooks/useNowMinute";
64import { useSearchableSetting } from "./settingsSearch";
65​
66// Console log labels for the atom commands.
67const UNLINK_COMMAND_LABEL = "unlink environment";
68const LINK_COMMAND_LABEL = "link environment";
69​
70const failureToast = (title: string, description: string) =>
71 toastManager.add(stackedThreadToast({ type: "error", title, description }));
72​
73export function LinkedEnvironmentsSettings({
74 environmentId,
75 environmentLabel,
76 isSearchTarget,
77}: {
78 readonly environmentId: EnvironmentId;
79 readonly environmentLabel: string | null;
80 readonly isSearchTarget: boolean;
81}) {
82 const searchableSetting = useSearchableSetting();
83 const gt = useGT();
84 const links = useEnvironmentQuery(
85 peerLinkEnvironment.list({ environmentId, input: {} }),
86 useMessages(),
87 );
88 // Links made outside this client bump nothing the shared list reads, so showing the panel
89 // asks again. Listing probes every linked environment, too costly for a timer nobody asked for.
90 // A list still loading counts as read now, so the next return to the window asks again.
91 useLiveRefresh(
92 () => {
93 if (!links.isPending) links.refresh();
94 },
95 {
96 key: `linked-environments:${environmentId}`,
97 intervalMs: null,
98 refreshOnShow: true,
99 },
100 );
101 const canLink = useAtomValue(peerLinkEnvironment.link.permissionAtom(environmentId));
102 const search = searchableSetting("linked-environments");
103 // A batch needs at least two other machines this app has saved.
104 const otherMachines = useEnvironments().environments.length - 1;
105 return (
106 <SettingsSection
107 {...(isSearchTarget ? { id: search.id } : {})}
108 title={environmentLabel === null ? search.title : `${search.title} · ${environmentLabel}`}
109 headerAction={
110 canLink ? (
111 <div className="flex items-center gap-2">
112 {otherMachines > 1 ? (
113 <LinkSeveralEnvironmentsAction environmentId={environmentId} />
114 ) : null}
115 <LinkEnvironmentAction environmentId={environmentId} />
116 </div>
117 ) : null
118 }
119 >
120 {links.error ? (
121 <SettingsRow title={gt("Could not load linked environments")} description={links.error} />
122 ) : !links.data ? (
123 <SettingsRow title={gt("Loading linked environments…")} role="status" />
124 ) : links.data.links.length === 0 ? (
125 <SettingsRow
126 title={gt("No linked environments")}
127 description={gt(
128 "Link another machine running T3 Code, such as a VPS, so agents here can launch and drive threads there.",
129 )}
130 />
131 ) : (
132 links.data.links.map((link) => (
133 <LinkedEnvironmentRow
134 key={link.environmentId}
135 environmentId={environmentId}
136 link={link}
137 />
138 ))
139 )}
140 </SettingsSection>
141 );
143​
144function LinkedEnvironmentRow({
145 environmentId,
146 link,
147}: {
148 readonly environmentId: EnvironmentId;
149 readonly link: PeerLinkSummary;
150}) {
151 const gt = useGT();
152 const m = useMessages();
153 const nowMinute = useNowMinute();
154 const health = peerLinkHealth(link, DateTime.makeUnsafe(nowMinute));
155 const canUnlink = useAtomValue(peerLinkEnvironment.unlink.permissionAtom(environmentId));
156 const { busy, forget } = useForgetPeerLink(environmentId, link);
157 const status = peerLinkStatusText(health, gt);
158 return (
159 <div className={ITEM_ROW_CLASSNAME}>
160 <div className={ITEM_ROW_INNER_CLASSNAME}>
161 <div className="min-w-0 flex-1 space-y-1">
162 <div className="flex min-h-5 items-center gap-1.5">
163 <ConnectionStatusDot
164 tooltipText={status}
165 dotClassName={
166 health.kind === "reachable"
167 ? health.expiresInDays === null
168 ? "bg-success"
169 : "bg-warning"
170 : health.kind === "expired" || health.kind === "failing"
171 ? "bg-destructive"
172 : "bg-muted-foreground/30"
173 }
174 pingClassName={null}
175 />
176 <h3 className="text-sm font-medium text-foreground">{link.label}</h3>
177 </div>
178 <p className="text-xs text-muted-foreground">
179 {m(accessConfig[link.access].label)} · {status}
180 </p>
181 <p className="truncate text-xs text-muted-foreground/80">{link.urls.join(", ")}</p>
182 </div>
183 {canUnlink ? (
184 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
185 <Button
186 size="xs"
187 variant="destructive-outline"
188 disabled={busy}
189 onClick={() => void forget()}
190 >
191 {busy ? gt("Forgetting…") : gt("Forget")}
192 </Button>
193 </div>
194 ) : null}
195 </div>
196 </div>
197 );
199​
200function LinkEnvironmentAction({ environmentId }: { readonly environmentId: EnvironmentId }) {
201 const gt = useGT();
202 const [open, setOpen] = useState(false);
203 return (
204 <LinkEnvironmentDialog
205 environmentId={environmentId}
206 open={open}
207 onOpenChange={setOpen}
208 trigger={
209 <DialogTrigger
210 render={
211 <Button size="xs" variant="default">
212 <PlusIcon className="size-3" />
213 {gt("Link", { $context: "verb, links an environment" })}
214 </Button>
215 }
216 />
217 }
218 />
219 );
221​
222/** What the link dialog opens with when something other than its own button opened it. */
223export interface LinkEnvironmentPrefill {
224 /** The machine to link to, by environment id, or `ANOTHER_ADDRESS` with `address`. */
225 readonly choice: string | null;
226 readonly address?: string;
227 /**
228 * With `address`: the machine there, and one of this app's that links to it at full access and
229 * so can get the pairing code from it.
230 */
231 readonly through?: {
232 readonly viaEnvironmentId: EnvironmentId;
233 readonly environmentId: EnvironmentId;
234 readonly label: string;
235 };
237​
238/**
239 * The one link flow. When this client is connected to the picked machine and may create pairing
240 * links there, it mints the code itself; otherwise it asks for one.
241 */
242export function LinkEnvironmentDialog({
243 environmentId,
244 open,
245 onOpenChange,
246 trigger = null,
247 prefill,
248}: {
249 readonly environmentId: EnvironmentId;
250 readonly open: boolean;
251 readonly onOpenChange: (open: boolean) => void;
252 readonly trigger?: ReactNode;
253 readonly prefill?: LinkEnvironmentPrefill;
254}) {
255 const gt = useGT();
256 const m = useMessages();
257 const setOpen = onOpenChange;
258 // Named in the title: from the map, nothing else on screen says which machine is linking.
259 const source = useEnvironment(environmentId);
260 const saved = useLinkableMachines(environmentId, open);
261 const routes = useLinkThroughRoutes(environmentId, open);
262 // Machines this app has no entry for are still pickable when one of its environments links
263 // to them at full access.
264 const machines = [
265 ...saved,
266 ...[...routes.values()]
267 .filter((route) => saved.every((machine) => machine.environmentId !== route.environmentId))
268 .map((route) => ({
269 environmentId: route.environmentId,
270 label: route.label,
271 machine: "server" as const,
272 connected: false,
273 connectOnly: false,
274 linked: false,
275 urls: route.urls,
276 })),
277 ];
278 // Null until the user picks; with no other machines known, only an address is left.
279 const [choice, setChoice] = useState<string | null>(prefill?.choice ?? null);
280 const [address, setAddress] = useState(prefill?.address ?? "");
281 const [pairingCode, setPairingCode] = useState("");
282 const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");
283 const [busy, setBusy] = useState(false);
284 // Machines whose minting already failed, so the dialog asks for a code instead.
285 const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
286 // Enter then a click can both run before a re-render; this guard is synchronous.
287 const inFlight = useRef(false);
288 const formId = useId();
289 const link = useAtomCommand(peerLinkEnvironment.link, { label: LINK_COMMAND_LABEL });
290 const linkOnTarget = useAtomCommand(peerLinkEnvironment.link, {
291 label: "link environment back",
292 // The failure cause holds the request, and with it the code; keep it out of the console.
293 reportFailure: false,
294 reportDefect: false,
295 });
296 const pairThrough = useAtomCommand(peerLinkEnvironment.pairLink, {
297 label: "pair link through a linked environment",
298 // The answer is a credential; keep it out of the console.
299 reportFailure: false,
300 reportDefect: false,
301 });
302 // Machines that would not give a code through a link, so the dialog asks for one instead.
303 const [throughFailed, setThroughFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
304 const [alsoLinkBack, setAlsoLinkBack] = useState(false);
305 const selected = choice ?? (machines.length === 0 ? ANOTHER_ADDRESS : null);
306 // Only for the machine the dialog opened for: another choice or address is another machine.
307 const prefilledThrough =
308 prefill?.through !== undefined &&
309 selected === ANOTHER_ADDRESS &&
310 address === (prefill.address ?? "")
311 ? prefill.through
312 : null;
313 const machine = machines.find((candidate) => candidate.environmentId === selected) ?? null;
314 const targetId = machine?.environmentId ?? null;
315 const connected = usePreparedConnection(targetId);
316 const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
317 // A picked machine that left the list has no address here either.
318 const needsAddress = selected !== null && (machine === null || machine.urls.length === 0);
319 // This client mints a code there when it is connected with a session that may
320 // create pairing links, and only for its own addresses: anything can answer
321 // as that machine at one typed in, so that one gets a code the user fetched.
322 const canMint =
323 targetId !== null &&
324 !needsAddress &&
325 Option.isSome(connected) &&
326 mayMint &&
327 !mintFailed.has(targetId);
328 // Minting with this client's own session there comes first: it needs no third machine.
329 const throughCandidate =
330 prefilledThrough ?? (targetId === null || canMint ? null : (routes.get(targetId) ?? null));
331 const via = useEnvironment(throughCandidate?.viaEnvironmentId ?? null);
332 // The environment holding the link refuses a level this client's session there does not hold.
333 const mayPairThrough = useAtomValue(
334 peerLinkEnvironment.pairLink.permissionAtom(
335 throughCandidate?.viaEnvironmentId ?? null,
336 throughCandidate === null
337 ? undefined
338 : { environmentId: throughCandidate.environmentId, access },
339 ),
340 );
341 const through =
342 throughCandidate !== null &&
343 via !== null &&
344 mayPairThrough &&
345 !throughFailed.has(throughCandidate.environmentId)
346 ? throughCandidate
347 : null;
348 const linkBack = useLinkBackOffers(environmentId, targetId === null ? [] : [targetId], open);
349 const backOffer = linkBack.offerFor(targetId);
350 const ready =
351 through !== null ||
352 (selected !== null &&
353 (!needsAddress || address.trim().length > 0) &&
354 (canMint || pairingCode.trim().length > 0));
355 const handleOpenChange = (next: boolean) => {
356 setOpen(next);
357 if (!next) {
358 setChoice(prefill?.choice ?? null);
359 setAddress(prefill?.address ?? "");
360 setPairingCode("");
361 setAccess("approval-required");
362 setMintFailed(new Set());
363 setThroughFailed(new Set());
364 setAlsoLinkBack(false);
365 }
366 };
367 // Settles to what to link with, or null after reporting why the linked machine gave no code.
368 const resolveThrough = async (target: NonNullable<typeof through>) => {
369 const asked = await pairThrough({
370 environmentId: target.viaEnvironmentId,
371 input: { environmentId: target.environmentId, access },
372 });
373 if (asked._tag === "Success" && asked.value.type === "credential") {
374 const [url, ...alternateUrls] = asked.value.urls;
375 if (url !== undefined) {
376 return {
377 url,
378 ...(alternateUrls.length > 0 ? { alternateUrls } : {}),
379 expectedEnvironmentId: asked.value.environmentId,
380 expectedLabel: asked.value.label,
381 pairingCode: asked.value.credential,
382 };
383 }
384 }
385 if (asked._tag === "Failure" && isAtomCommandInterrupted(asked)) return null;
386 setThroughFailed((failed) => new Set(failed).add(target.environmentId));
387 failureToast(
388 gt("{via} could not get a pairing code from {target}", {
389 via: via?.label ?? "",
390 target: target.label,
391 }),
392 gt("Enter its address and a pairing code from it instead."),
393 );
394 return null;
395 };
396 // Settles to the code to link with, or null after reporting why there is none.
397 const resolvePairingCode = async () => {
398 if (!canMint || targetId === null) return pairingCode.trim();
399 const minted = await mintPairingCodeOn(targetId, access);
400 if (Result.isSuccess(minted)) return minted.success;
401 setMintFailed((failed) => new Set(failed).add(targetId));
402 failureToast(
403 gt("Could not link the environment"),
404 linkRequestFailureMessage(minted.failure, resolveMessage),
405 );
406 return null;
407 };
408 const submit = async () => {
409 const [url, ...alternateUrls] =
410 machine === null || needsAddress ? [address.trim()] : machine.urls;
411 if (inFlight.current || !ready || url === undefined) return;
412 inFlight.current = true;
413 setBusy(true);
414 const throughInput = through === null ? null : await resolveThrough(through);
415 const code = through === null ? await resolvePairingCode() : null;
416 const result =
417 through !== null
418 ? throughInput === null
419 ? null
420 : await link({ environmentId, input: { ...throughInput, access } })
421 : code === null
422 ? null
423 : await link({
424 environmentId,
425 input: {
426 url,
427 ...(alternateUrls.length > 0 ? { alternateUrls } : {}),
428 // A typed address links alone: only this app's own addresses name a machine.
429 ...(machine === null || needsAddress
430 ? {}
431 : { expectedEnvironmentId: machine.environmentId, expectedLabel: machine.label }),
432 pairingCode: code,
433 access,
434 },
435 });
436 // The link back is its own link, made on the other machine: it never undoes this one.
437 const back =
438 result?._tag === "Success" &&
439 alsoLinkBack &&
440 backOffer.kind === "offered" &&
441 linkBack.source !== null &&
442 targetId !== null &&
443 // A typed address can answer as another machine: the picked one links back only if it did.
444 result.value.environmentId === targetId
445 ? await linkWithMintedCode({
446 machine: linkBack.source,
447 access,
448 mint: mintPairingCodeOn,
449 link: async (input) => {
450 const reverse = await linkOnTarget({ environmentId: targetId, input });
451 return reverse._tag === "Success"
452 ? Result.succeed(reverse.value)
453 : Result.fail(squashAtomCommandFailure(reverse));
454 },
455 })
456 : null;
457 inFlight.current = false;
458 setBusy(false);
459 if (result === null) return;
460 if (result._tag === "Success") {
461 const names = { source: source?.label ?? "", target: result.value.label };
462 toastManager.add({
463 type: "success",
464 title:
465 back?.kind === "linked"
466 ? gt("Linked {source} and {target} both ways", names)
467 : gt("Linked {label}", { label: result.value.label }),
468 });
469 if (back?.kind === "failed") {
470 failureToast(
471 gt("Could not link {target} back to {source}", names),
472 back.detail ?? linkBatchFailureLabel(back.failure, m),
473 );
474 }
475 handleOpenChange(false);
476 } else if (!isAtomCommandInterrupted(result)) {
477 failureToast(gt("Could not link the environment"), String(squashAtomCommandFailure(result)));
478 }
479 };
480 return (
481 <Dialog
482 open={open}
483 onOpenChange={(next) => {
484 if (!next && busy) return;
485 handleOpenChange(next);
486 }}
487 >
488 {trigger}
489 <DialogPopup className="max-w-md">
490 <DialogHeader>
491 <DialogTitle>
492 {source === null ? (
493 <T>Link an environment</T>
494 ) : through !== null ? (
495 gt("Link {source} to {target}", { source: source.label, target: through.label })
496 ) : machine === null ? (
497 gt("Link {label} to another machine", { label: source.label })
498 ) : (
499 gt("Link {source} to {target}", { source: source.label, target: machine.label })
500 )}
501 </DialogTitle>
502 <DialogDescription>
503 <T>
504 Agents here can then launch, message and wait on threads there. It appears under
505 Authorized clients in that environment's Sharing & access, where it can be revoked.
506 </T>
507 </DialogDescription>
508 </DialogHeader>
509 <DialogPanel>
510 <form
511 id={formId}
512 className="space-y-4"
513 autoComplete="off"
514 onSubmit={(event) => {
515 event.preventDefault();
516 void submit();
517 }}
518 >
519 {machines.length > 0 && (through === null || through !== prefilledThrough) ? (
520 <LinkMachineSelect
521 machines={machines}
522 value={selected}
523 disabled={busy}
524 onChange={(next) => {
525 // The opt-in names one machine: it does not carry over to another.
526 if (next !== selected) setAlsoLinkBack(false);
527 setChoice(next);
528 }}
529 />
530 ) : null}
531 {machine?.linked ? (
532 <p className="text-xs text-muted-foreground">
533 <T>Already linked. Linking again renews it with the access you pick.</T>
534 </p>
535 ) : null}
536 {through !== null ? (
537 <p className="text-xs text-muted-foreground">
538 {gt(
539 "{via} links to {target} at full access, so it gets the pairing code. No code to paste.",
540 { via: via?.label ?? "", target: through.label },
541 )}
542 </p>
543 ) : null}
544 {needsAddress && through === null ? (
545 <label className="block space-y-1.5">
546 <span className="block text-xs font-medium text-foreground">
547 <T>Address</T>
548 </span>
549 <Input
550 value={address}
551 onChange={(event) => {
552 setAddress(event.target.value);
553 // Machines found after typing began must not hide the address being typed.
554 if (choice === null) setChoice(ANOTHER_ADDRESS);
555 }}
556 placeholder="https://box.example.ts.net"
557 disabled={busy}
558 autoFocus={machines.length === 0}
559 nativeInput
560 spellCheck={false}
561 />
562 {machine !== null ? (
563 <span className="block text-xs text-muted-foreground">
564 <T>
565 This app has no address for <Var>{machine.label}</Var> that another machine
566 can reach. Enter its https or Tailscale address.
567 </T>
568 </span>
569 ) : null}
570 </label>
571 ) : null}
572 {needsAddress && through === null && address.trim() ? (
573 <LinkAddressWarning address={address} />
574 ) : null}
575 {selected === null || canMint || through !== null ? null : (
576 <label className="block space-y-1.5">
577 <span className="block text-xs font-medium text-foreground">
578 <T>Pairing code</T>
579 </span>
580 <Input
581 value={pairingCode}
582 onChange={(event) => setPairingCode(event.target.value)}
583 placeholder={
584 machine === null
585 ? gt("From Sharing & access there, or t3 pair")
586 : gt("Paste the code")
587 }
588 disabled={busy}
589 autoComplete="one-time-code"
590 nativeInput
591 spellCheck={false}
592 />
593 {machine !== null ? (
594 <span className="block text-xs text-muted-foreground">
595 <T>
596 Create a link on <Var>{machine.label}</Var>: Settings → Sharing & access →
597 Authorized clients → Create link, then paste its code here.
598 </T>
599 </span>
600 ) : null}
601 </label>
602 )}
603 <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
604 {machine === null || source === null ? null : backOffer.kind === "offered" ? (
605 <label className="flex cursor-pointer items-start gap-2.5 text-sm has-data-disabled:cursor-default">
606 <Checkbox
607 checked={alsoLinkBack}
608 disabled={busy}
609 onCheckedChange={setAlsoLinkBack}
610 />
611 <span className="min-w-0 space-y-0.5">
612 <span className="block font-medium text-foreground">
613 {gt("Also link {target} back to {source}", {
614 source: source.label,
615 target: machine.label,
616 })}
617 </span>
618 <span className="block text-xs text-muted-foreground">
619 {gt("Agents on {target} can then work on {source} too.", {
620 source: source.label,
621 target: machine.label,
622 })}
623 </span>
624 </span>
625 </label>
626 ) : backOffer.kind === "blocked" ? (
627 <p className="text-xs text-muted-foreground">
628 {linkBackBlockLabel(
629 backOffer.reason,
630 { source: source.label, target: machine.label },
631 m,
632 )}
633 </p>
634 ) : null}
635 </form>
636 </DialogPanel>
637 <DialogFooter variant="bare">
638 <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
639 <T>Cancel</T>
640 </DialogClose>
641 <Button form={formId} type="submit" disabled={busy || !ready}>
642 {busy ? gt("Linking…") : gt("Link", { $context: "verb, links an environment" })}
643 </Button>
644 </DialogFooter>
645 </DialogPopup>
646 </Dialog>
647 );
649​
650/** What a link's health means for the user, in a sentence. */
651export function peerLinkStatusText(health: PeerLinkHealth, gt: ReturnType<typeof useGT>): string {
652 return health.kind === "expired"
653 ? gt("Expired. Link it again with a new pairing code.")
654 : health.kind === "unreachable"
655 ? (health.detail ?? gt("Not answering right now."))
656 : health.kind === "failing"
657 ? health.detail
658 : health.expiresInDays !== null
659 ? gt(
660 "{days, plural, one {Expires in {days} day. Link it again to renew.} other {Expires in {days} days. Link it again to renew.}}",
661 { days: health.expiresInDays },
662 )
663 : gt("Reachable");
665​
666/** Forgets `link` from `environmentId` after the user confirms. */
667export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSummary) {
668 const gt = useGT();
669 const unlink = useAtomCommand(peerLinkEnvironment.unlink, { label: UNLINK_COMMAND_LABEL });
670 const [busy, setBusy] = useState(false);
671 const forget = async () => {
672 const confirmed = await (requestConfirmDialog(
673 gt(
674 "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.",
675 { label: link.label },
676 ),
677 { variant: "destructive" },
678 ) ?? Promise.resolve(false));
679 if (!confirmed) return;
680 setBusy(true);
681 const result = await unlink({ environmentId, input: { environmentId: link.environmentId } });
682 setBusy(false);
683 if (result._tag === "Success") {
684 if (result.value.removed && result.value.endedThere !== true) {
685 toastManager.add({
686 type: "warning",
687 title: gt("{label} did not answer", { label: link.label }),
688 description: gt(
689 "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.",
690 { label: link.label },
691 ),
692 });
693 }
694 } else if (!isAtomCommandInterrupted(result)) {
695 failureToast(gt("Could not forget the link"), String(squashAtomCommandFailure(result)));
696 }
697 };
698 return { busy, forget };