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