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

ThreadRelationshipsControl.tsx

473 lines18.7 KB

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