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