Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 HANDOFF_LINK_DEFAULT_ACCESS,
4 handoffLinkCandidates,
5 handoffRequestDisplay,
6 type HandoffRequestItem,
7 handoffRequestTarget,
8} from "@t3tools/client-runtime/handoff-request";
9import {
10 linkRequestFailureMessage,
11 type LinkableMachine,
12} from "@t3tools/client-runtime/link-request";
13import {
14 isAtomCommandInterrupted,
15 squashAtomCommandFailure,
16} from "@t3tools/client-runtime/state/runtime";
17import {
18 AuthAccessWriteScope,
19 type AuthMcpClientAccess,
20 type EnvironmentId,
21 type OrchestrationV2ProjectedTurnItem,
22 type ProjectId,
23} from "@t3tools/contracts";
24import * as Result from "effect/Result";
25import { T, msg, useGT, useMessages } from "gt-react-native";
26import { useRef, useState } from "react";
27import { View, type ColorValue } from "react-native";
28
29import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
30import { AppText as Text } from "../../components/ui/AppText";
31import { Button } from "../../components/ui/Button";
32import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
33import { scopedThreadKey } from "../../lib/scopedEntities";
34import { SettingsSection } from "../settings/components/SettingsSection";
35import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks";
36import { mintPairingCodeOn } from "../../state/peerPairingCode";
37import { useEnvironmentQuery } from "../../state/query";
38import { useEnvironmentScope } from "../../state/session";
39import { threadHandoffEnvironment, useCanMoveThreads } from "../../state/threadHandoff";
40import { useAtomCommand } from "../../state/use-atom-command";
41import { threadHasQueuedMessages, useQueuedThreadKeys } from "../../state/use-thread-outbox";
42import { useHandoffProject } from "./useHandoffProject";
43import { LINK_ACCESS_CHOICES } from "./LinkRequestCard";
44
45const TITLE = msg("Move this thread");
46const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" };
47
48/** An agent's ask to move its thread: the user picks the machine and moves it, or declines. */
49export function HandoffRequestCard(props: {
50 readonly environmentId: EnvironmentId;
51 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
52 readonly iconColor: ColorValue;
53}) {
54 const m = useMessages();
55 const { item, visibility } = props.projectedItem;
56 if (item.type !== "handoff_request") return null;
57 const display = handoffRequestDisplay(item, visibility, m);
58 if (display.kind === "pending") {
59 return <PendingHandoffRequest environmentId={props.environmentId} item={item} />;
60 }
61 const icon: AppSymbolName =
62 display.kind === "pending-elsewhere" ? LOCK_SYMBOL : display.accepted ? "checkmark" : "minus";
63 return (
64 <View className="mb-3 min-h-9 flex-row items-center gap-2 px-1">
65 <SymbolView name={icon} size={13} tintColor={props.iconColor} type="monochrome" />
66 <Text className="flex-1 font-sans text-sm text-foreground-muted" numberOfLines={2}>
67 {m(TITLE)} · {display.label}
68 </Text>
69 </View>
70 );
71}
72
73function PendingHandoffRequest(props: {
74 readonly environmentId: EnvironmentId;
75 readonly item: HandoffRequestItem;
76}) {
77 const gt = useGT();
78 const m = useMessages();
79 const { item } = props;
80 const canMove = useCanMoveThreads(props.environmentId);
81 const targets = useEnvironmentQuery(
82 threadHandoffEnvironment.options({
83 environmentId: props.environmentId,
84 input: { threadId: item.threadId },
85 }),
86 );
87 const start = useAtomCommand(threadHandoffEnvironment.start, { reportFailure: false });
88 const cancel = useAtomCommand(threadHandoffEnvironment.cancel, { reportFailure: false });
89 const link = useAtomCommand(peerLinkEnvironment.link, {
90 // The failure cause holds the request, and with it the code; keep it out of the logs.
91 reportFailure: false,
92 reportDefect: false,
93 });
94 const [picked, setPicked] = useState<EnvironmentId | null>(null);
95 const [access, setAccess] = useState<AuthMcpClientAccess>(HANDOFF_LINK_DEFAULT_ACCESS);
96 const [busy, setBusy] = useState<"move" | "decline" | null>(null);
97 const [error, setError] = useState<string | null>(null);
98 // Two taps can land before a re-render; this guard is synchronous.
99 const inFlight = useRef(false);
100 // A message in the outbox exists only on this device, and a moved thread refuses it.
101 const outboxWaiting = useQueuedThreadKeys().has(
102 scopedThreadKey(props.environmentId, item.threadId),
103 );
104 const options = targets.data?.options ?? [];
105 // Machines this client is connected to that the thread's environment has no link to yet.
106 // Linking is changed on this thread's machine too, which this session may not be allowed to.
107 const mayLinkHere = useAtomValue(peerLinkEnvironment.link.permissionAtom(props.environmentId));
108 const linkable = handoffLinkCandidates(useLinkableMachines(props.environmentId, true)).filter(
109 (machine) =>
110 targets.data !== null &&
111 mayLinkHere &&
112 !options.some((option) => option.environmentId === machine.environmentId),
113 );
114 const wanted = picked ?? item.environmentId;
115 const pickedLinkable = linkable.find((machine) => machine.environmentId === wanted);
116 // This device creates the link's code there, which its session must be allowed to.
117 const mayLink = useEnvironmentScope(pickedLinkable?.environmentId ?? null, AuthAccessWriteScope);
118 const toLink = mayLink ? pickedLinkable : undefined;
119 const chosen = pickedLinkable === undefined ? handoffRequestTarget(options, wanted) : undefined;
120 const target = toLink ?? chosen;
121 const suggestedProject =
122 target?.environmentId === item.environmentId ? item.projectId : undefined;
123 const needsProject =
124 suggestedProject === undefined &&
125 (toLink !== undefined || chosen?.projectSelectionRequired === true);
126 const project = useHandoffProject(
127 { environmentId: props.environmentId, threadId: item.threadId },
128 target?.environmentId,
129 needsProject,
130 busy !== null || !canMove,
131 chosen?.projectChoices,
132 item.id,
133 );
134 const move = (environmentId: EnvironmentId, projectId?: ProjectId) =>
135 start({
136 environmentId: props.environmentId,
137 input: {
138 threadId: item.threadId,
139 environmentId,
140 turnItemId: item.id,
141 ...(projectId === undefined ? {} : { projectId }),
142 },
143 });
144
145 const answer = async (
146 key: "move" | "decline",
147 send: () => ReturnType<typeof start> | ReturnType<typeof cancel>,
148 ) => {
149 if (inFlight.current) return;
150 inFlight.current = true;
151 setBusy(key);
152 setError(null);
153 const result = await send().finally(() => {
154 inFlight.current = false;
155 setBusy(null);
156 });
157 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
158 const failure = squashAtomCommandFailure(result);
159 setError(failure instanceof Error ? failure.message : gt`The thread could not be moved.`);
160 };
161
162 /** Links the thread's environment to `machine`; resolves to what went wrong, or null. */
163 const linkTo = async (machine: LinkableMachine): Promise<unknown> => {
164 const [url, ...alternateUrls] = machine.urls;
165 if (url === undefined) return "interrupted";
166 const code = await mintPairingCodeOn(machine.environmentId, access);
167 if (Result.isFailure(code)) return code.failure;
168 const linked = await link({
169 environmentId: props.environmentId,
170 input: {
171 url,
172 ...(alternateUrls.length === 0 ? {} : { alternateUrls }),
173 pairingCode: code.success,
174 access,
175 expectedEnvironmentId: machine.environmentId,
176 expectedLabel: machine.label,
177 },
178 });
179 if (linked._tag !== "Failure") return null;
180 return isAtomCommandInterrupted(linked) ? "interrupted" : squashAtomCommandFailure(linked);
181 };
182
183 /** Links to a machine this client is connected to, then moves the thread there. */
184 const linkAndMove = async (machine: LinkableMachine) => {
185 if (inFlight.current) return;
186 inFlight.current = true;
187 setBusy("move");
188 setError(null);
189 const failure = await linkTo(machine);
190 inFlight.current = false;
191 setBusy(null);
192 if (failure !== null) {
193 if (failure !== "interrupted") setError(linkRequestFailureMessage(failure, m));
194 return;
195 }
196 // Linking took a while; a message queued here meanwhile would be stranded by the move.
197 if (threadHasQueuedMessages(scopedThreadKey(props.environmentId, item.threadId))) return;
198 targets.refresh();
199 if (project.clone) project.clone();
200 else
201 await answer("move", () =>
202 move(machine.environmentId, project.projectId ?? suggestedProject),
203 );
204 };
205
206 return (
207 <View className="mb-3 gap-3 rounded-[20px] border border-border bg-card-alt p-4">
208 <View className="gap-1">
209 <Text className="font-t3-bold text-base text-foreground">
210 <T>Move this thread to another machine?</T>
211 </Text>
212 <Text className="font-sans text-xs text-foreground-muted">
213 {outboxWaiting
214 ? gt`A message is still waiting to send from this device. Send or discard it first.`
215 : targets.data === null
216 ? (targets.error ?? gt`Asking linked machines…`)
217 : options.length === 0 && linkable.length === 0
218 ? gt`This machine has no linked machines.`
219 : gt`It moves with its conversation and its code, uncommitted changes included. This copy becomes read-only.`}
220 </Text>
221 </View>
222 {error !== null ? (
223 <Text accessibilityRole="alert" className="font-sans text-sm text-danger-foreground">
224 {error}
225 </Text>
226 ) : !canMove ? (
227 <Text className="font-sans text-xs text-foreground-muted">
228 <T>Only someone who can run agents on this machine can move it or decline.</T>
229 </Text>
230 ) : null}
231 {options.length > 0 || linkable.length > 0 ? (
232 <SettingsSection title={gt`Machine`}>
233 {options.map((option, index) => (
234 <ListChoiceRow
235 key={option.environmentId}
236 label={option.label}
237 {...(option.reason === null ? {} : { description: option.reason })}
238 selected={chosen?.environmentId === option.environmentId}
239 separated={index > 0}
240 disabled={
241 busy !== null ||
242 (option.reason !== null && !option.projectSelectionRequired) ||
243 !canMove
244 }
245 onPress={() => setPicked(option.environmentId)}
246 />
247 ))}
248 {linkable.map((machine, index) => (
249 <ListChoiceRow
250 key={machine.environmentId}
251 label={machine.label}
252 description={gt`Not linked yet`}
253 selected={pickedLinkable?.environmentId === machine.environmentId}
254 separated={options.length + index > 0}
255 disabled={busy !== null || !canMove}
256 onPress={() => setPicked(machine.environmentId)}
257 />
258 ))}
259 </SettingsSection>
260 ) : null}
261 {pickedLinkable !== undefined && !mayLink ? (
262 <Text className="font-sans text-xs text-foreground-muted">
263 {gt`This device may not create a link on ${{ machine: pickedLinkable.label }}. Link it from Settings on a device that can.`}
264 </Text>
265 ) : null}
266 {toLink !== undefined ? (
267 <>
268 <Text className="font-sans text-xs text-foreground-muted">
269 {gt`This machine is not linked to ${{ machine: toLink.label }} yet. Moving the thread links them first, with a code this device creates there. Choose what agents here may do there.`}
270 </Text>
271 <SettingsSection title={gt`What agents here may do there`}>
272 {/* A thread cannot be moved over a read-only link. */}
273 {LINK_ACCESS_CHOICES.filter((choice) => choice.access !== "read-only").map(
274 (choice, index) => (
275 <ListChoiceRow
276 key={choice.access}
277 label={m(choice.label)}
278 description={m(choice.description)}
279 selected={choice.access === access}
280 separated={index > 0}
281 disabled={busy !== null}
282 onPress={() => setAccess(choice.access)}
283 />
284 ),
285 )}
286 </SettingsSection>
287 </>
288 ) : null}
289 {project.picker}
290 {needsProject && project.picker === null && project.clone === undefined ? (
291 <Text className="font-sans text-xs text-foreground-muted">
292 {chosen?.reason ?? gt`No project is available on this machine.`}
293 </Text>
294 ) : null}
295 <Button
296 label={
297 project.clone
298 ? gt`Add project and move`
299 : toLink === undefined
300 ? gt`Move`
301 : gt`Link and move`
302 }
303 tone="primary"
304 fullWidth
305 loading={busy === "move"}
306 disabled={
307 busy !== null ||
308 outboxWaiting ||
309 !canMove ||
310 target === undefined ||
311 (needsProject && !project.projectId && !project.clone)
312 }
313 onPress={() => {
314 if (toLink !== undefined) void linkAndMove(toLink);
315 else if (project.clone) project.clone();
316 else if (chosen !== undefined)
317 void answer("move", () =>
318 move(chosen.environmentId, project.projectId ?? suggestedProject),
319 );
320 }}
321 />
322 <Button
323 label={gt`Not now`}
324 tone="text"
325 loading={busy === "decline"}
326 disabled={busy !== null || !canMove}
327 onPress={() =>
328 void answer("decline", () =>
329 cancel({
330 environmentId: props.environmentId,
331 input: { threadId: item.threadId, turnItemId: item.id },
332 }),
333 )
334 }
335 />
336 </View>
337 );
338}