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

ThreadRelationshipsControl.tsx

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