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 { useThemeColor } from "../../lib/useThemeColor";
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 backdropColor = useThemeColor("--color-backdrop");
103 const sheetColor = useThemeColor("--color-sheet");
104 const iconColor = useThemeColor("--color-icon-subtle");
105
106 if (rows.length === 0 && !canDetach) return null;
107
108 const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];
109 const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;
110 const summary = primaryParent
111 ? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`
112 : "Agent session connected";
113
114 const openThread = (threadId: ThreadId, archivedThread: boolean) => {
115 setVisible(false);
116 void Haptics.selectionAsync();
117 if (archivedThread) {
118 navigation.navigate("SettingsSheet", { screen: "SettingsArchive" });
119 return;
120 }
121 navigation.navigate("Thread", {
122 environmentId: props.environmentId,
123 threadId,
124 });
125 };
126
127 const merge = async () => {
128 if (!canMerge || mergeTargetThreadId === null || latestMergeBackRun === null) return;
129 setBusyAction("merge");
130 const result = await mergeBack({
131 environmentId: props.environmentId,
132 input: {
133 sourceThreadId: props.threadId,
134 targetThreadId: mergeTargetThreadId,
135 runId: latestMergeBackRun.id,
136 creationSource: "mobile",
137 },
138 });
139 setBusyAction(null);
140 if (result._tag === "Success") openThread(mergeTargetThreadId, false);
141 };
142
143 const detach = async () => {
144 if (!canDetach) return;
145 setBusyAction("detach");
146 await stopSession({
147 environmentId: props.environmentId,
148 input: { threadId: props.threadId },
149 });
150 setBusyAction(null);
151 };
152
153 return (
154 <>
155 <Pressable
156 accessibilityRole="button"
157 accessibilityLabel={`${summary}. Show thread relationships`}
158 onPress={() => {
159 void Haptics.selectionAsync();
160 setVisible(true);
161 }}
162 className="mb-4 min-h-11 flex-row items-center gap-2 rounded-xl border border-neutral-300/60 bg-card px-3 py-2.5 dark:border-white/[0.1]"
163 >
164 <SymbolView
165 name={primaryParent ? relationshipSymbol(primaryParent.edge) : "link"}
166 size={14}
167 tintColor={iconColor}
168 type="monochrome"
169 />
170 <Text className="min-w-0 flex-1 font-t3-medium text-xs text-foreground" numberOfLines={1}>
171 {summary}
172 </Text>
173 {rows.length > 1 ? (
174 <Text className="text-2xs tabular-nums text-foreground-muted">+{rows.length - 1}</Text>
175 ) : null}
176 <SymbolView name="chevron.right" size={12} tintColor={iconColor} type="monochrome" />
177 </Pressable>
178
179 <Modal
180 transparent
181 animationType="fade"
182 visible={visible}
183 statusBarTranslucent
184 onRequestClose={() => setVisible(false)}
185 >
186 <View className="flex-1 justify-end">
187 <View
188 pointerEvents="none"
189 className="absolute inset-0"
190 style={{ backgroundColor: backdropColor }}
191 />
192 <Pressable className="absolute inset-0" onPress={() => setVisible(false)} />
193 <View
194 className="max-h-[78%] rounded-t-[28px] px-4 pt-3"
195 style={{ backgroundColor: sheetColor, paddingBottom: Math.max(insets.bottom, 16) }}
196 >
197 <View className="mb-4 h-1 w-10 self-center rounded-full bg-neutral-400/40" />
198 <View className="mb-3 flex-row items-center justify-between px-1">
199 <View>
200 <Text className="font-t3-bold text-lg text-foreground">Thread lineage</Text>
201 <Text className="text-xs text-foreground-muted">
202 {rows.length} related {rows.length === 1 ? "thread" : "threads"}
203 </Text>
204 </View>
205 <Pressable
206 accessibilityRole="button"
207 accessibilityLabel="Close thread lineage"
208 onPress={() => setVisible(false)}
209 className="h-10 w-10 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/[0.07]"
210 >
211 <SymbolView name="xmark" size={14} tintColor={iconColor} type="monochrome" />
212 </Pressable>
213 </View>
214
215 <ScrollView contentContainerStyle={{ gap: 8 }} showsVerticalScrollIndicator={false}>
216 {rows.map(({ threadId, edge }) => {
217 const node = graph.nodes.get(threadId);
218 const availability = threadAvailability(
219 node?.thread ?? null,
220 node?.missing ?? true,
221 );
222 const archivedThread = availability === "Archived";
223 const disabled = availability === "Unavailable" || availability === "Deleted";
224 return (
225 <Pressable
226 key={`${edge.kind}:${threadId}`}
227 accessibilityRole={disabled ? undefined : "link"}
228 accessibilityState={{ disabled }}
229 disabled={disabled}
230 onPress={() => openThread(threadId, archivedThread)}
231 className="min-h-14 flex-row items-center gap-3 rounded-2xl border border-neutral-300/50 bg-card px-3 py-2.5 dark:border-white/[0.08]"
232 >
233 <View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/60 dark:bg-white/[0.06]">
234 <SymbolView
235 name={relationshipSymbol(edge)}
236 size={14}
237 tintColor={iconColor}
238 type="monochrome"
239 />
240 </View>
241 <View className="min-w-0 flex-1">
242 <Text className="text-3xs uppercase tracking-wide text-foreground-muted">
243 {relationshipLabel(edge, props.threadId)}
244 </Text>
245 <Text className="font-t3-medium text-sm text-foreground" numberOfLines={1}>
246 {node?.thread?.title ?? threadId}
247 </Text>
248 </View>
249 {availability ? (
250 <Text className="text-2xs text-foreground-muted">{availability}</Text>
251 ) : (
252 <SymbolView
253 name="chevron.right"
254 size={12}
255 tintColor={iconColor}
256 type="monochrome"
257 />
258 )}
259 </Pressable>
260 );
261 })}
262 </ScrollView>
263
264 {canMerge || canDetach ? (
265 <View className="mt-4 gap-2 border-t border-neutral-300/50 pt-4 dark:border-white/[0.08]">
266 {canMerge ? (
267 <Pressable
268 accessibilityRole="button"
269 disabled={busyAction !== null}
270 onPress={() => void merge()}
271 className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl bg-primary px-3"
272 >
273 {busyAction === "merge" ? (
274 <ActivityIndicator color="white" />
275 ) : (
276 <SymbolView name="arrow.triangle.merge" size={14} tintColor="white" />
277 )}
278 <Text className="font-t3-medium text-sm text-primary-foreground">
279 Merge back to source
280 </Text>
281 </Pressable>
282 ) : null}
283 {canDetach ? (
284 <Pressable
285 accessibilityRole="button"
286 disabled={busyAction !== null}
287 onPress={() => void detach()}
288 className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl border border-neutral-300/60 px-3 dark:border-white/[0.1]"
289 >
290 {busyAction === "detach" ? <ActivityIndicator /> : null}
291 <Text className="font-t3-medium text-sm text-foreground">
292 Disconnect agent session
293 </Text>
294 </Pressable>
295 ) : null}
296 </View>
297 ) : null}
298 </View>
299 </View>
300 </Modal>
301 </>
302 );
303}