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