Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { ThreadDetailsControl } from "./ThreadDetailsControl";
3import { ThreadHoverCardPopup } from "../ThreadHoverCard";
4import { ThreadDetailsSection } from "./ThreadDetailsSection";
5import { SectionHeaderStatus } from "../ui/collapsible-section-header";
6import { SubagentTooltipContent } from "./SubagentTooltipContent";
7import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
8import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
9import {
10 deriveWorkflowGroups,
11 projectedSubagentsToRuntime,
12 type RuntimeSubagent,
13} from "@t3tools/client-runtime/state/subagentRuntime";
14import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
15import { deriveProviderSubagentStatus } from "@t3tools/client-runtime/state/thread-execution";
16import {
17 deriveThreadRelationshipGraph,
18 immediateThreadRelationships,
19 isParentThreadRelationship,
20 threadRelationshipRowStatus,
21 orderWebThreadLineageRows,
22 resolveMergeBackTargetThreadId,
23 type ThreadRelationshipEdge,
24 type ThreadRelationshipWalkRow,
25} from "@t3tools/client-runtime/state/thread-relationships";
26import {
27 canDetachThreadProviderSession,
28 resolveLatestMergeBackRun,
29} from "@t3tools/client-runtime/state/thread-workflows";
30import {
31 isOrchestrationV2WorkActive,
32 isProviderNativeSubagentThread,
33 NodeId,
34 type EnvironmentId,
35 type OrchestrationV2RemoteTaskChild,
36 type OrchestrationV2Subagent,
37 type OrchestrationV2ThreadShell,
38 type ServerProvider,
39 type ThreadId,
40} from "@t3tools/contracts";
41import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
42import { groupBy } from "effect/Array";
43import * as DateTime from "effect/DateTime";
44import { useNavigate } from "@tanstack/react-router";
45import {
46 ArrowRightIcon,
47 BotIcon,
48 ChevronDownIcon,
49 CornerLeftUpIcon,
50 GitForkIcon,
51 LoaderCircleIcon,
52 MoreHorizontalIcon,
53 PlusIcon,
54 SquareIcon,
55 UnplugIcon,
56} from "lucide-react";
57import { useState, type ReactNode } from "react";
58
59import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
60import { buildThreadRouteParams } from "../../threadRoutes";
61import {
62 useProjects,
63 useThreadProjection,
64 useThreadRelationshipShells,
65} from "../../state/entities";
66import { useEnvironment, useEnvironmentProviders } from "../../state/environments";
67import { threadEnvironment } from "../../state/threads";
68import { orchestrationEnvironment } from "../../state/orchestration";
69import { useAtomCommand } from "../../state/use-atom-command";
70import { AgentElapsed } from "./AgentElapsed";
71import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon";
72import { ThreadLineageWorkflowRow } from "./ThreadLineageWorkflowRow";
73
74import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
75import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
76import { toastManager } from "../ui/toast";
77import { cn } from "~/lib/utils";
78import {
79 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
80 THREAD_DETAILS_PANEL_ICON_CLASS,
81 THREAD_DETAILS_PANEL_LABEL_CLASS,
82 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
83 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
84 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
85} from "./threadDetailsPanelStyles";
86
87const THREAD_LINEAGE_INITIAL_COUNT = 6;
88const THREAD_LINEAGE_PAGE_COUNT = 12;
89
90function resolveThreadLineageWindow<Row>(
91 rows: ReadonlyArray<Row>,
92 visibleCount: number,
93): { readonly visibleRows: ReadonlyArray<Row>; readonly hiddenCount: number } {
94 const visibleRows = rows.slice(0, visibleCount);
95 return { visibleRows, hiddenCount: rows.length - visibleRows.length };
96}
97
98function ThreadLineageRowList(props: {
99 readonly hiddenCount: number;
100 readonly onShowMore: () => void;
101 readonly children: ReactNode;
102}) {
103 return (
104 <>
105 {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
106 <ul
107 aria-label="Related threads"
108 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)]"
109 >
110 {props.children}
111 </ul>
112 {props.hiddenCount > 0 ? (
113 <button
114 type="button"
115 onClick={props.onShowMore}
116 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]`}
117 >
118 <PlusIcon aria-hidden className="size-4 shrink-0" />
119 Show {Math.min(props.hiddenCount, THREAD_LINEAGE_PAGE_COUNT)} more
120 </button>
121 ) : null}
122 </>
123 );
124}
125
126function ThreadLineageGroup(props: {
127 readonly label: string | null;
128 readonly rows: ReadonlyArray<ThreadRelationshipWalkRow>;
129 readonly expanded: boolean;
130 readonly children: (rows: ReadonlyArray<ThreadRelationshipWalkRow>) => ReactNode;
131}) {
132 const [expanded, setExpanded] = useState(props.expanded);
133 const [visibleCount, setVisibleCount] = useState(THREAD_LINEAGE_INITIAL_COUNT);
134 const { visibleRows, hiddenCount } = resolveThreadLineageWindow(props.rows, visibleCount);
135 const failedCount = props.rows.filter(
136 ({ edge }) => edge.status === "failed" || edge.status === "error",
137 ).length;
138 if (props.rows.length === 0) return null;
139 return (
140 <div>
141 {props.label ? (
142 <ThreadDetailsControl aria-expanded={expanded} onClick={() => setExpanded(!expanded)}>
143 <BotIcon aria-hidden className={THREAD_DETAILS_PANEL_ICON_CLASS} />
144 <span className={cn(THREAD_DETAILS_PANEL_LABEL_CLASS, "min-w-0 flex-1 truncate")}>
145 {props.label}
146 </span>
147 {failedCount > 0 ? <SectionHeaderStatus>{failedCount} failed</SectionHeaderStatus> : null}
148 {expanded ? null : (
149 <span className="shrink-0 text-xs font-normal tabular-nums text-muted-foreground">
150 {props.rows.length}
151 </span>
152 )}
153 <ChevronDownIcon
154 aria-hidden
155 className={cn(
156 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
157 "transition-transform",
158 !expanded && "-rotate-90",
159 )}
160 />
161 </ThreadDetailsControl>
162 ) : null}
163 {expanded ? (
164 <ThreadLineageRowList
165 hiddenCount={hiddenCount}
166 onShowMore={() => setVisibleCount((count) => count + THREAD_LINEAGE_PAGE_COUNT)}
167 >
168 {props.children(visibleRows)}
169 </ThreadLineageRowList>
170 ) : null}
171 </div>
172 );
173}
174
175function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) {
176 if (edge.kind === "transfer") return "Context transfer";
177 if (edge.kind === "subagent") {
178 return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
179 }
180 return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread";
181}
182
183function relationshipThreadTitle(input: {
184 readonly title: string;
185 readonly isSubagent: boolean;
186}): string {
187 if (!input.isSubagent) return input.title;
188 return formatSubagentDisplayTitle(input.title);
189}
190
191function currentSubagent<Agent extends RuntimeSubagent>(
192 agent: Agent | undefined,
193 childThread: OrchestrationV2ThreadShell | null | undefined,
194): Agent | undefined {
195 if (!agent || !childThread || isOrchestrationV2WorkActive(agent.status)) return agent;
196 const liveStatus =
197 childThread.activityRunStatus ?? (childThread.status === "queued" ? "queued" : null);
198 const newerRun =
199 childThread.latestRunRequestedAt &&
200 DateTime.toEpochMillis(childThread.latestRunRequestedAt) >
201 Date.parse(agent.completedAt ?? agent.startedAt ?? agent.updatedAt);
202 if (!liveStatus && !newerRun) return agent;
203 const status = liveStatus ?? childThread.status;
204 const startedAt = liveStatus ? childThread.activityRunStartedAt : childThread.latestRunStartedAt;
205 const completedAt = liveStatus ? null : childThread.latestRunCompletedAt;
206 return {
207 ...agent,
208 status:
209 status === "preparing" || status === "starting" || status === "queued"
210 ? "pending"
211 : status === "rolled_back"
212 ? "interrupted"
213 : status,
214 startedAt: startedAt ? DateTime.formatIso(startedAt) : null,
215 completedAt: completedAt ? DateTime.formatIso(completedAt) : null,
216 progress: null,
217 result: null,
218 error: null,
219 };
220}
221
222/**
223 * A task delegated to a linked environment. It has no thread here, so it opens
224 * the thread there, when this client is connected to that environment.
225 */
226function RemoteSubagentRow(props: {
227 readonly agent: OrchestrationV2Subagent & {
228 readonly remoteChild: OrchestrationV2RemoteTaskChild;
229 };
230 readonly provider: ServerProvider | undefined;
231}) {
232 const navigate = useNavigate();
233 const environment = useEnvironment(props.agent.remoteChild.environmentId);
234 const { remoteChild } = props.agent;
235 const status = props.agent.status;
236 const failed = status === "failed";
237 const title = relationshipThreadTitle({
238 title: props.agent.title ?? "Subagent",
239 isSubagent: true,
240 });
241 return (
242 <li className="group relative flex h-8 items-center rounded-lg">
243 <Tooltip>
244 <TooltipTrigger
245 delay={200}
246 render={
247 <ThreadDetailsControl
248 size="sm"
249 variant="ghost"
250 part="row"
251 disabled={environment === null}
252 onClick={() =>
253 void navigate({
254 to: "/$environmentId/$threadId",
255 params: buildThreadRouteParams(
256 scopeThreadRef(remoteChild.environmentId, remoteChild.threadId),
257 ),
258 })
259 }
260 />
261 }
262 >
263 <ThreadRelationshipIcon
264 driver={props.agent.driver}
265 provider={props.provider}
266 fallbackIcon={BotIcon}
267 status={status}
268 />
269 <span className="min-w-0 flex-1">
270 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
271 {title}
272 </span>
273 </span>
274 <span
275 className={`shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"}`}
276 >
277 on {remoteChild.label} · {threadRelationshipStatusLabel(status)}
278 </span>
279 </TooltipTrigger>
280 <TooltipPopup side="left">
281 {environment === null
282 ? `Runs on ${remoteChild.label}. Connect to it to open the thread there.`
283 : `Open on ${remoteChild.label}`}
284 </TooltipPopup>
285 </Tooltip>
286 </li>
287 );
288}
289
290export function ThreadRelationshipsPanel(props: {
291 readonly environmentId: EnvironmentId;
292 readonly threadId: ThreadId;
293}) {
294 const ref = scopeThreadRef(props.environmentId, props.threadId);
295 const projection = useThreadProjection(ref)?.projection ?? null;
296 const providersByEnvironment = useEnvironmentProviders();
297 const relationshipShells = useThreadRelationshipShells(ref);
298 const allProjects = useProjects();
299 const archived = useArchivedThreadSnapshots([props.environmentId]);
300 const archivedShells = archived.snapshots.find(
301 (entry) => entry.environmentId === props.environmentId,
302 )?.snapshot.threads;
303 const currentThread =
304 projection?.thread ??
305 relationshipShells.find((thread) => thread.id === props.threadId) ??
306 archivedShells?.find((thread) => thread.id === props.threadId);
307 const parentThreadId =
308 currentThread?.forkedFrom?.type === "run"
309 ? currentThread.forkedFrom.threadId
310 : currentThread?.lineage.parentThreadId;
311 const parentShell = parentThreadId
312 ? (relationshipShells.find((thread) => thread.id === parentThreadId) ??
313 archivedShells?.find((thread) => thread.id === parentThreadId))
314 : undefined;
315 const parentRef =
316 parentShell && isProviderNativeSubagentThread(parentShell)
317 ? scopeThreadRef(props.environmentId, parentShell.id)
318 : null;
319 const parentProjection = useThreadProjection(parentRef)?.projection;
320 const navigate = useNavigate();
321 const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
322 const stopSession = useAtomCommand(threadEnvironment.stopSession);
323 const interruptTurn = useAtomCommand(threadEnvironment.interruptTurn);
324 const stopWorkflowCommand = useAtomCommand(orchestrationEnvironment.stopWorkflow);
325 const canOperateWorkflow = useAtomValue(
326 orchestrationEnvironment.stopWorkflow.permissionAtom(props.environmentId),
327 );
328 const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
329 const [stoppingId, setStoppingId] = useState<string | null>(null);
330 // Derive graphs after hooks to preserve their compiler cache.
331 const providers = providersByEnvironment.get(props.environmentId);
332 const projects = allProjects.filter((project) => project.environmentId === props.environmentId);
333 const parentNativeStatus = parentProjection
334 ? deriveProviderSubagentStatus(parentProjection)?.status
335 : undefined;
336 const projected = projection?.subagents ?? [];
337 const runtimeSubagents = projectedSubagentsToRuntime(projected);
338 const byId = new Map(runtimeSubagents.map((agent) => [agent.id, agent]));
339 const subagentsByThreadId = new Map(
340 projected
341 .filter((subagent) => subagent.childThreadId !== null)
342 .map((subagent) => [
343 subagent.childThreadId,
344 {
345 ...byId.get(subagent.id)!,
346 id: subagent.id,
347 threadId: subagent.threadId,
348 runId: subagent.runId,
349 nativeTaskRef: subagent.nativeTaskRef,
350 nativeStatus: subagent.status,
351 driver: subagent.driver,
352 providerInstanceId: subagent.providerInstanceId,
353 origin: subagent.origin,
354 modelSelection: subagent.modelSelection,
355 },
356 ]),
357 );
358 const workflowGroupsById = new Map(
359 deriveWorkflowGroups(runtimeSubagents).map((group) => [group.workflow.id, group]),
360 );
361 const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
362 ...relationshipShells,
363 ...(archivedShells ?? []),
364 ];
365 const graph = deriveThreadRelationshipGraph({ threads: shells, projection });
366 const currentProject = projects.find((project) => project.id === currentThread?.projectId);
367 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
368 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
369 const relationshipRows = orderWebThreadLineageRows({
370 graph,
371 rows: immediateThreadRelationships(graph, props.threadId),
372 currentThreadId: props.threadId,
373 mergeTargetThreadId,
374 }).map((row) => {
375 const agent =
376 row.edge.kind === "subagent" && !isParentThreadRelationship(row.edge, props.threadId)
377 ? subagentsByThreadId.get(row.threadId)
378 : undefined;
379 const workflowGroup = agent === undefined ? undefined : workflowGroupsById.get(agent.id);
380 return workflowGroup === undefined
381 ? row
382 : { ...row, edge: { ...row.edge, status: workflowGroup.workflow.status } };
383 });
384 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
385 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
386
387 const {
388 related = [],
389 active = [],
390 previous = [],
391 } = groupBy(relationshipRows, ({ edge }) => {
392 if (edge.kind !== "subagent" || isParentThreadRelationship(edge, props.threadId))
393 return "related";
394 return ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes(
395 edge.status ?? "",
396 )
397 ? "previous"
398 : "active";
399 });
400 const groups = [
401 { id: "related", label: null, rows: related, expanded: true },
402 { id: "active", label: null, rows: active, expanded: true },
403 { id: "previous", label: "Previous agents", rows: previous, expanded: false },
404 ];
405 // Tasks running in a linked environment have no thread here; they get their own rows.
406 const remoteSubagents = (projection?.subagents ?? []).filter(
407 (agent): agent is OrchestrationV2Subagent & { remoteChild: OrchestrationV2RemoteTaskChild } =>
408 agent.remoteChild !== undefined,
409 );
410 const runningCount =
411 (projection?.subagents.filter(
412 (agent) => agent.childThreadId === null && agent.status === "running",
413 ).length ?? 0) + active.filter(({ edge }) => edge.status === "running").length;
414
415 if (relationshipRows.length === 0 && runningCount === 0 && remoteSubagents.length === 0) {
416 return null;
417 }
418
419 const openThread = (threadId: ThreadId) => {
420 void navigate({
421 to: "/$environmentId/$threadId",
422 params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
423 });
424 };
425
426 const merge = async () => {
427 if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return;
428 setBusyAction("merge");
429 const result = await mergeBack({
430 environmentId: props.environmentId,
431 input: {
432 sourceThreadId: props.threadId,
433 targetThreadId: mergeTargetThreadId,
434 runId: latestMergeBackRun.id,
435 },
436 });
437 setBusyAction(null);
438 if (result._tag === "Success") openThread(mergeTargetThreadId);
439 };
440
441 const detach = async () => {
442 if (!canDetach || busyAction !== null) return;
443 setBusyAction("detach");
444 await stopSession({
445 environmentId: props.environmentId,
446 input: { threadId: props.threadId },
447 });
448 setBusyAction(null);
449 };
450
451 const stopSubagent = async (
452 childThreadId: ThreadId,
453 agent: Pick<OrchestrationV2Subagent, "id" | "threadId">,
454 ) => {
455 if (stoppingId !== null) return;
456 setStoppingId(childThreadId);
457 const result = await interruptTurn({
458 environmentId: props.environmentId,
459 input: { threadId: agent.threadId, subagentId: agent.id },
460 });
461 setStoppingId(null);
462 if (result._tag === "Failure") {
463 toastManager.add({ type: "error", title: "Could not stop subagent" });
464 }
465 };
466
467 const stopWorkflow = async (subagentId: string) => {
468 if (stoppingId !== null) return;
469 setStoppingId(subagentId);
470 const result = await stopWorkflowCommand({
471 environmentId: props.environmentId,
472 input: { threadId: props.threadId, subagentId: NodeId.make(subagentId) },
473 });
474 setStoppingId(null);
475 if (result._tag === "Failure") {
476 toastManager.add({ type: "error", title: "Could not stop workflow" });
477 }
478 };
479
480 const parentTitle =
481 mergeTargetThreadId === null
482 ? null
483 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
484
485 return (
486 <ThreadDetailsSection
487 headingId="thread-details-lineage-heading"
488 title={runningCount > 0 ? `Lineage · ${runningCount} running` : "Lineage"}
489 // A lone "Previous agents" row names itself; the heading returns for status or actions.
490 showHeading={runningCount > 0 || canDetach || related.length > 0 || active.length > 0}
491 data-thread-relationships-panel
492 actions={
493 canDetach ? (
494 <Menu>
495 <MenuTrigger
496 render={
497 <ThreadDetailsControl
498 size="icon-xs"
499 variant="ghost"
500 part="icon"
501 aria-label="More thread actions"
502 disabled={busyAction !== null}
503 />
504 }
505 >
506 <MoreHorizontalIcon className="size-3.5" />
507 </MenuTrigger>
508 <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">
509 <MenuItem onClick={() => void detach()}>
510 <UnplugIcon className="size-3.5" />
511 Disconnect agent session
512 </MenuItem>
513 </MenuPopup>
514 </Menu>
515 ) : null
516 }
517 >
518 {groups.map((group) => (
519 <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>
520 {(visibleRows) =>
521 visibleRows.map(({ threadId, edge }) => {
522 const node = graph.nodes.get(threadId);
523 const isSubagent = edge.kind === "subagent";
524 const isMergeTarget = threadId === mergeTargetThreadId;
525 const isParent = isParentThreadRelationship(edge, props.threadId);
526 const rowStatus =
527 (isParent && threadId === parentRef?.threadId
528 ? (node?.thread?.activityRunStatus ?? parentNativeStatus)
529 : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge });
530 const RelationshipIcon = isParent
531 ? CornerLeftUpIcon
532 : isSubagent
533 ? BotIcon
534 : GitForkIcon;
535 const relationship = relationshipLabel(edge, props.threadId);
536 const projectedAgent =
537 isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;
538 const workflowGroup =
539 projectedAgent === undefined
540 ? undefined
541 : workflowGroupsById.get(projectedAgent.id);
542 const agent = workflowGroup
543 ? projectedAgent
544 : currentSubagent(projectedAgent, node?.thread);
545 const failed = rowStatus === "failed" || rowStatus === "error";
546 const canStop =
547 agent &&
548 (agent.origin === "app_owned" ||
549 (agent.origin === "provider_native" &&
550 agent.driver === "claudeAgent" &&
551 agent.runId != null &&
552 agent.nativeTaskRef?.strength === "strong" &&
553 agent.nativeTaskRef.nativeId !== null &&
554 ["pending", "running", "waiting"].includes(agent.nativeStatus))) &&
555 agent.startedAt &&
556 ["pending", "running", "waiting"].includes(agent.status);
557 const threadTitle = relationshipThreadTitle({
558 title:
559 workflowGroup?.workflow.workflowName ??
560 node?.thread?.title ??
561 agent?.title ??
562 threadId,
563 isSubagent,
564 });
565 const provider = providers?.find(
566 (entry) =>
567 entry.instanceId ===
568 (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),
569 );
570 const providerDriver = agent?.driver ?? provider?.driver;
571 const canStopWorkflow =
572 canOperateWorkflow &&
573 workflowGroup?.workflow.status === "running" &&
574 agent?.origin === "provider_native" &&
575 providerDriver === "claudeAgent";
576 const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop)
577 ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0"
578 : "";
579 const project = projects.find((project) => project.id === node?.thread?.projectId);
580 const relationshipHint = node?.missing
581 ? "This related thread is unavailable"
582 : `Open ${relationship.toLowerCase()} in this chat`;
583 const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;
584 const relationshipTooltip = agent ? (
585 <SubagentTooltipContent
586 title={threadTitle}
587 model={agent.model}
588 providerInstanceId={agent.providerInstanceId}
589 origin={agent.origin}
590 modelSelection={agent.modelSelection}
591 provider={provider}
592 providers={providers}
593 driver={providerDriver}
594 elapsed={<AgentElapsed agent={agent} />}
595 status={agent.status}
596 result={agent.result}
597 progress={agent.progress}
598 parentThread={currentThread ?? undefined}
599 childThread={node?.thread ?? undefined}
600 parentProject={currentProject}
601 childProject={project}
602 />
603 ) : (
604 relationshipHint
605 );
606 const relationshipContent = (
607 <>
608 <ThreadRelationshipIcon
609 driver={isSubagent && !isParent ? providerDriver : undefined}
610 provider={provider}
611 fallbackIcon={RelationshipIcon}
612 status={rowStatus}
613 />
614 <span className="min-w-0 flex-1">
615 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
616 {threadTitle}
617 </span>
618 </span>
619 {agent ? null : (
620 <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
621 )}
622 {agent &&
623 !failed &&
624 (deriveSubagentElapsedMs(agent, 0) !== null || canStopWorkflow) ? (
625 <span
626 className={`shrink-0 text-2xs font-normal tabular-nums text-muted-foreground ${canStopWorkflow ? "min-w-6 text-end" : ""} ${trailingVisibilityClass}`}
627 >
628 <AgentElapsed agent={agent} compact />
629 </span>
630 ) : !isMergeTarget ? (
631 <span
632 className={
633 workflowGroup
634 ? "sr-only"
635 : `shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"} ${trailingVisibilityClass}`
636 }
637 >
638 {threadRelationshipStatusLabel(rowStatus)}
639 </span>
640 ) : null}
641 </>
642 );
643 const relationshipLink = (
644 <Tooltip>
645 <TooltipTrigger
646 delay={200}
647 render={
648 <ThreadDetailsControl
649 size="sm"
650 variant="ghost"
651 part={workflowGroup ? "primary" : "row"}
652 disabled={node?.missing === true}
653 onClick={() => openThread(threadId)}
654 />
655 }
656 >
657 {relationshipContent}
658 </TooltipTrigger>
659 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
660 </Tooltip>
661 );
662 if (workflowGroup && agent) {
663 return (
664 <ThreadLineageWorkflowRow
665 key={threadId}
666 group={workflowGroup}
667 providerInstanceId={agent.providerInstanceId}
668 provider={provider}
669 providers={providers}
670 driver={providerDriver}
671 onOpenThread={(memberThreadId) => openThread(memberThreadId as ThreadId)}
672 isThreadAvailable={(memberThreadId) =>
673 graph.nodes.get(memberThreadId as ThreadId)?.missing === false
674 }
675 onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined}
676 stopping={stoppingId === agent.id}
677 stopDisabled={stoppingId !== null}
678 header={relationshipLink}
679 />
680 );
681 }
682 return (
683 <li key={threadId} className="group relative flex h-8 items-center rounded-lg">
684 {isMergeTarget ? (
685 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
686 <Tooltip>
687 <TooltipTrigger
688 delay={200}
689 render={
690 <ThreadDetailsControl
691 size="sm"
692 variant="ghost"
693 part="primary"
694 aria-label={`${threadTitle} ${threadRelationshipStatusLabel(rowStatus)}`}
695 disabled={node?.missing === true}
696 onClick={() => openThread(threadId)}
697 />
698 }
699 >
700 {relationshipContent}
701 </TooltipTrigger>
702 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
703 </Tooltip>
704 <span
705 aria-hidden="true"
706 className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS}
707 />
708 <Tooltip>
709 <TooltipTrigger
710 render={
711 <ThreadDetailsControl
712 size="sm"
713 variant="ghost"
714 part="secondary"
715 aria-label={
716 parentTitle
717 ? `Merge back to ${parentTitle}`
718 : "Merge back to source conversation"
719 }
720 disabled={!canMerge || busyAction !== null}
721 onClick={() => void merge()}
722 >
723 {busyAction === "merge" ? (
724 <LoaderCircleIcon className="size-3 animate-spin" />
725 ) : (
726 <PullRequestGlyph.merged className="size-3" />
727 )}
728 </ThreadDetailsControl>
729 }
730 />
731 <TooltipPopup side="left">
732 {latestMergeBackRun === null
733 ? "Complete a run in this fork before merging it back"
734 : parentTitle
735 ? `Merge this conversation back into ${parentTitle}`
736 : "Merge this conversation back into its source"}
737 </TooltipPopup>
738 </Tooltip>
739 <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">
740 {threadRelationshipStatusLabel(rowStatus)}
741 </span>
742 </div>
743 ) : (
744 relationshipLink
745 )}
746 {canStop && agent ? (
747 <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">
748 <Tooltip>
749 <TooltipTrigger
750 render={
751 <ThreadDetailsControl
752 size="icon-xs"
753 variant="ghost"
754 part="icon"
755 tone="destructive"
756 aria-label={`Stop subagent ${threadTitle}`}
757 disabled={stoppingId !== null}
758 onClick={() => void stopSubagent(threadId, agent)}
759 />
760 }
761 >
762 {stoppingId === threadId ? (
763 <LoaderCircleIcon aria-hidden className="size-3 animate-spin" />
764 ) : (
765 <SquareIcon aria-hidden className="size-3 fill-current" />
766 )}
767 </TooltipTrigger>
768 <TooltipPopup side="left">Stop subagent</TooltipPopup>
769 </Tooltip>
770 </div>
771 ) : null}
772 </li>
773 );
774 })
775 }
776 </ThreadLineageGroup>
777 ))}
778 {remoteSubagents.length > 0 ? (
779 <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>
780 {remoteSubagents.map((agent) => (
781 <RemoteSubagentRow
782 key={agent.id}
783 agent={agent}
784 // Its provider instance belongs to the environment it runs in.
785 provider={providersByEnvironment
786 .get(agent.remoteChild.environmentId)
787 ?.find((entry) => entry.instanceId === agent.providerInstanceId)}
788 />
789 ))}
790 </ThreadLineageRowList>
791 ) : null}
792 </ThreadDetailsSection>
793 );
794}