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

ThreadRelationshipsControl.tsx

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