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

ThreadRelationshipsControl.tsx

1,030 lines39.0 KB

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