Open History to see the last commit
1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import { ThreadHoverCardPopup } from "../ThreadHoverCard";
3import { ThreadDetailsSection } from "./ThreadDetailsSection";
4import { CollapsibleSectionHeader, SectionHeaderStatus } from "../ui/collapsible-section-header";
5import { SubagentTooltipContent } from "./SubagentTooltipContent";
6import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
7import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
8import { projectedSubagentsToRuntime } from "@t3tools/client-runtime/state/subagentRuntime";
9import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
10import {
11 deriveThreadRelationshipGraph,
12 immediateThreadRelationships,
13 isParentThreadRelationship,
14 threadRelationshipRowStatus,
15 orderWebThreadLineageRows,
16 resolveMergeBackTargetThreadId,
17 type ThreadRelationshipEdge,
18 type ThreadRelationshipWalkRow,
19} from "@t3tools/client-runtime/state/thread-relationships";
20import {
21 canDetachThreadProviderSession,
22 resolveLatestMergeBackRun,
23} from "@t3tools/client-runtime/state/thread-workflows";
24import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
25import { groupBy } from "effect/Array";
26import { useNavigate } from "@tanstack/react-router";
27import {
28 ArrowRightIcon,
29 BotIcon,
30 CornerLeftUpIcon,
31 GitForkIcon,
32 LoaderCircleIcon,
33 MoreHorizontalIcon,
34 PlusIcon,
35 UnplugIcon,
36} from "lucide-react";
37import { useMemo, useState, type ReactNode } from "react";
38
39import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
40import { buildThreadRouteParams } from "../../threadRoutes";
41import {
42 useProjects,
43 useServerConfigs,
44 useThreadProjection,
45 useThreadShells,
46} from "../../state/entities";
47import { threadEnvironment } from "../../state/threads";
48import { useAtomCommand } from "../../state/use-atom-command";
49import { AgentElapsed } from "./AgentElapsed";
50import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon";
51
52import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
53import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
54import {
55 THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS,
56 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
57 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
58} from "./threadDetailsPanelStyles";
59
60// Lineage paging: a busy thread can accumulate dozens of forks and subagents,
61// and the panel it lives in already scrolls. Show a workable window, keep the
62// rest behind Show more, and bound what is shown so the sections below Lineage
63// stay reachable.
64const THREAD_LINEAGE_INITIAL_COUNT = 6;
65const THREAD_LINEAGE_PAGE_COUNT = 12;
66
67export function resolveThreadLineageWindow<Row>(
68 rows: ReadonlyArray<Row>,
69 visibleCount: number,
70): { readonly visibleRows: ReadonlyArray<Row>; readonly hiddenCount: number } {
71 const visibleRows = rows.slice(0, visibleCount);
72 return { visibleRows, hiddenCount: rows.length - visibleRows.length };
73}
74
75export function ThreadLineageRowList(props: {
76 readonly hiddenCount: number;
77 readonly onShowMore: () => void;
78 readonly children: ReactNode;
79}) {
80 return (
81 <>
82 {/*
83 Bounded rather than free-growing so Lineage cannot push the rest of the
84 thread details panel out of view. Plain overflow, not a ScrollArea
85 component: this sits inside an already scrolling panel, where a
86 max-height-only virtual viewport measures badly. Every row is a focusable
87 button, so keyboard users reach and scroll the region through the rows
88 themselves and the container needs no extra tab stop of its own.
89 */}
90 <ul
91 aria-label="Related threads"
92 className="m-0 max-h-[13.5rem] list-none overflow-y-auto overscroll-contain p-0"
93 >
94 {props.children}
95 </ul>
96 {props.hiddenCount > 0 ? (
97 <button
98 type="button"
99 onClick={props.onShowMore}
100 className={`flex h-9 w-full cursor-pointer items-center rounded-lg ${THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS} text-sm font-medium text-muted-foreground/70 hover:bg-black/[0.055] hover:text-foreground/80 dark:hover:bg-white/[0.075]`}
101 >
102 <PlusIcon aria-hidden className="size-4 shrink-0" />
103 Show {Math.min(props.hiddenCount, THREAD_LINEAGE_PAGE_COUNT)} more
104 </button>
105 ) : null}
106 </>
107 );
108}
109
110function ThreadLineageGroup(props: {
111 readonly label: string | null;
112 readonly rows: ReadonlyArray<ThreadRelationshipWalkRow>;
113 readonly expanded: boolean;
114 readonly children: (rows: ReadonlyArray<ThreadRelationshipWalkRow>) => ReactNode;
115}) {
116 const [expanded, setExpanded] = useState(props.expanded);
117 const [visibleCount, setVisibleCount] = useState(THREAD_LINEAGE_INITIAL_COUNT);
118 const { visibleRows, hiddenCount } = resolveThreadLineageWindow(props.rows, visibleCount);
119 const failedCount = props.rows.filter(
120 ({ edge }) => edge.status === "failed" || edge.status === "error",
121 ).length;
122 if (props.rows.length === 0) return null;
123 return (
124 <div>
125 {props.label ? (
126 <CollapsibleSectionHeader
127 expanded={expanded}
128 onClick={() => setExpanded(!expanded)}
129 accessory={
130 failedCount > 0 ? <SectionHeaderStatus>{failedCount} failed</SectionHeaderStatus> : null
131 }
132 >
133 {props.label}
134 {!expanded && ` (${props.rows.length})`}
135 </CollapsibleSectionHeader>
136 ) : null}
137 {expanded ? (
138 <ThreadLineageRowList
139 hiddenCount={hiddenCount}
140 onShowMore={() => setVisibleCount((count) => count + THREAD_LINEAGE_PAGE_COUNT)}
141 >
142 {props.children(visibleRows)}
143 </ThreadLineageRowList>
144 ) : null}
145 </div>
146 );
147}
148
149function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) {
150 if (edge.kind === "transfer") return "Context transfer";
151 if (edge.kind === "subagent") {
152 return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
153 }
154 return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread";
155}
156
157function relationshipThreadTitle(input: {
158 readonly title: string;
159 readonly isSubagent: boolean;
160}): string {
161 if (!input.isSubagent) return input.title;
162 return formatSubagentDisplayTitle(input.title);
163}
164
165export function ThreadRelationshipsPanel(props: {
166 readonly environmentId: EnvironmentId;
167 readonly threadId: ThreadId;
168}) {
169 const ref = scopeThreadRef(props.environmentId, props.threadId);
170 const projection = useThreadProjection(ref)?.projection ?? null;
171 const providers = useServerConfigs().get(props.environmentId)?.providers;
172 const subagentsByThreadId = useMemo(
173 () =>
174 new Map(
175 (projection?.subagents ?? [])
176 .filter((subagent) => subagent.childThreadId !== null)
177 .map((subagent) => [
178 subagent.childThreadId,
179 {
180 ...projectedSubagentsToRuntime([subagent])[0]!,
181 driver: subagent.driver,
182 providerInstanceId: subagent.providerInstanceId,
183 },
184 ]),
185 ),
186 [projection?.subagents],
187 );
188 const threadShells = useThreadShells();
189 const projects = useProjects().filter((project) => project.environmentId === props.environmentId);
190 const archived = useArchivedThreadSnapshots([props.environmentId]);
191 const archivedShells = archived.snapshots.find(
192 (entry) => entry.environmentId === props.environmentId,
193 )?.snapshot.threads;
194 const graph = useMemo(() => {
195 const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
196 ...threadShells
197 .filter((thread) => thread.environmentId === props.environmentId)
198 .map((thread) => thread.source),
199 ...(archivedShells ?? []),
200 ];
201 return deriveThreadRelationshipGraph({ threads: shells, projection });
202 }, [archivedShells, projection, props.environmentId, threadShells]);
203 const currentThread = projection?.thread ?? graph.nodes.get(props.threadId)?.thread;
204 const currentProject = projects.find((project) => project.id === currentThread?.projectId);
205 const navigate = useNavigate();
206 const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
207 const stopSession = useAtomCommand(threadEnvironment.stopSession);
208 const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
209 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
210 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
211 const relationshipRows = useMemo(
212 () =>
213 orderWebThreadLineageRows({
214 graph,
215 rows: immediateThreadRelationships(graph, props.threadId),
216 currentThreadId: props.threadId,
217 mergeTargetThreadId,
218 }),
219 [graph, mergeTargetThreadId, props.threadId],
220 );
221 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
222 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
223
224 const {
225 related = [],
226 active = [],
227 previous = [],
228 } = groupBy(relationshipRows, ({ edge }) => {
229 if (edge.kind !== "subagent" || isParentThreadRelationship(edge, props.threadId))
230 return "related";
231 return ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes(
232 edge.status ?? "",
233 )
234 ? "previous"
235 : "active";
236 });
237 const groups = [
238 { id: "related", label: null, rows: related, expanded: true },
239 { id: "active", label: null, rows: active, expanded: true },
240 { id: "previous", label: "Previous agents", rows: previous, expanded: false },
241 ];
242 const runningCount =
243 projection?.subagents.filter((agent) => agent.status === "running").length ??
244 active.filter(({ edge }) => edge.status === "running").length;
245
246 if (relationshipRows.length === 0 && runningCount === 0) {
247 return null;
248 }
249
250 const openThread = (threadId: ThreadId) => {
251 void navigate({
252 to: "/$environmentId/$threadId",
253 params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
254 });
255 };
256
257 const merge = async () => {
258 if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return;
259 setBusyAction("merge");
260 const result = await mergeBack({
261 environmentId: props.environmentId,
262 input: {
263 sourceThreadId: props.threadId,
264 targetThreadId: mergeTargetThreadId,
265 runId: latestMergeBackRun.id,
266 },
267 });
268 setBusyAction(null);
269 if (result._tag === "Success") openThread(mergeTargetThreadId);
270 };
271
272 const detach = async () => {
273 if (!canDetach || busyAction !== null) return;
274 setBusyAction("detach");
275 await stopSession({
276 environmentId: props.environmentId,
277 input: { threadId: props.threadId },
278 });
279 setBusyAction(null);
280 };
281
282 const parentTitle =
283 mergeTargetThreadId === null
284 ? null
285 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
286
287 return (
288 <ThreadDetailsSection
289 headingId="thread-details-lineage-heading"
290 title={runningCount > 0 ? `Lineage · ${runningCount} running` : "Lineage"}
291 data-thread-relationships-panel
292 actions={
293 canDetach ? (
294 <Menu>
295 <MenuTrigger
296 render={
297 <ThreadDetailsControl
298 size="icon-xs"
299 variant="ghost"
300 part="icon"
301 aria-label="More thread actions"
302 disabled={busyAction !== null}
303 />
304 }
305 >
306 <MoreHorizontalIcon className="size-3.5" />
307 </MenuTrigger>
308 <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">
309 <MenuItem onClick={() => void detach()}>
310 <UnplugIcon className="size-3.5" />
311 Disconnect agent session
312 </MenuItem>
313 </MenuPopup>
314 </Menu>
315 ) : null
316 }
317 >
318 {groups.map((group) => (
319 <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>
320 {(visibleRows) =>
321 visibleRows.map(({ threadId, edge }) => {
322 const node = graph.nodes.get(threadId);
323 const isSubagent = edge.kind === "subagent";
324 const isMergeTarget = threadId === mergeTargetThreadId;
325 const isParent = isParentThreadRelationship(edge, props.threadId);
326 const status = threadRelationshipRowStatus(graph, { threadId, edge });
327 const RelationshipIcon = isParent
328 ? CornerLeftUpIcon
329 : isSubagent
330 ? BotIcon
331 : GitForkIcon;
332 const relationship = relationshipLabel(edge, props.threadId);
333 const agent = isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;
334 const threadTitle = relationshipThreadTitle({
335 title: node?.thread?.title ?? agent?.title ?? threadId,
336 isSubagent,
337 });
338 const provider = providers?.find(
339 (entry) =>
340 entry.instanceId ===
341 (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),
342 );
343 const providerDriver = agent?.driver ?? provider?.driver;
344 const project = projects.find((project) => project.id === node?.thread?.projectId);
345 const relationshipHint = node?.missing
346 ? "This related thread is unavailable"
347 : `Open ${relationship.toLowerCase()} in this chat`;
348 const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;
349 const relationshipTooltip = agent ? (
350 <SubagentTooltipContent
351 title={threadTitle}
352 model={agent.model}
353 provider={provider}
354 driver={providerDriver}
355 elapsed={<AgentElapsed agent={agent} />}
356 status={agent.status}
357 result={agent.result}
358 progress={agent.progress}
359 parentThread={currentThread ?? undefined}
360 childThread={node?.thread ?? undefined}
361 parentProject={currentProject}
362 childProject={project}
363 />
364 ) : (
365 relationshipHint
366 );
367 const relationshipContent = (
368 <>
369 <ThreadRelationshipIcon
370 driver={isSubagent && !isParent ? providerDriver : undefined}
371 provider={provider}
372 fallbackIcon={RelationshipIcon}
373 status={status}
374 />
375 <span className="min-w-0 flex-1">
376 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
377 {threadTitle}
378 </span>
379 </span>
380 {agent ? (
381 agent.startedAt ? (
382 <span className="shrink-0 text-2xs font-normal tabular-nums text-muted-foreground">
383 <AgentElapsed agent={agent} />
384 </span>
385 ) : null
386 ) : (
387 <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
388 )}
389 {!isMergeTarget ? (
390 <span className="shrink-0 text-2xs text-muted-foreground">
391 {threadRelationshipStatusLabel(status)}
392 </span>
393 ) : null}
394 </>
395 );
396 return (
397 <li key={threadId} className="group flex h-9 items-center rounded-lg">
398 {isMergeTarget ? (
399 <div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
400 <Tooltip>
401 <TooltipTrigger
402 delay={200}
403 render={
404 <ThreadDetailsControl
405 size="sm"
406 variant="ghost"
407 part="link-primary"
408 aria-label={`${threadTitle} ${threadRelationshipStatusLabel(status)}`}
409 disabled={node?.missing === true}
410 onClick={() => openThread(threadId)}
411 />
412 }
413 >
414 {relationshipContent}
415 </TooltipTrigger>
416 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
417 </Tooltip>
418 <span
419 aria-hidden="true"
420 className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS}
421 />
422 <Tooltip>
423 <TooltipTrigger
424 render={
425 <ThreadDetailsControl
426 size="sm"
427 variant="ghost"
428 part="secondary"
429 aria-label={
430 parentTitle
431 ? `Merge back to ${parentTitle}`
432 : "Merge back to source conversation"
433 }
434 disabled={!canMerge || busyAction !== null}
435 onClick={() => void merge()}
436 >
437 {busyAction === "merge" ? (
438 <LoaderCircleIcon className="size-3 animate-spin" />
439 ) : (
440 <PullRequestGlyph.merged className="size-3" />
441 )}
442 </ThreadDetailsControl>
443 }
444 />
445 <TooltipPopup side="left">
446 {latestMergeBackRun === null
447 ? "Complete a run in this fork before merging it back"
448 : parentTitle
449 ? `Merge this conversation back into ${parentTitle}`
450 : "Merge this conversation back into its source"}
451 </TooltipPopup>
452 </Tooltip>
453 <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">
454 {threadRelationshipStatusLabel(status)}
455 </span>
456 </div>
457 ) : (
458 <Tooltip>
459 <TooltipTrigger
460 delay={200}
461 render={
462 <ThreadDetailsControl
463 size="sm"
464 variant="ghost"
465 disabled={node?.missing === true}
466 onClick={() => openThread(threadId)}
467 part="row"
468 />
469 }
470 >
471 {relationshipContent}
472 </TooltipTrigger>
473 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
474 </Tooltip>
475 )}
476 </li>
477 );
478 })
479 }
480 </ThreadLineageGroup>
481 ))}
482 </ThreadDetailsSection>
483 );
484}