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