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