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