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

ThreadRelationshipsControl.tsx

373 lines14.5 KB

1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import {
3 deriveThreadRelationshipGraph,
4 immediateThreadRelationships,
5 isParentThreadRelationship,
6 orderWebThreadLineageRows,
7 resolveMergeBackTargetThreadId,
8 type ThreadRelationshipEdge,
9} from "@t3tools/client-runtime/state/thread-relationships";
10import {
11 canDetachThreadProviderSession,
12 resolveLatestMergeBackRun,
13} from "@t3tools/client-runtime/state/thread-workflows";
14import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
15import { useNavigate } from "@tanstack/react-router";
16import {
17 ArrowRightIcon,
18 BotIcon,
19 CornerLeftUpIcon,
20 GitForkIcon,
21 GitMergeIcon,
22 LoaderCircleIcon,
23 MoreHorizontalIcon,
24 PlusIcon,
25 UnplugIcon,
26} from "lucide-react";
27import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
28​
29import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
30import { buildThreadRouteParams } from "../../threadRoutes";
31import { useThreadProjection, useThreadShells } from "../../state/entities";
32import { threadEnvironment } from "../../state/threads";
33import { useAtomCommand } from "../../state/use-atom-command";
34import { cn } from "../../lib/utils";
35import { Button } from "../ui/button";
36import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
37import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
38import {
39 THREAD_DETAILS_PANEL_ICON_ACTION_CLASS,
40 THREAD_DETAILS_PANEL_LINK_ROW_CLASS,
41 THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS,
42 THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS,
43 THREAD_DETAILS_PANEL_LINK_SPLIT_SECONDARY_CLASS,
44 THREAD_DETAILS_PANEL_MENU_POPUP_CLASS,
45 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
46} from "./threadDetailsPanelStyles";
47​
48const THREAD_RELATIONSHIP_ICON_CLASS = "size-4 shrink-0 text-muted-foreground";
49​
50// Lineage paging: a busy thread can accumulate dozens of forks and subagents,
51// and the panel it lives in already scrolls. Show a workable window, keep the
52// rest behind Show more, and bound what is shown so the sections below Lineage
53// stay reachable.
54const THREAD_LINEAGE_INITIAL_COUNT = 6;
55const THREAD_LINEAGE_PAGE_COUNT = 12;
56​
57export function resolveThreadLineageWindow<Row>(
58 rows: ReadonlyArray<Row>,
59 visibleCount: number,
60): { readonly visibleRows: ReadonlyArray<Row>; readonly hiddenCount: number } {
61 const visibleRows = rows.slice(0, visibleCount);
62 return { visibleRows, hiddenCount: rows.length - visibleRows.length };
64​
65export function ThreadLineageRowList(props: {
66 readonly hiddenCount: number;
67 readonly onShowMore: () => void;
68 readonly children: ReactNode;
69}) {
70 return (
71 <>
72 {/*
73 Bounded rather than free-growing so Lineage cannot push the rest of the
74 thread details panel out of view. Plain overflow, not a ScrollArea
75 component: this sits inside an already scrolling panel, where a
76 max-height-only virtual viewport measures badly. Every row is a focusable
77 button, so keyboard users reach and scroll the region through the rows
78 themselves and the container needs no extra tab stop of its own.
79 */}
80 <ul
81 aria-label="Related threads"
82 className="m-0 max-h-[13.5rem] list-none overflow-y-auto overscroll-contain p-0"
83 >
84 {props.children}
85 </ul>
86 {props.hiddenCount > 0 ? (
87 <button
88 type="button"
89 onClick={props.onShowMore}
90 className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-left text-[13px] font-medium text-muted-foreground/70 hover:bg-black/[0.055] hover:text-foreground/80 dark:hover:bg-white/[0.075]"
91 >
92 <PlusIcon aria-hidden className="-mx-0.5 size-4 shrink-0" />
93 Show {Math.min(props.hiddenCount, THREAD_LINEAGE_PAGE_COUNT)} more
94 </button>
95 ) : null}
96 </>
97 );
99​
100function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) {
101 if (edge.kind === "transfer") return "Context transfer";
102 if (edge.kind === "subagent") {
103 return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
104 }
105 return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread";
107​
108function statusDotClass(status: string | null): string {
109 if (status === "running" || status === "in_progress") return "bg-info";
110 if (status === "failed" || status === "error") return "bg-destructive";
111 if (status === "completed") return "bg-success";
112 return "bg-muted-foreground/45";
114​
115function relationshipThreadTitle(input: {
116 readonly title: string;
117 readonly isSubagent: boolean;
118}): string {
119 if (!input.isSubagent) return input.title;
120 return input.title.replace(/^Subagent:\s*/i, "");
122​
123export function ThreadRelationshipsPanel(props: {
124 readonly environmentId: EnvironmentId;
125 readonly threadId: ThreadId;
126}) {
127 const ref = scopeThreadRef(props.environmentId, props.threadId);
128 const projection = useThreadProjection(ref)?.projection ?? null;
129 const threadShells = useThreadShells();
130 const archived = useArchivedThreadSnapshots([props.environmentId]);
131 const archivedShells = archived.snapshots.find(
132 (entry) => entry.environmentId === props.environmentId,
133 )?.snapshot.threads;
134 const graph = useMemo(() => {
135 const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
136 ...threadShells
137 .filter((thread) => thread.environmentId === props.environmentId)
138 .map((thread) => thread.source),
139 ...(archivedShells ?? []),
140 ];
141 return deriveThreadRelationshipGraph({ threads: shells, projection });
142 }, [archivedShells, projection, props.environmentId, threadShells]);
143 const navigate = useNavigate();
144 const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
145 const stopSession = useAtomCommand(threadEnvironment.stopSession);
146 const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
147 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
148 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
149 const relationshipRows = useMemo(
150 () =>
151 orderWebThreadLineageRows({
152 graph,
153 rows: immediateThreadRelationships(graph, props.threadId),
154 currentThreadId: props.threadId,
155 mergeTargetThreadId,
156 }),
157 [graph, mergeTargetThreadId, props.threadId],
158 );
159 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
160 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
161​
162 const [visibleCount, setVisibleCount] = useState(THREAD_LINEAGE_INITIAL_COUNT);
163 const lineageResetKey = scopedThreadKey(ref);
164 const lastLineageResetKeyRef = useRef(lineageResetKey);
165 if (lastLineageResetKeyRef.current !== lineageResetKey) {
166 lastLineageResetKeyRef.current = lineageResetKey;
167 setVisibleCount(THREAD_LINEAGE_INITIAL_COUNT);
168 }
169 const showMore = useCallback(
170 () => setVisibleCount((count) => count + THREAD_LINEAGE_PAGE_COUNT),
171 [],
172 );
173 const { visibleRows, hiddenCount } = resolveThreadLineageWindow(relationshipRows, visibleCount);
174​
175 if (relationshipRows.length === 0) {
176 return null;
177 }
178​
179 const openThread = (threadId: ThreadId) => {
180 void navigate({
181 to: "/$environmentId/$threadId",
182 params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
183 });
184 };
185​
186 const merge = async () => {
187 if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return;
188 setBusyAction("merge");
189 const result = await mergeBack({
190 environmentId: props.environmentId,
191 input: {
192 sourceThreadId: props.threadId,
193 targetThreadId: mergeTargetThreadId,
194 runId: latestMergeBackRun.id,
195 },
196 });
197 setBusyAction(null);
198 if (result._tag === "Success") openThread(mergeTargetThreadId);
199 };
200​
201 const detach = async () => {
202 if (!canDetach || busyAction !== null) return;
203 setBusyAction("detach");
204 await stopSession({
205 environmentId: props.environmentId,
206 input: { threadId: props.threadId },
207 });
208 setBusyAction(null);
209 };
210​
211 const parentTitle =
212 mergeTargetThreadId === null
213 ? null
214 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
215​
216 return (
217 <section
218 aria-labelledby="thread-details-lineage-heading"
219 className="border-t border-border/65 px-2 pb-2.5 pt-2"
220 data-thread-relationships-panel
221 >
222 <div className="mb-1 flex min-h-8 items-center justify-between gap-2 px-2">
223 <h3
224 id="thread-details-lineage-heading"
225 className="text-[11px] font-medium text-muted-foreground"
226 >
227 Lineage
228 </h3>
229 <div className="flex shrink-0 items-center gap-1">
230 {canDetach ? (
231 <Menu>
232 <MenuTrigger
233 render={
234 <Button
235 size="icon-xs"
236 variant="ghost"
237 className={THREAD_DETAILS_PANEL_ICON_ACTION_CLASS}
238 aria-label="More thread actions"
239 disabled={busyAction !== null}
240 />
241 }
242 >
243 <MoreHorizontalIcon className="size-3.5" />
244 </MenuTrigger>
245 <MenuPopup align="end" className={THREAD_DETAILS_PANEL_MENU_POPUP_CLASS}>
246 <MenuItem onClick={() => void detach()}>
247 <UnplugIcon className="size-3.5" />
248 Disconnect agent session
249 </MenuItem>
250 </MenuPopup>
251 </Menu>
252 ) : null}
253 </div>
254 </div>
255​
256 <ThreadLineageRowList hiddenCount={hiddenCount} onShowMore={showMore}>
257 {visibleRows.map(({ threadId, edge }) => {
258 const node = graph.nodes.get(threadId);
259 const isSubagent = edge.kind === "subagent";
260 const isMergeTarget = threadId === mergeTargetThreadId;
261 const isParent = isParentThreadRelationship(edge, props.threadId);
262 const RelationshipIcon = isParent ? CornerLeftUpIcon : isSubagent ? BotIcon : GitForkIcon;
263 const relationship = relationshipLabel(edge, props.threadId);
264 const threadTitle = relationshipThreadTitle({
265 title: node?.thread?.title ?? threadId,
266 isSubagent,
267 });
268 const relationshipContent = (
269 <>
270 <span className="relative -mx-0.5 grid size-4 shrink-0 place-items-center">
271 <RelationshipIcon className={THREAD_RELATIONSHIP_ICON_CLASS} />
272 <span
273 className={cn(
274 "absolute -bottom-1 -right-1 size-2 rounded-full border-2 border-card",
275 statusDotClass(edge.status),
276 )}
277 aria-hidden="true"
278 />
279 </span>
280 <span className="min-w-0 flex-1">
281 <span className="block truncate text-[13px] font-medium leading-4 text-foreground/85">
282 {threadTitle}
283 </span>
284 </span>
285 <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
286 </>
287 );
288 return (
289 <li key={threadId} className="group flex h-9 items-center rounded-lg">
290 {isMergeTarget ? (
291 <div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
292 <Tooltip>
293 <TooltipTrigger
294 render={
295 <Button
296 size="sm"
297 variant="ghost"
298 className={THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS}
299 disabled={node?.missing === true}
300 onClick={() => openThread(threadId)}
301 />
302 }
303 >
304 {relationshipContent}
305 </TooltipTrigger>
306 <TooltipPopup side="left">
307 {node?.missing
308 ? "This related thread is unavailable"
309 : `Open ${relationship.toLowerCase()} in this chat`}
310 </TooltipPopup>
311 </Tooltip>
312 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
313 <Tooltip>
314 <TooltipTrigger
315 render={
316 <Button
317 size="sm"
318 variant="ghost"
319 className={THREAD_DETAILS_PANEL_LINK_SPLIT_SECONDARY_CLASS}
320 aria-label={
321 parentTitle
322 ? `Merge back to ${parentTitle}`
323 : "Merge back to source conversation"
324 }
325 disabled={!canMerge || busyAction !== null}
326 onClick={() => void merge()}
327 >
328 {busyAction === "merge" ? (
329 <LoaderCircleIcon className="size-3 animate-spin" />
330 ) : (
331 <GitMergeIcon className="size-3" />
332 )}
333 </Button>
334 }
335 />
336 <TooltipPopup side="left">
337 {latestMergeBackRun === null
338 ? "Complete a run in this fork before merging it back"
339 : parentTitle
340 ? `Merge this conversation back into ${parentTitle}`
341 : "Merge this conversation back into its source"}
342 </TooltipPopup>
343 </Tooltip>
344 </div>
345 ) : (
346 <Tooltip>
347 <TooltipTrigger
348 render={
349 <Button
350 size="sm"
351 variant="ghost"
352 disabled={node?.missing === true}
353 onClick={() => openThread(threadId)}
354 className={THREAD_DETAILS_PANEL_LINK_ROW_CLASS}
355 />
356 }
357 >
358 {relationshipContent}
359 </TooltipTrigger>
360 <TooltipPopup side="left">
361 {node?.missing
362 ? "This related thread is unavailable"
363 : `Open ${relationship.toLowerCase()} in this chat`}
364 </TooltipPopup>
365 </Tooltip>
366 )}
367 </li>
368 );
369 })}
370 </ThreadLineageRowList>
371 </section>
372 );