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

ThreadRelationshipsControl.tsx

612 lines25.0 KB

1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import { ThreadHoverCardPopup } from "../ThreadHoverCard";
3import { ThreadDetailsSection } from "./ThreadDetailsSection";
4import { CollapsibleSectionHeader, SectionHeaderStatus } from "../ui/collapsible-section-header";
5import { SubagentTooltipContent } from "./SubagentTooltipContent";
6import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
7import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
8import {
9 projectedSubagentsToRuntime,
10 type RuntimeSubagent,
11} from "@t3tools/client-runtime/state/subagentRuntime";
12import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
13import {
14 deriveThreadRelationshipGraph,
15 immediateThreadRelationships,
16 isParentThreadRelationship,
17 threadRelationshipRowStatus,
18 orderWebThreadLineageRows,
19 resolveMergeBackTargetThreadId,
20 type ThreadRelationshipEdge,
21 type ThreadRelationshipWalkRow,
22} from "@t3tools/client-runtime/state/thread-relationships";
23import {
24 canDetachThreadProviderSession,
25 resolveLatestMergeBackRun,
26} from "@t3tools/client-runtime/state/thread-workflows";
27import type {
28 EnvironmentId,
29 OrchestrationV2Subagent,
30 OrchestrationV2ThreadShell,
31 ThreadId,
32} from "@t3tools/contracts";
33import { deriveSubagentElapsedMs } from "@t3tools/shared/orchestrationTiming";
34import { groupBy } from "effect/Array";
35import * as DateTime from "effect/DateTime";
36import { useNavigate } from "@tanstack/react-router";
37import {
38 ArrowRightIcon,
39 BotIcon,
40 CornerLeftUpIcon,
41 GitForkIcon,
42 LoaderCircleIcon,
43 MoreHorizontalIcon,
44 PlusIcon,
45 SquareIcon,
46 UnplugIcon,
47} from "lucide-react";
48import { useMemo, useState, type ReactNode } from "react";
49​
50import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
51import { buildThreadRouteParams } from "../../threadRoutes";
52import {
53 useProjects,
54 useServerConfigs,
55 useThreadProjection,
56 useThreadShells,
57} from "../../state/entities";
58import { threadEnvironment } from "../../state/threads";
59import { useAtomCommand } from "../../state/use-atom-command";
60import { AgentElapsed } from "./AgentElapsed";
61import { ThreadRelationshipIcon, threadRelationshipStatusLabel } from "./ThreadRelationshipIcon";
62​
63import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
64import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
65import { toastManager } from "../ui/toast";
66import {
67 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
68 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
69 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
70} from "./threadDetailsPanelStyles";
71​
72// Lineage paging: a busy thread can accumulate dozens of forks and subagents,
73// and the panel it lives in already scrolls. Show a workable window, keep the
74// rest behind Show more, and bound what is shown so the sections below Lineage
75// stay reachable.
76const THREAD_LINEAGE_INITIAL_COUNT = 6;
77const THREAD_LINEAGE_PAGE_COUNT = 12;
78​
79export function resolveThreadLineageWindow<Row>(
80 rows: ReadonlyArray<Row>,
81 visibleCount: number,
82): { readonly visibleRows: ReadonlyArray<Row>; readonly hiddenCount: number } {
83 const visibleRows = rows.slice(0, visibleCount);
84 return { visibleRows, hiddenCount: rows.length - visibleRows.length };
86​
87export function ThreadLineageRowList(props: {
88 readonly hiddenCount: number;
89 readonly onShowMore: () => void;
90 readonly children: ReactNode;
91}) {
92 return (
93 <>
94 {/*
95 Bounded rather than free-growing so Lineage cannot push the rest of the
96 thread details panel out of view. Plain overflow, not a ScrollArea
97 component: this sits inside an already scrolling panel, where a
98 max-height-only virtual viewport measures badly. Every row is a focusable
99 button, so keyboard users reach and scroll the region through the rows
100 themselves and the container needs no extra tab stop of its own.
101 */}
102 <ul
103 aria-label="Related threads"
104 className="m-0 max-h-[13.5rem] list-none overflow-y-auto overscroll-contain p-0"
105 >
106 {props.children}
107 </ul>
108 {props.hiddenCount > 0 ? (
109 <button
110 type="button"
111 onClick={props.onShowMore}
112 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]`}
113 >
114 <PlusIcon aria-hidden className="size-4 shrink-0" />
115 Show {Math.min(props.hiddenCount, THREAD_LINEAGE_PAGE_COUNT)} more
116 </button>
117 ) : null}
118 </>
119 );
121​
122function ThreadLineageGroup(props: {
123 readonly label: string | null;
124 readonly rows: ReadonlyArray<ThreadRelationshipWalkRow>;
125 readonly expanded: boolean;
126 readonly children: (rows: ReadonlyArray<ThreadRelationshipWalkRow>) => ReactNode;
127}) {
128 const [expanded, setExpanded] = useState(props.expanded);
129 const [visibleCount, setVisibleCount] = useState(THREAD_LINEAGE_INITIAL_COUNT);
130 const { visibleRows, hiddenCount } = resolveThreadLineageWindow(props.rows, visibleCount);
131 const failedCount = props.rows.filter(
132 ({ edge }) => edge.status === "failed" || edge.status === "error",
133 ).length;
134 if (props.rows.length === 0) return null;
135 return (
136 <div>
137 {props.label ? (
138 <CollapsibleSectionHeader
139 expanded={expanded}
140 onClick={() => setExpanded(!expanded)}
141 accessory={
142 failedCount > 0 ? <SectionHeaderStatus>{failedCount} failed</SectionHeaderStatus> : null
143 }
144 >
145 {props.label}
146 {!expanded && ` (${props.rows.length})`}
147 </CollapsibleSectionHeader>
148 ) : null}
149 {expanded ? (
150 <ThreadLineageRowList
151 hiddenCount={hiddenCount}
152 onShowMore={() => setVisibleCount((count) => count + THREAD_LINEAGE_PAGE_COUNT)}
153 >
154 {props.children(visibleRows)}
155 </ThreadLineageRowList>
156 ) : null}
157 </div>
158 );
160​
161function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) {
162 if (edge.kind === "transfer") return "Context transfer";
163 if (edge.kind === "subagent") {
164 return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
165 }
166 return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread";
168​
169function relationshipThreadTitle(input: {
170 readonly title: string;
171 readonly isSubagent: boolean;
172}): string {
173 if (!input.isSubagent) return input.title;
174 return formatSubagentDisplayTitle(input.title);
176​
177/**
178 * The row's timer and hover card follow current child work, including queued
179 * follow-ups whose provider turn has not started yet.
180 */
181function currentSubagent<Agent extends RuntimeSubagent>(
182 agent: Agent | undefined,
183 childThread: OrchestrationV2ThreadShell | null | undefined,
184): Agent | undefined {
185 const liveStatus =
186 childThread?.activityRunStatus ?? (childThread?.status === "queued" ? "queued" : null);
187 if (!agent || !childThread) return agent;
188 const newerRun =
189 childThread.latestRunRequestedAt &&
190 DateTime.toEpochMillis(childThread.latestRunRequestedAt) >
191 Date.parse(agent.completedAt ?? agent.startedAt ?? agent.updatedAt);
192 if (!liveStatus && !newerRun) return agent;
193 const status = liveStatus ?? childThread.status;
194 const startedAt = liveStatus ? childThread.activityRunStartedAt : childThread.latestRunStartedAt;
195 const completedAt = liveStatus ? null : childThread.latestRunCompletedAt;
196 return {
197 ...agent,
198 status:
199 status === "preparing" || status === "starting" || status === "queued"
200 ? "pending"
201 : status === "rolled_back"
202 ? "interrupted"
203 : status,
204 startedAt: startedAt ? DateTime.formatIso(startedAt) : null,
205 completedAt: completedAt ? DateTime.formatIso(completedAt) : null,
206 // The task's output belongs to its recorded run, not newer child work.
207 progress: null,
208 result: null,
209 error: null,
210 };
212​
213export function ThreadRelationshipsPanel(props: {
214 readonly environmentId: EnvironmentId;
215 readonly threadId: ThreadId;
216}) {
217 const ref = scopeThreadRef(props.environmentId, props.threadId);
218 const projection = useThreadProjection(ref)?.projection ?? null;
219 const providers = useServerConfigs().get(props.environmentId)?.providers;
220 const subagentsByThreadId = useMemo(
221 () =>
222 new Map(
223 (projection?.subagents ?? [])
224 .filter((subagent) => subagent.childThreadId !== null)
225 .map((subagent) => [
226 subagent.childThreadId,
227 {
228 ...projectedSubagentsToRuntime([subagent])[0]!,
229 id: subagent.id,
230 threadId: subagent.threadId,
231 nativeTaskRef: subagent.nativeTaskRef,
232 nativeStatus: subagent.status,
233 driver: subagent.driver,
234 providerInstanceId: subagent.providerInstanceId,
235 origin: subagent.origin,
236 modelSelection: subagent.modelSelection,
237 },
238 ]),
239 ),
240 [projection?.subagents],
241 );
242 const threadShells = useThreadShells();
243 const projects = useProjects().filter((project) => project.environmentId === props.environmentId);
244 const archived = useArchivedThreadSnapshots([props.environmentId]);
245 const archivedShells = archived.snapshots.find(
246 (entry) => entry.environmentId === props.environmentId,
247 )?.snapshot.threads;
248 const graph = useMemo(() => {
249 const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
250 ...threadShells
251 .filter((thread) => thread.environmentId === props.environmentId)
252 .map((thread) => thread.source),
253 ...(archivedShells ?? []),
254 ];
255 return deriveThreadRelationshipGraph({ threads: shells, projection });
256 }, [archivedShells, projection, props.environmentId, threadShells]);
257 const currentThread = projection?.thread ?? graph.nodes.get(props.threadId)?.thread;
258 const currentProject = projects.find((project) => project.id === currentThread?.projectId);
259 const navigate = useNavigate();
260 const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
261 const stopSession = useAtomCommand(threadEnvironment.stopSession);
262 const interruptTurn = useAtomCommand(threadEnvironment.interruptTurn);
263 const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
264 const [stoppingThreadId, setStoppingThreadId] = useState<ThreadId | null>(null);
265 const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
266 const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
267 const relationshipRows = useMemo(
268 () =>
269 orderWebThreadLineageRows({
270 graph,
271 rows: immediateThreadRelationships(graph, props.threadId),
272 currentThreadId: props.threadId,
273 mergeTargetThreadId,
274 }),
275 [graph, mergeTargetThreadId, props.threadId],
276 );
277 const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
278 const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
279​
280 const {
281 related = [],
282 active = [],
283 previous = [],
284 } = groupBy(relationshipRows, ({ edge }) => {
285 if (edge.kind !== "subagent" || isParentThreadRelationship(edge, props.threadId))
286 return "related";
287 return ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes(
288 edge.status ?? "",
289 )
290 ? "previous"
291 : "active";
292 });
293 const groups = [
294 { id: "related", label: null, rows: related, expanded: true },
295 { id: "active", label: null, rows: active, expanded: true },
296 { id: "previous", label: "Previous agents", rows: previous, expanded: false },
297 ];
298 // Subagents without a child thread yet have no row, so count them separately.
299 const runningCount =
300 (projection?.subagents.filter(
301 (agent) => agent.childThreadId === null && agent.status === "running",
302 ).length ?? 0) + active.filter(({ edge }) => edge.status === "running").length;
303​
304 if (relationshipRows.length === 0 && runningCount === 0) {
305 return null;
306 }
307​
308 const openThread = (threadId: ThreadId) => {
309 void navigate({
310 to: "/$environmentId/$threadId",
311 params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
312 });
313 };
314​
315 const merge = async () => {
316 if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return;
317 setBusyAction("merge");
318 const result = await mergeBack({
319 environmentId: props.environmentId,
320 input: {
321 sourceThreadId: props.threadId,
322 targetThreadId: mergeTargetThreadId,
323 runId: latestMergeBackRun.id,
324 },
325 });
326 setBusyAction(null);
327 if (result._tag === "Success") openThread(mergeTargetThreadId);
328 };
329​
330 const detach = async () => {
331 if (!canDetach || busyAction !== null) return;
332 setBusyAction("detach");
333 await stopSession({
334 environmentId: props.environmentId,
335 input: { threadId: props.threadId },
336 });
337 setBusyAction(null);
338 };
339​
340 const stopSubagent = async (
341 childThreadId: ThreadId,
342 agent: Pick<OrchestrationV2Subagent, "id" | "origin" | "threadId">,
343 ) => {
344 if (stoppingThreadId !== null) return;
345 setStoppingThreadId(childThreadId);
346 const result = await interruptTurn({
347 environmentId: props.environmentId,
348 input:
349 agent.origin === "provider_native"
350 ? { threadId: agent.threadId, subagentId: agent.id }
351 : { threadId: childThreadId },
352 });
353 setStoppingThreadId(null);
354 if (result._tag === "Failure") {
355 toastManager.add({ type: "error", title: "Could not stop subagent" });
356 }
357 };
358​
359 const parentTitle =
360 mergeTargetThreadId === null
361 ? null
362 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
363​
364 return (
365 <ThreadDetailsSection
366 headingId="thread-details-lineage-heading"
367 title={runningCount > 0 ? `Lineage · ${runningCount} running` : "Lineage"}
368 data-thread-relationships-panel
369 actions={
370 canDetach ? (
371 <Menu>
372 <MenuTrigger
373 render={
374 <ThreadDetailsControl
375 size="icon-xs"
376 variant="ghost"
377 part="icon"
378 aria-label="More thread actions"
379 disabled={busyAction !== null}
380 />
381 }
382 >
383 <MoreHorizontalIcon className="size-3.5" />
384 </MenuTrigger>
385 <MenuPopup align="end" className="min-w-60 max-w-(--available-width)">
386 <MenuItem onClick={() => void detach()}>
387 <UnplugIcon className="size-3.5" />
388 Disconnect agent session
389 </MenuItem>
390 </MenuPopup>
391 </Menu>
392 ) : null
393 }
394 >
395 {groups.map((group) => (
396 <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>
397 {(visibleRows) =>
398 visibleRows.map(({ threadId, edge }) => {
399 const node = graph.nodes.get(threadId);
400 const isSubagent = edge.kind === "subagent";
401 const isMergeTarget = threadId === mergeTargetThreadId;
402 const isParent = isParentThreadRelationship(edge, props.threadId);
403 const status = threadRelationshipRowStatus(graph, { threadId, edge });
404 const RelationshipIcon = isParent
405 ? CornerLeftUpIcon
406 : isSubagent
407 ? BotIcon
408 : GitForkIcon;
409 const relationship = relationshipLabel(edge, props.threadId);
410 const agent = currentSubagent(
411 isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined,
412 node?.thread,
413 );
414 const failed = status === "failed" || status === "error";
415 const canStop =
416 agent &&
417 (agent.origin === "app_owned" ||
418 (agent.origin === "provider_native" &&
419 agent.driver === "claudeAgent" &&
420 agent.nativeTaskRef?.strength === "strong" &&
421 agent.nativeTaskRef.nativeId !== null &&
422 ["pending", "running", "waiting"].includes(agent.nativeStatus))) &&
423 agent.startedAt &&
424 ["pending", "running", "waiting"].includes(agent.status);
425 const trailingVisibilityClass = canStop
426 ? "group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0 [@media(hover:none)]:opacity-0"
427 : "";
428 const threadTitle = relationshipThreadTitle({
429 title: node?.thread?.title ?? agent?.title ?? threadId,
430 isSubagent,
431 });
432 const provider = providers?.find(
433 (entry) =>
434 entry.instanceId ===
435 (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),
436 );
437 const providerDriver = agent?.driver ?? provider?.driver;
438 const project = projects.find((project) => project.id === node?.thread?.projectId);
439 const relationshipHint = node?.missing
440 ? "This related thread is unavailable"
441 : `Open ${relationship.toLowerCase()} in this chat`;
442 const RelationshipPopup = agent ? ThreadHoverCardPopup : TooltipPopup;
443 const relationshipTooltip = agent ? (
444 <SubagentTooltipContent
445 title={threadTitle}
446 model={agent.model}
447 providerInstanceId={agent.providerInstanceId}
448 origin={agent.origin}
449 modelSelection={agent.modelSelection}
450 provider={provider}
451 providers={providers}
452 driver={providerDriver}
453 elapsed={<AgentElapsed agent={agent} />}
454 status={agent.status}
455 result={agent.result}
456 progress={agent.progress}
457 parentThread={currentThread ?? undefined}
458 childThread={node?.thread ?? undefined}
459 parentProject={currentProject}
460 childProject={project}
461 />
462 ) : (
463 relationshipHint
464 );
465 const relationshipContent = (
466 <>
467 <ThreadRelationshipIcon
468 driver={isSubagent && !isParent ? providerDriver : undefined}
469 provider={provider}
470 fallbackIcon={RelationshipIcon}
471 status={status}
472 />
473 <span className="min-w-0 flex-1">
474 <span className="block truncate text-left text-sm font-medium leading-4 text-foreground/85">
475 {threadTitle}
476 </span>
477 </span>
478 {agent ? null : (
479 <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
480 )}
481 {/* One trailing item keeps room for the title: the icon dot already
482 carries status, so an agent with a known time shows only that. */}
483 {agent && !failed && deriveSubagentElapsedMs(agent, 0) !== null ? (
484 <span
485 className={`shrink-0 text-2xs font-normal tabular-nums text-muted-foreground ${trailingVisibilityClass}`}
486 >
487 <AgentElapsed agent={agent} compact />
488 </span>
489 ) : !isMergeTarget ? (
490 <span
491 className={`shrink-0 text-2xs ${failed ? "text-destructive" : "text-muted-foreground"} ${trailingVisibilityClass}`}
492 >
493 {threadRelationshipStatusLabel(status)}
494 </span>
495 ) : null}
496 </>
497 );
498 return (
499 <li key={threadId} className="group relative flex h-8 items-center rounded-lg">
500 {isMergeTarget ? (
501 <div className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}>
502 <Tooltip>
503 <TooltipTrigger
504 delay={200}
505 render={
506 <ThreadDetailsControl
507 size="sm"
508 variant="ghost"
509 part="primary"
510 aria-label={`${threadTitle} ${threadRelationshipStatusLabel(status)}`}
511 disabled={node?.missing === true}
512 onClick={() => openThread(threadId)}
513 />
514 }
515 >
516 {relationshipContent}
517 </TooltipTrigger>
518 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
519 </Tooltip>
520 <span
521 aria-hidden="true"
522 className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS}
523 />
524 <Tooltip>
525 <TooltipTrigger
526 render={
527 <ThreadDetailsControl
528 size="sm"
529 variant="ghost"
530 part="secondary"
531 aria-label={
532 parentTitle
533 ? `Merge back to ${parentTitle}`
534 : "Merge back to source conversation"
535 }
536 disabled={!canMerge || busyAction !== null}
537 onClick={() => void merge()}
538 >
539 {busyAction === "merge" ? (
540 <LoaderCircleIcon className="size-3 animate-spin" />
541 ) : (
542 <PullRequestGlyph.merged className="size-3" />
543 )}
544 </ThreadDetailsControl>
545 }
546 />
547 <TooltipPopup side="left">
548 {latestMergeBackRun === null
549 ? "Complete a run in this fork before merging it back"
550 : parentTitle
551 ? `Merge this conversation back into ${parentTitle}`
552 : "Merge this conversation back into its source"}
553 </TooltipPopup>
554 </Tooltip>
555 <span className="shrink-0 border border-transparent ps-1 pe-2.5 text-2xs font-medium text-muted-foreground">
556 {threadRelationshipStatusLabel(status)}
557 </span>
558 </div>
559 ) : (
560 <Tooltip>
561 <TooltipTrigger
562 delay={200}
563 render={
564 <ThreadDetailsControl
565 size="sm"
566 variant="ghost"
567 disabled={node?.missing === true}
568 onClick={() => openThread(threadId)}
569 part="row"
570 />
571 }
572 >
573 {relationshipContent}
574 </TooltipTrigger>
575 <RelationshipPopup side="left">{relationshipTooltip}</RelationshipPopup>
576 </Tooltip>
577 )}
578 {canStop && agent ? (
579 <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">
580 <Tooltip>
581 <TooltipTrigger
582 render={
583 <ThreadDetailsControl
584 size="icon-xs"
585 variant="ghost"
586 part="icon"
587 tone="destructive"
588 aria-label={`Stop subagent ${threadTitle}`}
589 disabled={stoppingThreadId !== null}
590 onClick={() => void stopSubagent(threadId, agent)}
591 />
592 }
593 >
594 {stoppingThreadId === threadId ? (
595 <LoaderCircleIcon aria-hidden className="size-3 animate-spin" />
596 ) : (
597 <SquareIcon aria-hidden className="size-3 fill-current" />
598 )}
599 </TooltipTrigger>
600 <TooltipPopup side="left">Stop subagent</TooltipPopup>
601 </Tooltip>
602 </div>
603 ) : null}
604 </li>
605 );
606 })
607 }
608 </ThreadLineageGroup>
609 ))}
610 </ThreadDetailsSection>
611 );