Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadRelationshipsControl.tsx

1,148 lines43.4 KB

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