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

ThreadRelationshipsControl.tsx

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