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

LinkRequestCard.tsx

536 lines19.9 KB

1import { pipe } from "effect/Function";
2import { useAtomValue } from "@effect/atom-react";
3import {
4 ANOTHER_ADDRESS,
5 type LinkableMachine,
6 linkRequestAnswerInput,
7 linkRequestDefaultAccess,
8 linkRequestDisplay,
9 linkRequestFailureMessage,
10 linkRequestInitialMachine,
11 type LinkRequestItem,
12 linkRequestTarget,
13 linkRequestTargetName,
14 rankMachinesByHint,
15} from "@t3tools/client-runtime/link-request";
16import {
17 isAtomCommandInterrupted,
18 squashAtomCommandFailure,
19} from "@t3tools/client-runtime/state/runtime";
20import {
21 AuthAccessWriteScope,
22 type AuthMcpClientAccess,
23 type EnvironmentId,
24 type OrchestrationV2ProjectedTurnItem,
25} from "@t3tools/contracts";
26import * as Option from "effect/Option";
27import * as Result from "effect/Result";
28import { T, useGT, useMessages, Var } from "gt-react";
29import { CheckIcon, LinkIcon, MinusIcon, XIcon } from "lucide-react";
30import { useId, useRef, useState } from "react";
31​
32import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
33import { mintPairingCodeOn } from "../../state/peerPairingCode";
34import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks";
35import { useAtomCommand } from "../../state/use-atom-command";
36import { accessConfig } from "../auth/ConnectAgentSurface";
37import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
38import { LinkAccessPicker } from "../settings/LinkAccessPicker";
39import { LinkAddressWarning, LinkMachineBadge } from "../settings/LinkMachineSelect";
40import { Button } from "../ui/button";
41import { Dialog } from "../ui/dialog";
42import { Input } from "../ui/input";
43import { Radio, RadioGroup } from "../ui/radio-group";
44import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
45import { WorkLogRow } from "./WorkLog";
46​
47/** Whether the agent left the machine for the user to pick. */
48const picksMachine = (item: LinkRequestItem) =>
49 item.environmentId === undefined && item.url === undefined;
50​
51/**
52 * Inline card for a link an agent asked the user to make. The user picks the
53 * access in a dialog; the pairing code lives only in that dialog's state and
54 * the RPC payload, and is never logged, toasted, or persisted.
55 */
56export function LinkRequestCard(props: {
57 readonly environmentId: EnvironmentId;
58 readonly item: LinkRequestItem;
59 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
60}) {
61 const { item } = props;
62 const messages = useMessages();
63 const display = linkRequestDisplay(
64 item,
65 props.visibility,
66 (access: AuthMcpClientAccess) => messages(accessConfig[access].label),
67 messages,
68 );
69 if (display.kind === "answered" || display.kind === "pending-elsewhere") {
70 const Icon =
71 display.kind === "pending-elsewhere"
72 ? LinkIcon
73 : display.outcome === "linked"
74 ? CheckIcon
75 : display.outcome === "failed"
76 ? XIcon
77 : MinusIcon;
78 return (
79 <WorkLogRow
80 data-v2-item-type={item.type}
81 icon={<Icon className="size-3.5 text-icon-muted" aria-hidden />}
82 label={display.label}
83 />
84 );
85 }
86 return <PendingLinkRequest environmentId={props.environmentId} item={item} />;
88​
89function PendingLinkRequest(props: {
90 readonly environmentId: EnvironmentId;
91 readonly item: LinkRequestItem;
92}) {
93 const { item } = props;
94 const gt = useGT();
95 const messages = useMessages();
96 const [open, setOpen] = useState(false);
97 const [declining, setDeclining] = useState(false);
98 const [error, setError] = useState<string | null>(null);
99 const answer = useAtomCommand(peerLinkEnvironment.answerRequest, {
100 label: "decline link request",
101 reportFailure: false,
102 reportDefect: false,
103 });
104 const canAnswer = useAtomValue(
105 peerLinkEnvironment.answerRequest.permissionAtom(props.environmentId),
106 );
107 const target = linkRequestTargetName(item, messages);
108​
109 const decline = async () => {
110 const input = linkRequestAnswerInput(item, { type: "decline" });
111 if (input === null) return;
112 setDeclining(true);
113 setError(null);
114 const result = await answer({ environmentId: props.environmentId, input }).finally(() =>
115 setDeclining(false),
116 );
117 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
118 pipe(
119 squashAtomCommandFailure(result),
120 (failure) => linkRequestFailureMessage(failure, messages),
121 setError,
122 );
123 }
124 };
125​
126 return (
127 <div
128 data-v2-item-type={item.type}
129 className="flex min-w-0 flex-col gap-3 rounded-xl border border-border/60 bg-card p-4"
130 >
131 <div className="flex min-w-0 flex-col gap-1">
132 <p className="text-sm font-medium text-foreground">
133 {item.url === undefined
134 ? gt`Link a machine to this environment`
135 : gt`Link ${{ target }} to this environment`}
136 </p>
137 {item.reason.trim() ? <p className="text-sm text-muted-foreground">{item.reason}</p> : null}
138 </div>
139 {error !== null ? (
140 <p role="alert" className="text-xs text-destructive">
141 {error}
142 </p>
143 ) : null}
144 {canAnswer ? (
145 <div className="flex min-w-0 items-center justify-end gap-2">
146 <Button
147 type="button"
148 size="xs"
149 variant="ghost-muted"
150 disabled={declining}
151 onClick={() => void decline()}
152 >
153 <T>Decline</T>
154 </Button>
155 <Button type="button" size="xs" disabled={declining} onClick={() => setOpen(true)}>
156 {picksMachine(item) ? gt`Choose machine…` : gt`Review link…`}
157 </Button>
158 </div>
159 ) : (
160 <p className="text-xs text-muted-foreground">
161 <T>Only a session that manages access here can answer this.</T>
162 </p>
163 )}
164 <LinkRequestDialog
165 environmentId={props.environmentId}
166 item={item}
167 open={open}
168 onOpenChange={setOpen}
169 />
170 </div>
171 );
173​
174/** The dialog's steps: where to link, then what agents may do there. */
175type LinkStep = "machine" | "access";
176​
177function LinkRequestDialog(props: {
178 readonly environmentId: EnvironmentId;
179 readonly item: LinkRequestItem;
180 readonly open: boolean;
181 readonly onOpenChange: (open: boolean) => void;
182}) {
183 const { item } = props;
184 const gt = useGT();
185 const messages = useMessages();
186 const formId = useId();
187 const pickMachine = picksMachine(item);
188 const listed = useLinkableMachines(props.environmentId, props.open);
189 const machines = rankMachinesByHint(listed, item.hint);
190 // Null until the user picks; until then the hint's best match is picked.
191 const [choice, setChoice] = useState<string | null>(null);
192 const [address, setAddress] = useState(item.url ?? "");
193 const [access, setAccess] = useState<AuthMcpClientAccess>(() => linkRequestDefaultAccess(item));
194 const [pairingCode, setPairingCode] = useState("");
195 const [step, setStep] = useState<LinkStep>("machine");
196 const [busy, setBusy] = useState(false);
197 const [error, setError] = useState<string | null>(null);
198 // Machines whose minting already failed, so the dialog asks for a code instead.
199 const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
200 // Enter then a click can both run before a re-render; this guard is synchronous.
201 const inFlight = useRef(false);
202 const answer = useAtomCommand(peerLinkEnvironment.answerRequest, {
203 label: "answer link request",
204 // The failure cause holds the request, and with it the code; keep it out of the console.
205 reportFailure: false,
206 reportDefect: false,
207 });
208 const selected = choice ?? linkRequestInitialMachine(item, machines);
209 const target = linkRequestTarget(item, machines, selected, messages);
210 const targetName =
211 target.kind === "machine" ? target.label : linkRequestTargetName(item, messages);
212 // Without a catalog entry or an address, the name is the generic "a machine".
213 const unnamed =
214 item.url === undefined &&
215 !(
216 target.kind === "machine" &&
217 machines.some((machine) => machine.environmentId === target.environmentId)
218 );
219 const targetId = target.kind === "machine" ? target.environmentId : null;
220 const connected = usePreparedConnection(targetId);
221 const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
222 const needsAddress =
223 target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
224 // This client mints a code there when it is connected with a session that may
225 // create pairing links, and only for its own addresses: anything can answer
226 // as that machine at one typed in, so that one gets a code the user fetched.
227 const canMint =
228 targetId !== null &&
229 !needsAddress &&
230 Option.isSome(connected) &&
231 mayMint &&
232 !mintFailed.has(targetId);
233 // An address the agent gave is already filled in; only one the user must type is asked for.
234 const asksAddress = needsAddress && item.url === undefined;
235 const useExisting = target.kind === "machine" && target.linked;
236 // A named machine with an address it answers at has nothing to choose before access.
237 const steps: ReadonlyArray<LinkStep> =
238 pickMachine || asksAddress ? ["machine", "access"] : ["access"];
239 const current: LinkStep = steps.includes(step) ? step : "access";
240 const machineReady =
241 target.kind !== "none" && (useExisting || !needsAddress || address.trim().length > 0);
242 const ready = machineReady && (useExisting || canMint || pairingCode.trim().length > 0);
243​
244 const reset = () => {
245 setChoice(null);
246 setAddress(item.url ?? "");
247 setAccess(linkRequestDefaultAccess(item));
248 setPairingCode("");
249 setStep("machine");
250 setError(null);
251 };
252​
253 // Every close resets, so a reopened dialog never shows the last answer or its pairing code.
254 const close = () => {
255 props.onOpenChange(false);
256 reset();
257 };
258​
259 // Settles to the answer to send, an error to show, or nothing to do.
260 const prepareAnswer = async () => {
261 if (target.kind === "none") return null;
262 if (target.kind === "machine" && target.linked) {
263 return linkRequestAnswerInput(item, {
264 type: "use-existing",
265 environmentId: target.environmentId,
266 });
267 }
268 let code = pairingCode;
269 if (canMint && targetId !== null) {
270 const minted = await mintPairingCodeOn(targetId, access);
271 if (Result.isFailure(minted)) {
272 setMintFailed((failed) => new Set(failed).add(targetId));
273 setError(linkRequestFailureMessage(minted.failure, messages));
274 return null;
275 }
276 code = minted.success;
277 }
278 return linkRequestAnswerInput(item, {
279 type: "link",
280 target: target.kind === "machine" && target.urls.length > 0 ? target : { url: address },
281 access,
282 pairingCode: code,
283 });
284 };
285​
286 const submit = async () => {
287 if (inFlight.current || target.kind === "none") return;
288 inFlight.current = true;
289 setBusy(true);
290 setError(null);
291 const input = await prepareAnswer();
292 const result =
293 input === null ? null : await answer({ environmentId: props.environmentId, input });
294 inFlight.current = false;
295 setBusy(false);
296 if (result === null) return;
297 if (result._tag === "Success") {
298 // The card switches to its answered row once the item updates.
299 close();
300 } else if (!isAtomCommandInterrupted(result)) {
301 pipe(
302 squashAtomCommandFailure(result),
303 (failure) => linkRequestFailureMessage(failure, messages),
304 setError,
305 );
306 }
307 };
308​
309 // The machine step ends the dialog when the machine is linked here already.
310 const finishesHere = current === "access" || useExisting;
311​
312 return (
313 <Dialog
314 open={props.open}
315 onOpenChange={(next) => {
316 // An answer that lands after a close would still link, and would close a reopened dialog.
317 if (!next && busy) return;
318 if (next) props.onOpenChange(true);
319 else close();
320 }}
321 >
322 <WizardPopup>
323 <WizardHeader
324 title={pickMachine || unnamed ? gt`Link a machine` : gt`Link ${{ targetName }}`}
325 description={gt`Agents here can then launch, message and wait on threads there. Revoke it in that machine's Sharing & access.`}
326 >
327 {steps.length > 1 && !useExisting ? (
328 <WizardSteps
329 steps={[
330 gt({ context: "wizard step title" })`Machine`,
331 gt({ context: "wizard step title" })`Access`,
332 ]}
333 currentStep={steps.indexOf(current)}
334 summaries={[target.kind === "none" ? null : targetName, null]}
335 showSummaries
336 isStepDisabled={(index) => busy || (index === 1 && !machineReady)}
337 onStepChange={(index) => {
338 const next = steps[index];
339 if (next !== undefined) setStep(next);
340 }}
341 />
342 ) : null}
343 </WizardHeader>
344 <WizardPanel holdHeight={busy}>
345 <form
346 id={formId}
347 className="space-y-4"
348 autoComplete="off"
349 onSubmit={(event) => {
350 event.preventDefault();
351 if (finishesHere) void submit();
352 else if (machineReady) setStep("access");
353 }}
354 >
355 {current === "machine" ? (
356 <>
357 {pickMachine ? (
358 <MachinePicker
359 machines={machines}
360 value={selected}
361 disabled={busy}
362 onChange={(next) => {
363 setChoice(next);
364 setError(null);
365 }}
366 />
367 ) : null}
368 {asksAddress ? (
369 <label className="block space-y-1.5">
370 <span className="block text-xs font-medium text-foreground">
371 <T>Address</T>
372 </span>
373 <Input
374 value={address}
375 onChange={(event) => setAddress(event.target.value)}
376 placeholder="https://machine.tailnet.ts.net"
377 disabled={busy}
378 nativeInput
379 spellCheck={false}
380 />
381 {target.kind === "machine" ? (
382 <span className="block text-xs text-muted-foreground">
383 {unnamed ? (
384 <T>
385 This app has no address for a machine that another machine can reach.
386 Enter its https or Tailscale address.
387 </T>
388 ) : (
389 <T>
390 This app has no address for <Var>{target.label}</Var> that another
391 machine can reach. Enter its https or Tailscale address.
392 </T>
393 )}
394 </span>
395 ) : null}
396 </label>
397 ) : null}
398 </>
399 ) : (
400 <>
401 {item.url !== undefined && target.kind === "machine" ? (
402 <p className="truncate text-xs text-muted-foreground">{item.url}</p>
403 ) : null}
404 {useExisting ? null : (
405 <>
406 {needsAddress ? <LinkAddressWarning address={address} /> : null}
407 {canMint ? null : (
408 <label className="block space-y-1.5">
409 <span className="block text-xs font-medium text-foreground">
410 <T>Pairing code</T>
411 </span>
412 <Input
413 value={pairingCode}
414 onChange={(event) => setPairingCode(event.target.value)}
415 placeholder={gt`Paste the code`}
416 disabled={busy}
417 autoComplete="one-time-code"
418 nativeInput
419 spellCheck={false}
420 />
421 <span className="block text-xs text-muted-foreground">
422 {unnamed ? (
423 <T>
424 Create a link on a machine: Settings → Sharing & access → Authorized
425 clients → Create link, then paste its code here.
426 </T>
427 ) : (
428 <T>
429 Create a link on <Var>{targetName}</Var>: Settings → Sharing & access
430 → Authorized clients → Create link, then paste its code here.
431 </T>
432 )}
433 </span>
434 </label>
435 )}
436 <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
437 </>
438 )}
439 </>
440 )}
441 {useExisting ? (
442 <p className="text-xs text-muted-foreground">
443 <T>
444 This environment is already linked to <Var>{targetName}</Var>. The agent can use
445 that link as it is; change its access in Settings → Environments.
446 </T>
447 </p>
448 ) : null}
449 {error !== null ? (
450 <p role="alert" className="text-xs text-destructive">
451 {error}
452 </p>
453 ) : null}
454 </form>
455 </WizardPanel>
456 <WizardFooter>
457 {current === "access" && steps.length > 1 ? (
458 <Button
459 variant="outline"
460 type="button"
461 disabled={busy}
462 onClick={() => {
463 setStep("machine");
464 setError(null);
465 }}
466 >
467 <T>Back</T>
468 </Button>
469 ) : (
470 <Button variant="outline" type="button" disabled={busy} onClick={close}>
471 <T>Cancel</T>
472 </Button>
473 )}
474 <Button
475 form={formId}
476 type="submit"
477 disabled={busy || (finishesHere ? !ready : !machineReady)}
478 >
479 {busy
480 ? gt`Linking…`
481 : useExisting
482 ? gt`Use this link`
483 : finishesHere
484 ? gt({ context: "verb, button that links two machines" })`Link`
485 : gt`Continue`}
486 </Button>
487 </WizardFooter>
488 </WizardPopup>
489 </Dialog>
490 );
492​
493/** The user's other machines, best match for the agent's hint first, then an address. */
494function MachinePicker(props: {
495 readonly machines: ReadonlyArray<LinkableMachine>;
496 readonly value: string | null;
497 readonly disabled: boolean;
498 readonly onChange: (value: string) => void;
499}) {
500 const gt = useGT();
501 const labelId = useId();
502 return (
503 <div className="space-y-2">
504 <span id={labelId} className="block text-xs font-medium">
505 {gt({ context: "label for a list of machines to choose from" })`Machine`}
506 </span>
507 <RadioGroup
508 aria-labelledby={labelId}
509 value={props.value}
510 disabled={props.disabled}
511 onValueChange={(next) => props.onChange(next as string)}
512 >
513 {props.machines.map((machine) => (
514 <label
515 key={machine.environmentId}
516 className="flex cursor-pointer items-center gap-2.5 rounded-lg border px-3 py-2 text-sm"
517 >
518 <Radio value={machine.environmentId} />
519 <EnvironmentMachineIcon
520 kind={machine.machine}
521 className="size-4 shrink-0 text-muted-foreground"
522 />
523 <span className="min-w-0 flex-1 truncate font-medium">{machine.label}</span>
524 <LinkMachineBadge machine={machine} />
525 </label>
526 ))}
527 <label className="flex cursor-pointer items-center gap-2.5 rounded-lg border px-3 py-2 text-sm">
528 <Radio value={ANOTHER_ADDRESS} />
529 <span className="min-w-0 flex-1 font-medium">
530 <T>Another address…</T>
531 </span>
532 </label>
533 </RadioGroup>
534 </div>
535 );