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

LinkRequestCard.tsx

510 lines19.0 KB

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