Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadHandoffCard.tsx

230 lines8.8 KB

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`Its agent can change only what ${{ origin: props.thread.linkOrigin?.label ?? "" }} started here and cannot use this machine's links, until you make it a normal thread.`}
58 </Text>
59 {props.canAdopt ? (
60 <Button
61 label={gt`Make it a normal thread`}
62 size="compact"
63 loading={adopting}
64 onPress={() => void makeNormal()}
65 />
66 ) : null}
67 </View>
68 );
70​
71/**
72 * 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),
73 * under way, or failed (with a way to try again). A moved thread is followed to where it
74 * continues, pairing with that machine first when needed, so it reads as one thread; the card
75 * stays only when this device cannot reach the machine.
76 */
77export function ThreadHandoffCard({ thread }: { readonly thread: EnvironmentThreadShell }) {
78 const gt = useGT();
79 const navigation = useNavigation();
80 const openThread = useOpenLinkedThread();
81 const openLinkedRead = useOpenLinkedThreadRead();
82 const cancel = useAtomCommand(threadHandoffEnvironment.cancel, { reportFailure: false });
83 const canMove = useCanMoveThreads(thread.environmentId);
84 // Adopting is local to this machine, so it does not need linked environments switched on.
85 const canAdopt = useAtomValue(
86 threadHandoffEnvironment.adopt.permissionAtom(thread.environmentId),
87 );
88 const { presentationById } = useEnvironments();
89 const [cancelling, setCancelling] = useState(false);
90 const [dismissed, setDismissed] = useState<string | null>(null);
91 const handoff = thread.handoff;
92 const moved = handoff?.state === "departed" ? handoff : null;
93 const movedId = moved?.handoffId;
94 const connectedThere =
95 moved !== null && presentationById.get(moved.environmentId)?.connection.phase === "connected";
96 const connection = useConnectLinkedEnvironment({
97 viaEnvironmentId: thread.environmentId,
98 environmentId: moved?.environmentId ?? thread.environmentId,
99 threadId: moved?.threadId ?? thread.id,
100 label: moved?.label ?? "",
101 title: thread.title,
102 });
103 const screenFocused = useIsFocused();
104 const follow = useEffectEvent((reachable: boolean, focused: boolean) => {
105 // Another screen the user opened on top is theirs to keep; coming back follows then.
106 if (moved === null || !focused) return;
107 if (reachable) {
108 navigation.dispatch(
109 StackActions.replace("Thread", {
110 environmentId: moved.environmentId,
111 threadId: moved.threadId,
112 }),
113 );
114 return;
115 }
116 if (followTried.has(moved.environmentId)) return;
117 followTried.add(moved.environmentId);
118 void connection.connect();
119 });
120 // 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
121 useEffect(() => {
122 if (movedId !== undefined) follow(connectedThere, screenFocused);
123 }, [movedId, connectedThere, screenFocused]);
124 if (handoff === null && threadAwaitsAdoption(thread)) {
125 return <AdoptMovedThread thread={thread} canAdopt={canAdopt} />;
126 }
127 if (handoff === null || (handoff.state === "failed" && dismissed === handoff.handoffId)) {
128 return null;
129 }
130 const machine = handoff.label;
131​
132 const keepHere = async () => {
133 setCancelling(true);
134 const result = await cancel({
135 environmentId: thread.environmentId,
136 input: { threadId: thread.id },
137 });
138 setCancelling(false);
139 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
140 const failure = squashAtomCommandFailure(result);
141 Dialog.alert(
142 gt`Could not cancel the move`,
143 failure instanceof Error ? failure.message : gt`Try again.`,
144 );
145 };
146​
147 const openThere = () => {
148 if (handoff.state !== "departed") return;
149 if (presentationById.get(handoff.environmentId)?.connection.phase === "connected") {
150 openThread({ environmentId: handoff.environmentId, threadId: handoff.threadId });
151 return;
152 }
153 // Without a connection to that machine, this one reads the thread over its link.
154 openLinkedRead(
155 { environmentId: handoff.environmentId, threadId: handoff.threadId },
156 { viaEnvironmentId: thread.environmentId, label: machine },
157 thread.title,
158 );
159 };
160​
161 const title =
162 handoff.state === "pending"
163 ? gt`Moving to ${{ machine }} when this turn ends`
164 : handoff.state === "departing"
165 ? gt`Moving to ${{ machine }}…`
166 : handoff.state === "departed"
167 ? connection.state.phase === "connecting"
168 ? gt`Connecting to ${{ machine }}…`
169 : gt`This thread continues on ${{ machine }}`
170 : gt`Could not move to ${{ machine }}`;
171 const detail =
172 handoff.state === "pending"
173 ? gt`Sending a message keeps it here instead.`
174 : handoff.state === "departed"
175 ? gt`This copy is read-only.`
176 : handoff.state === "failed"
177 ? handoff.lastError
178 : null;
179​
180 return (
181 <View className="mx-3 mb-2 gap-2 rounded-xl border border-border-subtle bg-screen p-3">
182 <Text
183 className={cn(
184 "text-sm font-t3-bold",
185 handoff.state === "failed" ? "text-danger-foreground" : "text-foreground",
186 )}
187 >
188 {title}
189 </Text>
190 {detail === null ? null : <Text className="text-sm text-foreground-secondary">{detail}</Text>}
191 {handoff.state === "pending" ? (
192 <Button
193 label={gt`Keep it here`}
194 size="compact"
195 loading={cancelling}
196 disabled={!canMove}
197 onPress={() => void keepHere()}
198 />
199 ) : handoff.state === "departed" ? (
200 <Button
201 label={gt`Open on ${{ machine }}`}
202 size="compact"
203 icon="arrow.up.right"
204 onPress={openThere}
205 />
206 ) : handoff.state === "failed" ? (
207 <View className="flex-row gap-2">
208 {canMove ? (
209 <Button
210 label={gt`Try again`}
211 size="compact"
212 onPress={() =>
213 navigation.navigate("ThreadHandoff", {
214 environmentId: thread.environmentId,
215 threadId: thread.id,
216 })
217 }
218 />
219 ) : null}
220 <Button
221 label={gt`Dismiss`}
222 size="compact"
223 tone="text"
224 onPress={() => setDismissed(handoff.handoffId)}
225 />
226 </View>
227 ) : null}
228 </View>
229 );