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