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

ThreadRelationshipsControl.tsx

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