The best way to control Claude Code, Codex and more from any computer or phone

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