Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 linkBatchBlockLabel,
4 linkBatchCandidates,
5 linkBatchFailureLabel,
6 type LinkBatchOutcome,
7 linkBatchSummary,
8 linkListState,
9 runLinkBatch,
10} from "@t3tools/client-runtime/link-batch";
11import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request";
12import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
13import {
14 AuthAccessWriteScope,
15 type AuthMcpClientAccess,
16 type EnvironmentId,
17} from "@t3tools/contracts";
18import * as Result from "effect/Result";
19import { T, useGT, useMessages, plural, part, n } from "gt-react-native";
20import { useMemo, useRef, useState } from "react";
21import { Pressable, ScrollView, View } from "react-native";
22import { useSafeAreaInsets } from "react-native-safe-area-context";
23
24import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
25import { SymbolView } from "../../components/ui/AppSymbol";
26import { AppText as Text } from "../../components/ui/AppText";
27import { Button } from "../../components/ui/Button";
28import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
29import { Sheet } from "../../components/ui/Sheet";
30import { useEnvironmentServerConfig } from "../../state/entities";
31import { useEnvironments } from "../../state/environments";
32import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks";
33import { mintPairingCodeOn } from "../../state/peerPairingCode";
34import { useEnvironmentQuery } from "../../state/query";
35import { useEnvironmentsWithScope } from "../../state/session";
36import { useAtomCommand } from "../../state/use-atom-command";
37import { SettingsSection } from "../settings/components/SettingsSection";
38import { LINK_ACCESS_CHOICES } from "../threads/LinkRequestCard";
39
40const NO_MACHINES: ReadonlySet<EnvironmentId> = new Set();
41const NO_OUTCOMES: ReadonlyMap<EnvironmentId, LinkBatchOutcome> = new Map();
42
43/** Offers a batch link from `environmentId` once this app has two other machines saved. */
44export function LinkSeveralEnvironmentsAction(props: {
45 readonly environmentId: EnvironmentId;
46 readonly environmentLabel: string;
47}) {
48 const gt = useGT();
49 const [open, setOpen] = useState(false);
50 const config = useEnvironmentServerConfig(props.environmentId);
51 const canLink = useAtomValue(peerLinkEnvironment.link.permissionAtom(props.environmentId));
52 const otherMachines = useEnvironments().environments.length - 1;
53 if (!canLink || !offersLinkedEnvironments(config) || otherMachines < 2) return null;
54 return (
55 <View className="mt-3">
56 <Button
57 label={gt`Link several machines to ${{ environment: props.environmentLabel }}…`}
58 onPress={() => setOpen(true)}
59 fullWidth
60 />
61 {open ? (
62 <LinkSeveralSheet environmentId={props.environmentId} onClose={() => setOpen(false)} />
63 ) : null}
64 </View>
65 );
66}
67
68/**
69 * Each pairing code is minted on its machine and passed straight to the linking
70 * environment; none is ever held in state, shown, or logged.
71 */
72function LinkSeveralSheet(props: {
73 readonly environmentId: EnvironmentId;
74 readonly onClose: () => void;
75}) {
76 const gt = useGT();
77 const m = useMessages();
78 const insets = useSafeAreaInsets();
79 const machines = useLinkableMachines(props.environmentId, true);
80 // The same shared list `useLinkableMachines` reads `linked` from.
81 const links = useEnvironmentQuery(
82 peerLinkEnvironment.list({ environmentId: props.environmentId, input: {} }),
83 );
84 const linksState = linkListState(links);
85 const machineIds = machines.map((machine) => machine.environmentId).join("\n");
86 const scoped = useMemo(
87 () =>
88 machineIds
89 .split("\n")
90 .filter((id) => id.length > 0)
91 .map((id) => ({ environmentId: id as EnvironmentId })),
92 [machineIds],
93 );
94 const writable = useEnvironmentsWithScope(scoped, AuthAccessWriteScope);
95 const [selected, setSelected] = useState(NO_MACHINES);
96 const [access, setAccess] = useState<AuthMcpClientAccess>("approval-required");
97 const [outcomes, setOutcomes] = useState(NO_OUTCOMES);
98 const [linking, setLinking] = useState(NO_MACHINES);
99 // Two taps can both run before a re-render; this guard is synchronous.
100 const inFlight = useRef(false);
101 const link = useAtomCommand(peerLinkEnvironment.linkInBatch, {
102 label: "link several environments",
103 // The failure cause holds the request, and with it the code; keep it out of the console.
104 reportFailure: false,
105 reportDefect: false,
106 });
107 const candidates = linkBatchCandidates(machines, writable, linksState);
108 const selectable = candidates.flatMap(({ machine, blocked }) =>
109 blocked === null && outcomes.get(machine.environmentId)?.kind !== "linked" ? [machine] : [],
110 );
111 const chosen = selectable.filter((machine) => selected.has(machine.environmentId));
112 const busy = linking.size > 0;
113 const summary = linkBatchSummary(outcomes);
114 const allChosen = selectable.length > 0 && chosen.length === selectable.length;
115
116 const toggle = (id: EnvironmentId) =>
117 setSelected((current) => {
118 const next = new Set(current);
119 if (!next.delete(id)) next.add(id);
120 return next;
121 });
122 const submit = async () => {
123 if (inFlight.current || chosen.length === 0) return;
124 inFlight.current = true;
125 setLinking(new Set(chosen.map((machine) => machine.environmentId)));
126 const results = await runLinkBatch({
127 machines: chosen,
128 access,
129 mint: mintPairingCodeOn,
130 link: async (input) => {
131 const result = await link({ environmentId: props.environmentId, input });
132 return result._tag === "Success"
133 ? Result.succeed(result.value)
134 : Result.fail(squashAtomCommandFailure(result));
135 },
136 refreshLinks: links.refresh,
137 onOutcome: (id, outcome) => {
138 setOutcomes((current) => new Map(current).set(id, outcome));
139 setLinking((current) => {
140 const next = new Set(current);
141 next.delete(id);
142 return next;
143 });
144 },
145 });
146 inFlight.current = false;
147 setLinking(NO_MACHINES);
148 // What failed stays picked, so linking again retries only those.
149 setSelected(new Set(linkBatchSummary(results).failed));
150 };
151
152 return (
153 <Sheet
154 title={gt`Link several environments`}
155 onClose={props.onClose}
156 // A batch that lands after a close would still link.
157 dismissDisabled={busy}
158 >
159 <ScrollView
160 nestedScrollEnabled
161 className="flex-1 bg-sheet-solid"
162 contentInsetAdjustmentBehavior="automatic"
163 contentContainerClassName="gap-5 p-5"
164 contentContainerStyle={{ paddingBottom: insets.bottom + 20 }}
165 >
166 <Text className="font-sans text-sm leading-5 text-foreground-muted">
167 <T>
168 Agents here can then launch, message and wait on threads on each machine you pick. Each
169 appears under Authorized clients in that machine's Sharing & access, where it can be
170 revoked.
171 </T>
172 </Text>
173 {candidates.length === 0 ? (
174 <Text className="font-sans text-sm leading-5 text-foreground-muted">
175 <T>This app knows no other machines. Add them under Environments first.</T>
176 </Text>
177 ) : (
178 <>
179 {linksState === "loading" ? (
180 <Text
181 accessibilityLiveRegion="polite"
182 className="font-sans text-sm leading-5 text-foreground-muted"
183 >
184 <T>Checking which machines are already linked…</T>
185 </Text>
186 ) : linksState === "failed" ? (
187 <View className="gap-2">
188 <Text
189 accessibilityLiveRegion="polite"
190 className="font-sans text-sm leading-5 text-danger-foreground"
191 >
192 {gt`Could not check which machines are already linked, so none can be picked: ${{ error: links.error ?? "" }}`}
193 </Text>
194 <Button
195 label={gt`Retry`}
196 size="compact"
197 disabled={links.isPending}
198 onPress={links.refresh}
199 />
200 </View>
201 ) : null}
202 <SettingsSection title={gt`Machines`}>
203 {candidates.map(({ machine, blocked }, index) => {
204 const id = machine.environmentId;
205 const outcome = outcomes.get(id);
206 const available = blocked === null && outcome?.kind !== "linked";
207 const checked = available && selected.has(id);
208 const status = linking.has(id)
209 ? gt`Linking…`
210 : outcome?.kind === "linked"
211 ? gt({ context: "status of a machine that was just linked" })`Linked`
212 : outcome?.kind === "failed"
213 ? `${linkBatchFailureLabel(outcome.failure, m)}${outcome.detail === null ? "" : `: ${outcome.detail}`}`
214 : blocked === null
215 ? null
216 : linkBatchBlockLabel(blocked, m);
217 return (
218 <Pressable
219 key={id}
220 accessibilityRole="checkbox"
221 accessibilityLabel={machine.label}
222 accessibilityHint={status ?? undefined}
223 accessibilityState={{ checked, disabled: busy || !available }}
224 className={
225 index > 0
226 ? "flex-row items-center gap-3 border-t border-border-subtle p-4 active:opacity-70"
227 : "flex-row items-center gap-3 p-4 active:opacity-70"
228 }
229 disabled={busy || !available}
230 onPress={() => toggle(id)}
231 >
232 <EnvironmentMachineSymbol
233 kind={machine.machine}
234 size={18}
235 tintColorClassName="accent-foreground-muted"
236 />
237 <View className="min-w-0 flex-1 gap-0.5">
238 <Text
239 className={
240 available
241 ? "text-lg text-foreground android:text-base"
242 : "text-lg text-foreground-muted android:text-base"
243 }
244 numberOfLines={1}
245 >
246 {machine.label}
247 </Text>
248 {status === null ? null : (
249 <Text
250 className={
251 outcome?.kind === "failed"
252 ? "text-sm text-danger-foreground"
253 : "text-sm text-foreground-muted"
254 }
255 >
256 {status}
257 </Text>
258 )}
259 </View>
260 {checked ? (
261 <SymbolView
262 name="checkmark"
263 size={18}
264 tintColorClassName="accent-icon"
265 type="monochrome"
266 weight="semibold"
267 />
268 ) : null}
269 </Pressable>
270 );
271 })}
272 </SettingsSection>
273 <Button
274 label={allChosen ? gt`Select none` : gt`Select all`}
275 tone="text"
276 size="compact"
277 disabled={busy || selectable.length === 0}
278 onPress={() =>
279 setSelected(
280 allChosen
281 ? NO_MACHINES
282 : new Set(selectable.map((machine) => machine.environmentId)),
283 )
284 }
285 />
286 </>
287 )}
288 <SettingsSection title={gt`What agents here may do there`}>
289 {LINK_ACCESS_CHOICES.map((choice, index) => (
290 <ListChoiceRow
291 key={choice.access}
292 label={m(choice.label)}
293 description={m(choice.description)}
294 selected={choice.access === access}
295 separated={index > 0}
296 disabled={busy}
297 onPress={() => setAccess(choice.access)}
298 />
299 ))}
300 </SettingsSection>
301 {outcomes.size > 0 && !busy ? (
302 <Text
303 accessibilityLiveRegion="polite"
304 className="font-sans text-sm leading-5 text-foreground-muted"
305 >
306 {summary.failed.length === 0
307 ? gt`${plural(
308 { linked: summary.linked },
309 {
310 one: part`Linked ${n} machine.`,
311 other: part`Linked ${n} machines.`,
312 },
313 )}`
314 : gt`Linked ${{ linked: summary.linked }} of ${{ total: outcomes.size }}. The ones that failed stay selected, so you can try them again.`}
315 </Text>
316 ) : null}
317 <Button
318 label={
319 busy
320 ? gt`Linking…`
321 : gt`${plural(
322 { count: chosen.length },
323 {
324 one: part`Link ${n} machine`,
325 other: part`Link ${n} machines`,
326 },
327 )}`
328 }
329 disabled={busy || chosen.length === 0}
330 onPress={() => void submit()}
331 tone="primary"
332 fullWidth
333 />
334 <Button
335 label={outcomes.size > 0 ? gt`Done` : gt`Cancel`}
336 tone="secondary"
337 disabled={busy}
338 onPress={props.onClose}
339 fullWidth
340 />
341 </ScrollView>
342 </Sheet>
343 );
344}