The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 434 lines 17.6 KB
Raw
1 import {
2 linkBatchBlockLabel,
3 linkBatchCandidates,
4 linkBatchFailureLabel,
5 type LinkBatchOutcome,
6 linkBatchSummary,
7 linkListState,
8 runLinkBatch,
9 } from "@t3tools/client-runtime/link-batch";
10 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11 import {
12 AuthAccessWriteScope,
13 type AuthMcpClientAccess,
14 type EnvironmentId,
15 } from "@t3tools/contracts";
16 import * as Result from "effect/Result";
17 import { T, useGT, useMessages } from "gt-react";
18 import { useId, useRef, useState } from "react";
19
20 import { useEnvironments } from "~/state/environments";
21 import { mintPairingCodeOn } from "~/state/peerPairingCode";
22 import { peerLinkEnvironment, useLinkableMachines, useLinkBackOffers } from "~/state/peerLinks";
23 import { useEnvironmentQuery } from "~/state/query";
24 import { useEnvironmentsWithScope } from "~/state/session";
25 import { useAtomCommand } from "~/state/use-atom-command";
26 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
27 import { Button } from "../ui/button";
28 import { Checkbox } from "../ui/checkbox";
29 import {
30 Dialog,
31 DialogClose,
32 DialogDescription,
33 DialogFooter,
34 DialogHeader,
35 DialogPanel,
36 DialogPopup,
37 DialogTitle,
38 } from "../ui/dialog";
39 import { LinkAccessPicker } from "./LinkAccessPicker";
40
41 const NO_MACHINES: ReadonlySet<EnvironmentId> = new Set();
42 const NO_OUTCOMES: ReadonlyMap<EnvironmentId, LinkBatchOutcome> = new Map();
43
44 export 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 */
69 export 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}", { 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(
278 "Could not check which machines are already linked, so none can be picked: {error}",
279 { error: links.error ?? "" },
280 )}
281 </span>
282 <Button
283 type="button"
284 size="xs"
285 variant="outline"
286 disabled={links.isPending}
287 onClick={links.refresh}
288 >
289 <T>Retry</T>
290 </Button>
291 </>
292 )}
293 </div>
294 )}
295 <ul className="max-h-72 divide-y overflow-y-auto rounded-lg border">
296 {candidates.map(({ machine, blocked }) => {
297 const id = machine.environmentId;
298 const outcome = outcomes.get(id);
299 const available = blocked === null && outcome?.kind !== "linked";
300 const back = outcome?.kind === "linked" ? outcome.back : undefined;
301 const status = linking.has(id)
302 ? gt("Linking…")
303 : outcome?.kind === "linked"
304 ? back?.kind === "linked"
305 ? gt("Linked both ways", {
306 $context:
307 "status of a machine that was just linked in both directions",
308 })
309 : back?.kind === "failed"
310 ? gt("Linked one way", {
311 $context:
312 "status of a machine: the link to it was made, the link back from it failed",
313 })
314 : gt("Linked", { $context: "status of a machine that was just linked" })
315 : outcome?.kind === "failed"
316 ? linkBatchFailureLabel(outcome.failure, m)
317 : blocked === null
318 ? null
319 : linkBatchBlockLabel(blocked, m);
320 return (
321 <li key={id}>
322 <label className="flex cursor-pointer items-center gap-2.5 px-3 py-2 text-sm has-data-disabled:cursor-default">
323 <Checkbox
324 checked={available && selected.has(id)}
325 disabled={busy || !available}
326 onCheckedChange={(checked) => toggle(id, checked)}
327 />
328 <EnvironmentMachineIcon
329 kind={machine.machine}
330 className="size-4 shrink-0 text-muted-foreground"
331 />
332 <span className="min-w-0 flex-1">
333 <span className="block truncate font-medium">{machine.label}</span>
334 {outcome?.kind === "failed" && outcome.detail !== null ? (
335 <span className="block text-xs text-destructive">
336 {outcome.detail}
337 </span>
338 ) : null}
339 {back?.kind === "failed" ? (
340 <span className="block text-xs text-destructive">
341 {gt("Could not link back: {reason}", {
342 reason: back.detail ?? linkBatchFailureLabel(back.failure, m),
343 })}
344 </span>
345 ) : null}
346 </span>
347 {status === null ? null : (
348 <span
349 className={
350 outcome?.kind === "failed" || back?.kind === "failed"
351 ? "shrink-0 text-xs text-destructive"
352 : "shrink-0 text-xs text-muted-foreground"
353 }
354 >
355 {status}
356 </span>
357 )}
358 </label>
359 </li>
360 );
361 })}
362 </ul>
363 </div>
364 )}
365 {unlisted > 0 ? (
366 <p className="text-xs text-muted-foreground">
367 {gt(
368 "{count, plural, one {# machine needs a pairing code, so it is not listed.} other {# machines need a pairing code, so they are not listed.}}",
369 { count: unlisted },
370 )}
371 </p>
372 ) : null}
373 {outcomes.size > 0 && !busy ? (
374 <p role="status" className="text-xs text-muted-foreground">
375 {summary.failed.length === 0
376 ? gt("{linked, plural, one {Linked # machine.} other {Linked # machines.}}", {
377 linked: summary.linked,
378 })
379 : gt(
380 "Linked {linked} of {total}. The ones that failed stay selected, so you can try them again.",
381 { linked: summary.linked, total: outcomes.size },
382 )}
383 {backFailed > 0
384 ? ` ${gt(
385 "{count, plural, one {# machine could not link back.} other {# machines could not link back.}}",
386 { count: backFailed },
387 )}`
388 : null}
389 </p>
390 ) : null}
391 <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
392 {backOffered && sourceLabel !== undefined ? (
393 <label className="flex cursor-pointer items-start gap-2.5 text-sm has-data-disabled:cursor-default">
394 <Checkbox
395 checked={alsoLinkBack}
396 disabled={busy}
397 onCheckedChange={setAlsoLinkBack}
398 />
399 <span className="min-w-0 space-y-0.5">
400 <span className="block font-medium text-foreground">
401 {gt("Also link each machine back to {source}", { source: sourceLabel })}
402 </span>
403 <span className="block text-xs text-muted-foreground">
404 {gt("Agents there can then work on {source} too.", { source: sourceLabel })}
405 {alsoLinkBack && oneWayOnly > 0
406 ? ` ${gt(
407 "{count, plural, one {# machine stays one-way.} other {# machines stay one-way.}}",
408 { count: oneWayOnly },
409 )}`
410 : null}
411 </span>
412 </span>
413 </label>
414 ) : null}
415 </form>
416 </DialogPanel>
417 <DialogFooter variant="bare">
418 <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
419 {outcomes.size > 0 ? gt("Done") : gt("Cancel")}
420 </DialogClose>
421 {outcomes.size > 0 && !busy && chosen.length === 0 ? null : (
422 <Button form={formId} type="submit" disabled={busy || chosen.length === 0}>
423 {busy
424 ? gt("Linking…")
425 : gt("{count, plural, one {Link # machine} other {Link # machines}}", {
426 count: chosen.length,
427 })}
428 </Button>
429 )}
430 </DialogFooter>
431 </DialogPopup>
432 </Dialog>
433 );
434 }