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

ThreadRelationshipsControl.tsx

887 lines35.5 KB

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