Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { AuthMcpClientAccess, type EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import { peerLinkHealth } from "@t3tools/client-runtime/state/peerLinks";
8import * as DateTime from "effect/DateTime";
9import { PlusIcon } from "lucide-react";
10import { useId, useState } from "react";
11
12import { requestConfirmDialog } from "~/confirmDialog";
13import { peerLinkEnvironment } from "~/state/peerLinks";
14import { useEnvironmentQuery } from "~/state/query";
15import { useAtomCommand } from "~/state/use-atom-command";
16import { AccessOption, accessConfig } from "../auth/ConnectAgentSurface";
17import { ConnectionStatusDot } from "../ConnectionStatusDot";
18import { Button } from "../ui/button";
19import {
20 Dialog,
21 DialogClose,
22 DialogDescription,
23 DialogFooter,
24 DialogHeader,
25 DialogPanel,
26 DialogPopup,
27 DialogTitle,
28 DialogTrigger,
29} from "../ui/dialog";
30import { Input } from "../ui/input";
31import { RadioGroup } from "../ui/radio-group";
32import { stackedThreadToast, toastManager } from "../ui/toast";
33import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
34import { SettingsRow, SettingsSection } from "./settingsLayout";
35import { useNowMinute } from "../../hooks/useNowMinute";
36import { searchableSetting } from "./settingsSearch";
37
38const failureToast = (title: string, description: string) =>
39 toastManager.add(stackedThreadToast({ type: "error", title, description }));
40
41export function LinkedEnvironmentsSettings({
42 environmentId,
43 environmentLabel,
44 isSearchTarget,
45}: {
46 readonly environmentId: EnvironmentId;
47 readonly environmentLabel: string | null;
48 readonly isSearchTarget: boolean;
49}) {
50 const links = useEnvironmentQuery(peerLinkEnvironment.list({ environmentId, input: {} }));
51 const canLink = useAtomValue(peerLinkEnvironment.link.permissionAtom(environmentId));
52 const search = searchableSetting("linked-environments");
53 return (
54 <SettingsSection
55 {...(isSearchTarget ? { id: search.id } : {})}
56 title={environmentLabel === null ? search.title : `${search.title} · ${environmentLabel}`}
57 headerAction={canLink ? <LinkEnvironmentAction environmentId={environmentId} /> : null}
58 >
59 {links.error ? (
60 <SettingsRow title="Could not load linked environments" description={links.error} />
61 ) : !links.data ? (
62 <SettingsRow title="Loading linked environments…" role="status" />
63 ) : links.data.links.length === 0 ? (
64 <SettingsRow
65 title="No linked environments"
66 description="Link another machine running T3 Code, such as a VPS, so agents here can launch and drive threads there."
67 />
68 ) : (
69 links.data.links.map((link) => (
70 <LinkedEnvironmentRow
71 key={link.environmentId}
72 environmentId={environmentId}
73 link={link}
74 />
75 ))
76 )}
77 </SettingsSection>
78 );
79}
80
81function LinkedEnvironmentRow({
82 environmentId,
83 link,
84}: {
85 readonly environmentId: EnvironmentId;
86 readonly link: PeerLinkSummary;
87}) {
88 const nowMinute = useNowMinute();
89 const health = peerLinkHealth(link, DateTime.makeUnsafe(nowMinute));
90 const unlink = useAtomCommand(peerLinkEnvironment.unlink, { label: "unlink environment" });
91 const canUnlink = useAtomValue(peerLinkEnvironment.unlink.permissionAtom(environmentId));
92 const [busy, setBusy] = useState(false);
93 const forget = async () => {
94 const confirmed = await (requestConfirmDialog(
95 `Forget ${link.label}? Agents here stop working there. Revoke "T3 Code · …" in ${link.label}'s Connections to end the session there too.`,
96 { variant: "destructive" },
97 ) ?? Promise.resolve(false));
98 if (!confirmed) return;
99 setBusy(true);
100 const result = await unlink({ environmentId, input: { environmentId: link.environmentId } });
101 setBusy(false);
102 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
103 failureToast("Could not forget the link", String(squashAtomCommandFailure(result)));
104 }
105 };
106 const status =
107 health.kind === "expired"
108 ? "Expired. Link it again with a new pairing code."
109 : health.kind === "unreachable"
110 ? (health.detail ?? "Not answering right now.")
111 : health.kind === "failing"
112 ? health.detail
113 : health.expiresInDays !== null
114 ? `Expires in ${health.expiresInDays} ${health.expiresInDays === 1 ? "day" : "days"}. Link it again to renew.`
115 : "Reachable";
116 return (
117 <div className={ITEM_ROW_CLASSNAME}>
118 <div className={ITEM_ROW_INNER_CLASSNAME}>
119 <div className="min-w-0 flex-1 space-y-1">
120 <div className="flex min-h-5 items-center gap-1.5">
121 <ConnectionStatusDot
122 tooltipText={status}
123 dotClassName={
124 health.kind === "reachable"
125 ? health.expiresInDays === null
126 ? "bg-success"
127 : "bg-warning"
128 : health.kind === "expired" || health.kind === "failing"
129 ? "bg-destructive"
130 : "bg-muted-foreground/30"
131 }
132 pingClassName={null}
133 />
134 <h3 className="text-sm font-medium text-foreground">{link.label}</h3>
135 </div>
136 <p className="text-xs text-muted-foreground">
137 {accessConfig[link.access].label} · {status}
138 </p>
139 <p className="truncate text-xs text-muted-foreground/80">{link.urls.join(", ")}</p>
140 </div>
141 {canUnlink ? (
142 <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
143 <Button
144 size="xs"
145 variant="destructive-outline"
146 disabled={busy}
147 onClick={() => void forget()}
148 >
149 {busy ? "Forgetting…" : "Forget"}
150 </Button>
151 </div>
152 ) : null}
153 </div>
154 </div>
155 );
156}
157
158function LinkEnvironmentAction({ environmentId }: { readonly environmentId: EnvironmentId }) {
159 const [open, setOpen] = useState(false);
160 const [url, setUrl] = useState("");
161 const [pairingCode, setPairingCode] = useState("");
162 const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");
163 const [busy, setBusy] = useState(false);
164 const formId = useId();
165 const accessLabelId = `${formId}-access`;
166 const link = useAtomCommand(peerLinkEnvironment.link, { label: "link environment" });
167 const handleOpenChange = (next: boolean) => {
168 setOpen(next);
169 if (!next) {
170 setUrl("");
171 setPairingCode("");
172 setAccess("approval-required");
173 }
174 };
175 const submit = async () => {
176 setBusy(true);
177 const result = await link({
178 environmentId,
179 input: { url: url.trim(), pairingCode: pairingCode.trim(), access },
180 });
181 setBusy(false);
182 if (result._tag === "Success") {
183 toastManager.add({ type: "success", title: `Linked ${result.value.label}` });
184 handleOpenChange(false);
185 } else if (!isAtomCommandInterrupted(result)) {
186 failureToast("Could not link the environment", String(squashAtomCommandFailure(result)));
187 }
188 };
189 return (
190 <Dialog
191 open={open}
192 onOpenChange={(next) => {
193 if (!next && busy) return;
194 handleOpenChange(next);
195 }}
196 >
197 <DialogTrigger
198 render={
199 <Button size="xs" variant="default">
200 <PlusIcon className="size-3" />
201 Link
202 </Button>
203 }
204 />
205 <DialogPopup className="max-w-md">
206 <DialogHeader>
207 <DialogTitle>Link an environment</DialogTitle>
208 <DialogDescription>
209 Agents here can then launch, message and wait on threads there. It appears in that
210 environment's Connections, where it can be revoked.
211 </DialogDescription>
212 </DialogHeader>
213 <DialogPanel>
214 <form
215 id={formId}
216 className="space-y-4"
217 onSubmit={(event) => {
218 event.preventDefault();
219 void submit();
220 }}
221 >
222 <label className="block space-y-1.5">
223 <span className="block text-xs font-medium text-foreground">Address</span>
224 <Input
225 value={url}
226 onChange={(event) => setUrl(event.target.value)}
227 placeholder="https://box.example.ts.net"
228 disabled={busy}
229 autoFocus
230 nativeInput
231 spellCheck={false}
232 />
233 </label>
234 <label className="block space-y-1.5">
235 <span className="block text-xs font-medium text-foreground">Pairing code</span>
236 <Input
237 value={pairingCode}
238 onChange={(event) => setPairingCode(event.target.value)}
239 placeholder="From that environment's Connections, or t3 pair there"
240 disabled={busy}
241 autoComplete="one-time-code"
242 nativeInput
243 spellCheck={false}
244 />
245 </label>
246 <div className="space-y-2">
247 <span id={accessLabelId} className="block text-xs font-medium">
248 What agents here may do there
249 </span>
250 <RadioGroup
251 aria-labelledby={accessLabelId}
252 disabled={busy}
253 value={access}
254 onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
255 >
256 {AuthMcpClientAccess.literals.map((option) => (
257 <AccessOption key={option} access={option} selected={option === access} />
258 ))}
259 </RadioGroup>
260 <p className="text-xs text-muted-foreground">
261 An agent never gets more access there than its own mode here. Below full access, it
262 can change only threads this link started, not that environment's own threads,
263 projects or settings.
264 </p>
265 </div>
266 </form>
267 </DialogPanel>
268 <DialogFooter variant="bare">
269 <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
270 Cancel
271 </DialogClose>
272 <Button
273 form={formId}
274 type="submit"
275 disabled={busy || url.trim().length === 0 || pairingCode.trim().length === 0}
276 >
277 {busy ? "Linking…" : "Link"}
278 </Button>
279 </DialogFooter>
280 </DialogPopup>
281 </Dialog>
282 );
283}