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 selectLatestSubagentsByChildThread,
25 type ThreadRelationshipEdge,
26 type ThreadRelationshipWalkRow,
27} from "@t3tools/client-runtime/state/thread-relationships";
28import {
29 canDetachThreadProviderSession,
30 resolveLatestMergeBackRun,
31} from "@t3tools/client-runtime/state/thread-workflows";
32import {
33 isOrchestrationV2WorkActive,
34 isProviderNativeSubagentThread,
35 NodeId,
36 type EnvironmentId,
37 type OrchestrationV2DelegatedFrom,
38 type OrchestrationV2RemoteTaskChild,
39 type OrchestrationV2Subagent,
40 type OrchestrationV2ThreadShell,
41 type ScopedThreadRef,
42 type ServerProvider,
43 type ThreadId,
44} from "@t3tools/contracts";
45import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
46import { groupBy } from "effect/Array";
47import * as DateTime from "effect/DateTime";
48import { useNavigate, useRouter } from "@tanstack/react-router";
49import {
50 ArrowRightIcon,
51 BotIcon,
52 ChevronDownIcon,
53 CornerLeftUpIcon,
54 GitForkIcon,
55 MessagesSquareIcon,
56 MoreHorizontalIcon,
57 PlusIcon,
58 SquareIcon,
59 UnplugIcon,
60} from "lucide-react";
61import { msg, T, useGT, useMessages, Var } from "gt-react";
62import { useRef, useState, type ComponentProps, type ReactNode } from "react";
63import type { MessageResolver } from "~/i18n/messages";
64
65import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
66import { buildThreadRouteParams } from "../../threadRoutes";
67import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread";
68import { useLinkedThreadOpener } from "../../state/linkedThreadView";
69import {
70 useProjects,
71 useQuietThreadProjection,
72 useQuietThreadShell,
73 useThreadRelationshipShells,
74 useReopenedRemoteTasks,
75 useHiddenThreadKeys,
76 useAnyEnvironmentHiding,
77} from "../../state/entities";
78import { useEnvironment, useEnvironmentProviders } from "../../state/environments";
79import { serverEnvironment } from "../../state/server";
80import {
81 applyProviderInstanceSettings,
82 deriveProviderInstanceEntries,
83 hasInstanceBadge,
84} from "../../providerInstances";
85import { threadEnvironment } from "../../state/threads";
86import { orchestrationEnvironment, threadTitlesRead } from "../../state/orchestration";
87import { useAtomCommand } from "../../state/use-atom-command";
88import { useEnvironmentQuery } from "../../state/query";
89import { AgentElapsed } from "./AgentElapsed";
90import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon";
91import { ThreadLineageWorkflowRow } from "./ThreadLineageWorkflowRow";
92import { useSideThreadTrigger } from "../../hooks/useSideThreadTrigger";
93import { openSideThread, resolveThreadOpenRoute } from "../../lib/sideChatPane";
94
95import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
96import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
97import { SharedTooltipTrigger } from "../ui/shared-tooltip";
98import { toastManager } from "../ui/toast";
99import { Spinner } from "../ui/spinner";
100import { cn } from "~/lib/utils";
101import {
102 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
103 THREAD_DETAILS_PANEL_ICON_CLASS,
104 THREAD_DETAILS_PANEL_LABEL_CLASS,
105 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
106 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
107 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
108} from "./threadDetailsPanelStyles";
109
110const THREAD_LINEAGE_INITIAL_COUNT = 6;
111const THREAD_LINEAGE_PAGE_COUNT = 12;
112
113function resolveThreadLineageWindow<Row>(
114 rows: ReadonlyArray<Row>,
115 visibleCount: number,
116): { readonly visibleRows: ReadonlyArray<Row>; readonly hiddenCount: number } {
117 const visibleRows = rows.slice(0, visibleCount);
118 return { visibleRows, hiddenCount: rows.length - visibleRows.length };
119}
120
121function ThreadLineageRowList(props: {
122 readonly hiddenCount: number;
123 readonly onShowMore: () => void;
124 readonly children: ReactNode;
125}) {
126 const gt = useGT();
127 const listRef = useRef<HTMLUListElement>(null);
128 const showMore = () => {
129 const exhausting = props.hiddenCount <= THREAD_LINEAGE_PAGE_COUNT;
130 props.onShowMore();
131 // The button unmounts on the final page; focus the list so focus isn't dropped.
132 if (exhausting) listRef.current?.focus({ preventScroll: true });
133 };
134 return (
135 <>
136 {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
137 <ul
138 ref={listRef}
139 tabIndex={-1}
140 aria-label={gt`Related threads`}
141 className="m-0 max-h-[13.5rem] list-none overflow-y-auto p-0 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70 has-data-workflow-expanded:max-h-[min(28rem,55dvh)]"
142 >
143 {props.children}
144 </ul>
145 {props.hiddenCount > 0 ? (
146 <button
147 type="button"
148 onClick={showMore}
149 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]`}
150 >
151 <PlusIcon aria-hidden className="size-4 shrink-0" />
152 <T>
153 Show <Var>{Math.min(props.hiddenCount, THREAD_LINEAGE_PAGE_COUNT)}</Var> more
154 </T>
155 </button>
156 ) : null}
157 </>
158 );
159}
160
161type RemoteSubagent = OrchestrationV2Subagent & {
162 readonly remoteChild: OrchestrationV2RemoteTaskChild;
163};
164
165/** A task delegated to a linked environment has no thread here, so it gets its own row kind. */
166type LineageRow = ThreadRelationshipWalkRow | { readonly remote: RemoteSubagent };
167
168const lineageRowStatus = (row: LineageRow) =>
169 "remote" in row ? row.remote.status : row.edge.status;
170
171const isFinishedAgentStatus = (status: string | null | undefined) =>
172 ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes(status ?? "");
173
174function ThreadLineageGroup<Row extends LineageRow>(props: {
175 readonly label: string | null;
176 readonly rows: ReadonlyArray<Row>;
177 readonly expanded: boolean;
178 readonly onExpandedChange?: ((expanded: boolean) => void) | undefined;
179 readonly children: (rows: ReadonlyArray<Row>) => ReactNode;
180}) {
181 const [uncontrolledExpanded, setUncontrolledExpanded] = useState(props.expanded);
182 const expanded = props.onExpandedChange ? props.expanded : uncontrolledExpanded;
183 const [visibleCount, setVisibleCount] = useState(THREAD_LINEAGE_INITIAL_COUNT);
184 const { visibleRows, hiddenCount } = resolveThreadLineageWindow(props.rows, visibleCount);
185 const failedCount = props.rows.filter((row) => {
186 const status = lineageRowStatus(row);
187 return status === "failed" || status === "error";
188 }).length;
189 if (props.rows.length === 0) return null;
190 return (
191 <div>
192 {props.label ? (
193 <ThreadDetailsControl
194 aria-expanded={expanded}
195 onClick={() => {
196 const next = !expanded;
197 if (props.onExpandedChange) props.onExpandedChange(next);
198 else setUncontrolledExpanded(next);
199 }}
200 >
201 <BotIcon aria-hidden className={THREAD_DETAILS_PANEL_ICON_CLASS} />
202 <span className={cn(THREAD_DETAILS_PANEL_LABEL_CLASS, "min-w-0 flex-1 truncate")}>
203 {props.label}
204 </span>
205 {failedCount > 0 ? (
206 <SectionHeaderStatus>
207 <T>
208 <Var>{failedCount}</Var> failed
209 </T>
210 </SectionHeaderStatus>
211 ) : null}
212 {expanded ? null : (
213 <span className="shrink-0 text-xs font-normal tabular-nums text-muted-foreground">
214 {props.rows.length}
215 </span>
216 )}
217 <ChevronDownIcon
218 aria-hidden
219 className={cn(
220 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
221 "transition-transform",
222 !expanded && "-rotate-90",
223 )}
224 />
225 </ThreadDetailsControl>
226 ) : null}
227 {expanded ? (
228 <ThreadLineageRowList
229 hiddenCount={hiddenCount}
230 onShowMore={() => setVisibleCount((count) => count + THREAD_LINEAGE_PAGE_COUNT)}
231 >
232 {props.children(visibleRows)}
233 </ThreadLineageRowList>
234 ) : null}
235 </div>
236 );
237}
238
239function relationshipHint(
240 edge: ThreadRelationshipEdge,
241 currentThreadId: ThreadId,
242 sideChat: boolean,
243 resolve: MessageResolver,
244) {
245 if (sideChat) return resolve(msg("Open side chat"));
246 if (edge.kind === "transfer") return resolve(msg("Open context transfer in this chat"));
247 if (edge.kind === "subagent") {
248 return edge.sourceThreadId === currentThreadId
249 ? resolve(msg("Open subagent"))
250 : resolve(msg("Open parent agent in this chat"));
251 }
252 return edge.sourceThreadId === currentThreadId
253 ? resolve(msg("Open fork in this chat"))
254 : resolve(msg("Open parent thread in this chat"));
255}
256
257function relationshipThreadTitle(input: {
258 readonly title: string;
259 readonly isSubagent: boolean;
260}): string {
261 if (!input.isSubagent) return input.title;
262 return formatSubagentDisplayTitle(input.title);
263}
264
265/** The full title, since the row truncates it, with what a click does. */
266function LineageTooltipContent(props: { readonly title: string; readonly hint: string }) {
267 return (
268 <>
269 <span className="block font-medium">{props.title}</span>
270 <span className="block text-muted-foreground">{props.hint}</span>
271 </>
272 );
273}
274
275function LineageSubagentTooltip({
276 childRef,
277 ...props
278}: Omit<ComponentProps<typeof SubagentTooltipContent>, "provider"> & {
279 readonly childRef: ScopedThreadRef;
280}) {
281 // Idle children may be omitted from the shell. Read their family only while the card is open.
282 const family = useEnvironmentQuery(
283 props.origin === "app_owned" && props.childThread === undefined
284 ? orchestrationEnvironment.threadFamily({
285 environmentId: childRef.environmentId,
286 input: { threadId: childRef.threadId },
287 })
288 : null,
289 );
290 const child =
291 props.childThread ?? family.data?.threads.find((thread) => thread.id === childRef.threadId);
292 const selection = props.origin === "app_owned" ? child?.modelSelection : undefined;
293 const providerInstanceId = selection?.instanceId ?? props.providerInstanceId;
294 const provider = props.providers?.find((provider) => provider.instanceId === providerInstanceId);
295 return (
296 <SubagentTooltipContent
297 {...props}
298 model={selection?.model ?? props.model}
299 providerInstanceId={providerInstanceId}
300 modelSelection={selection ?? props.modelSelection}
301 provider={provider}
302 driver={provider?.driver ?? props.driver}
303 childThread={child}
304 />
305 );
306}
307
308function currentSubagent<Agent extends RuntimeSubagent>(
309 agent: Agent | undefined,
310 childThread: OrchestrationV2ThreadShell | null | undefined,
311): Agent | undefined {
312 if (!agent || !childThread || isOrchestrationV2WorkActive(agent.status)) return agent;
313 const liveStatus =
314 childThread.activityRunStatus ?? (childThread.status === "queued" ? "queued" : null);
315 const newerRun =
316 childThread.latestRunRequestedAt &&
317 DateTime.toEpochMillis(childThread.latestRunRequestedAt) >
318 Date.parse(agent.completedAt ?? agent.startedAt ?? agent.updatedAt);
319 if (!liveStatus && !newerRun) return agent;
320 const status = liveStatus ?? childThread.status;
321 const startedAt = liveStatus ? childThread.activityRunStartedAt : childThread.latestRunStartedAt;
322 const completedAt = liveStatus ? null : childThread.latestRunCompletedAt;
323 return {
324 ...agent,
325 status:
326 status === "preparing" || status === "starting" || status === "queued"
327 ? "pending"
328 : status === "rolled_back"
329 ? "interrupted"
330 : status,
331 startedAt: startedAt ? DateTime.formatIso(startedAt) : null,
332 completedAt: completedAt ? DateTime.formatIso(completedAt) : null,
333 progress: null,
334 result: null,
335 error: null,
336 };
337}
338
339/**
340 * A task delegated to a linked environment. It has no thread here, so it opens the thread there:
341 * in place when this client is connected to that environment, else read-only through this one.
342 */
343function RemoteSubagentRow(props: {
344 readonly agent: RemoteSubagent;
345 /** The thread that delegated the task; its environment holds the link and its panel shows the read. */
346 readonly parentRef: ScopedThreadRef;
347 readonly provider: ServerProvider | undefined;
348 readonly anyInstanceBadge: boolean;
349}) {
350 const gt = useGT();
351 const m = useMessages();
352 const { remoteChild } = props.agent;
353 const childRef = scopeThreadRef(remoteChild.environmentId, remoteChild.threadId);
354 const child = useQuietThreadShell(childRef);
355 const connected = useEnvironment(remoteChild.environmentId)?.connection.phase === "connected";
356 const titles = useEnvironmentQuery(
357 connected && child === null
358 ? orchestrationEnvironment.threadTitles({
359 environmentId: childRef.environmentId,
360 input: { threadIds: [childRef.threadId] },
361 })
362 : null,
363 );
364 const status = props.agent.status;
365 const failed = status === "failed";
366 const timing = {
367 status,
368 startedAt: props.agent.startedAt ? DateTime.formatIso(props.agent.startedAt) : null,
369 completedAt: props.agent.completedAt ? DateTime.formatIso(props.agent.completedAt) : null,
370 };
371 const showElapsed = !failed && deriveSubagentElapsedMs(timing, 0) !== null;
372 const title = relationshipThreadTitle({
373 title: child?.title ?? titles.data?.[childRef.threadId] ?? props.agent.title ?? gt`Subagent`,
374 isSubagent: true,
375 });
376 const opener = useLinkedThreadOpener(props.parentRef, remoteChild, title);
377 const trigger = useSideThreadTrigger();
378 return (
379 <li className="group relative flex h-8 items-center rounded-lg">
380 <Tooltip>
381 <TooltipTrigger
382 delay={200}
383 render={
384 <ThreadDetailsControl
385 size="sm"
386 variant="ghost"
387 part="row"
388 {...(opener ? trigger(opener.open, { panel: opener.mode === "linked" }) : {})}
389 />
390 }
391 >
392 <ThreadRelationshipIcon
393 // The task's own driver here is only a "remote" label.
394 driver={props.provider?.driver}
395 provider={props.provider}
396 anyInstanceBadge={props.anyInstanceBadge}
397 fallbackIcon={BotIcon}
398 status={status}
399 />
400 <span className="min-w-0 flex-1">
401 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
402 {title}
403 </span>
404 </span>
405 <span
406 className={`flex max-w-1/2 shrink-0 gap-1 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"}`}
407 >
408 <span className="truncate">
409 <T>
410 on <Var>{remoteChild.label}</Var>
411 </T>
412 </span>
413 <span className="shrink-0 tabular-nums">
414 ·{" "}
415 {showElapsed ? (
416 <AgentElapsed agent={timing} compact />
417 ) : (
418 threadRelationshipStatusLabel(status, m)
419 )}
420 </span>
421 </span>
422 </TooltipTrigger>
423 <TooltipPopup side="left">
424 <LineageTooltipContent
425 title={title}
426 hint={
427 opener?.mode === "linked"
428 ? gt`Read the thread on ${{ label: remoteChild.label }}`
429 : gt`Open on ${{ label: remoteChild.label }}`
430 }
431 />
432 </TooltipPopup>
433 </Tooltip>
434 </li>
435 );
436}
437
438/**
439 * The thread on a linked environment whose agent delegated this one. It opens
440 * there when this client is connected to that environment.
441 */
442function DelegatedFromRow(props: {
443 readonly delegatedFrom: OrchestrationV2DelegatedFrom;
444 readonly fallbackLabel: string | undefined;
445 readonly anyInstanceBadge: boolean;
446}) {
447 const gt = useGT();
448 const navigate = useNavigate();
449 const router = useRouter();
450 const { delegatedFrom } = props;
451 const environment = useEnvironment(delegatedFrom.environmentId);
452 const parentRef = scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
453 // The title it had at delegation, until this client sees the parent itself.
454 const parent = useQuietThreadShell(parentRef);
455 const readParent = useAtomCommand(threadTitlesRead);
456 const [opening, setOpening] = useState(false);
457 const label = environment?.label ?? props.fallbackLabel;
458 const title = parent?.title ?? delegatedFrom.title;
459 // The parent may have been deleted there since delegation, and the shell can't
460 // tell a deleted parent from one this client never loaded, so ask its environment.
461 const openParent = async () => {
462 if (opening) return;
463 setOpening(true);
464 const location = router.latestLocation;
465 const result = await readParent({
466 environmentId: delegatedFrom.environmentId,
467 input: { threadIds: [delegatedFrom.threadId] },
468 });
469 setOpening(false);
470 // The read can outlast the user's stay on this thread; a late answer must not pull them back.
471 if (router.latestLocation !== location) return;
472 if (result._tag === "Failure") {
473 toastManager.add({ type: "error", title: gt`Could not open the parent thread` });
474 return;
475 }
476 // Deleted and unknown threads are absent from the titles.
477 if (result.value[delegatedFrom.threadId] === undefined) {
478 toastManager.add({ type: "info", title: gt`The parent thread was deleted` });
479 return;
480 }
481 void navigate({
482 to: "/$environmentId/$threadId",
483 params: buildThreadRouteParams(parentRef),
484 });
485 };
486 return (
487 <li className="group relative flex h-8 items-center rounded-lg">
488 <Tooltip>
489 <TooltipTrigger
490 delay={200}
491 render={
492 <ThreadDetailsControl
493 size="sm"
494 variant="ghost"
495 part="row"
496 aria-disabled={environment === null || undefined}
497 onClick={() => {
498 if (environment === null) return;
499 void openParent();
500 }}
501 />
502 }
503 >
504 <ThreadRelationshipIcon
505 anyInstanceBadge={props.anyInstanceBadge}
506 fallbackIcon={CornerLeftUpIcon}
507 status={null}
508 />
509 <span className="min-w-0 flex-1">
510 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
511 {title}
512 </span>
513 </span>
514 {label ? (
515 <span className="max-w-1/2 shrink-0 truncate text-2xs text-muted-foreground">
516 <T>
517 on <Var>{label}</Var>
518 </T>
519 </span>
520 ) : null}
521 </TooltipTrigger>
522 <TooltipPopup side="left">
523 <LineageTooltipContent
524 title={title}
525 hint={
526 environment === null
527 ? label
528 ? gt`Delegated from ${{ label }}. Connect to it to open the parent thread.`
529 : gt`Delegated from a linked environment. Connect to it to open the parent thread.`
530 : gt`Open parent agent on ${{ label: environment.label }}`
531 }
532 />
533 </TooltipPopup>
534 </Tooltip>
535 </li>
536 );
537}
538
539export function ThreadRelationshipsPanel(props: {
540 readonly environmentId: EnvironmentId;
541 readonly threadId: ThreadId;
542 readonly showLineage: boolean;
543 readonly showSideChats: boolean;
544}) {
545 const gt = useGT();
546 const m = useMessages();
547 const ref = scopeThreadRef(props.environmentId, props.threadId);
548 const projection = useQuietThreadProjection(ref)?.projection ?? null;
549 const providersByEnvironment = useEnvironmentProviders();
550 const settings = useAtomValue(serverEnvironment.settingsValueAtom(props.environmentId));
551 const relationshipShells = useThreadRelationshipShells(ref);
552 const hiddenKeys = useHiddenThreadKeys();
553 const hidingAnywhere = useAnyEnvironmentHiding();
554 const allProjects = useProjects();
555 const archived = useArchivedThreadSnapshots([props.environmentId]);
556 const archivedShells = archived.snapshots.find(
557 (entry) => entry.environmentId === props.environmentId,
558 )?.snapshot.threads;
559 const currentThread =
560 projection?.thread ??
561 relationshipShells.find((thread) => thread.id === props.threadId) ??
562 archivedShells?.find((thread) => thread.id === props.threadId);
563 const parentThreadId =
564 currentThread?.forkedFrom?.type === "run"
565 ? currentThread.forkedFrom.threadId
566 : currentThread?.lineage.parentThreadId;
567 const parentShell = parentThreadId
568 ? (relationshipShells.find((thread) => thread.id === parentThreadId) ??
569 archivedShells?.find((thread) => thread.id === parentThreadId))
570 : undefined;
571 const parentRef =
572 parentShell && isProviderNativeSubagentThread(parentShell)
573 ? scopeThreadRef(props.environmentId, parentShell.id)
574 : null;
575 const parentProjection = useQuietThreadProjection(parentRef)?.projection;
576 const navigate = useNavigate();
577 const trigger = useSideThreadTrigger();
578 const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
579 const stopSession = useAtomCommand(threadEnvironment.stopSession);
580 const interruptTurn = useAtomCommand(threadEnvironment.interruptTurn);
581 const stopWorkflowCommand = useAtomCommand(orchestrationEnvironment.stopWorkflow);
582 const canOperateWorkflow = useAtomValue(
583 orchestrationEnvironment.stopWorkflow.permissionAtom(props.environmentId),
584 );
585 const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
586 const mergeErrorToastId = useRef<string | null>(null);
587 const detachErrorToastId = useRef<string | null>(null);
588 const [stoppingId, setStoppingId] = useState<string | null>(null);
589 const [expandedPreviousKey, setExpandedPreviousKey] = useState<string | null>(null);
590 const threadScopeKey = scopedThreadKey(ref);
591 const previousExpanded = expandedPreviousKey === threadScopeKey;
592 // Derive graphs after hooks to preserve their compiler cache.
593 const providers = providersByEnvironment.get(props.environmentId);
594 const derivedProviderEntries = deriveProviderInstanceEntries(providers ?? []);
595 const providerEntries = settings
596 ? applyProviderInstanceSettings(
597 derivedProviderEntries,
598 settings,
599 currentThread?.projectId ?? null,
600 )
601 : derivedProviderEntries;
602 const projects = allProjects.filter((project) => project.environmentId === props.environmentId);
603 const parentNativeStatus = parentProjection
604 ? deriveProviderSubagentStatus(parentProjection)?.status
605 : undefined;
606 const projected = projection?.subagents ?? [];
607 const runtimeSubagents = projectedSubagentsToRuntime(projected);
608 const byId = new Map(runtimeSubagents.map((agent) => [agent.id, agent]));
609 const subagentsByThreadId = new Map(
610 [...selectLatestSubagentsByChildThread(projected).entries()].map(
611 ([childThreadId, subagent]) => [
612 childThreadId,
613 {
614 ...byId.get(subagent.id)!,
615 id: subagent.id,
616 threadId: subagent.threadId,
617 runId: subagent.runId,
618 nativeTaskRef: subagent.nativeTaskRef,
619 nativeStatus: subagent.status,
620 driver: subagent.driver,
621 providerInstanceId: subagent.providerInstanceId,
622 origin: subagent.origin,
623 modelSelection: subagent.modelSelection,
624 },
625 ],
626 ),
627 );
628 const workflowGroupsById = new Map(
629 deriveWorkflowGroups(runtimeSubagents, m).map((group) => [group.workflow.id, group]),
630 );
631 const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
632 ...relationshipShells,
633 ...(archivedShells ?? []),
634 ];
635 const graph = deriveThreadRelationshipGraph({ threads: shells, projection });
636 const isHiddenRelation = (threadId: ThreadId) =>
637 hiddenKeys.has(threadKey({ environmentId: props.environmentId, threadId }));
638 // While hiding, an unloaded parent, fork or transfer may be hidden; unloaded subagent
639 // children (idle, left out of the shell) follow this visible thread, so they stay.
640 const isHiddenUnloadedRelation = (row: { threadId: ThreadId; edge: ThreadRelationshipEdge }) =>
641 hidingAnywhere &&
642 graph.nodes.get(row.threadId)?.missing === true &&
643 (row.edge.kind !== "subagent" || isParentThreadRelationship(row.edge, props.threadId));
644 const currentProject = projects.find((project) => project.id === currentThread?.projectId);
645 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
646 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
647 const relationshipRows = orderWebThreadLineageRows({
648 graph,
649 rows: immediateThreadRelationships(graph, props.threadId),
650 currentThreadId: props.threadId,
651 mergeTargetThreadId,
652 })
653 // The graph rebuilds missing parents from lineage, so filter the rows it returns.
654 .filter((row) => !isHiddenRelation(row.threadId) && !isHiddenUnloadedRelation(row))
655 .map((row) => {
656 const agent =
657 row.edge.kind === "subagent" && !isParentThreadRelationship(row.edge, props.threadId)
658 ? subagentsByThreadId.get(row.threadId)
659 : undefined;
660 const workflowGroup = agent === undefined ? undefined : workflowGroupsById.get(agent.id);
661 return workflowGroup === undefined
662 ? row
663 : { ...row, edge: { ...row.edge, status: workflowGroup.workflow.status } };
664 });
665 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
666 const unlistedThreadIds = relationshipRows
667 .filter(
668 ({ threadId, edge }) =>
669 !relationshipShells.some((thread) => thread.id === threadId) &&
670 (edge.kind !== "subagent" || !subagentsByThreadId.get(threadId)?.title),
671 )
672 .map(({ threadId }) => threadId);
673 const threadTitles = useEnvironmentQuery(
674 unlistedThreadIds.length === 0
675 ? null
676 : orchestrationEnvironment.threadTitles({
677 environmentId: props.environmentId,
678 input: { threadIds: unlistedThreadIds },
679 }),
680 );
681 const resolvedThreadTitles = threadTitles.data ?? {};
682 // Omitted and archived threads remain reachable; only a settled lookup proves one is gone.
683 const visibleRelationships = relationshipRows.filter(
684 ({ threadId, edge }) =>
685 edge.kind === "subagent" ||
686 !unlistedThreadIds.includes(threadId) ||
687 !threadTitles.isSuccess ||
688 threadTitles.isPending ||
689 Object.hasOwn(resolvedThreadTitles, threadId),
690 );
691 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
692
693 const {
694 related = [],
695 active = [],
696 previous = [],
697 sideChats = [],
698 } = groupBy(visibleRelationships, ({ threadId, edge }) => {
699 const isParent = isParentThreadRelationship(edge, props.threadId);
700 if (!isParent && graph.nodes.get(threadId)?.thread?.lineage.sideChat === true)
701 return "sideChats";
702 if (edge.kind !== "subagent" || isParent) return "related";
703 return isFinishedAgentStatus(edge.status) ? "previous" : "active";
704 });
705 const liveShellIds = new Set(relationshipShells.map((thread) => thread.id));
706 const hasOmittedAppOwnedChild = (rows: ReadonlyArray<ThreadRelationshipWalkRow>) =>
707 rows.some(({ threadId, edge }) => {
708 if (edge.kind !== "subagent" || isParentThreadRelationship(edge, props.threadId)) {
709 return false;
710 }
711 const subagent = subagentsByThreadId.get(threadId);
712 return subagent?.origin === "app_owned" && !liveShellIds.has(threadId);
713 });
714 // Idle children are omitted from the shell. Load the family once an omitted child row is visible
715 // (typically when Previous agents is expanded).
716 const family = useEnvironmentQuery(
717 props.showLineage &&
718 (hasOmittedAppOwnedChild(active) || (previousExpanded && hasOmittedAppOwnedChild(previous)))
719 ? orchestrationEnvironment.threadFamily({
720 environmentId: props.environmentId,
721 input: { threadId: props.threadId },
722 })
723 : null,
724 );
725 const familyShellById = new Map(
726 (family.data?.threads ?? []).map((thread) => [thread.id, thread]),
727 );
728 const reopened = useReopenedRemoteTasks(ref);
729 const { remoteActive = [], remotePrevious = [] } = groupBy(
730 (projection?.subagents ?? [])
731 .filter((agent): agent is RemoteSubagent => agent.remoteChild !== undefined)
732 // A reopened task runs again; its recorded times belong to the earlier run.
733 .map((remote) => ({
734 remote: reopened.has(remote.id)
735 ? { ...remote, status: "running" as const, startedAt: null }
736 : remote,
737 })),
738 ({ remote }) => (isFinishedAgentStatus(remote.status) ? "remotePrevious" : "remoteActive"),
739 );
740 const groups: ReadonlyArray<{
741 id: string;
742 label: string | null;
743 rows: ReadonlyArray<LineageRow>;
744 expanded: boolean;
745 }> = [
746 { id: "related", label: null, rows: related, expanded: true },
747 { id: "active", label: null, rows: [...active, ...remoteActive], expanded: true },
748 {
749 id: "previous",
750 label: gt`Previous agents`,
751 rows: [...previous, ...remotePrevious],
752 expanded: previousExpanded,
753 },
754 ];
755 const runningCount =
756 (projection?.subagents.filter(
757 (agent) => agent.childThreadId === null && agent.status === "running",
758 ).length ?? 0) +
759 active.filter(({ edge }) => edge.status === "running").length +
760 reopened.size;
761
762 // A linked environment's agent may have delegated this thread from there.
763 const delegatedFrom = currentThread?.delegatedFrom;
764
765 const lineageVisible =
766 props.showLineage &&
767 (related.length > 0 ||
768 active.length > 0 ||
769 previous.length > 0 ||
770 runningCount > 0 ||
771 remoteActive.length > 0 ||
772 remotePrevious.length > 0 ||
773 delegatedFrom !== undefined ||
774 // Disconnect lives in this heading, so a thread with only side chats still shows it.
775 (canDetach && sideChats.length > 0));
776 const sideChatsVisible = props.showSideChats && sideChats.length > 0;
777 const runningSideChats = sideChats.filter(({ edge }) => edge.status === "running").length;
778
779 if (!lineageVisible && !sideChatsVisible) {
780 return null;
781 }
782
783 // Idle children can be omitted from the shell; opening one loads its own detail.
784 const openThread = (threadId: ThreadId) => {
785 const routeRef = resolveThreadOpenRoute(
786 scopeThreadRef(props.environmentId, threadId),
787 graph.nodes.get(threadId)?.thread ?? null,
788 );
789 if (routeRef.threadId === ref.threadId) return;
790 void navigate({
791 to: "/$environmentId/$threadId",
792 params: buildThreadRouteParams(routeRef),
793 });
794 };
795
796 // A subagent or side chat of this thread opens beside it or in its place, as the click asks.
797 const openSideThreadRow = (threadId: ThreadId, intent: SideThreadOpenIntent) => {
798 openSideThread({
799 threadRef: scopeThreadRef(props.environmentId, threadId),
800 panelRef: ref,
801 intent,
802 navigate: (threadRef) =>
803 void navigate({
804 to: "/$environmentId/$threadId",
805 params: buildThreadRouteParams(threadRef),
806 }),
807 });
808 };
809
810 const merge = async () => {
811 if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return;
812 if (mergeErrorToastId.current !== null) {
813 toastManager.close(mergeErrorToastId.current);
814 mergeErrorToastId.current = null;
815 }
816 setBusyAction("merge");
817 const result = await mergeBack({
818 environmentId: props.environmentId,
819 input: {
820 sourceThreadId: props.threadId,
821 targetThreadId: mergeTargetThreadId,
822 runId: latestMergeBackRun.id,
823 },
824 });
825 setBusyAction(null);
826 if (result._tag === "Failure") {
827 mergeErrorToastId.current = toastManager.add({
828 type: "error",
829 title: gt`Could not merge back`,
830 });
831 return;
832 }
833 openThread(mergeTargetThreadId);
834 };
835
836 const detach = async () => {
837 if (!canDetach || busyAction !== null) return;
838 if (detachErrorToastId.current !== null) {
839 toastManager.close(detachErrorToastId.current);
840 detachErrorToastId.current = null;
841 }
842 setBusyAction("detach");
843 const result = await stopSession({
844 environmentId: props.environmentId,
845 input: { threadId: props.threadId },
846 });
847 setBusyAction(null);
848 if (result._tag === "Failure") {
849 detachErrorToastId.current = toastManager.add({
850 type: "error",
851 title: gt`Could not disconnect agent session`,
852 });
853 }
854 };
855
856 const stopSubagent = async (
857 childThreadId: ThreadId,
858 agent: Pick<OrchestrationV2Subagent, "id" | "threadId">,
859 ) => {
860 if (stoppingId !== null) return;
861 setStoppingId(childThreadId);
862 const result = await interruptTurn({
863 environmentId: props.environmentId,
864 input: { threadId: agent.threadId, subagentId: agent.id },
865 });
866 setStoppingId(null);
867 if (result._tag === "Failure") {
868 toastManager.add({ type: "error", title: gt`Could not stop subagent` });
869 }
870 };
871
872 const stopWorkflow = async (subagentId: string) => {
873 if (stoppingId !== null) return;
874 setStoppingId(subagentId);
875 const result = await stopWorkflowCommand({
876 environmentId: props.environmentId,
877 input: { threadId: props.threadId, subagentId: NodeId.make(subagentId) },
878 });
879 setStoppingId(null);
880 if (result._tag === "Failure") {
881 toastManager.add({ type: "error", title: gt`Could not stop workflow` });
882 }
883 };
884
885 const parentTitle =
886 mergeTargetThreadId === null
887 ? null
888 : isHiddenRelation(mergeTargetThreadId)
889 ? null
890 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
891
892 const renderRelationshipRow = ({ threadId, edge }: ThreadRelationshipWalkRow) => {
893 const node = graph.nodes.get(threadId);
894 // The family read is fresher than an archived snapshot's copy of an omitted child.
895 const childThread =
896 (liveShellIds.has(threadId) ? node?.thread : familyShellById.get(threadId)) ??
897 node?.thread ??
898 null;
899 const isSubagent = edge.kind === "subagent";
900 const isMergeTarget = threadId === mergeTargetThreadId;
901 const isParent = isParentThreadRelationship(edge, props.threadId);
902 const rowStatus =
903 (isParent && threadId === parentRef?.threadId
904 ? (node?.thread?.activityRunStatus ?? parentNativeStatus)
905 : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge });
906 const RelationshipIcon = isParent
907 ? CornerLeftUpIcon
908 : isSubagent
909 ? BotIcon
910 : node?.thread?.lineage.sideChat === true
911 ? MessagesSquareIcon
912 : GitForkIcon;
913
914 const projectedAgent = isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;
915 const workflowGroup =
916 projectedAgent === undefined ? undefined : workflowGroupsById.get(projectedAgent.id);
917 const agent = workflowGroup ? projectedAgent : currentSubagent(projectedAgent, childThread);
918 const failed = rowStatus === "failed" || rowStatus === "error";
919 const canStop =
920 agent &&
921 (agent.origin === "app_owned" ||
922 (agent.origin === "provider_native" &&
923 agent.driver === "claudeAgent" &&
924 agent.runId != null &&
925 agent.nativeTaskRef?.strength === "strong" &&
926 agent.nativeTaskRef.nativeId !== null &&
927 ["pending", "running", "waiting"].includes(agent.nativeStatus))) &&
928 agent.startedAt &&
929 ["pending", "running", "waiting"].includes(agent.status);
930 const threadTitle = relationshipThreadTitle({
931 title:
932 workflowGroup?.workflow.workflowName ??
933 // Fresher than an archived snapshot's copy.
934 (Object.hasOwn(resolvedThreadTitles, threadId)
935 ? resolvedThreadTitles[threadId]
936 : undefined) ??
937 childThread?.title ??
938 agent?.title ??
939 threadId,
940 isSubagent,
941 });
942 const childSelection = agent?.origin === "app_owned" ? childThread?.modelSelection : undefined;
943 const providerInstanceId =
944 childSelection?.instanceId ?? agent?.providerInstanceId ?? childThread?.providerInstanceId;
945 const provider = providers?.find((entry) => entry.instanceId === providerInstanceId);
946 const providerDriver = provider?.driver ?? agent?.driver;
947 const canStopWorkflow =
948 canOperateWorkflow &&
949 workflowGroup?.workflow.status === "running" &&
950 agent?.origin === "provider_native" &&
951 providerDriver === "claudeAgent";
952 const trailingVisibilityClass = (workflowGroup ? canStopWorkflow : canStop)
953 ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0"
954 : "";
955 const project = projects.find((project) => project.id === childThread?.projectId);
956 const isSideChat = node?.thread?.lineage.sideChat === true && !isParent;
957 const hint = relationshipHint(edge, props.threadId, isSideChat, m);
958 const openProps =
959 isSideChat || (isSubagent && !isParent)
960 ? trigger((intent) => openSideThreadRow(threadId, intent))
961 : { onClick: () => openThread(threadId) };
962 const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;
963 const relationshipTooltip = agent ? (
964 <LineageSubagentTooltip
965 childRef={scopeThreadRef(props.environmentId, threadId)}
966 title={threadTitle}
967 model={agent.model}
968 providerInstanceId={agent.providerInstanceId}
969 origin={agent.origin}
970 modelSelection={agent.modelSelection}
971 providers={providers}
972 driver={providerDriver}
973 elapsed={<AgentElapsed agent={agent} />}
974 status={agent.status}
975 result={agent.result}
976 progress={agent.progress}
977 parentThread={currentThread ?? undefined}
978 childThread={childThread ?? undefined}
979 parentProject={currentProject}
980 childProject={project}
981 />
982 ) : (
983 <LineageTooltipContent title={threadTitle} hint={hint} />
984 );
985 const relationshipContent = (
986 <>
987 <ThreadRelationshipIcon
988 driver={isSubagent && !isParent ? providerDriver : undefined}
989 provider={provider}
990 providerEntries={providerEntries}
991 fallbackIcon={RelationshipIcon}
992 status={rowStatus}
993 />
994 <span className="min-w-0 flex-1">
995 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
996 {threadTitle}
997 </span>
998 </span>
999 {agent ? null : (
1000 <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
1001 )}
1002 {agent && !failed && (deriveSubagentElapsedMs(agent, 0) !== null || canStopWorkflow) ? (
1003 <span
1004 className={`shrink-0 text-2xs font-normal tabular-nums text-muted-foreground ${canStopWorkflow ? "min-w-6 text-end" : ""} ${trailingVisibilityClass}`}
1005 >
1006 <AgentElapsed agent={agent} compact />
1007 </span>
1008 ) : !isMergeTarget ? (
1009 <span
1010 className={
1011 workflowGroup
1012 ? "sr-only"
1013 : `shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"} ${trailingVisibilityClass}`
1014 }
1015 >
1016 {threadRelationshipStatusLabel(rowStatus, m)}
1017 </span>
1018 ) : null}
1019 </>
1020 );
1021 const relationshipLink = (
1022 <Tooltip>
1023 <TooltipTrigger
1024 delay={200}
1025 render={
1026 <ThreadDetailsControl
1027 size="sm"
1028 variant="ghost"
1029 part={workflowGroup ? "primary" : "row"}
1030 {...openProps}
1031 />
1032 }
1033 >
1034 {relationshipContent}
1035 </TooltipTrigger>
1036 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
1037 </Tooltip>
1038 );
1039 if (workflowGroup && agent) {
1040 return (
1041 <ThreadLineageWorkflowRow
1042 key={threadId}
1043 group={workflowGroup}
1044 providerInstanceId={agent.providerInstanceId}
1045 provider={provider}
1046 providers={providers}
1047 providerEntries={providerEntries}
1048 driver={providerDriver}
1049 onOpenThread={(memberThreadId, intent) =>
1050 openSideThreadRow(memberThreadId as ThreadId, intent)
1051 }
1052 onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined}
1053 stopping={stoppingId === agent.id}
1054 stopDisabled={stoppingId !== null}
1055 header={relationshipLink}
1056 />
1057 );
1058 }
1059 return (
1060 <li key={threadId} className="group relative flex h-8 items-center rounded-lg">
1061 {isMergeTarget ? (
1062 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
1063 <Tooltip>
1064 <TooltipTrigger
1065 delay={200}
1066 render={
1067 <ThreadDetailsControl
1068 size="sm"
1069 variant="ghost"
1070 part="primary"
1071 aria-label={`${threadTitle} ${threadRelationshipStatusLabel(rowStatus, m)}`}
1072 onClick={() => openThread(threadId)}
1073 />
1074 }
1075 >
1076 {relationshipContent}
1077 </TooltipTrigger>
1078 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
1079 </Tooltip>
1080 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
1081 <SharedTooltipTrigger
1082 render={
1083 <ThreadDetailsControl
1084 size="sm"
1085 variant="ghost"
1086 part="secondary"
1087 aria-label={
1088 parentTitle
1089 ? gt`Merge back to ${{ parentTitle }}`
1090 : gt`Merge back to source conversation`
1091 }
1092 aria-disabled={!canMerge || busyAction !== null || undefined}
1093 onClick={() => void merge()}
1094 >
1095 {busyAction === "merge" ? (
1096 <Spinner size="xs" />
1097 ) : (
1098 <PullRequestGlyph.merged className="size-3" />
1099 )}
1100 </ThreadDetailsControl>
1101 }
1102 label={
1103 latestMergeBackRun === null
1104 ? gt`Complete a run in this fork before merging it back`
1105 : parentTitle
1106 ? gt`Merge this conversation back into ${{ parentTitle }}`
1107 : gt`Merge this conversation back into its source`
1108 }
1109 side="left"
1110 />
1111 <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">
1112 {threadRelationshipStatusLabel(rowStatus, m)}
1113 </span>
1114 </div>
1115 ) : (
1116 relationshipLink
1117 )}
1118 {canStop && agent ? (
1119 <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">
1120 <SharedTooltipTrigger
1121 render={
1122 <ThreadDetailsControl
1123 size="icon-xs"
1124 variant="ghost"
1125 part="icon"
1126 tone="destructive"
1127 aria-label={gt`Stop subagent ${{ threadTitle }}`}
1128 disabled={stoppingId !== null}
1129 onClick={() => void stopSubagent(threadId, agent)}
1130 />
1131 }
1132 label={
1133 <>
1134 <T>Stop subagent</T>
1135 </>
1136 }
1137 side="left"
1138 >
1139 {stoppingId === threadId ? (
1140 <Spinner aria-hidden size="xs" />
1141 ) : (
1142 <SquareIcon aria-hidden className="size-3 fill-current" />
1143 )}
1144 </SharedTooltipTrigger>
1145 </div>
1146 ) : null}
1147 </li>
1148 );
1149 };
1150
1151 return (
1152 <TooltipProvider>
1153 {lineageVisible ? (
1154 <ThreadDetailsSection
1155 headingId="thread-details-lineage-heading"
1156 title={
1157 runningCount > 0
1158 ? gt`Lineage · ${{ runningCount }} running`
1159 : gt({ context: "thread details section: parent and child agents" })`Lineage`
1160 }
1161 // A lone "Previous agents" row names itself; the heading returns for status or actions.
1162 showHeading={
1163 runningCount > 0 ||
1164 canDetach ||
1165 related.length > 0 ||
1166 active.length > 0 ||
1167 remoteActive.length > 0 ||
1168 delegatedFrom !== undefined
1169 }
1170 data-thread-relationships-panel
1171 actions={
1172 canDetach ? (
1173 <Menu>
1174 <MenuTrigger
1175 render={
1176 <ThreadDetailsControl
1177 size="icon-xs"
1178 variant="ghost"
1179 part="icon"
1180 aria-label={gt`More thread actions`}
1181 disabled={busyAction !== null}
1182 />
1183 }
1184 >
1185 <MoreHorizontalIcon className="size-3.5" />
1186 </MenuTrigger>
1187 <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">
1188 <MenuItem onClick={() => void detach()}>
1189 <UnplugIcon className="size-3.5" />
1190 <T>Disconnect agent session</T>
1191 </MenuItem>
1192 </MenuPopup>
1193 </Menu>
1194 ) : null
1195 }
1196 >
1197 {delegatedFrom === undefined ? null : (
1198 <ThreadLineageRowList hiddenCount={0} onShowMore={() => {}}>
1199 <DelegatedFromRow
1200 delegatedFrom={delegatedFrom}
1201 fallbackLabel={currentThread?.linkOrigin?.label}
1202 anyInstanceBadge={hasInstanceBadge(providerEntries)}
1203 />
1204 </ThreadLineageRowList>
1205 )}
1206 {groups.map((group) => (
1207 <ThreadLineageGroup
1208 key={`${threadScopeKey}:${group.id}`}
1209 {...group}
1210 onExpandedChange={
1211 group.id === "previous"
1212 ? (expanded) => setExpandedPreviousKey(expanded ? threadScopeKey : null)
1213 : undefined
1214 }
1215 >
1216 {(visibleRows) =>
1217 visibleRows.map((row) =>
1218 "remote" in row ? (
1219 <RemoteSubagentRow
1220 key={row.remote.id}
1221 agent={row.remote}
1222 parentRef={ref}
1223 // Its provider instance belongs to the environment it runs in.
1224 provider={providersByEnvironment
1225 .get(row.remote.remoteChild.environmentId)
1226 ?.find((entry) => entry.instanceId === row.remote.providerInstanceId)}
1227 anyInstanceBadge={hasInstanceBadge(providerEntries)}
1228 />
1229 ) : (
1230 renderRelationshipRow(row)
1231 ),
1232 )
1233 }
1234 </ThreadLineageGroup>
1235 ))}
1236 </ThreadDetailsSection>
1237 ) : null}
1238 {sideChatsVisible ? (
1239 <ThreadDetailsSection
1240 headingId="thread-details-side-chats-heading"
1241 title={
1242 runningSideChats > 0 ? gt`Side chats · ${{ runningSideChats }} running` : gt`Side chats`
1243 }
1244 data-thread-side-chats-panel
1245 >
1246 <ThreadLineageGroup
1247 key={`${scopedThreadKey(ref)}:side-chats`}
1248 label={null}
1249 rows={sideChats}
1250 expanded
1251 >
1252 {(visibleRows) => visibleRows.map(renderRelationshipRow)}
1253 </ThreadLineageGroup>
1254 </ThreadDetailsSection>
1255 ) : null}
1256 </TooltipProvider>
1257 );
1258}