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

ThreadRelationshipsControl.tsx

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