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

ThreadRelationshipsControl.tsx

332 lines12.8 KB

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