@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 545 lines 19.8 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import {
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";
15 import {
16 isAtomCommandInterrupted,
17 squashAtomCommandFailure,
18 } from "@t3tools/client-runtime/state/runtime";
19 import {
20 AuthAccessWriteScope,
21 type AuthMcpClientAccess,
22 type EnvironmentId,
23 type OrchestrationV2ProjectedTurnItem,
24 } from "@t3tools/contracts";
25 import * as Option from "effect/Option";
26 import * as Result from "effect/Result";
27 import { msg, T, useGT, useMessages, Var } from "gt-react-native";
28 import { useMemo, useRef, useState } from "react";
29 import { Pressable, ScrollView, View, type ColorValue } from "react-native";
30 import { useSafeAreaInsets } from "react-native-safe-area-context";
31
32 import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
33 import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
34 import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
35 import type { MessageResolver } from "../../i18n/messages";
36 import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks";
37 import { mintPairingCodeOn } from "../../state/peerPairingCode";
38 import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
39 import { useAtomCommand } from "../../state/use-atom-command";
40 import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow";
41 import { SettingsSection } from "../settings/components/SettingsSection";
42 import { Button } from "../../components/ui/Button";
43 import { Sheet } from "../../components/ui/Sheet";
44 import { RUNTIME_MODE_CHOICES } from "./thread-settings-options";
45
46 /** The same five levels as web's access picker: read-only, then the runtime modes. */
47 export 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 ];
59 const 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
64 const LINK_SYMBOL: AppSymbolName = { ios: "link", android: "desktop_windows" };
65
66 /** Whether the agent left the machine for the user to pick. */
67 const 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 */
75 export 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
105 function 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} to this environment", { target: linkDestination(item.url) })}
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("Decline", { $context: "verb, refuses the link request" })}
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
197 function 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={
300 pickMachine || targetName === null
301 ? gt("Link a machine")
302 : gt("Link {targetName}", { targetName })
303 }
304 onClose={props.onClose}
305 // An answer that lands after a close would still link, and would close a reopened sheet.
306 dismissDisabled={busy}
307 >
308 <ScrollView
309 nestedScrollEnabled
310 className="flex-1 bg-sheet-solid"
311 contentInsetAdjustmentBehavior="automatic"
312 contentContainerClassName="gap-5 p-5"
313 contentContainerStyle={{ paddingBottom: insets.bottom + 20 }}
314 keyboardShouldPersistTaps="handled"
315 >
316 <View className="gap-1">
317 <Text className="font-sans text-sm leading-5 text-foreground-muted">
318 <T>
319 Agents here can then launch, message and wait on threads there. It appears under
320 Authorized clients in that machine's Sharing & access, where it can be revoked.
321 </T>
322 </Text>
323 {item.url !== undefined && target.kind === "machine" ? (
324 <Text className="font-sans text-xs text-foreground-muted" numberOfLines={1}>
325 {item.url}
326 </Text>
327 ) : null}
328 </View>
329 {needsAddress && !useExisting && address.trim() ? (
330 <View
331 accessibilityRole="alert"
332 className="gap-1 rounded-xl border border-warning-border bg-warning p-3"
333 >
334 <Text className="font-t3-bold text-sm text-warning-foreground">
335 <T>Check this address</T>
336 </Text>
337 <Text className="font-sans text-xs leading-snug text-warning-foreground">
338 <T>
339 This app cannot confirm it is one of your machines. The pairing code you paste is
340 sent there.
341 </T>
342 </Text>
343 <Text selectable className="font-sans text-xs leading-snug text-warning-foreground">
344 {linkDestination(address)}
345 </Text>
346 </View>
347 ) : null}
348 {pickMachine ? (
349 <SettingsSection title={gt("Machine")}>
350 {machines.map((machine, index) => (
351 <MachineRow
352 key={machine.environmentId}
353 machine={machine}
354 selected={selected === machine.environmentId}
355 separated={index > 0}
356 disabled={busy}
357 onPress={() => {
358 setChoice(machine.environmentId);
359 setError(null);
360 }}
361 />
362 ))}
363 <SettingsChoiceRow
364 label={gt("Another address…")}
365 description={gt(
366 "Link a machine this app does not know, by its https or Tailscale address.",
367 )}
368 selected={selected === ANOTHER_ADDRESS}
369 separated={machines.length > 0}
370 disabled={busy}
371 onPress={() => {
372 setChoice(ANOTHER_ADDRESS);
373 setError(null);
374 }}
375 />
376 </SettingsSection>
377 ) : null}
378 {needsAddress && item.url === undefined ? (
379 <View className="gap-2">
380 <TextInput
381 accessibilityLabel={gt("Address")}
382 placeholder="https://machine.tailnet.ts.net"
383 value={address}
384 onChangeText={setAddress}
385 editable={!busy}
386 autoCorrect={false}
387 autoCapitalize="none"
388 keyboardType="url"
389 spellCheck={false}
390 />
391 {target.kind === "machine" ? (
392 <Text className="font-sans text-xs text-foreground-muted">
393 <T>
394 This app has no address for <Var>{target.label}</Var> that another machine can
395 reach. Enter its https or Tailscale address.
396 </T>
397 </Text>
398 ) : null}
399 </View>
400 ) : null}
401 {useExisting ? (
402 <Text className="font-sans text-sm leading-5 text-foreground-muted">
403 <T>
404 This environment is already linked to <Var>{targetName}</Var>. The agent can use that
405 link as it is; change its access in Settings → Environments.
406 </T>
407 </Text>
408 ) : target.kind === "none" ? null : (
409 <>
410 {canMint ? null : (
411 <View className="gap-2">
412 <TextInput
413 accessibilityLabel={gt("Pairing code")}
414 placeholder={gt("Paste the code")}
415 value={pairingCode}
416 onChangeText={setPairingCode}
417 editable={!busy}
418 autoCorrect={false}
419 autoCapitalize="none"
420 autoComplete="one-time-code"
421 textContentType="oneTimeCode"
422 spellCheck={false}
423 />
424 <Text className="font-sans text-xs text-foreground-muted">
425 {targetName === null ? (
426 <T>
427 Create a link on a machine: Settings → Sharing & access → Authorized clients →
428 Create link, then paste its code here.
429 </T>
430 ) : (
431 <T>
432 Create a link on <Var>{targetName}</Var>: Settings → Sharing & access →
433 Authorized clients → Create link, then paste its code here.
434 </T>
435 )}
436 </Text>
437 </View>
438 )}
439 <SettingsSection title={gt("What agents here may do there")}>
440 {LINK_ACCESS_CHOICES.map((choice, index) => (
441 <SettingsChoiceRow
442 key={choice.access}
443 label={m(choice.label)}
444 description={m(choice.description)}
445 selected={choice.access === access}
446 separated={index > 0}
447 disabled={busy}
448 onPress={() => setAccess(choice.access)}
449 />
450 ))}
451 </SettingsSection>
452 <Text className="font-sans text-xs text-foreground-muted">
453 <T>
454 An agent here never gets more there than its own mode here either. Threads it starts
455 there cannot change that environment's own threads, projects or settings.
456 </T>
457 </Text>
458 </>
459 )}
460 {error !== null ? (
461 <Text
462 accessibilityRole="alert"
463 accessibilityLiveRegion="polite"
464 className="font-sans text-sm text-danger-foreground"
465 >
466 {error}
467 </Text>
468 ) : null}
469 <Button
470 label={
471 busy
472 ? gt("Linking…")
473 : useExisting
474 ? gt("Use this link")
475 : gt("Link", { $context: "verb, confirms linking the machine" })
476 }
477 disabled={busy || !ready}
478 onPress={() => void submit()}
479 tone="primary"
480 fullWidth
481 />
482 <Button
483 label={gt("Cancel")}
484 tone="secondary"
485 disabled={busy}
486 onPress={props.onClose}
487 fullWidth
488 />
489 </ScrollView>
490 </Sheet>
491 );
492 }
493
494 /** One machine in the sheet's list: its glyph, name, and whether it is linked or reachable. */
495 function MachineRow(props: {
496 readonly machine: LinkableMachine;
497 readonly selected: boolean;
498 readonly separated: boolean;
499 readonly disabled: boolean;
500 readonly onPress: () => void;
501 }) {
502 const gt = useGT();
503 const { machine } = props;
504 const status = machine.linked
505 ? gt("Linked")
506 : machine.connected
507 ? null
508 : machine.connectOnly
509 ? "T3 Connect"
510 : gt("Not connected");
511 return (
512 <Pressable
513 accessibilityRole="radio"
514 accessibilityState={{ checked: props.selected, disabled: props.disabled }}
515 className={
516 props.separated
517 ? "flex-row items-center gap-3 border-t border-border-subtle p-4 active:opacity-70"
518 : "flex-row items-center gap-3 p-4 active:opacity-70"
519 }
520 disabled={props.disabled}
521 onPress={props.onPress}
522 >
523 <EnvironmentMachineSymbol
524 kind={machine.machine}
525 size={18}
526 tintColorClassName="accent-foreground-muted"
527 />
528 <View className="min-w-0 flex-1 gap-0.5">
529 <Text className="text-lg text-foreground android:text-base" numberOfLines={1}>
530 {machine.label}
531 </Text>
532 {status === null ? null : <Text className="text-sm text-foreground-muted">{status}</Text>}
533 </View>
534 {props.selected ? (
535 <SymbolView
536 name="checkmark"
537 size={18}
538 tintColorClassName="accent-icon"
539 type="monochrome"
540 weight="semibold"
541 />
542 ) : null}
543 </Pressable>
544 );
545 }