Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { StackActions, useIsFocused, useNavigation } from "@react-navigation/native";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import { threadAwaitsAdoption } from "@t3tools/client-runtime/state/peerLinks";
8import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
9import { useGT } from "gt-react-native";
10import { useEffect, useEffectEvent, useState } from "react";
11import { View } from "react-native";
12
13import { AppText as Text } from "../../components/ui/AppText";
14import { Button } from "../../components/ui/Button";
15import * as Dialog from "../../components/ui/Dialog";
16import { cn } from "../../lib/cn";
17import { useEnvironments } from "../../state/environments";
18import { useConnectLinkedEnvironment } from "../../state/linkedThread";
19import { threadHandoffEnvironment, useCanMoveThreads } from "../../state/threadHandoff";
20import { useAtomCommand } from "../../state/use-atom-command";
21import { useOpenLinkedThread, useOpenLinkedThreadRead } from "./useOpenLinkedThread";
22
23/** Machines an unasked connect was tried for; a failed one leaves the card's button after that. */
24const followTried = new Set<string>();
25
26/**
27 * A thread that was moved here over a link below full access: its agent stays limited to what
28 * that link started until someone who may run agents here takes the thread over.
29 */
30function AdoptMovedThread(props: {
31 readonly thread: EnvironmentThreadShell;
32 readonly canAdopt: boolean;
33}) {
34 const gt = useGT();
35 const adopt = useAtomCommand(threadHandoffEnvironment.adopt, { reportFailure: false });
36 const [adopting, setAdopting] = useState(false);
37 const makeNormal = async () => {
38 setAdopting(true);
39 const result = await adopt({
40 environmentId: props.thread.environmentId,
41 input: { threadId: props.thread.id },
42 });
43 setAdopting(false);
44 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
45 const failure = squashAtomCommandFailure(result);
46 Dialog.alert(
47 gt("Could not make it a normal thread"),
48 failure instanceof Error ? failure.message : gt("Try again."),
49 );
50 };
51 return (
52 <View className="mx-3 mb-2 gap-2 rounded-xl border border-border-subtle bg-screen p-3">
53 <Text className="text-sm font-t3-bold text-foreground">
54 {gt("This thread was moved here over a limited link")}
55 </Text>
56 <Text className="text-sm text-foreground-secondary">
57 {gt(
58 "Its agent can change only what {origin} started here and cannot use this machine's links, until you make it a normal thread.",
59 { origin: props.thread.linkOrigin?.label ?? "" },
60 )}
61 </Text>
62 {props.canAdopt ? (
63 <Button
64 label={gt("Make it a normal thread")}
65 size="compact"
66 loading={adopting}
67 onPress={() => void makeNormal()}
68 />
69 ) : null}
70 </View>
71 );
72}
73
74/**
75 * A thread's move to a linked machine: asked for by its agent, waiting for its turn to end (with a way to keep it here),
76 * under way, or failed (with a way to try again). A moved thread is followed to where it
77 * continues, pairing with that machine first when needed, so it reads as one thread; the card
78 * stays only when this device cannot reach the machine.
79 */
80export function ThreadHandoffCard({ thread }: { readonly thread: EnvironmentThreadShell }) {
81 const gt = useGT();
82 const navigation = useNavigation();
83 const openThread = useOpenLinkedThread();
84 const openLinkedRead = useOpenLinkedThreadRead();
85 const cancel = useAtomCommand(threadHandoffEnvironment.cancel, { reportFailure: false });
86 const canMove = useCanMoveThreads(thread.environmentId);
87 // Adopting is local to this machine, so it does not need linked environments switched on.
88 const canAdopt = useAtomValue(
89 threadHandoffEnvironment.adopt.permissionAtom(thread.environmentId),
90 );
91 const { presentationById } = useEnvironments();
92 const [cancelling, setCancelling] = useState(false);
93 const [dismissed, setDismissed] = useState<string | null>(null);
94 const handoff = thread.handoff;
95 const moved = handoff?.state === "departed" ? handoff : null;
96 const movedId = moved?.handoffId;
97 const connectedThere =
98 moved !== null && presentationById.get(moved.environmentId)?.connection.phase === "connected";
99 const connection = useConnectLinkedEnvironment({
100 viaEnvironmentId: thread.environmentId,
101 environmentId: moved?.environmentId ?? thread.environmentId,
102 threadId: moved?.threadId ?? thread.id,
103 label: moved?.label ?? "",
104 title: thread.title,
105 });
106 const screenFocused = useIsFocused();
107 const follow = useEffectEvent((reachable: boolean, focused: boolean) => {
108 // Another screen the user opened on top is theirs to keep; coming back follows then.
109 if (moved === null || !focused) return;
110 if (reachable) {
111 navigation.dispatch(
112 StackActions.replace("Thread", {
113 environmentId: moved.environmentId,
114 threadId: moved.threadId,
115 }),
116 );
117 return;
118 }
119 if (followTried.has(moved.environmentId)) return;
120 followTried.add(moved.environmentId);
121 void connection.connect();
122 });
123 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a move the server reports takes the screen to the thread it continues as, pairing over the network first
124 useEffect(() => {
125 if (movedId !== undefined) follow(connectedThere, screenFocused);
126 }, [movedId, connectedThere, screenFocused]);
127 if (handoff === null && threadAwaitsAdoption(thread)) {
128 return <AdoptMovedThread thread={thread} canAdopt={canAdopt} />;
129 }
130 if (handoff === null || (handoff.state === "failed" && dismissed === handoff.handoffId)) {
131 return null;
132 }
133 const machine = handoff.label;
134
135 const keepHere = async () => {
136 setCancelling(true);
137 const result = await cancel({
138 environmentId: thread.environmentId,
139 input: { threadId: thread.id },
140 });
141 setCancelling(false);
142 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
143 const failure = squashAtomCommandFailure(result);
144 Dialog.alert(
145 gt("Could not cancel the move"),
146 failure instanceof Error ? failure.message : gt("Try again."),
147 );
148 };
149
150 const openThere = () => {
151 if (handoff.state !== "departed") return;
152 if (presentationById.get(handoff.environmentId)?.connection.phase === "connected") {
153 openThread({ environmentId: handoff.environmentId, threadId: handoff.threadId });
154 return;
155 }
156 // Without a connection to that machine, this one reads the thread over its link.
157 openLinkedRead(
158 { environmentId: handoff.environmentId, threadId: handoff.threadId },
159 { viaEnvironmentId: thread.environmentId, label: machine },
160 thread.title,
161 );
162 };
163
164 const title =
165 handoff.state === "pending"
166 ? gt("Moving to {machine} when this turn ends", { machine })
167 : handoff.state === "departing"
168 ? gt("Moving to {machine}…", { machine })
169 : handoff.state === "departed"
170 ? connection.state.phase === "connecting"
171 ? gt("Connecting to {machine}…", { machine })
172 : gt("This thread continues on {machine}", { machine })
173 : gt("Could not move to {machine}", { machine });
174 const detail =
175 handoff.state === "pending"
176 ? gt("Sending a message keeps it here instead.")
177 : handoff.state === "departed"
178 ? gt("This copy is read-only.")
179 : handoff.state === "failed"
180 ? handoff.lastError
181 : null;
182
183 return (
184 <View className="mx-3 mb-2 gap-2 rounded-xl border border-border-subtle bg-screen p-3">
185 <Text
186 className={cn(
187 "text-sm font-t3-bold",
188 handoff.state === "failed" ? "text-danger-foreground" : "text-foreground",
189 )}
190 >
191 {title}
192 </Text>
193 {detail === null ? null : <Text className="text-sm text-foreground-secondary">{detail}</Text>}
194 {handoff.state === "pending" ? (
195 <Button
196 label={gt("Keep it here")}
197 size="compact"
198 loading={cancelling}
199 disabled={!canMove}
200 onPress={() => void keepHere()}
201 />
202 ) : handoff.state === "departed" ? (
203 <Button
204 label={gt("Open on {machine}", { machine })}
205 size="compact"
206 icon="arrow.up.right"
207 onPress={openThere}
208 />
209 ) : handoff.state === "failed" ? (
210 <View className="flex-row gap-2">
211 {canMove ? (
212 <Button
213 label={gt("Try again")}
214 size="compact"
215 onPress={() =>
216 navigation.navigate("ThreadHandoff", {
217 environmentId: thread.environmentId,
218 threadId: thread.id,
219 })
220 }
221 />
222 ) : null}
223 <Button
224 label={gt("Dismiss")}
225 size="compact"
226 tone="text"
227 onPress={() => setDismissed(handoff.handoffId)}
228 />
229 </View>
230 ) : null}
231 </View>
232 );
233}