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

LinkRequestCard.tsx

511 lines18.8 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 { useMemo, useRef, useState } from "react";
27import { Pressable, ScrollView, View, type ColorValue } from "react-native";
28import { useSafeAreaInsets } from "react-native-safe-area-context";
29​
30import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
31import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
32import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
33import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks";
34import { mintPairingCodeOn } from "../../state/peerPairingCode";
35import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
36import { useAtomCommand } from "../../state/use-atom-command";
37import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow";
38import { SettingsSection } from "../settings/components/SettingsSection";
39import { Button } from "../../components/ui/Button";
40import { Sheet } from "../../components/ui/Sheet";
41import { RUNTIME_MODE_CHOICES } from "./thread-settings-options";
42​
43/** The same five levels as web's access picker: read-only, then the runtime modes. */
44const ACCESS_CHOICES: ReadonlyArray<{
45 readonly access: AuthMcpClientAccess;
46 readonly label: string;
47 readonly description: string;
48}> = [
49 {
50 access: "read-only",
51 label: "Read only",
52 description: "Read projects and threads. Cannot start, message or change anything.",
53 },
54 ...RUNTIME_MODE_CHOICES.map((choice) => ({ ...choice, access: choice.mode })),
55];
56const accessLabel = (access: AuthMcpClientAccess) =>
57 ACCESS_CHOICES.find((choice) => choice.access === access)?.label ?? access;
58​
59const LINK_SYMBOL: AppSymbolName = { ios: "link", android: "desktop_windows" };
60​
61/** The machine list's row for linking by an address typed in. */
62const ANOTHER_ADDRESS = "another-address";
63​
64/** Whether the agent left the machine for the user to pick. */
65const picksMachine = (item: LinkRequestItem) =>
66 item.environmentId === undefined && item.url === undefined;
67​
68/**
69 * Feed card for a link an agent asked the user to make. The user picks the
70 * access in a sheet; the pairing code lives only in that sheet's state and
71 * the RPC payload, and is never logged, alerted, or persisted.
72 */
73export function LinkRequestCard(props: {
74 readonly environmentId: EnvironmentId;
75 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
76 readonly iconColor: ColorValue;
77}) {
78 const { item, visibility } = props.projectedItem;
79 if (item.type !== "link_request") return null;
80 const display = linkRequestDisplay(item, visibility, accessLabel);
81 if (display.kind === "pending") {
82 return <PendingLinkRequest environmentId={props.environmentId} item={item} />;
83 }
84 const icon: AppSymbolName =
85 display.kind === "pending-elsewhere"
86 ? LINK_SYMBOL
87 : display.outcome === "linked"
88 ? "checkmark"
89 : display.outcome === "failed"
90 ? "xmark"
91 : "minus";
92 return (
93 <View className="mb-3 min-h-9 flex-row items-center gap-2 px-1">
94 <SymbolView name={icon} size={13} tintColor={props.iconColor} type="monochrome" />
95 <Text className="flex-1 font-sans text-sm text-foreground-muted" numberOfLines={2}>
96 {display.label}
97 </Text>
98 </View>
99 );
101​
102function PendingLinkRequest(props: {
103 readonly environmentId: EnvironmentId;
104 readonly item: LinkRequestItem;
105}) {
106 const { item } = props;
107 const [open, setOpen] = useState(false);
108 const [declining, setDeclining] = useState(false);
109 const [error, setError] = useState<string | null>(null);
110 const answer = useAtomCommand(peerLinkEnvironment.answerRequest, {
111 label: "decline link request",
112 reportFailure: false,
113 reportDefect: false,
114 });
115 const canAnswer = useAtomValue(
116 peerLinkEnvironment.answerRequest.permissionAtom(props.environmentId),
117 );
118 const target = linkRequestTargetName(item);
119​
120 const decline = async () => {
121 const input = linkRequestAnswerInput(item, { type: "decline" });
122 if (input === null) return;
123 setDeclining(true);
124 setError(null);
125 const result = await answer({ environmentId: props.environmentId, input }).finally(() =>
126 setDeclining(false),
127 );
128 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
129 pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError);
130 }
131 };
132​
133 return (
134 <View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">
135 <View className="gap-1">
136 <Text className="font-t3-bold text-base text-foreground">
137 {picksMachine(item)
138 ? "Link a machine to this environment"
139 : `Link ${target} to this environment`}
140 </Text>
141 {item.reason.trim() ? (
142 <Text className="font-sans text-sm leading-5 text-foreground-muted">{item.reason}</Text>
143 ) : null}
144 {item.label !== undefined && item.url !== undefined ? (
145 <Text className="font-sans text-xs text-foreground-muted" numberOfLines={1}>
146 {item.url}
147 </Text>
148 ) : null}
149 </View>
150 {error !== null ? (
151 <Text
152 accessibilityRole="alert"
153 accessibilityLiveRegion="polite"
154 className="font-sans text-sm text-danger-foreground"
155 >
156 {error}
157 </Text>
158 ) : null}
159 {canAnswer ? (
160 <>
161 <Button
162 label={picksMachine(item) ? "Choose machine…" : "Review link…"}
163 disabled={declining}
164 onPress={() => setOpen(true)}
165 tone="primary"
166 fullWidth
167 />
168 <View className="flex-row justify-end">
169 <Pressable
170 accessibilityRole="button"
171 accessibilityState={{ disabled: declining }}
172 disabled={declining}
173 hitSlop={8}
174 className="px-1 py-1 active:opacity-60 disabled:opacity-50"
175 onPress={() => void decline()}
176 >
177 <Text className="font-sans text-xs text-foreground-muted">Decline</Text>
178 </Pressable>
179 </View>
180 </>
181 ) : (
182 <Text className="font-sans text-xs text-foreground-muted">
183 Only a session that manages access here can answer this.
184 </Text>
185 )}
186 {open ? (
187 <LinkRequestSheet
188 environmentId={props.environmentId}
189 item={item}
190 onClose={() => setOpen(false)}
191 />
192 ) : null}
193 </View>
194 );
196​
197/** What the sheet links; see web's LinkRequestDialog for the same rules. */
198type SheetTarget =
199 | { readonly kind: "none" }
200 | {
201 readonly kind: "machine";
202 readonly environmentId: EnvironmentId;
203 readonly label: string;
204 readonly urls: ReadonlyArray<string>;
205 readonly linked: boolean;
206 }
207 | { readonly kind: "address" };
208​
209function resolveTarget(
210 item: LinkRequestItem,
211 machines: ReadonlyArray<LinkableMachine>,
212 choice: string | null,
213): SheetTarget {
214 if (item.environmentId === undefined && item.url !== undefined) return { kind: "address" };
215 const chosen = item.environmentId ?? choice;
216 if (chosen === null) return { kind: "none" };
217 if (chosen === ANOTHER_ADDRESS) return { kind: "address" };
218 const machine = machines.find((candidate) => candidate.environmentId === chosen);
219 return {
220 kind: "machine",
221 environmentId: machine?.environmentId ?? (chosen as EnvironmentId),
222 label: machine?.label ?? linkRequestTargetName(item),
223 urls: [...new Set([...(machine?.urls ?? []), ...(item.url === undefined ? [] : [item.url])])],
224 linked: machine?.linked ?? false,
225 };
227​
228function LinkRequestSheet(props: {
229 readonly environmentId: EnvironmentId;
230 readonly item: LinkRequestItem;
231 readonly onClose: () => void;
232}) {
233 const { item } = props;
234 const insets = useSafeAreaInsets();
235 const pickMachine = picksMachine(item);
236 const listed = useLinkableMachines(props.environmentId, true);
237 const machines = useMemo(() => rankMachinesByHint(listed, item.hint), [listed, item.hint]);
238 const [choice, setChoice] = useState<string | null>(null);
239 const [address, setAddress] = useState(item.url ?? "");
240 const [access, setAccess] = useState<AuthMcpClientAccess>(() => linkRequestDefaultAccess(item));
241 const [pairingCode, setPairingCode] = useState("");
242 const [busy, setBusy] = useState(false);
243 const [error, setError] = useState<string | null>(null);
244 const [mintFailed, setMintFailed] = useState<ReadonlySet<EnvironmentId>>(new Set());
245 // Submit then a tap can both run before a re-render; this guard is synchronous.
246 const inFlight = useRef(false);
247 const answer = useAtomCommand(peerLinkEnvironment.answerRequest, {
248 label: "answer link request",
249 // The failure cause holds the request, and with it the code; keep it out of the console.
250 reportFailure: false,
251 reportDefect: false,
252 });
253 const selected = choice ?? linkRequestInitialMachine(item, machines);
254 const target = resolveTarget(item, machines, selected);
255 const targetName = target.kind === "machine" ? target.label : linkRequestTargetName(item);
256 // This phone can mint a code there when it is connected to that environment
257 // with a session that may create pairing links.
258 const targetId = target.kind === "machine" ? target.environmentId : null;
259 const connected = usePreparedConnection(targetId);
260 const mayMint = useEnvironmentScope(targetId, AuthAccessWriteScope);
261 const canMint =
262 targetId !== null && Option.isSome(connected) && mayMint && !mintFailed.has(targetId);
263 const needsAddress =
264 target.kind === "address" || (target.kind === "machine" && target.urls.length === 0);
265 const useExisting = target.kind === "machine" && target.linked;
266 const ready =
267 target.kind !== "none" &&
268 (useExisting ||
269 ((!needsAddress || address.trim().length > 0) && (canMint || pairingCode.trim().length > 0)));
270​
271 const prepareAnswer = async () => {
272 if (target.kind === "none") return null;
273 if (target.kind === "machine" && target.linked) {
274 return linkRequestAnswerInput(item, {
275 type: "use-existing",
276 environmentId: target.environmentId,
277 });
278 }
279 let code = pairingCode;
280 if (canMint && targetId !== null) {
281 const minted = await mintPairingCodeOn(targetId, access);
282 if (Result.isFailure(minted)) {
283 setMintFailed((failed) => new Set(failed).add(targetId));
284 setError(linkRequestFailureMessage(minted.failure));
285 return null;
286 }
287 code = minted.success;
288 }
289 return linkRequestAnswerInput(item, {
290 type: "link",
291 target:
292 target.kind === "address"
293 ? { url: address }
294 : { ...target, urls: needsAddress ? [address.trim()] : target.urls },
295 access,
296 pairingCode: code,
297 });
298 };
299​
300 const submit = async () => {
301 if (inFlight.current || target.kind === "none") return;
302 inFlight.current = true;
303 setBusy(true);
304 setError(null);
305 const input = await prepareAnswer();
306 const result =
307 input === null ? null : await answer({ environmentId: props.environmentId, input });
308 inFlight.current = false;
309 setBusy(false);
310 if (result === null) return;
311 if (result._tag === "Success") {
312 setPairingCode("");
313 props.onClose();
314 } else if (!isAtomCommandInterrupted(result)) {
315 pipe(squashAtomCommandFailure(result), linkRequestFailureMessage, setError);
316 }
317 };
318​
319 return (
320 <Sheet
321 title={pickMachine ? "Link a machine" : `Link ${targetName}`}
322 onClose={props.onClose}
323 // An answer that lands after a close would still link, and would close a reopened sheet.
324 dismissDisabled={busy}
325 >
326 <ScrollView
327 className="flex-1 bg-sheet-solid"
328 contentInsetAdjustmentBehavior="automatic"
329 contentContainerClassName="gap-5 p-5"
330 contentContainerStyle={{ paddingBottom: insets.bottom + 20 }}
331 keyboardShouldPersistTaps="handled"
332 >
333 <View className="gap-1">
334 <Text className="font-sans text-sm leading-5 text-foreground-muted">
335 Agents here can then launch, message and wait on threads there. It appears in that
336 machine's Connections, where it can be revoked.
337 </Text>
338 {!pickMachine && item.url !== undefined ? (
339 <Text className="font-sans text-xs text-foreground-muted" numberOfLines={1}>
340 {item.url}
341 </Text>
342 ) : null}
343 </View>
344 {pickMachine ? (
345 <SettingsSection title="Machine">
346 {machines.map((machine, index) => (
347 <MachineRow
348 key={machine.environmentId}
349 machine={machine}
350 selected={selected === machine.environmentId}
351 separated={index > 0}
352 disabled={busy}
353 onPress={() => {
354 setChoice(machine.environmentId);
355 setError(null);
356 }}
357 />
358 ))}
359 <SettingsChoiceRow
360 label="Another address…"
361 description="Link a machine this app does not know, by its https or Tailscale address."
362 selected={selected === ANOTHER_ADDRESS}
363 separated={machines.length > 0}
364 disabled={busy}
365 onPress={() => {
366 setChoice(ANOTHER_ADDRESS);
367 setError(null);
368 }}
369 />
370 </SettingsSection>
371 ) : null}
372 {needsAddress && !(item.url !== undefined && item.environmentId === undefined) ? (
373 <View className="gap-2">
374 <TextInput
375 accessibilityLabel="Address"
376 placeholder="https://machine.tailnet.ts.net"
377 value={address}
378 onChangeText={setAddress}
379 editable={!busy}
380 autoCorrect={false}
381 autoCapitalize="none"
382 keyboardType="url"
383 spellCheck={false}
384 />
385 {target.kind === "machine" ? (
386 <Text className="font-sans text-xs text-foreground-muted">
387 This app has no address for {target.label} that another machine can reach. Enter its
388 https or Tailscale address.
389 </Text>
390 ) : null}
391 </View>
392 ) : null}
393 {useExisting ? (
394 <Text className="font-sans text-sm leading-5 text-foreground-muted">
395 This environment is already linked to {targetName}. The agent can use that link as it
396 is; change its access in Settings → Connections.
397 </Text>
398 ) : target.kind === "none" ? null : (
399 <>
400 {canMint ? null : (
401 <View className="gap-2">
402 <TextInput
403 accessibilityLabel="Pairing code"
404 placeholder="Paste the code"
405 value={pairingCode}
406 onChangeText={setPairingCode}
407 editable={!busy}
408 autoCorrect={false}
409 autoCapitalize="none"
410 autoComplete="one-time-code"
411 textContentType="oneTimeCode"
412 spellCheck={false}
413 />
414 <Text className="font-sans text-xs text-foreground-muted">
415 Create a link on {targetName}: Settings → Connections → Create link, then paste
416 its code here.
417 </Text>
418 </View>
419 )}
420 <SettingsSection title="What agents here may do there">
421 {ACCESS_CHOICES.map((choice, index) => (
422 <SettingsChoiceRow
423 key={choice.access}
424 label={choice.label}
425 description={choice.description}
426 selected={choice.access === access}
427 separated={index > 0}
428 disabled={busy}
429 onPress={() => setAccess(choice.access)}
430 />
431 ))}
432 </SettingsSection>
433 <Text className="font-sans text-xs text-foreground-muted">
434 An agent here never gets more there than its own mode here either. Threads it starts
435 there cannot change that environment's own threads, projects or settings.
436 </Text>
437 </>
438 )}
439 {error !== null ? (
440 <Text
441 accessibilityRole="alert"
442 accessibilityLiveRegion="polite"
443 className="font-sans text-sm text-danger-foreground"
444 >
445 {error}
446 </Text>
447 ) : null}
448 <Button
449 label={busy ? "Linking…" : useExisting ? "Use this link" : "Link"}
450 disabled={busy || !ready}
451 onPress={() => void submit()}
452 tone="primary"
453 fullWidth
454 />
455 <Button label="Cancel" tone="secondary" disabled={busy} onPress={props.onClose} fullWidth />
456 </ScrollView>
457 </Sheet>
458 );
460​
461/** One machine in the sheet's list: its glyph, name, and whether it is linked or reachable. */
462function MachineRow(props: {
463 readonly machine: LinkableMachine;
464 readonly selected: boolean;
465 readonly separated: boolean;
466 readonly disabled: boolean;
467 readonly onPress: () => void;
468}) {
469 const { machine } = props;
470 const status = machine.linked
471 ? "Linked"
472 : machine.connected
473 ? null
474 : machine.connectOnly
475 ? "T3 Connect"
476 : "Not connected";
477 return (
478 <Pressable
479 accessibilityRole="radio"
480 accessibilityState={{ checked: props.selected, disabled: props.disabled }}
481 className={
482 props.separated
483 ? "flex-row items-center gap-3 border-t border-border-subtle p-4 active:opacity-70"
484 : "flex-row items-center gap-3 p-4 active:opacity-70"
485 }
486 disabled={props.disabled}
487 onPress={props.onPress}
488 >
489 <EnvironmentMachineSymbol
490 kind={machine.machine}
491 size={18}
492 tintColorClassName="accent-foreground-muted"
493 />
494 <View className="min-w-0 flex-1 gap-0.5">
495 <Text className="text-lg text-foreground android:text-base" numberOfLines={1}>
496 {machine.label}
497 </Text>
498 {status === null ? null : <Text className="text-sm text-foreground-muted">{status}</Text>}
499 </View>
500 {props.selected ? (
501 <SymbolView
502 name="checkmark"
503 size={18}
504 tintColorClassName="accent-icon"
505 type="monochrome"
506 weight="semibold"
507 />
508 ) : null}
509 </Pressable>
510 );