Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { ANOTHER_ADDRESS, linkRequestFailureMessage } from "@t3tools/client-runtime/link-request";
3import {
4 AuthAccessWriteScope,
5 type AuthMcpClientAccess,
6 type EnvironmentId,
7 type PeerLinkSummary,
8} from "@t3tools/contracts";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
14import * as DateTime from "effect/DateTime";
15import * as Option from "effect/Option";
16import * as Result from "effect/Result";
17import { PlusIcon } from "lucide-react";
18import { T, useGT, useMessages, Var } from "gt-react";
19import { useId, useRef, useState } from "react";
20
21import { requestConfirmDialog } from "~/confirmDialog";
22import { mintPairingCodeOn } from "~/state/peerPairingCode";
23import { peerLinkEnvironment, useLinkableMachines } from "~/state/peerLinks";
24import { useEnvironmentQuery } from "~/state/query";
25import { useEnvironmentScope, usePreparedConnection } from "~/state/session";
26import { useAtomCommand } from "~/state/use-atom-command";
27import { accessConfig } from "../auth/ConnectAgentSurface";
28import { ConnectionStatusDot } from "../ConnectionStatusDot";
29import { Button } from "../ui/button";
30import {
31 Dialog,
32 DialogClose,
33 DialogDescription,
34 DialogFooter,
35 DialogHeader,
36 DialogPanel,
37 DialogPopup,
38 DialogTitle,
39 DialogTrigger,
40} from "../ui/dialog";
41import { Input } from "../ui/input";
42import { stackedThreadToast, toastManager } from "../ui/toast";
43import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
44import { LinkAccessPicker } from "./LinkAccessPicker";
45import { LinkAddressWarning, LinkMachineSelect } from "./LinkMachineSelect";
46import { SettingsRow, SettingsSection } from "./settingsLayout";
47import { useLiveRefresh } from "../../hooks/useLiveRefresh";
48import { m as resolveMessage } from "../../i18n/messages";
49import { useNowMinute } from "../../hooks/useNowMinute";
50import { useSearchableSetting } from "./settingsSearch";
51
52// Console log labels for the atom commands.
53const UNLINK_COMMAND_LABEL = "unlink environment";
54const LINK_COMMAND_LABEL = "link environment";
55
56const failureToast = (title: string, description: string) =>
57 toastManager.add(stackedThreadToast({ type: "error", title, description }));
58
59export function LinkedEnvironmentsSettings({
60 environmentId,
61 environmentLabel,
62 isSearchTarget,
63}: {
64 readonly environmentId: EnvironmentId;
65 readonly environmentLabel: string | null;
66 readonly isSearchTarget: boolean;
67}) {
68 const searchableSetting = useSearchableSetting();
69 const gt = useGT();
70 const links = useEnvironmentQuery(
71 peerLinkEnvironment.list({ environmentId, input: {} }),
72 useMessages(),
73 );
74 // Links made outside this client bump nothing the shared list reads, so showing the panel
75 // asks again. Listing probes every linked environment, too costly for a timer nobody asked for.
76 // A list still loading counts as read now, so the next return to the window asks again.
77 useLiveRefresh(
78 () => {
79 if (!links.isPending) links.refresh();
80 },
81 {
82 key: `linked-environments:${environmentId}`,
83 intervalMs: null,
84 refreshOnShow: true,
85 },
86 );
87 const canLink = useAtomValue(peerLinkEnvironment.link.permissionAtom(environmentId));
88 const search = searchableSetting("linked-environments");
89 return (
90 <SettingsSection
91 {...(isSearchTarget ? { id: search.id } : {})}
92 title={environmentLabel === null ? search.title : `${search.title} · ${environmentLabel}`}
93 headerAction={canLink ? <LinkEnvironmentAction environmentId={environmentId} /> : null}
94 >
95 {links.error ? (
96 <SettingsRow title={gt("Could not load linked environments")} description={links.error} />
97 ) : !links.data ? (
98 <SettingsRow title={gt("Loading linked environments…")} role="status" />
99 ) : links.data.links.length === 0 ? (
100 <SettingsRow
101 title={gt("No linked environments")}
102 description={gt(
103 "Link another machine running T3 Code, such as a VPS, so agents here can launch and drive threads there.",
104 )}
105 />
106 ) : (
107 links.data.links.map((link) => (
108 <LinkedEnvironmentRow
109 key={link.environmentId}
110 environmentId={environmentId}
111 link={link}
112 />
113 ))
114 )}
115 </SettingsSection>
116 );
117}
118
119function LinkedEnvironmentRow({
120 environmentId,
121 link,
122}: {
123 readonly environmentId: EnvironmentId;
124 readonly link: PeerLinkSummary;
125}) {
126 const gt = useGT();
127 const m = useMessages();
128 const nowMinute = useNowMinute();
129 const health = peerLinkHealth(link, DateTime.makeUnsafe(nowMinute));
130 const unlink = useAtomCommand(peerLinkEnvironment.unlink, { label: UNLINK_COMMAND_LABEL });
131 const canUnlink = useAtomValue(peerLinkEnvironment.unlink.permissionAtom(environmentId));
132 const [busy, setBusy] = useState(false);
133 const forget = async () => {
134 const confirmed = await (requestConfirmDialog(
135 gt(
136 "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.",
137 { label: link.label },
138 ),
139 { variant: "destructive" },
140 ) ?? Promise.resolve(false));
141 if (!confirmed) return;
142 setBusy(true);
143 const result = await unlink({ environmentId, input: { environmentId: link.environmentId } });
144 setBusy(false);
145 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
146 failureToast(gt("Could not forget the link"), String(squashAtomCommandFailure(result)));
147 }
148 };
149 const status =
150 health.kind === "expired"
151 ? gt("Expired. Link it again with a new pairing code.")
152 : health.kind === "unreachable"
153 ? (health.detail ?? gt("Not answering right now."))
154 : health.kind === "failing"
155 ? health.detail
156 : health.expiresInDays !== null
157 ? gt(
158 "{days, plural, one {Expires in {days} day. Link it again to renew.} other {Expires in {days} days. Link it again to renew.}}",
159 { days: health.expiresInDays },
160 )
161 : gt("Reachable");
162 return (
163 <div className={ITEM_ROW_CLASSNAME}>
164 <div className={ITEM_ROW_INNER_CLASSNAME}>
165 <div className="min-w-0 flex-1 space-y-1">
166 <div className="flex min-h-5 items-center gap-1.5">
167 <ConnectionStatusDot
168 tooltipText={status}
169 dotClassName={
170 health.kind === "reachable"
171 ? health.expiresInDays === null
172 ? "bg-success"
173 : "bg-warning"
174 : health.kind === "expired" || health.kind === "failing"
175 ? "bg-destructive"
176 : "bg-muted-foreground/30"
177 }
178 pingClassName={null}
179 />
180 <h3 className="text-sm font-medium text-foreground">{link.label}</h3>
181 </div>
182 <p className="text-xs text-muted-foreground">
183 {m(accessConfig[link.access].label)} · {status}
184 </p>
185 <p className="truncate text-xs text-muted-foreground/80">{link.urls.join(", ")}</p>
186 </div>
187 {canUnlink ? (
188 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
189 <Button
190 size="xs"
191 variant="destructive-outline"
192 disabled={busy}
193 onClick={() => void forget()}
194 >
195 {busy ? gt("Forgetting…") : gt("Forget")}
196 </Button>
197 </div>
198 ) : null}
199 </div>
200 </div>
201 );
202}
203
204function LinkEnvironmentAction({ environmentId }: { readonly environmentId: EnvironmentId }) {
205 const gt = useGT();
206 const [open, setOpen] = useState(false);
207 const machines = useLinkableMachines(environmentId, open);
208 // Null until the user picks; with no other machines known, only an address is left.
209 const [choice, setChoice] = useState<string | null>(null);
210 const [address, setAddress] = useState("");
211 const [pairingCode, setPairingCode] = useState("");
212 const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");
213 const [busy, setBusy] = useState(false);
214 // Machines whose minting already failed, so the dialog asks for a code instead.
215 const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
216 // Enter then a click can both run before a re-render; this guard is synchronous.
217 const inFlight = useRef(false);
218 const formId = useId();
219 const link = useAtomCommand(peerLinkEnvironment.link, { label: LINK_COMMAND_LABEL });
220 const selected = choice ?? (machines.length === 0 ? ANOTHER_ADDRESS : null);
221 const machine = machines.find((candidate) => candidate.environmentId === selected) ?? null;
222 const targetId = machine?.environmentId ?? null;
223 const connected = usePreparedConnection(targetId);
224 const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
225 // A picked machine that left the list has no address here either.
226 const needsAddress = selected !== null && (machine === null || machine.urls.length === 0);
227 // This client mints a code there when it is connected with a session that may
228 // create pairing links, and only for its own addresses: anything can answer
229 // as that machine at one typed in, so that one gets a code the user fetched.
230 const canMint =
231 targetId !== null &&
232 !needsAddress &&
233 Option.isSome(connected) &&
234 mayMint &&
235 !mintFailed.has(targetId);
236 const ready =
237 selected !== null &&
238 (!needsAddress || address.trim().length > 0) &&
239 (canMint || pairingCode.trim().length > 0);
240 const handleOpenChange = (next: boolean) => {
241 setOpen(next);
242 if (!next) {
243 setChoice(null);
244 setAddress("");
245 setPairingCode("");
246 setAccess("approval-required");
247 setMintFailed(new Set());
248 }
249 };
250 // Settles to the code to link with, or null after reporting why there is none.
251 const resolvePairingCode = async () => {
252 if (!canMint || targetId === null) return pairingCode.trim();
253 const minted = await mintPairingCodeOn(targetId, access);
254 if (Result.isSuccess(minted)) return minted.success;
255 setMintFailed((failed) => new Set(failed).add(targetId));
256 failureToast(
257 gt("Could not link the environment"),
258 linkRequestFailureMessage(minted.failure, resolveMessage),
259 );
260 return null;
261 };
262 const submit = async () => {
263 const [url, ...alternateUrls] =
264 machine === null || needsAddress ? [address.trim()] : machine.urls;
265 if (inFlight.current || !ready || url === undefined) return;
266 inFlight.current = true;
267 setBusy(true);
268 const code = await resolvePairingCode();
269 const result =
270 code === null
271 ? null
272 : await link({
273 environmentId,
274 input: {
275 url,
276 ...(alternateUrls.length > 0 ? { alternateUrls } : {}),
277 // A typed address links alone: only this app's own addresses name a machine.
278 ...(machine === null || needsAddress
279 ? {}
280 : { expectedEnvironmentId: machine.environmentId, expectedLabel: machine.label }),
281 pairingCode: code,
282 access,
283 },
284 });
285 inFlight.current = false;
286 setBusy(false);
287 if (result === null) return;
288 if (result._tag === "Success") {
289 toastManager.add({
290 type: "success",
291 title: gt("Linked {label}", { label: result.value.label }),
292 });
293 handleOpenChange(false);
294 } else if (!isAtomCommandInterrupted(result)) {
295 failureToast(gt("Could not link the environment"), String(squashAtomCommandFailure(result)));
296 }
297 };
298 return (
299 <Dialog
300 open={open}
301 onOpenChange={(next) => {
302 if (!next && busy) return;
303 handleOpenChange(next);
304 }}
305 >
306 <DialogTrigger
307 render={
308 <Button size="xs" variant="default">
309 <PlusIcon className="size-3" />
310 {gt("Link", { $context: "verb, links an environment" })}
311 </Button>
312 }
313 />
314 <DialogPopup className="max-w-md">
315 <DialogHeader>
316 <DialogTitle>
317 <T>Link an environment</T>
318 </DialogTitle>
319 <DialogDescription>
320 <T>
321 Agents here can then launch, message and wait on threads there. It appears under
322 Authorized clients in that environment's Sharing & access, where it can be revoked.
323 </T>
324 </DialogDescription>
325 </DialogHeader>
326 <DialogPanel>
327 <form
328 id={formId}
329 className="space-y-4"
330 autoComplete="off"
331 onSubmit={(event) => {
332 event.preventDefault();
333 void submit();
334 }}
335 >
336 {machines.length > 0 ? (
337 <LinkMachineSelect
338 machines={machines}
339 value={selected}
340 disabled={busy}
341 onChange={setChoice}
342 />
343 ) : null}
344 {machine?.linked ? (
345 <p className="text-xs text-muted-foreground">
346 <T>Already linked. Linking again renews it with the access you pick.</T>
347 </p>
348 ) : null}
349 {needsAddress ? (
350 <label className="block space-y-1.5">
351 <span className="block text-xs font-medium text-foreground">
352 <T>Address</T>
353 </span>
354 <Input
355 value={address}
356 onChange={(event) => {
357 setAddress(event.target.value);
358 // Machines found after typing began must not hide the address being typed.
359 if (choice === null) setChoice(ANOTHER_ADDRESS);
360 }}
361 placeholder="https://box.example.ts.net"
362 disabled={busy}
363 autoFocus={machines.length === 0}
364 nativeInput
365 spellCheck={false}
366 />
367 {machine !== null ? (
368 <span className="block text-xs text-muted-foreground">
369 <T>
370 This app has no address for <Var>{machine.label}</Var> that another machine
371 can reach. Enter its https or Tailscale address.
372 </T>
373 </span>
374 ) : null}
375 </label>
376 ) : null}
377 {needsAddress && address.trim() ? <LinkAddressWarning address={address} /> : null}
378 {selected === null || canMint ? null : (
379 <label className="block space-y-1.5">
380 <span className="block text-xs font-medium text-foreground">
381 <T>Pairing code</T>
382 </span>
383 <Input
384 value={pairingCode}
385 onChange={(event) => setPairingCode(event.target.value)}
386 placeholder={
387 machine === null
388 ? gt("From Sharing & access there, or t3 pair")
389 : gt("Paste the code")
390 }
391 disabled={busy}
392 autoComplete="one-time-code"
393 nativeInput
394 spellCheck={false}
395 />
396 {machine !== null ? (
397 <span className="block text-xs text-muted-foreground">
398 <T>
399 Create a link on <Var>{machine.label}</Var>: Settings → Sharing & access →
400 Authorized clients → Create link, then paste its code here.
401 </T>
402 </span>
403 ) : null}
404 </label>
405 )}
406 <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
407 </form>
408 </DialogPanel>
409 <DialogFooter variant="bare">
410 <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
411 <T>Cancel</T>
412 </DialogClose>
413 <Button form={formId} type="submit" disabled={busy || !ready}>
414 {busy ? gt("Linking…") : gt("Link", { $context: "verb, links an environment" })}
415 </Button>
416 </DialogFooter>
417 </DialogPopup>
418 </Dialog>
419 );
420}