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