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