Open History to see the last commit
1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import {
3 deriveThreadRelationshipGraph,
4 immediateThreadRelationships,
5 resolveMergeBackTargetThreadId,
6 type ThreadRelationshipEdge,
7} from "@t3tools/client-runtime/state/thread-relationships";
8import {
9 canDetachThreadProviderSession,
10 resolveLatestMergeBackRun,
11} from "@t3tools/client-runtime/state/thread-workflows";
12import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
13import { useNavigate } from "@tanstack/react-router";
14import {
15 ArrowRightIcon,
16 BotIcon,
17 CornerLeftUpIcon,
18 GitForkIcon,
19 GitMergeIcon,
20 LoaderCircleIcon,
21 MoreHorizontalIcon,
22 UnplugIcon,
23} from "lucide-react";
24import { useState } from "react";
25
26import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
27import { buildThreadRouteParams } from "../../threadRoutes";
28import { useThreadProjection, useThreadShells } from "../../state/entities";
29import { threadEnvironment } from "../../state/threads";
30import { useAtomCommand } from "../../state/use-atom-command";
31import { cn } from "../../lib/utils";
32import { Button } from "../ui/button";
33import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
34import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
35import {
36 THREAD_DETAILS_PANEL_ICON_ACTION_CLASS,
37 THREAD_DETAILS_PANEL_LINK_ROW_CLASS,
38 THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS,
39 THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS,
40 THREAD_DETAILS_PANEL_LINK_SPLIT_SECONDARY_CLASS,
41 THREAD_DETAILS_PANEL_MENU_POPUP_CLASS,
42 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
43} from "./threadDetailsPanelStyles";
44
45const THREAD_RELATIONSHIP_ICON_CLASS = "size-4 shrink-0 text-muted-foreground";
46
47function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) {
48 if (edge.kind === "transfer") return "Context transfer";
49 if (edge.kind === "subagent") {
50 return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
51 }
52 return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread";
53}
54
55function isParentRelationship(edge: ThreadRelationshipEdge, currentThreadId: ThreadId): boolean {
56 return edge.kind !== "transfer" && edge.targetThreadId === currentThreadId;
57}
58
59function relationshipSortKey(input: {
60 readonly edge: ThreadRelationshipEdge;
61 readonly threadId: ThreadId;
62 readonly currentThreadId: ThreadId;
63 readonly mergeTargetThreadId: ThreadId | null;
64}): number {
65 if (isParentRelationship(input.edge, input.currentThreadId)) return 0;
66 if (input.threadId === input.mergeTargetThreadId) return 1;
67 return 2;
68}
69
70function statusDotClass(status: string | null): string {
71 if (status === "running" || status === "in_progress") return "bg-info";
72 if (status === "failed" || status === "error") return "bg-destructive";
73 if (status === "completed") return "bg-success";
74 return "bg-muted-foreground/45";
75}
76
77function relationshipThreadTitle(input: {
78 readonly title: string;
79 readonly isSubagent: boolean;
80}): string {
81 if (!input.isSubagent) return input.title;
82 return input.title.replace(/^Subagent:\s*/i, "");
83}
84
85export function ThreadRelationshipsPanel(props: {
86 readonly environmentId: EnvironmentId;
87 readonly threadId: ThreadId;
88}) {
89 const ref = scopeThreadRef(props.environmentId, props.threadId);
90 const projection = useThreadProjection(ref)?.projection ?? null;
91 const threadShells = useThreadShells();
92 const activeShells = threadShells.filter(
93 (thread) => thread.environmentId === props.environmentId,
94 );
95 const archived = useArchivedThreadSnapshots([props.environmentId]);
96 const archivedShells = archived.snapshots.find(
97 (entry) => entry.environmentId === props.environmentId,
98 )?.snapshot.threads;
99 const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
100 ...activeShells.map((thread) => thread.source),
101 ...(archivedShells ?? []),
102 ];
103 const graph = deriveThreadRelationshipGraph({ threads: shells, projection });
104 const navigate = useNavigate();
105 const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
106 const stopSession = useAtomCommand(threadEnvironment.stopSession);
107 const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
108 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
109 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
110 const relationshipRows = immediateThreadRelationships(graph, props.threadId).toSorted(
111 (left, right) =>
112 relationshipSortKey({
113 edge: left.edge,
114 threadId: left.threadId,
115 currentThreadId: props.threadId,
116 mergeTargetThreadId,
117 }) -
118 relationshipSortKey({
119 edge: right.edge,
120 threadId: right.threadId,
121 currentThreadId: props.threadId,
122 mergeTargetThreadId,
123 }),
124 );
125 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
126 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
127
128 if (relationshipRows.length === 0) {
129 return null;
130 }
131
132 const openThread = (threadId: ThreadId) => {
133 void navigate({
134 to: "/$environmentId/$threadId",
135 params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
136 });
137 };
138
139 const merge = async () => {
140 if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return;
141 setBusyAction("merge");
142 const result = await mergeBack({
143 environmentId: props.environmentId,
144 input: {
145 sourceThreadId: props.threadId,
146 targetThreadId: mergeTargetThreadId,
147 runId: latestMergeBackRun.id,
148 },
149 });
150 setBusyAction(null);
151 if (result._tag === "Success") openThread(mergeTargetThreadId);
152 };
153
154 const detach = async () => {
155 if (!canDetach || busyAction !== null) return;
156 setBusyAction("detach");
157 await stopSession({
158 environmentId: props.environmentId,
159 input: { threadId: props.threadId },
160 });
161 setBusyAction(null);
162 };
163
164 const parentTitle =
165 mergeTargetThreadId === null
166 ? null
167 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
168
169 return (
170 <section
171 aria-labelledby="thread-details-lineage-heading"
172 className="border-t border-border/65 px-2 pb-2.5 pt-2"
173 data-thread-relationships-panel
174 >
175 <div className="mb-1 flex min-h-8 items-center justify-between gap-2 px-2">
176 <h3
177 id="thread-details-lineage-heading"
178 className="text-[11px] font-medium text-muted-foreground"
179 >
180 Lineage
181 </h3>
182 <div className="flex shrink-0 items-center gap-1">
183 {canDetach ? (
184 <Menu>
185 <MenuTrigger
186 render={
187 <Button
188 size="icon-xs"
189 variant="ghost"
190 className={THREAD_DETAILS_PANEL_ICON_ACTION_CLASS}
191 aria-label="More thread actions"
192 disabled={busyAction !== null}
193 />
194 }
195 >
196 <MoreHorizontalIcon className="size-3.5" />
197 </MenuTrigger>
198 <MenuPopup align="end" className={THREAD_DETAILS_PANEL_MENU_POPUP_CLASS}>
199 <MenuItem onClick={() => void detach()}>
200 <UnplugIcon className="size-3.5" />
201 Disconnect agent session
202 </MenuItem>
203 </MenuPopup>
204 </Menu>
205 ) : null}
206 </div>
207 </div>
208
209 {relationshipRows.length > 0 ? (
210 <ul className="m-0 list-none p-0">
211 {relationshipRows.map(({ threadId, edge }) => {
212 const node = graph.nodes.get(threadId);
213 const isSubagent = edge.kind === "subagent";
214 const isMergeTarget = threadId === mergeTargetThreadId;
215 const isParent = isParentRelationship(edge, props.threadId);
216 const RelationshipIcon = isParent
217 ? CornerLeftUpIcon
218 : isSubagent
219 ? BotIcon
220 : GitForkIcon;
221 const relationship = relationshipLabel(edge, props.threadId);
222 const threadTitle = relationshipThreadTitle({
223 title: node?.thread?.title ?? threadId,
224 isSubagent,
225 });
226 const relationshipContent = (
227 <>
228 <span className="relative -mx-0.5 grid size-4 shrink-0 place-items-center">
229 <RelationshipIcon className={THREAD_RELATIONSHIP_ICON_CLASS} />
230 <span
231 className={cn(
232 "absolute -bottom-1 -right-1 size-2 rounded-full border-2 border-card",
233 statusDotClass(edge.status),
234 )}
235 aria-hidden="true"
236 />
237 </span>
238 <span className="min-w-0 flex-1">
239 <span className="block truncate text-[13px] font-medium leading-4 text-foreground/85">
240 {threadTitle}
241 </span>
242 </span>
243 <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
244 </>
245 );
246 return (
247 <li key={threadId} className="group flex h-9 items-center rounded-lg">
248 {isMergeTarget ? (
249 <div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
250 <Tooltip>
251 <TooltipTrigger
252 render={
253 <Button
254 size="sm"
255 variant="ghost"
256 className={THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS}
257 disabled={node?.missing === true}
258 onClick={() => openThread(threadId)}
259 />
260 }
261 >
262 {relationshipContent}
263 </TooltipTrigger>
264 <TooltipPopup side="left">
265 {node?.missing
266 ? "This related thread is unavailable"
267 : `Open ${relationship.toLowerCase()} in this chat`}
268 </TooltipPopup>
269 </Tooltip>
270 <span
271 aria-hidden="true"
272 className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS}
273 />
274 <Tooltip>
275 <TooltipTrigger
276 render={
277 <Button
278 size="sm"
279 variant="ghost"
280 className={THREAD_DETAILS_PANEL_LINK_SPLIT_SECONDARY_CLASS}
281 aria-label={
282 parentTitle
283 ? `Merge back to ${parentTitle}`
284 : "Merge back to source conversation"
285 }
286 disabled={!canMerge || busyAction !== null}
287 onClick={() => void merge()}
288 >
289 {busyAction === "merge" ? (
290 <LoaderCircleIcon className="size-3 animate-spin" />
291 ) : (
292 <GitMergeIcon className="size-3" />
293 )}
294 </Button>
295 }
296 />
297 <TooltipPopup side="left">
298 {latestMergeBackRun === null
299 ? "Complete a run in this fork before merging it back"
300 : parentTitle
301 ? `Merge this conversation back into ${parentTitle}`
302 : "Merge this conversation back into its source"}
303 </TooltipPopup>
304 </Tooltip>
305 </div>
306 ) : (
307 <Tooltip>
308 <TooltipTrigger
309 render={
310 <Button
311 size="sm"
312 variant="ghost"
313 disabled={node?.missing === true}
314 onClick={() => openThread(threadId)}
315 className={THREAD_DETAILS_PANEL_LINK_ROW_CLASS}
316 />
317 }
318 >
319 {relationshipContent}
320 </TooltipTrigger>
321 <TooltipPopup side="left">
322 {node?.missing
323 ? "This related thread is unavailable"
324 : `Open ${relationship.toLowerCase()} in this chat`}
325 </TooltipPopup>
326 </Tooltip>
327 )}
328 </li>
329 );
330 })}
331 </ul>
332 ) : null}
333 </section>
334 );
335}