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

ThreadRelationshipsControl.tsx

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