Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LinkedEnvironmentsSettings.tsx

358 lines13.9 KB

1import { useAtomValue } from "@effect/atom-react";
2import { 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 { ANOTHER_ADDRESS, 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 );
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 );
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 // This client can mint a code there when it is connected to that
187 // environment with a session that may create pairing links.
188 const targetId = machine?.environmentId ?? null;
189 const connected = usePreparedConnection(targetId);
190 const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
191 const canMint =
192 targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId);
193 const needsAddress = selected === ANOTHER_ADDRESS || machine?.urls.length === 0;
194 const ready =
195 selected !== null &&
196 (!needsAddress || address.trim().length > 0) &&
197 (canMint || pairingCode.trim().length > 0);
198 const handleOpenChange = (next: boolean) => {
199 setOpen(next);
200 if (!next) {
201 setChoice(null);
202 setAddress("");
203 setPairingCode("");
204 setAccess("approval-required");
205 setMintFailed(new Set());
206 }
207 };
208 // Settles to the code to link with, or null after reporting why there is none.
209 const resolvePairingCode = async () => {
210 if (!canMint || targetId === null) return pairingCode.trim();
211 const minted = await mintPairingCodeOn(targetId, access);
212 if (Result.isSuccess(minted)) return minted.success;
213 setMintFailed((failed) => new Set(failed).add(targetId));
214 failureToast("Could not link the environment", linkRequestFailureMessage(minted.failure));
215 return null;
216 };
217 const submit = async () => {
218 const [url, ...alternateUrls] =
219 machine === null || needsAddress ? [address.trim()] : machine.urls;
220 if (inFlight.current || !ready || url === undefined) return;
221 inFlight.current = true;
222 setBusy(true);
223 const code = await resolvePairingCode();
224 const result =
225 code === null
226 ? null
227 : await link({
228 environmentId,
229 input: {
230 url,
231 ...(alternateUrls.length > 0 ? { alternateUrls } : {}),
232 ...(machine === null
233 ? {}
234 : { expectedEnvironmentId: machine.environmentId, expectedLabel: machine.label }),
235 pairingCode: code,
236 access,
237 },
238 });
239 inFlight.current = false;
240 setBusy(false);
241 if (result === null) return;
242 if (result._tag === "Success") {
243 toastManager.add({ type: "success", title: `Linked ${result.value.label}` });
244 handleOpenChange(false);
245 } else if (!isAtomCommandInterrupted(result)) {
246 failureToast("Could not link the environment", String(squashAtomCommandFailure(result)));
247 }
248 };
249 return (
250 <Dialog
251 open={open}
252 onOpenChange={(next) => {
253 if (!next && busy) return;
254 handleOpenChange(next);
255 }}
256 >
257 <DialogTrigger
258 render={
259 <Button size="xs" variant="default">
260 <PlusIcon className="size-3" />
261 Link
262 </Button>
263 }
264 />
265 <DialogPopup className="max-w-md">
266 <DialogHeader>
267 <DialogTitle>Link an environment</DialogTitle>
268 <DialogDescription>
269 Agents here can then launch, message and wait on threads there. It appears in that
270 environment's Connections, where it can be revoked.
271 </DialogDescription>
272 </DialogHeader>
273 <DialogPanel>
274 <form
275 id={formId}
276 className="space-y-4"
277 autoComplete="off"
278 onSubmit={(event) => {
279 event.preventDefault();
280 void submit();
281 }}
282 >
283 {machines.length > 0 ? (
284 <LinkMachineSelect
285 machines={machines}
286 value={selected}
287 disabled={busy}
288 onChange={setChoice}
289 />
290 ) : null}
291 {machine?.linked ? (
292 <p className="text-xs text-muted-foreground">
293 Already linked. Linking again renews it with the access you pick.
294 </p>
295 ) : null}
296 {needsAddress ? (
297 <label className="block space-y-1.5">
298 <span className="block text-xs font-medium text-foreground">Address</span>
299 <Input
300 value={address}
301 onChange={(event) => {
302 setAddress(event.target.value);
303 // Machines found after typing began must not hide the address being typed.
304 if (choice === null) setChoice(ANOTHER_ADDRESS);
305 }}
306 placeholder="https://box.example.ts.net"
307 disabled={busy}
308 autoFocus={machines.length === 0}
309 nativeInput
310 spellCheck={false}
311 />
312 {machine !== null ? (
313 <span className="block text-xs text-muted-foreground">
314 This app has no address for {machine.label} that another machine can reach.
315 Enter its https or Tailscale address.
316 </span>
317 ) : null}
318 </label>
319 ) : null}
320 {selected === null || canMint ? null : (
321 <label className="block space-y-1.5">
322 <span className="block text-xs font-medium text-foreground">Pairing code</span>
323 <Input
324 value={pairingCode}
325 onChange={(event) => setPairingCode(event.target.value)}
326 placeholder={
327 machine === null
328 ? "From that environment's Connections, or t3 pair there"
329 : "Paste the code"
330 }
331 disabled={busy}
332 autoComplete="one-time-code"
333 nativeInput
334 spellCheck={false}
335 />
336 {machine !== null ? (
337 <span className="block text-xs text-muted-foreground">
338 Create a link on {machine.label}: Settings → Connections → Create link, then
339 paste its code here.
340 </span>
341 ) : null}
342 </label>
343 )}
344 <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
345 </form>
346 </DialogPanel>
347 <DialogFooter variant="bare">
348 <DialogClose disabled={busy} render={<Button variant="outline" type="button" />}>
349 Cancel
350 </DialogClose>
351 <Button form={formId} type="submit" disabled={busy || !ready}>
352 {busy ? "Linking…" : "Link"}
353 </Button>
354 </DialogFooter>
355 </DialogPopup>
356 </Dialog>
357 );