Open History to see the last commit
1import {
2 linkBatchBlockLabel,
3 linkBatchCandidates,
4 linkBatchFailureLabel,
5 type LinkBatchOutcome,
6 linkBatchSummary,
7 linkListState,
8 runLinkBatch,
9} from "@t3tools/client-runtime/link-batch";
10import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11import {
12 AuthAccessWriteScope,
13 type AuthMcpClientAccess,
14 type EnvironmentId,
15} from "@t3tools/contracts";
16import * as Result from "effect/Result";
17import { T, useGT, useMessages, plural, part, n } from "gt-react";
18import { useId, useRef, useState } from "react";
19
20import { useEnvironments } from "~/state/environments";
21import { mintPairingCodeOn } from "~/state/peerPairingCode";
22import { peerLinkEnvironment, useLinkableMachines, useLinkBackOffers } from "~/state/peerLinks";
23import { useEnvironmentQuery } from "~/state/query";
24import { useEnvironmentsWithScope } from "~/state/session";
25import { useAtomCommand } from "~/state/use-atom-command";
26import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
27import { Button } from "../ui/button";
28import { Checkbox } from "../ui/checkbox";
29import {
30 Dialog,
31 DialogClose,
32 DialogDescription,
33 DialogFooter,
34 DialogHeader,
35 DialogPanel,
36 DialogPopup,
37 DialogTitle,
38} from "../ui/dialog";
39import { LinkAccessPicker } from "./LinkAccessPicker";
40
41const NO_MACHINES: ReadonlySet<EnvironmentId> = new Set();
42const NO_OUTCOMES: ReadonlyMap<EnvironmentId, LinkBatchOutcome> = new Map();
43
44export function LinkSeveralEnvironmentsAction({
45 environmentId,
46}: {
47 readonly environmentId: EnvironmentId;
48}) {
49 const [open, setOpen] = useState(false);
50 return (
51 <>
52 <Button size="xs" variant="outline" onClick={() => setOpen(true)}>
53 <T>Link several…</T>
54 </Button>
55 <LinkSeveralEnvironmentsDialog
56 environmentId={environmentId}
57 open={open}
58 onOpenChange={setOpen}
59 />
60 </>
61 );
62}
63
64/**
65 * Links the machines this app already reaches in one go. Each pairing code is
66 * minted on its machine and passed straight to the linking environment; none
67 * is ever held in state, shown, or logged.
68 */
69export function LinkSeveralEnvironmentsDialog({
70 environmentId,
71 open,
72 onOpenChange,
73 preset,
74 presetOnly = false,
75}: {
76 readonly environmentId: EnvironmentId;
77 readonly open: boolean;
78 readonly onOpenChange: (open: boolean) => void;
79 /** Machines picked before the dialog opened. Those a batch cannot link stay unticked. */
80 readonly preset?: ReadonlyArray<EnvironmentId>;
81 /** Lists only the `preset` machines: they were picked for this link, not as a suggestion. */
82 readonly presetOnly?: boolean;
83}) {
84 const gt = useGT();
85 const m = useMessages();
86 const formId = useId();
87 const sourceLabel = useEnvironments().environments.find(
88 (environment) => environment.environmentId === environmentId,
89 )?.label;
90 const known = useLinkableMachines(environmentId, open);
91 const machines =
92 presetOnly && preset !== undefined
93 ? known.filter((machine) => preset.includes(machine.environmentId))
94 : known;
95 // The same shared list `useLinkableMachines` reads `linked` from.
96 const links = useEnvironmentQuery(
97 open ? peerLinkEnvironment.list({ environmentId, input: {} }) : null,
98 );
99 const linksState = linkListState(links);
100 const writable = useEnvironmentsWithScope(machines, AuthAccessWriteScope);
101 const [selected, setSelected] = useState<ReadonlySet<EnvironmentId>>(() => new Set(preset));
102 const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");
103 const [outcomes, setOutcomes] = useState(NO_OUTCOMES);
104 const [linking, setLinking] = useState(NO_MACHINES);
105 // Enter then a click can both run before a re-render; this guard is synchronous.
106 const inFlight = useRef(false);
107 // The failure cause holds the request, and with it the code; keep it out of the console.
108 const quiet = { reportFailure: false, reportDefect: false };
109 const link = useAtomCommand(peerLinkEnvironment.linkInBatch, {
110 label: "link several environments",
111 ...quiet,
112 });
113 // Each machine links back once, so each refreshes its own list.
114 const linkOn = useAtomCommand(peerLinkEnvironment.link, {
115 label: "link environment back",
116 ...quiet,
117 });
118 const [alsoLinkBack, setAlsoLinkBack] = useState(false);
119 const candidates = linkBatchCandidates(machines, writable, linksState);
120 const selectable = candidates.flatMap(({ machine, blocked }) =>
121 blocked === null && outcomes.get(machine.environmentId)?.kind !== "linked" ? [machine] : [],
122 );
123 const chosen = selectable.filter((machine) => selected.has(machine.environmentId));
124 const linkBack = useLinkBackOffers(
125 environmentId,
126 selectable.map((machine) => machine.environmentId),
127 open,
128 );
129 const canLinkBack = (machine: { readonly environmentId: EnvironmentId }) =>
130 linkBack.offerFor(machine.environmentId).kind === "offered";
131 const backOffered = linkBack.source !== null && selectable.some(canLinkBack);
132 const oneWayOnly = chosen.filter((machine) => !canLinkBack(machine)).length;
133 const busy = linking.size > 0;
134 const summary = linkBatchSummary(outcomes);
135 const backFailed = [...outcomes.values()].filter(
136 (outcome) => outcome.kind === "linked" && outcome.back?.kind === "failed",
137 ).length;
138 // Picked on the map, but only another machine's link names them: this app has no session there.
139 const unlisted = (preset ?? []).filter(
140 (id) => !candidates.some(({ machine }) => machine.environmentId === id),
141 ).length;
142
143 const handleOpenChange = (next: boolean) => {
144 onOpenChange(next);
145 if (!next) {
146 setSelected(NO_MACHINES);
147 setOutcomes(NO_OUTCOMES);
148 setAccess("approval-required");
149 setAlsoLinkBack(false);
150 }
151 };
152 const toggle = (id: EnvironmentId, checked: boolean) =>
153 setSelected((current) => {
154 const next = new Set(current);
155 if (checked) next.add(id);
156 else next.delete(id);
157 return next;
158 });
159 const submit = async () => {
160 if (inFlight.current || chosen.length === 0) return;
161 inFlight.current = true;
162 setLinking(new Set(chosen.map((machine) => machine.environmentId)));
163 const results = await runLinkBatch({
164 machines: chosen,
165 access,
166 mint: mintPairingCodeOn,
167 link: async (input) => {
168 const result = await link({ environmentId, input });
169 return result._tag === "Success"
170 ? Result.succeed(result.value)
171 : Result.fail(squashAtomCommandFailure(result));
172 },
173 ...(alsoLinkBack && linkBack.source !== null
174 ? {
175 back: {
176 source: linkBack.source,
177 targets: new Set(chosen.filter(canLinkBack).map((machine) => machine.environmentId)),
178 link: async (targetId, input) => {
179 const result = await linkOn({ environmentId: targetId, input });
180 return result._tag === "Success"
181 ? Result.succeed(result.value)
182 : Result.fail(squashAtomCommandFailure(result));
183 },
184 },
185 }
186 : {}),
187 refreshLinks: links.refresh,
188 onOutcome: (id, outcome) => {
189 setOutcomes((current) => new Map(current).set(id, outcome));
190 setLinking((current) => {
191 const next = new Set(current);
192 next.delete(id);
193 return next;
194 });
195 },
196 });
197 inFlight.current = false;
198 setLinking(NO_MACHINES);
199 // What failed stays picked, so linking again retries only those.
200 setSelected(new Set(linkBatchSummary(results).failed));
201 };
202
203 return (
204 <Dialog
205 open={open}
206 onOpenChange={(next) => {
207 if (!next && busy) return;
208 handleOpenChange(next);
209 }}
210 >
211 <DialogPopup className="max-w-md">
212 <DialogHeader>
213 <DialogTitle>
214 {sourceLabel === undefined
215 ? gt`Link several environments`
216 : gt`Link several machines from ${{ source: sourceLabel }}`}
217 </DialogTitle>
218 <DialogDescription>
219 <T>
220 Agents here can then launch, message and wait on threads on each machine you pick.
221 Each appears under Authorized clients in that machine's Sharing & access, where it can
222 be revoked.
223 </T>
224 </DialogDescription>
225 </DialogHeader>
226 <DialogPanel>
227 <form
228 id={formId}
229 className="space-y-4"
230 onSubmit={(event) => {
231 event.preventDefault();
232 void submit();
233 }}
234 >
235 {candidates.length === 0 ? (
236 <p className="text-sm text-muted-foreground">
237 {presetOnly ? (
238 <T>This app is not connected to any of the machines you picked.</T>
239 ) : (
240 <T>This app knows no other machines. Add them under Environments first.</T>
241 )}
242 </p>
243 ) : (
244 <div className="space-y-1.5">
245 <div className="flex items-center justify-between gap-2">
246 <span className="text-xs font-medium text-foreground">
247 <T>Machines</T>
248 </span>
249 <Button
250 type="button"
251 size="xs"
252 variant="ghost-muted"
253 disabled={busy || selectable.length === 0}
254 onClick={() =>
255 setSelected(
256 chosen.length === selectable.length
257 ? NO_MACHINES
258 : new Set(selectable.map((machine) => machine.environmentId)),
259 )
260 }
261 >
262 {chosen.length === selectable.length && selectable.length > 0
263 ? gt`Select none`
264 : gt`Select all`}
265 </Button>
266 </div>
267 {linksState === "loaded" ? null : (
268 <div
269 role="status"
270 className="flex items-center justify-between gap-2 text-xs text-muted-foreground"
271 >
272 {linksState === "loading" ? (
273 <T>Checking which machines are already linked…</T>
274 ) : (
275 <>
276 <span className="text-destructive">
277 {gt`Could not check which machines are already linked, so none can be picked: ${{ error: links.error ?? "" }}`}
278 </span>
279 <Button
280 type="button"
281 size="xs"
282 variant="outline"
283 disabled={links.isPending}
284 onClick={links.refresh}
285 >
286 <T>Retry</T>
287 </Button>
288 </>
289 )}
290 </div>
291 )}
292 <ul className="max-h-72 divide-y overflow-y-auto rounded-lg border">
293 {candidates.map(({ machine, blocked }) => {
294 const id = machine.environmentId;
295 const outcome = outcomes.get(id);
296 const available = blocked === null && outcome?.kind !== "linked";
297 const back = outcome?.kind === "linked" ? outcome.back : undefined;
298 const status = linking.has(id)
299 ? gt`Linking…`
300 : outcome?.kind === "linked"
301 ? back?.kind === "linked"
302 ? gt({
303 context:
304 "status of a machine that was just linked in both directions",
305 })`Linked both ways`
306 : back?.kind === "failed"
307 ? gt({
308 context:
309 "status of a machine: the link to it was made, the link back from it failed",
310 })`Linked one way`
311 : gt({ context: "status of a machine that was just linked" })`Linked`
312 : outcome?.kind === "failed"
313 ? linkBatchFailureLabel(outcome.failure, m)
314 : blocked === null
315 ? null
316 : linkBatchBlockLabel(blocked, m);
317 return (
318 <li key={id}>
319 <label className="flex cursor-pointer items-center gap-2.5 px-3 py-2 text-sm has-data-disabled:cursor-default">
320 <Checkbox
321 checked={available && selected.has(id)}
322 disabled={busy || !available}
323 onCheckedChange={(checked) => toggle(id, checked)}
324 />
325 <EnvironmentMachineIcon
326 kind={machine.machine}
327 className="size-4 shrink-0 text-muted-foreground"
328 />
329 <span className="min-w-0 flex-1">
330 <span className="block truncate font-medium">{machine.label}</span>
331 {outcome?.kind === "failed" && outcome.detail !== null ? (
332 <span className="block text-xs text-destructive">
333 {outcome.detail}
334 </span>
335 ) : null}
336 {back?.kind === "failed" ? (
337 <span className="block text-xs text-destructive">
338 {gt`Could not link back: ${{ reason: back.detail ?? linkBatchFailureLabel(back.failure, m) }}`}
339 </span>
340 ) : null}
341 </span>
342 {status === null ? null : (
343 <span
344 className={
345 outcome?.kind === "failed" || back?.kind === "failed"
346 ? "shrink-0 text-xs text-destructive"
347 : "shrink-0 text-xs text-muted-foreground"
348 }
349 >
350 {status}
351 </span>
352 )}
353 </label>
354 </li>
355 );
356 })}
357 </ul>
358 </div>
359 )}
360 {unlisted > 0 ? (
361 <p className="text-xs text-muted-foreground">
362 {gt`${plural(
363 { count: unlisted },
364 {
365 one: part`${n} machine needs a pairing code, so it is not listed.`,
366 other: part`${n} machines need a pairing code, so they are not listed.`,
367 },
368 )}`}
369 </p>
370 ) : null}
371 {outcomes.size > 0 && !busy ? (
372 <p role="status" className="text-xs text-muted-foreground">
373 {summary.failed.length === 0
374 ? gt`${plural(
375 { linked: summary.linked },
376 {
377 one: part`Linked ${n} machine.`,
378 other: part`Linked ${n} machines.`,
379 },
380 )}`
381 : gt`Linked ${{ linked: summary.linked }} of ${{ total: outcomes.size }}. The ones that failed stay selected, so you can try them again.`}
382 {backFailed > 0
383 ? ` ${gt`${plural(
384 { count: backFailed },
385 {
386 one: part`${n} machine could not link back.`,
387 other: part`${n} machines could not link back.`,
388 },
389 )}`}`
390 : null}
391 </p>
392 ) : null}
393 <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
394 {backOffered && sourceLabel !== undefined ? (
395 <label className="flex cursor-pointer items-start gap-2.5 text-sm has-data-disabled:cursor-default">
396 <Checkbox
397 checked={alsoLinkBack}
398 disabled={busy}
399 onCheckedChange={setAlsoLinkBack}
400 />
401 <span className="min-w-0 space-y-0.5">
402 <span className="block font-medium text-foreground">
403 {gt`Also link each machine back to ${{ source: sourceLabel }}`}
404 </span>
405 <span className="block text-xs text-muted-foreground">
406 {gt`Agents there can then work on ${{ source: sourceLabel }} too.`}
407 {alsoLinkBack && oneWayOnly > 0
408 ? ` ${gt`${plural(
409 { count: oneWayOnly },
410 {
411 one: part`${n} machine stays one-way.`,
412 other: part`${n} machines stay one-way.`,
413 },
414 )}`}`
415 : null}
416 </span>
417 </span>
418 </label>
419 ) : null}
420 </form>
421 </DialogPanel>
422 <DialogFooter variant="bare">
423 <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
424 {outcomes.size > 0 ? gt`Done` : gt`Cancel`}
425 </DialogClose>
426 {outcomes.size > 0 && !busy && chosen.length === 0 ? null : (
427 <Button form={formId} type="submit" disabled={busy || chosen.length === 0}>
428 {busy
429 ? gt`Linking…`
430 : gt`${plural(
431 { count: chosen.length },
432 {
433 one: part`Link ${n} machine`,
434 other: part`Link ${n} machines`,
435 },
436 )}`}
437 </Button>
438 )}
439 </DialogFooter>
440 </DialogPopup>
441 </Dialog>
442 );
443}