Open History to see the last commit
1import * as Haptics from "expo-haptics";
2import { SymbolView, type SFSymbol } from "expo-symbols";
3import {
4 deriveThreadRelationshipGraph,
5 immediateThreadRelationships,
6 resolveMergeBackTargetThreadId,
7 type ThreadRelationshipEdge,
8} from "@t3tools/client-runtime/state/thread-relationships";
9import {
10 canDetachThreadProviderSession,
11 resolveLatestMergeBackRun,
12} from "@t3tools/client-runtime/state/thread-workflows";
13import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
14import { copySorted } from "@t3tools/shared/Array";
15import { useNavigation } from "@react-navigation/native";
16import { useMemo, useState } from "react";
17import { ActivityIndicator, Modal, Pressable, ScrollView, View } from "react-native";
18import { useSafeAreaInsets } from "react-native-safe-area-context";
19
20import { AppText as Text } from "../../components/AppText";
21import { useUniwindTheme } from "../../lib/useUniwindTheme";
22import { useThreadShells } from "../../state/entities";
23import { threadEnvironment } from "../../state/threads";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { useThreadProjection } from "../../state/use-thread-detail";
26import { useArchivedThreadSnapshots } from "../archive/useArchivedThreadSnapshots";
27
28function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId): string {
29 if (edge.kind === "transfer") {
30 return edge.sourceThreadId === currentThreadId ? "Context sent to" : "Context received from";
31 }
32 if (edge.kind === "subagent") {
33 return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
34 }
35 return edge.sourceThreadId === currentThreadId ? "Fork" : "Forked from";
36}
37
38function relationshipSymbol(edge: ThreadRelationshipEdge): SFSymbol {
39 if (edge.kind === "subagent") return "person.2";
40 if (edge.kind === "transfer") return "arrow.left.arrow.right";
41 return "arrow.triangle.branch";
42}
43
44function threadAvailability(
45 thread: OrchestrationV2ThreadShell | null,
46 missing: boolean,
47): string | null {
48 if (missing) return "Unavailable";
49 if (thread?.deletedAt !== null && thread?.deletedAt !== undefined) return "Deleted";
50 if (thread?.archivedAt !== null && thread?.archivedAt !== undefined) return "Archived";
51 return null;
52}
53
54const EMPTY_THREAD_SHELLS: ReadonlyArray<OrchestrationV2ThreadShell> = [];
55
56export function ThreadRelationshipsBanner(props: {
57 readonly environmentId: EnvironmentId;
58 readonly threadId: ThreadId;
59}) {
60 const scopedProjection = useThreadProjection(props);
61 const projection = scopedProjection?.projection ?? null;
62 const threadShells = useThreadShells();
63 const environmentIds = useMemo(() => [props.environmentId], [props.environmentId]);
64 const archived = useArchivedThreadSnapshots(environmentIds);
65 const archivedShells =
66 archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot
67 .threads ?? EMPTY_THREAD_SHELLS;
68 const shells = useMemo<ReadonlyArray<OrchestrationV2ThreadShell>>(() => {
69 const environmentShells: OrchestrationV2ThreadShell[] = [];
70 for (const thread of threadShells) {
71 if (thread.environmentId === props.environmentId) {
72 environmentShells.push(thread.source);
73 }
74 }
75 environmentShells.push(...archivedShells);
76 return environmentShells;
77 }, [archivedShells, props.environmentId, threadShells]);
78 const graph = useMemo(
79 () => deriveThreadRelationshipGraph({ threads: shells, projection }),
80 [projection, shells],
81 );
82 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
83 const rows = useMemo(
84 () =>
85 copySorted(
86 immediateThreadRelationships(graph, props.threadId),
87 (left, right) =>
88 Number(right.threadId === mergeTargetThreadId) -
89 Number(left.threadId === mergeTargetThreadId),
90 ),
91 [graph, mergeTargetThreadId, props.threadId],
92 );
93 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
94 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
95 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
96 const [visible, setVisible] = useState(false);
97 const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
98 const navigation = useNavigation();
99 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
100 const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
101 const insets = useSafeAreaInsets();
102 const theme = useUniwindTheme();
103 const backdropColor = theme["--color-backdrop"];
104 const sheetColor = theme["--color-sheet"];
105 const iconColor = theme["--color-icon-subtle"];
106
107 if (rows.length === 0 && !canDetach) return null;
108
109 const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];
110 const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;
111 const summary = primaryParent
112 ? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`
113 : "Agent session connected";
114
115 const openThread = (threadId: ThreadId, archivedThread: boolean) => {
116 setVisible(false);
117 void Haptics.selectionAsync();
118 if (archivedThread) {
119 navigation.navigate("SettingsSheet", {
120 screen: "SettingsContent",
121 params: { screen: "SettingsArchive" },
122 });
123 return;
124 }
125 navigation.navigate("Thread", {
126 environmentId: props.environmentId,
127 threadId,
128 });
129 };
130
131 const merge = async () => {
132 if (!canMerge || mergeTargetThreadId === null || latestMergeBackRun === null) return;
133 setBusyAction("merge");
134 const result = await mergeBack({
135 environmentId: props.environmentId,
136 input: {
137 sourceThreadId: props.threadId,
138 targetThreadId: mergeTargetThreadId,
139 runId: latestMergeBackRun.id,
140 creationSource: "mobile",
141 },
142 });
143 setBusyAction(null);
144 if (result._tag === "Success") openThread(mergeTargetThreadId, false);
145 };
146
147 const detach = async () => {
148 if (!canDetach) return;
149 setBusyAction("detach");
150 await stopSession({
151 environmentId: props.environmentId,
152 input: { threadId: props.threadId },
153 });
154 setBusyAction(null);
155 };
156
157 return (
158 <>
159 <Pressable
160 accessibilityRole="button"
161 accessibilityLabel={`${summary}. Show thread relationships`}
162 onPress={() => {
163 void Haptics.selectionAsync();
164 setVisible(true);
165 }}
166 className="mb-4 min-h-11 flex-row items-center gap-2 rounded-xl border border-adaptive-neutral-300-a60-white-a12 bg-card px-3 py-2.5"
167 >
168 <SymbolView
169 name={primaryParent ? relationshipSymbol(primaryParent.edge) : "link"}
170 size={14}
171 tintColor={iconColor}
172 type="monochrome"
173 />
174 <Text className="min-w-0 flex-1 font-t3-medium text-xs text-foreground" numberOfLines={1}>
175 {summary}
176 </Text>
177 {rows.length > 1 ? (
178 <Text className="text-2xs tabular-nums text-foreground-muted">+{rows.length - 1}</Text>
179 ) : null}
180 <SymbolView name="chevron.right" size={12} tintColor={iconColor} type="monochrome" />
181 </Pressable>
182
183 <Modal
184 transparent
185 animationType="fade"
186 visible={visible}
187 statusBarTranslucent
188 onRequestClose={() => setVisible(false)}
189 >
190 <View className="flex-1 justify-end">
191 <View
192 pointerEvents="none"
193 className="absolute inset-0"
194 style={{ backgroundColor: backdropColor }}
195 />
196 <Pressable className="absolute inset-0" onPress={() => setVisible(false)} />
197 <View
198 className="max-h-[78%] rounded-t-[28px] px-4 pt-3"
199 style={{ backgroundColor: sheetColor, paddingBottom: Math.max(insets.bottom, 16) }}
200 >
201 <View className="mb-4 h-1 w-10 self-center rounded-full bg-neutral-400/40" />
202 <View className="mb-3 flex-row items-center justify-between px-1">
203 <View>
204 <Text className="font-t3-bold text-lg text-foreground">Thread lineage</Text>
205 <Text className="text-xs text-foreground-muted">
206 {rows.length} related {rows.length === 1 ? "thread" : "threads"}
207 </Text>
208 </View>
209 <Pressable
210 accessibilityRole="button"
211 accessibilityLabel="Close thread lineage"
212 onPress={() => setVisible(false)}
213 className="h-10 w-10 items-center justify-center rounded-full bg-adaptive-neutral-200-a70-white-a8"
214 >
215 <SymbolView name="xmark" size={14} tintColor={iconColor} type="monochrome" />
216 </Pressable>
217 </View>
218
219 <ScrollView contentContainerStyle={{ gap: 8 }} showsVerticalScrollIndicator={false}>
220 {rows.map(({ threadId, edge }) => {
221 const node = graph.nodes.get(threadId);
222 const availability = threadAvailability(
223 node?.thread ?? null,
224 node?.missing ?? true,
225 );
226 const archivedThread = availability === "Archived";
227 const disabled = availability === "Unavailable" || availability === "Deleted";
228 return (
229 <Pressable
230 key={`${edge.kind}:${threadId}`}
231 accessibilityRole={disabled ? undefined : "link"}
232 accessibilityState={{ disabled }}
233 disabled={disabled}
234 onPress={() => openThread(threadId, archivedThread)}
235 className="min-h-14 flex-row items-center gap-3 rounded-2xl border border-adaptive-neutral-300-a60-white-a12 bg-card px-3 py-2.5"
236 >
237 <View className="h-8 w-8 items-center justify-center rounded-full bg-adaptive-neutral-200-a70-white-a8">
238 <SymbolView
239 name={relationshipSymbol(edge)}
240 size={14}
241 tintColor={iconColor}
242 type="monochrome"
243 />
244 </View>
245 <View className="min-w-0 flex-1">
246 <Text className="text-3xs uppercase tracking-wide text-foreground-muted">
247 {relationshipLabel(edge, props.threadId)}
248 </Text>
249 <Text className="font-t3-medium text-sm text-foreground" numberOfLines={1}>
250 {node?.thread?.title ?? threadId}
251 </Text>
252 </View>
253 {availability ? (
254 <Text className="text-2xs text-foreground-muted">{availability}</Text>
255 ) : (
256 <SymbolView
257 name="chevron.right"
258 size={12}
259 tintColor={iconColor}
260 type="monochrome"
261 />
262 )}
263 </Pressable>
264 );
265 })}
266 </ScrollView>
267
268 {canMerge || canDetach ? (
269 <View className="mt-4 gap-2 border-t border-adaptive-neutral-300-a60-white-a12 pt-4">
270 {canMerge ? (
271 <Pressable
272 accessibilityRole="button"
273 disabled={busyAction !== null}
274 onPress={() => void merge()}
275 className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl bg-primary px-3"
276 >
277 {busyAction === "merge" ? (
278 <ActivityIndicator color="white" />
279 ) : (
280 <SymbolView name="arrow.triangle.merge" size={14} tintColor="white" />
281 )}
282 <Text className="font-t3-medium text-sm text-primary-foreground">
283 Merge back to source
284 </Text>
285 </Pressable>
286 ) : null}
287 {canDetach ? (
288 <Pressable
289 accessibilityRole="button"
290 disabled={busyAction !== null}
291 onPress={() => void detach()}
292 className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl border border-adaptive-neutral-300-a60-white-a12 px-3"
293 >
294 {busyAction === "detach" ? <ActivityIndicator /> : null}
295 <Text className="font-t3-medium text-sm text-foreground">
296 Disconnect agent session
297 </Text>
298 </Pressable>
299 ) : null}
300 </View>
301 ) : null}
302 </View>
303 </View>
304 </Modal>
305 </>
306 );
307}