The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 540 lines 20 KB
Raw
1 import { pipe } from "effect/Function";
2 import { useAtomValue } from "@effect/atom-react";
3 import {
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";
16 import {
17 isAtomCommandInterrupted,
18 squashAtomCommandFailure,
19 } from "@t3tools/client-runtime/state/runtime";
20 import {
21 AuthAccessWriteScope,
22 type AuthMcpClientAccess,
23 type EnvironmentId,
24 type OrchestrationV2ProjectedTurnItem,
25 } from "@t3tools/contracts";
26 import * as Option from "effect/Option";
27 import * as Result from "effect/Result";
28 import { T, useGT, useMessages, Var } from "gt-react";
29 import { CheckIcon, LinkIcon, MinusIcon, XIcon } from "lucide-react";
30 import { useId, useRef, useState } from "react";
31
32 import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
33 import { mintPairingCodeOn } from "../../state/peerPairingCode";
34 import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks";
35 import { useAtomCommand } from "../../state/use-atom-command";
36 import { accessConfig } from "../auth/ConnectAgentSurface";
37 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
38 import { LinkAccessPicker } from "../settings/LinkAccessPicker";
39 import { LinkAddressWarning, LinkMachineBadge } from "../settings/LinkMachineSelect";
40 import { Button } from "../ui/button";
41 import { Dialog } from "../ui/dialog";
42 import { Input } from "../ui/input";
43 import { Radio, RadioGroup } from "../ui/radio-group";
44 import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
45 import { WorkLogRow } from "./WorkLog";
46
47 /** Whether the agent left the machine for the user to pick. */
48 const 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 */
56 export 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} />;
87 }
88
89 function 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", { target })}
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 );
172 }
173
174 /** The dialog's steps: where to link, then what agents may do there. */
175 type LinkStep = "machine" | "access";
176
177 function 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={
325 pickMachine || unnamed ? gt("Link a machine") : gt("Link {targetName}", { targetName })
326 }
327 description={gt(
328 "Agents here can then launch, message and wait on threads there. Revoke it in that machine's Sharing & access.",
329 )}
330 >
331 {steps.length > 1 && !useExisting ? (
332 <WizardSteps
333 steps={[
334 gt("Machine", { $context: "wizard step title" }),
335 gt("Access", { $context: "wizard step title" }),
336 ]}
337 currentStep={steps.indexOf(current)}
338 summaries={[target.kind === "none" ? null : targetName, null]}
339 showSummaries
340 isStepDisabled={(index) => busy || (index === 1 && !machineReady)}
341 onStepChange={(index) => {
342 const next = steps[index];
343 if (next !== undefined) setStep(next);
344 }}
345 />
346 ) : null}
347 </WizardHeader>
348 <WizardPanel holdHeight={busy}>
349 <form
350 id={formId}
351 className="space-y-4"
352 autoComplete="off"
353 onSubmit={(event) => {
354 event.preventDefault();
355 if (finishesHere) void submit();
356 else if (machineReady) setStep("access");
357 }}
358 >
359 {current === "machine" ? (
360 <>
361 {pickMachine ? (
362 <MachinePicker
363 machines={machines}
364 value={selected}
365 disabled={busy}
366 onChange={(next) => {
367 setChoice(next);
368 setError(null);
369 }}
370 />
371 ) : null}
372 {asksAddress ? (
373 <label className="block space-y-1.5">
374 <span className="block text-xs font-medium text-foreground">
375 <T>Address</T>
376 </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 {unnamed ? (
388 <T>
389 This app has no address for a machine that another machine can reach.
390 Enter its https or Tailscale address.
391 </T>
392 ) : (
393 <T>
394 This app has no address for <Var>{target.label}</Var> that another
395 machine can reach. Enter its https or Tailscale address.
396 </T>
397 )}
398 </span>
399 ) : null}
400 </label>
401 ) : null}
402 </>
403 ) : (
404 <>
405 {item.url !== undefined && target.kind === "machine" ? (
406 <p className="truncate text-xs text-muted-foreground">{item.url}</p>
407 ) : null}
408 {useExisting ? null : (
409 <>
410 {needsAddress ? <LinkAddressWarning address={address} /> : null}
411 {canMint ? null : (
412 <label className="block space-y-1.5">
413 <span className="block text-xs font-medium text-foreground">
414 <T>Pairing code</T>
415 </span>
416 <Input
417 value={pairingCode}
418 onChange={(event) => setPairingCode(event.target.value)}
419 placeholder={gt("Paste the code")}
420 disabled={busy}
421 autoComplete="one-time-code"
422 nativeInput
423 spellCheck={false}
424 />
425 <span className="block text-xs text-muted-foreground">
426 {unnamed ? (
427 <T>
428 Create a link on a machine: Settings → Sharing & access → Authorized
429 clients → Create link, then paste its code here.
430 </T>
431 ) : (
432 <T>
433 Create a link on <Var>{targetName}</Var>: Settings → Sharing & access
434 → Authorized clients → Create link, then paste its code here.
435 </T>
436 )}
437 </span>
438 </label>
439 )}
440 <LinkAccessPicker value={access} onChange={setAccess} disabled={busy} />
441 </>
442 )}
443 </>
444 )}
445 {useExisting ? (
446 <p className="text-xs text-muted-foreground">
447 <T>
448 This environment is already linked to <Var>{targetName}</Var>. The agent can use
449 that link as it is; change its access in Settings → Environments.
450 </T>
451 </p>
452 ) : null}
453 {error !== null ? (
454 <p role="alert" className="text-xs text-destructive">
455 {error}
456 </p>
457 ) : null}
458 </form>
459 </WizardPanel>
460 <WizardFooter>
461 {current === "access" && steps.length > 1 ? (
462 <Button
463 variant="outline"
464 type="button"
465 disabled={busy}
466 onClick={() => {
467 setStep("machine");
468 setError(null);
469 }}
470 >
471 <T>Back</T>
472 </Button>
473 ) : (
474 <Button variant="outline" type="button" disabled={busy} onClick={close}>
475 <T>Cancel</T>
476 </Button>
477 )}
478 <Button
479 form={formId}
480 type="submit"
481 disabled={busy || (finishesHere ? !ready : !machineReady)}
482 >
483 {busy
484 ? gt("Linking…")
485 : useExisting
486 ? gt("Use this link")
487 : finishesHere
488 ? gt("Link", { $context: "verb, button that links two machines" })
489 : gt("Continue")}
490 </Button>
491 </WizardFooter>
492 </WizardPopup>
493 </Dialog>
494 );
495 }
496
497 /** The user's other machines, best match for the agent's hint first, then an address. */
498 function MachinePicker(props: {
499 readonly machines: ReadonlyArray<LinkableMachine>;
500 readonly value: string | null;
501 readonly disabled: boolean;
502 readonly onChange: (value: string) => void;
503 }) {
504 const gt = useGT();
505 const labelId = useId();
506 return (
507 <div className="space-y-2">
508 <span id={labelId} className="block text-xs font-medium">
509 {gt("Machine", { $context: "label for a list of machines to choose from" })}
510 </span>
511 <RadioGroup
512 aria-labelledby={labelId}
513 value={props.value}
514 disabled={props.disabled}
515 onValueChange={(next) => props.onChange(next as string)}
516 >
517 {props.machines.map((machine) => (
518 <label
519 key={machine.environmentId}
520 className="flex cursor-pointer items-center gap-2.5 rounded-lg border px-3 py-2 text-sm"
521 >
522 <Radio value={machine.environmentId} />
523 <EnvironmentMachineIcon
524 kind={machine.machine}
525 className="size-4 shrink-0 text-muted-foreground"
526 />
527 <span className="min-w-0 flex-1 truncate font-medium">{machine.label}</span>
528 <LinkMachineBadge machine={machine} />
529 </label>
530 ))}
531 <label className="flex cursor-pointer items-center gap-2.5 rounded-lg border px-3 py-2 text-sm">
532 <Radio value={ANOTHER_ADDRESS} />
533 <span className="min-w-0 flex-1 font-medium">
534 <T>Another address…</T>
535 </span>
536 </label>
537 </RadioGroup>
538 </div>
539 );
540 }