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