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

ThreadRelationshipsControl.tsx

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