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