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

LinkRequestCard.tsx

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