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

ThreadRelationshipsControl.tsx

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