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