Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { threadKey } from "@t3tools/client-runtime/state/entities";
3import { ThreadDetailsControl } from "./ThreadDetailsControl";
4import { ThreadHoverCardPopup } from "../ThreadHoverCard";
5import { ThreadDetailsSection } from "./ThreadDetailsSection";
6import { SectionHeaderStatus } from "../ui/collapsible-section-header";
7import { SubagentTooltipContent } from "./SubagentTooltipContent";
8import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
9import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
10import {
11 deriveWorkflowGroups,
12 projectedSubagentsToRuntime,
13 type RuntimeSubagent,
14} from "@t3tools/client-runtime/state/subagentRuntime";
15import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
16import { deriveProviderSubagentStatus } from "@t3tools/client-runtime/state/thread-execution";
17import {
18 deriveThreadRelationshipGraph,
19 immediateThreadRelationships,
20 isParentThreadRelationship,
21 threadRelationshipRowStatus,
22 orderWebThreadLineageRows,
23 resolveMergeBackTargetThreadId,
24 type ThreadRelationshipEdge,
25 type ThreadRelationshipWalkRow,
26} from "@t3tools/client-runtime/state/thread-relationships";
27import {
28 canDetachThreadProviderSession,
29 resolveLatestMergeBackRun,
30} from "@t3tools/client-runtime/state/thread-workflows";
31import {
32 isOrchestrationV2WorkActive,
33 isProviderNativeSubagentThread,
34 NodeId,
35 type EnvironmentId,
36 type OrchestrationV2DelegatedFrom,
37 type OrchestrationV2RemoteTaskChild,
38 type OrchestrationV2Subagent,
39 type OrchestrationV2ThreadShell,
40 type ServerProvider,
41 type ThreadId,
42} from "@t3tools/contracts";
43import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
44import { groupBy } from "effect/Array";
45import * as DateTime from "effect/DateTime";
46import { useNavigate } from "@tanstack/react-router";
47import {
48 ArrowRightIcon,
49 BotIcon,
50 ChevronDownIcon,
51 CornerLeftUpIcon,
52 GitForkIcon,
53 MessagesSquareIcon,
54 MoreHorizontalIcon,
55 PlusIcon,
56 SquareIcon,
57 UnplugIcon,
58} from "lucide-react";
59import { useRef, useState, type ReactNode } from "react";
60
61import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
62import { buildThreadRouteParams } from "../../threadRoutes";
63import {
64 useProjects,
65 useQuietThreadShell,
66 useThreadProjection,
67 useThreadRelationshipShells,
68 useHiddenThreadKeys,
69 useAnyEnvironmentHiding,
70} from "../../state/entities";
71import { useEnvironment, useEnvironmentProviders } from "../../state/environments";
72import { serverEnvironment } from "../../state/server";
73import {
74 applyProviderInstanceSettings,
75 deriveProviderInstanceEntries,
76} from "../../providerInstances";
77import { threadEnvironment } from "../../state/threads";
78import { orchestrationEnvironment } from "../../state/orchestration";
79import { useAtomCommand } from "../../state/use-atom-command";
80import { useEnvironmentQuery } from "../../state/query";
81import { AgentElapsed } from "./AgentElapsed";
82import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon";
83import { ThreadLineageWorkflowRow } from "./ThreadLineageWorkflowRow";
84import { openSideChatTab } from "../../lib/sideChatPane";
85
86import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
87import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
88import { toastManager } from "../ui/toast";
89import { Spinner } from "../ui/spinner";
90import { cn } from "~/lib/utils";
91import {
92 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
93 THREAD_DETAILS_PANEL_ICON_CLASS,
94 THREAD_DETAILS_PANEL_LABEL_CLASS,
95 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
96 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
97 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
98} from "./threadDetailsPanelStyles";
99
100const THREAD_LINEAGE_INITIAL_COUNT = 6;
101const THREAD_LINEAGE_PAGE_COUNT = 12;
102
103function resolveThreadLineageWindow<Row>(
104 rows: ReadonlyArray<Row>,
105 visibleCount: number,
106): { readonly visibleRows: ReadonlyArray<Row>; readonly hiddenCount: number } {
107 const visibleRows = rows.slice(0, visibleCount);
108 return { visibleRows, hiddenCount: rows.length - visibleRows.length };
109}
110
111function ThreadLineageRowList(props: {
112 readonly hiddenCount: number;
113 readonly onShowMore: () => void;
114 readonly children: ReactNode;
115}) {
116 return (
117 <>
118 {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
119 <ul
120 aria-label="Related threads"
121 className="m-0 max-h-[13.5rem] list-none overflow-y-auto overscroll-contain p-0 has-data-workflow-expanded:max-h-[min(28rem,55dvh)]"
122 >
123 {props.children}
124 </ul>
125 {props.hiddenCount > 0 ? (
126 <button
127 type="button"
128 onClick={props.onShowMore}
129 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]`}
130 >
131 <PlusIcon aria-hidden className="size-4 shrink-0" />
132 Show {Math.min(props.hiddenCount, THREAD_LINEAGE_PAGE_COUNT)} more
133 </button>
134 ) : null}
135 </>
136 );
137}
138
139type RemoteSubagent = OrchestrationV2Subagent & {
140 readonly remoteChild: OrchestrationV2RemoteTaskChild;
141};
142
143/** A task delegated to a linked environment has no thread here, so it gets its own row kind. */
144type LineageRow = ThreadRelationshipWalkRow | { readonly remote: RemoteSubagent };
145
146const lineageRowStatus = (row: LineageRow) =>
147 "remote" in row ? row.remote.status : row.edge.status;
148
149const isFinishedAgentStatus = (status: string | null | undefined) =>
150 ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes(status ?? "");
151
152function ThreadLineageGroup<Row extends LineageRow>(props: {
153 readonly label: string | null;
154 readonly rows: ReadonlyArray<Row>;
155 readonly expanded: boolean;
156 readonly children: (rows: ReadonlyArray<Row>) => ReactNode;
157}) {
158 const [expanded, setExpanded] = useState(props.expanded);
159 const [visibleCount, setVisibleCount] = useState(THREAD_LINEAGE_INITIAL_COUNT);
160 const { visibleRows, hiddenCount } = resolveThreadLineageWindow(props.rows, visibleCount);
161 const failedCount = props.rows.filter((row) => {
162 const status = lineageRowStatus(row);
163 return status === "failed" || status === "error";
164 }).length;
165 if (props.rows.length === 0) return null;
166 return (
167 <div>
168 {props.label ? (
169 <ThreadDetailsControl aria-expanded={expanded} onClick={() => setExpanded(!expanded)}>
170 <BotIcon aria-hidden className={THREAD_DETAILS_PANEL_ICON_CLASS} />
171 <span className={cn(THREAD_DETAILS_PANEL_LABEL_CLASS, "min-w-0 flex-1 truncate")}>
172 {props.label}
173 </span>
174 {failedCount > 0 ? <SectionHeaderStatus>{failedCount} failed</SectionHeaderStatus> : null}
175 {expanded ? null : (
176 <span className="shrink-0 text-xs font-normal tabular-nums text-muted-foreground">
177 {props.rows.length}
178 </span>
179 )}
180 <ChevronDownIcon
181 aria-hidden
182 className={cn(
183 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
184 "transition-transform",
185 !expanded && "-rotate-90",
186 )}
187 />
188 </ThreadDetailsControl>
189 ) : null}
190 {expanded ? (
191 <ThreadLineageRowList
192 hiddenCount={hiddenCount}
193 onShowMore={() => setVisibleCount((count) => count + THREAD_LINEAGE_PAGE_COUNT)}
194 >
195 {props.children(visibleRows)}
196 </ThreadLineageRowList>
197 ) : null}
198 </div>
199 );
200}
201
202function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) {
203 if (edge.kind === "transfer") return "Context transfer";
204 if (edge.kind === "subagent") {
205 return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
206 }
207 return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread";
208}
209
210function relationshipThreadTitle(input: {
211 readonly title: string;
212 readonly isSubagent: boolean;
213}): string {
214 if (!input.isSubagent) return input.title;
215 return formatSubagentDisplayTitle(input.title);
216}
217
218/** The full title, since the row truncates it, with what a click does. */
219function LineageTooltipContent(props: { readonly title: string; readonly hint: string }) {
220 return (
221 <>
222 <span className="block font-medium">{props.title}</span>
223 <span className="block text-muted-foreground">{props.hint}</span>
224 </>
225 );
226}
227
228function currentSubagent<Agent extends RuntimeSubagent>(
229 agent: Agent | undefined,
230 childThread: OrchestrationV2ThreadShell | null | undefined,
231): Agent | undefined {
232 if (!agent || !childThread || isOrchestrationV2WorkActive(agent.status)) return agent;
233 const liveStatus =
234 childThread.activityRunStatus ?? (childThread.status === "queued" ? "queued" : null);
235 const newerRun =
236 childThread.latestRunRequestedAt &&
237 DateTime.toEpochMillis(childThread.latestRunRequestedAt) >
238 Date.parse(agent.completedAt ?? agent.startedAt ?? agent.updatedAt);
239 if (!liveStatus && !newerRun) return agent;
240 const status = liveStatus ?? childThread.status;
241 const startedAt = liveStatus ? childThread.activityRunStartedAt : childThread.latestRunStartedAt;
242 const completedAt = liveStatus ? null : childThread.latestRunCompletedAt;
243 return {
244 ...agent,
245 status:
246 status === "preparing" || status === "starting" || status === "queued"
247 ? "pending"
248 : status === "rolled_back"
249 ? "interrupted"
250 : status,
251 startedAt: startedAt ? DateTime.formatIso(startedAt) : null,
252 completedAt: completedAt ? DateTime.formatIso(completedAt) : null,
253 progress: null,
254 result: null,
255 error: null,
256 };
257}
258
259/**
260 * A task delegated to a linked environment. It has no thread here, so it opens
261 * the thread there, when this client is connected to that environment.
262 */
263function RemoteSubagentRow(props: {
264 readonly agent: RemoteSubagent;
265 readonly provider: ServerProvider | undefined;
266}) {
267 const navigate = useNavigate();
268 const environment = useEnvironment(props.agent.remoteChild.environmentId);
269 const { remoteChild } = props.agent;
270 const status = props.agent.status;
271 const failed = status === "failed";
272 const title = relationshipThreadTitle({
273 title: props.agent.title ?? "Subagent",
274 isSubagent: true,
275 });
276 return (
277 <li className="group relative flex h-8 items-center rounded-lg">
278 <Tooltip>
279 <TooltipTrigger
280 delay={200}
281 render={
282 <ThreadDetailsControl
283 size="sm"
284 variant="ghost"
285 part="row"
286 aria-disabled={environment === null || undefined}
287 onClick={() => {
288 if (environment === null) return;
289 void navigate({
290 to: "/$environmentId/$threadId",
291 params: buildThreadRouteParams(
292 scopeThreadRef(remoteChild.environmentId, remoteChild.threadId),
293 ),
294 });
295 }}
296 />
297 }
298 >
299 <ThreadRelationshipIcon
300 // The task's own driver here is only a "remote" label.
301 driver={props.provider?.driver}
302 provider={props.provider}
303 fallbackIcon={BotIcon}
304 status={status}
305 />
306 <span className="min-w-0 flex-1">
307 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
308 {title}
309 </span>
310 </span>
311 <span
312 className={`flex max-w-1/2 shrink-0 gap-1 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"}`}
313 >
314 <span className="truncate">on {remoteChild.label}</span>
315 <span className="shrink-0">· {threadRelationshipStatusLabel(status)}</span>
316 </span>
317 </TooltipTrigger>
318 <TooltipPopup side="left">
319 <LineageTooltipContent
320 title={title}
321 hint={
322 environment === null
323 ? `Runs on ${remoteChild.label}. Connect to it to open the thread there.`
324 : `Open on ${remoteChild.label}`
325 }
326 />
327 </TooltipPopup>
328 </Tooltip>
329 </li>
330 );
331}
332
333/**
334 * The thread on a linked environment whose agent delegated this one. It opens
335 * there when this client is connected to that environment.
336 */
337function DelegatedFromRow(props: {
338 readonly delegatedFrom: OrchestrationV2DelegatedFrom;
339 readonly fallbackLabel: string | undefined;
340}) {
341 const navigate = useNavigate();
342 const { delegatedFrom } = props;
343 const environment = useEnvironment(delegatedFrom.environmentId);
344 const parentRef = scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
345 // The title it had at delegation, until this client sees the parent itself.
346 const parent = useQuietThreadShell(parentRef);
347 const label = environment?.label ?? props.fallbackLabel;
348 const title = parent?.title ?? delegatedFrom.title;
349 return (
350 <li className="group relative flex h-8 items-center rounded-lg">
351 <Tooltip>
352 <TooltipTrigger
353 delay={200}
354 render={
355 <ThreadDetailsControl
356 size="sm"
357 variant="ghost"
358 part="row"
359 aria-disabled={environment === null || undefined}
360 onClick={() => {
361 if (environment === null) return;
362 void navigate({
363 to: "/$environmentId/$threadId",
364 params: buildThreadRouteParams(parentRef),
365 });
366 }}
367 />
368 }
369 >
370 <ThreadRelationshipIcon fallbackIcon={CornerLeftUpIcon} status={null} />
371 <span className="min-w-0 flex-1">
372 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
373 {title}
374 </span>
375 </span>
376 {label ? (
377 <span className="max-w-1/2 shrink-0 truncate text-2xs text-muted-foreground">
378 on {label}
379 </span>
380 ) : null}
381 </TooltipTrigger>
382 <TooltipPopup side="left">
383 <LineageTooltipContent
384 title={title}
385 hint={
386 environment === null
387 ? `Delegated from ${label ?? "a linked environment"}. Connect to it to open the parent thread.`
388 : `Open parent agent on ${environment.label}`
389 }
390 />
391 </TooltipPopup>
392 </Tooltip>
393 </li>
394 );
395}
396
397export function ThreadRelationshipsPanel(props: {
398 readonly environmentId: EnvironmentId;
399 readonly threadId: ThreadId;
400 readonly showLineage: boolean;
401 readonly showSideChats: boolean;
402}) {
403 const ref = scopeThreadRef(props.environmentId, props.threadId);
404 const projection = useThreadProjection(ref)?.projection ?? null;
405 const providersByEnvironment = useEnvironmentProviders();
406 const settings = useAtomValue(serverEnvironment.settingsValueAtom(props.environmentId));
407 const relationshipShells = useThreadRelationshipShells(ref);
408 const hiddenKeys = useHiddenThreadKeys();
409 const hidingAnywhere = useAnyEnvironmentHiding();
410 const allProjects = useProjects();
411 const archived = useArchivedThreadSnapshots([props.environmentId]);
412 const archivedShells = archived.snapshots.find(
413 (entry) => entry.environmentId === props.environmentId,
414 )?.snapshot.threads;
415 const currentThread =
416 projection?.thread ??
417 relationshipShells.find((thread) => thread.id === props.threadId) ??
418 archivedShells?.find((thread) => thread.id === props.threadId);
419 const parentThreadId =
420 currentThread?.forkedFrom?.type === "run"
421 ? currentThread.forkedFrom.threadId
422 : currentThread?.lineage.parentThreadId;
423 const parentShell = parentThreadId
424 ? (relationshipShells.find((thread) => thread.id === parentThreadId) ??
425 archivedShells?.find((thread) => thread.id === parentThreadId))
426 : undefined;
427 const parentRef =
428 parentShell && isProviderNativeSubagentThread(parentShell)
429 ? scopeThreadRef(props.environmentId, parentShell.id)
430 : null;
431 const parentProjection = useThreadProjection(parentRef)?.projection;
432 const navigate = useNavigate();
433 const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
434 const stopSession = useAtomCommand(threadEnvironment.stopSession);
435 const interruptTurn = useAtomCommand(threadEnvironment.interruptTurn);
436 const stopWorkflowCommand = useAtomCommand(orchestrationEnvironment.stopWorkflow);
437 const canOperateWorkflow = useAtomValue(
438 orchestrationEnvironment.stopWorkflow.permissionAtom(props.environmentId),
439 );
440 const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
441 const mergeErrorToastId = useRef<string | null>(null);
442 const detachErrorToastId = useRef<string | null>(null);
443 const [stoppingId, setStoppingId] = useState<string | null>(null);
444 // Derive graphs after hooks to preserve their compiler cache.
445 const providers = providersByEnvironment.get(props.environmentId);
446 const derivedProviderEntries = deriveProviderInstanceEntries(providers ?? []);
447 const providerEntries = settings
448 ? applyProviderInstanceSettings(
449 derivedProviderEntries,
450 settings,
451 currentThread?.projectId ?? null,
452 )
453 : derivedProviderEntries;
454 const projects = allProjects.filter((project) => project.environmentId === props.environmentId);
455 const parentNativeStatus = parentProjection
456 ? deriveProviderSubagentStatus(parentProjection)?.status
457 : undefined;
458 const projected = projection?.subagents ?? [];
459 const runtimeSubagents = projectedSubagentsToRuntime(projected);
460 const byId = new Map(runtimeSubagents.map((agent) => [agent.id, agent]));
461 const subagentsByThreadId = new Map(
462 projected
463 .filter((subagent) => subagent.childThreadId !== null)
464 .map((subagent) => [
465 subagent.childThreadId,
466 {
467 ...byId.get(subagent.id)!,
468 id: subagent.id,
469 threadId: subagent.threadId,
470 runId: subagent.runId,
471 nativeTaskRef: subagent.nativeTaskRef,
472 nativeStatus: subagent.status,
473 driver: subagent.driver,
474 providerInstanceId: subagent.providerInstanceId,
475 origin: subagent.origin,
476 modelSelection: subagent.modelSelection,
477 },
478 ]),
479 );
480 const workflowGroupsById = new Map(
481 deriveWorkflowGroups(runtimeSubagents).map((group) => [group.workflow.id, group]),
482 );
483 const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
484 ...relationshipShells,
485 ...(archivedShells ?? []),
486 ];
487 const graph = deriveThreadRelationshipGraph({ threads: shells, projection });
488 const isHiddenRelation = (threadId: ThreadId) =>
489 hiddenKeys.has(threadKey({ environmentId: props.environmentId, threadId }));
490 // While hiding, an unloaded parent, fork or transfer may be hidden; unloaded subagent
491 // children (idle, left out of the shell) follow this visible thread, so they stay.
492 const isHiddenUnloadedRelation = (row: { threadId: ThreadId; edge: ThreadRelationshipEdge }) =>
493 hidingAnywhere &&
494 graph.nodes.get(row.threadId)?.missing === true &&
495 (row.edge.kind !== "subagent" || isParentThreadRelationship(row.edge, props.threadId));
496 const currentProject = projects.find((project) => project.id === currentThread?.projectId);
497 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
498 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
499 const relationshipRows = orderWebThreadLineageRows({
500 graph,
501 rows: immediateThreadRelationships(graph, props.threadId),
502 currentThreadId: props.threadId,
503 mergeTargetThreadId,
504 })
505 // The graph rebuilds missing parents from lineage, so filter the rows it returns.
506 .filter((row) => !isHiddenRelation(row.threadId) && !isHiddenUnloadedRelation(row))
507 .map((row) => {
508 const agent =
509 row.edge.kind === "subagent" && !isParentThreadRelationship(row.edge, props.threadId)
510 ? subagentsByThreadId.get(row.threadId)
511 : undefined;
512 const workflowGroup = agent === undefined ? undefined : workflowGroupsById.get(agent.id);
513 return workflowGroup === undefined
514 ? row
515 : { ...row, edge: { ...row.edge, status: workflowGroup.workflow.status } };
516 });
517 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
518 const unlistedThreadIds = relationshipRows
519 .filter(
520 ({ threadId, edge }) =>
521 !relationshipShells.some((thread) => thread.id === threadId) &&
522 (edge.kind !== "subagent" || !subagentsByThreadId.get(threadId)?.title),
523 )
524 .map(({ threadId }) => threadId);
525 const threadTitles = useEnvironmentQuery(
526 unlistedThreadIds.length === 0
527 ? null
528 : orchestrationEnvironment.threadTitles({
529 environmentId: props.environmentId,
530 input: { threadIds: unlistedThreadIds },
531 }),
532 );
533 const resolvedThreadTitles = threadTitles.data ?? {};
534 // Omitted and archived threads remain reachable; only a settled lookup proves one is gone.
535 const visibleRelationships = relationshipRows.filter(
536 ({ threadId, edge }) =>
537 edge.kind === "subagent" ||
538 !unlistedThreadIds.includes(threadId) ||
539 !threadTitles.isSuccess ||
540 threadTitles.isPending ||
541 Object.hasOwn(resolvedThreadTitles, threadId),
542 );
543 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
544
545 const {
546 related = [],
547 active = [],
548 previous = [],
549 sideChats = [],
550 } = groupBy(visibleRelationships, ({ threadId, edge }) => {
551 const isParent = isParentThreadRelationship(edge, props.threadId);
552 if (!isParent && graph.nodes.get(threadId)?.thread?.lineage.sideChat === true)
553 return "sideChats";
554 if (edge.kind !== "subagent" || isParent) return "related";
555 return isFinishedAgentStatus(edge.status) ? "previous" : "active";
556 });
557 const { remoteActive = [], remotePrevious = [] } = groupBy(
558 (projection?.subagents ?? [])
559 .filter((agent): agent is RemoteSubagent => agent.remoteChild !== undefined)
560 .map((remote) => ({ remote })),
561 ({ remote }) => (isFinishedAgentStatus(remote.status) ? "remotePrevious" : "remoteActive"),
562 );
563 const groups: ReadonlyArray<{
564 id: string;
565 label: string | null;
566 rows: ReadonlyArray<LineageRow>;
567 expanded: boolean;
568 }> = [
569 { id: "related", label: null, rows: related, expanded: true },
570 { id: "active", label: null, rows: [...active, ...remoteActive], expanded: true },
571 {
572 id: "previous",
573 label: "Previous agents",
574 rows: [...previous, ...remotePrevious],
575 expanded: false,
576 },
577 ];
578 const runningCount =
579 (projection?.subagents.filter(
580 (agent) => agent.childThreadId === null && agent.status === "running",
581 ).length ?? 0) + active.filter(({ edge }) => edge.status === "running").length;
582
583 // A linked environment's agent may have delegated this thread from there.
584 const delegatedFrom = currentThread?.delegatedFrom;
585
586 const lineageVisible =
587 props.showLineage &&
588 (related.length > 0 ||
589 active.length > 0 ||
590 previous.length > 0 ||
591 runningCount > 0 ||
592 remoteActive.length > 0 ||
593 remotePrevious.length > 0 ||
594 delegatedFrom !== undefined ||
595 // Disconnect lives in this heading, so a thread with only side chats still shows it.
596 (canDetach && sideChats.length > 0));
597 const sideChatsVisible = props.showSideChats && sideChats.length > 0;
598 const runningSideChats = sideChats.filter(({ edge }) => edge.status === "running").length;
599
600 if (!lineageVisible && !sideChatsVisible) {
601 return null;
602 }
603
604 // Idle children can be omitted from the shell; opening one loads its own detail.
605 const openThread = (threadId: ThreadId) => {
606 if (openSideChatTab(ref, graph.nodes.get(threadId)?.thread ?? null)) return;
607 void navigate({
608 to: "/$environmentId/$threadId",
609 params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
610 });
611 };
612
613 const merge = async () => {
614 if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return;
615 if (mergeErrorToastId.current !== null) {
616 toastManager.close(mergeErrorToastId.current);
617 mergeErrorToastId.current = null;
618 }
619 setBusyAction("merge");
620 const result = await mergeBack({
621 environmentId: props.environmentId,
622 input: {
623 sourceThreadId: props.threadId,
624 targetThreadId: mergeTargetThreadId,
625 runId: latestMergeBackRun.id,
626 },
627 });
628 setBusyAction(null);
629 if (result._tag === "Failure") {
630 mergeErrorToastId.current = toastManager.add({
631 type: "error",
632 title: "Could not merge back",
633 });
634 return;
635 }
636 openThread(mergeTargetThreadId);
637 };
638
639 const detach = async () => {
640 if (!canDetach || busyAction !== null) return;
641 if (detachErrorToastId.current !== null) {
642 toastManager.close(detachErrorToastId.current);
643 detachErrorToastId.current = null;
644 }
645 setBusyAction("detach");
646 const result = await stopSession({
647 environmentId: props.environmentId,
648 input: { threadId: props.threadId },
649 });
650 setBusyAction(null);
651 if (result._tag === "Failure") {
652 detachErrorToastId.current = toastManager.add({
653 type: "error",
654 title: "Could not disconnect agent session",
655 });
656 }
657 };
658
659 const stopSubagent = async (
660 childThreadId: ThreadId,
661 agent: Pick<OrchestrationV2Subagent, "id" | "threadId">,
662 ) => {
663 if (stoppingId !== null) return;
664 setStoppingId(childThreadId);
665 const result = await interruptTurn({
666 environmentId: props.environmentId,
667 input: { threadId: agent.threadId, subagentId: agent.id },
668 });
669 setStoppingId(null);
670 if (result._tag === "Failure") {
671 toastManager.add({ type: "error", title: "Could not stop subagent" });
672 }
673 };
674
675 const stopWorkflow = async (subagentId: string) => {
676 if (stoppingId !== null) return;
677 setStoppingId(subagentId);
678 const result = await stopWorkflowCommand({
679 environmentId: props.environmentId,
680 input: { threadId: props.threadId, subagentId: NodeId.make(subagentId) },
681 });
682 setStoppingId(null);
683 if (result._tag === "Failure") {
684 toastManager.add({ type: "error", title: "Could not stop workflow" });
685 }
686 };
687
688 const parentTitle =
689 mergeTargetThreadId === null
690 ? null
691 : isHiddenRelation(mergeTargetThreadId)
692 ? null
693 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
694
695 const renderRelationshipRow = ({ threadId, edge }: ThreadRelationshipWalkRow) => {
696 const node = graph.nodes.get(threadId);
697 const isSubagent = edge.kind === "subagent";
698 const isMergeTarget = threadId === mergeTargetThreadId;
699 const isParent = isParentThreadRelationship(edge, props.threadId);
700 const rowStatus =
701 (isParent && threadId === parentRef?.threadId
702 ? (node?.thread?.activityRunStatus ?? parentNativeStatus)
703 : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge });
704 const RelationshipIcon = isParent
705 ? CornerLeftUpIcon
706 : isSubagent
707 ? BotIcon
708 : node?.thread?.lineage.sideChat === true
709 ? MessagesSquareIcon
710 : GitForkIcon;
711 const relationship =
712 node?.thread?.lineage.sideChat === true && !isParent
713 ? "Side chat"
714 : relationshipLabel(edge, props.threadId);
715 const projectedAgent = isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;
716 const workflowGroup =
717 projectedAgent === undefined ? undefined : workflowGroupsById.get(projectedAgent.id);
718 const agent = workflowGroup ? projectedAgent : currentSubagent(projectedAgent, node?.thread);
719 const failed = rowStatus === "failed" || rowStatus === "error";
720 const canStop =
721 agent &&
722 (agent.origin === "app_owned" ||
723 (agent.origin === "provider_native" &&
724 agent.driver === "claudeAgent" &&
725 agent.runId != null &&
726 agent.nativeTaskRef?.strength === "strong" &&
727 agent.nativeTaskRef.nativeId !== null &&
728 ["pending", "running", "waiting"].includes(agent.nativeStatus))) &&
729 agent.startedAt &&
730 ["pending", "running", "waiting"].includes(agent.status);
731 const threadTitle = relationshipThreadTitle({
732 title:
733 workflowGroup?.workflow.workflowName ??
734 // Fresher than an archived snapshot's copy.
735 (Object.hasOwn(resolvedThreadTitles, threadId)
736 ? resolvedThreadTitles[threadId]
737 : undefined) ??
738 node?.thread?.title ??
739 agent?.title ??
740 threadId,
741 isSubagent,
742 });
743 const provider = providers?.find(
744 (entry) =>
745 entry.instanceId === (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),
746 );
747 const providerDriver = agent?.driver ?? provider?.driver;
748 const canStopWorkflow =
749 canOperateWorkflow &&
750 workflowGroup?.workflow.status === "running" &&
751 agent?.origin === "provider_native" &&
752 providerDriver === "claudeAgent";
753 const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop)
754 ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0"
755 : "";
756 const project = projects.find((project) => project.id === node?.thread?.projectId);
757 const relationshipHint = `Open ${relationship.toLowerCase()} in this chat`;
758 const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;
759 const relationshipTooltip = agent ? (
760 <SubagentTooltipContent
761 title={threadTitle}
762 model={agent.model}
763 providerInstanceId={agent.providerInstanceId}
764 origin={agent.origin}
765 modelSelection={agent.modelSelection}
766 provider={provider}
767 providers={providers}
768 driver={providerDriver}
769 elapsed={<AgentElapsed agent={agent} />}
770 status={agent.status}
771 result={agent.result}
772 progress={agent.progress}
773 parentThread={currentThread ?? undefined}
774 childThread={node?.thread ?? undefined}
775 parentProject={currentProject}
776 childProject={project}
777 />
778 ) : (
779 <LineageTooltipContent title={threadTitle} hint={relationshipHint} />
780 );
781 const relationshipContent = (
782 <>
783 <ThreadRelationshipIcon
784 driver={isSubagent && !isParent ? providerDriver : undefined}
785 provider={provider}
786 providerEntries={providerEntries}
787 fallbackIcon={RelationshipIcon}
788 status={rowStatus}
789 />
790 <span className="min-w-0 flex-1">
791 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
792 {threadTitle}
793 </span>
794 </span>
795 {agent ? null : (
796 <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
797 )}
798 {agent && !failed && (deriveSubagentElapsedMs(agent, 0) !== null || canStopWorkflow) ? (
799 <span
800 className={`shrink-0 text-2xs font-normal tabular-nums text-muted-foreground ${canStopWorkflow ? "min-w-6 text-end" : ""} ${trailingVisibilityClass}`}
801 >
802 <AgentElapsed agent={agent} compact />
803 </span>
804 ) : !isMergeTarget ? (
805 <span
806 className={
807 workflowGroup
808 ? "sr-only"
809 : `shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"} ${trailingVisibilityClass}`
810 }
811 >
812 {threadRelationshipStatusLabel(rowStatus)}
813 </span>
814 ) : null}
815 </>
816 );
817 const relationshipLink = (
818 <Tooltip>
819 <TooltipTrigger
820 delay={200}
821 render={
822 <ThreadDetailsControl
823 size="sm"
824 variant="ghost"
825 part={workflowGroup ? "primary" : "row"}
826 onClick={() => openThread(threadId)}
827 />
828 }
829 >
830 {relationshipContent}
831 </TooltipTrigger>
832 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
833 </Tooltip>
834 );
835 if (workflowGroup && agent) {
836 return (
837 <ThreadLineageWorkflowRow
838 key={threadId}
839 group={workflowGroup}
840 providerInstanceId={agent.providerInstanceId}
841 provider={provider}
842 providers={providers}
843 providerEntries={providerEntries}
844 driver={providerDriver}
845 onOpenThread={(memberThreadId) => openThread(memberThreadId as ThreadId)}
846 onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined}
847 stopping={stoppingId === agent.id}
848 stopDisabled={stoppingId !== null}
849 header={relationshipLink}
850 />
851 );
852 }
853 return (
854 <li key={threadId} className="group relative flex h-8 items-center rounded-lg">
855 {isMergeTarget ? (
856 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
857 <Tooltip>
858 <TooltipTrigger
859 delay={200}
860 render={
861 <ThreadDetailsControl
862 size="sm"
863 variant="ghost"
864 part="primary"
865 aria-label={`${threadTitle} ${threadRelationshipStatusLabel(rowStatus)}`}
866 onClick={() => openThread(threadId)}
867 />
868 }
869 >
870 {relationshipContent}
871 </TooltipTrigger>
872 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
873 </Tooltip>
874 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
875 <Tooltip>
876 <TooltipTrigger
877 render={
878 <ThreadDetailsControl
879 size="sm"
880 variant="ghost"
881 part="secondary"
882 aria-label={
883 parentTitle
884 ? `Merge back to ${parentTitle}`
885 : "Merge back to source conversation"
886 }
887 disabled={!canMerge || busyAction !== null}
888 onClick={() => void merge()}
889 >
890 {busyAction === "merge" ? (
891 <Spinner size="xs" />
892 ) : (
893 <PullRequestGlyph.merged className="size-3" />
894 )}
895 </ThreadDetailsControl>
896 }
897 />
898 <TooltipPopup side="left">
899 {latestMergeBackRun === null
900 ? "Complete a run in this fork before merging it back"
901 : parentTitle
902 ? `Merge this conversation back into ${parentTitle}`
903 : "Merge this conversation back into its source"}
904 </TooltipPopup>
905 </Tooltip>
906 <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">
907 {threadRelationshipStatusLabel(rowStatus)}
908 </span>
909 </div>
910 ) : (
911 relationshipLink
912 )}
913 {canStop && agent ? (
914 <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">
915 <Tooltip>
916 <TooltipTrigger
917 render={
918 <ThreadDetailsControl
919 size="icon-xs"
920 variant="ghost"
921 part="icon"
922 tone="destructive"
923 aria-label={`Stop subagent ${threadTitle}`}
924 disabled={stoppingId !== null}
925 onClick={() => void stopSubagent(threadId, agent)}
926 />
927 }
928 >
929 {stoppingId === threadId ? (
930 <Spinner aria-hidden size="xs" />
931 ) : (
932 <SquareIcon aria-hidden className="size-3 fill-current" />
933 )}
934 </TooltipTrigger>
935 <TooltipPopup side="left">Stop subagent</TooltipPopup>
936 </Tooltip>
937 </div>
938 ) : null}
939 </li>
940 );
941 };
942
943 return (
944 <>
945 {lineageVisible ? (
946 <ThreadDetailsSection
947 headingId="thread-details-lineage-heading"
948 title={runningCount > 0 ? `Lineage · ${runningCount} running` : "Lineage"}
949 // A lone "Previous agents" row names itself; the heading returns for status or actions.
950 showHeading={
951 runningCount > 0 ||
952 canDetach ||
953 related.length > 0 ||
954 active.length > 0 ||
955 remoteActive.length > 0 ||
956 delegatedFrom !== undefined
957 }
958 data-thread-relationships-panel
959 actions={
960 canDetach ? (
961 <Menu>
962 <MenuTrigger
963 render={
964 <ThreadDetailsControl
965 size="icon-xs"
966 variant="ghost"
967 part="icon"
968 aria-label="More thread actions"
969 disabled={busyAction !== null}
970 />
971 }
972 >
973 <MoreHorizontalIcon className="size-3.5" />
974 </MenuTrigger>
975 <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">
976 <MenuItem onClick={() => void detach()}>
977 <UnplugIcon className="size-3.5" />
978 Disconnect agent session
979 </MenuItem>
980 </MenuPopup>
981 </Menu>
982 ) : null
983 }
984 >
985 {delegatedFrom === undefined ? null : (
986 <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>
987 <DelegatedFromRow
988 delegatedFrom={delegatedFrom}
989 fallbackLabel={currentThread?.linkOrigin?.label}
990 />
991 </ThreadLineageRowList>
992 )}
993 {groups.map((group) => (
994 <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>
995 {(visibleRows) =>
996 visibleRows.map((row) =>
997 "remote" in row ? (
998 <RemoteSubagentRow
999 key={row.remote.id}
1000 agent={row.remote}
1001 // Its provider instance belongs to the environment it runs in.
1002 provider={providersByEnvironment
1003 .get(row.remote.remoteChild.environmentId)
1004 ?.find((entry) => entry.instanceId === row.remote.providerInstanceId)}
1005 />
1006 ) : (
1007 renderRelationshipRow(row)
1008 ),
1009 )
1010 }
1011 </ThreadLineageGroup>
1012 ))}
1013 </ThreadDetailsSection>
1014 ) : null}
1015 {sideChatsVisible ? (
1016 <ThreadDetailsSection
1017 headingId="thread-details-side-chats-heading"
1018 title={runningSideChats > 0 ? `Side chats · ${runningSideChats} running` : "Side chats"}
1019 data-thread-side-chats-panel
1020 >
1021 <ThreadLineageGroup
1022 key={`${scopedThreadKey(ref)}:side-chats`}
1023 label={null}
1024 rows={sideChats}
1025 expanded
1026 >
1027 {(visibleRows) => visibleRows.map(renderRelationshipRow)}
1028 </ThreadLineageGroup>
1029 </ThreadDetailsSection>
1030 ) : null}
1031 </>
1032 );
1033}