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

ThreadRelationshipsControl.tsx

374 lines14.6 KB

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