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

ThreadRelationshipsControl.tsx

468 lines18.4 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​
244 if (relationshipRows.length === 0) {
245 return null;
246 }
247​
248 const openThread = (threadId: ThreadId) => {
249 void navigate({
250 to: "/$environmentId/$threadId",
251 params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
252 });
253 };
254​
255 const merge = async () => {
256 if (!latestMergeBackRun || mergeTargetThreadId === null || busyAction !== null) return;
257 setBusyAction("merge");
258 const result = await mergeBack({
259 environmentId: props.environmentId,
260 input: {
261 sourceThreadId: props.threadId,
262 targetThreadId: mergeTargetThreadId,
263 runId: latestMergeBackRun.id,
264 },
265 });
266 setBusyAction(null);
267 if (result._tag === "Success") openThread(mergeTargetThreadId);
268 };
269​
270 const detach = async () => {
271 if (!canDetach || busyAction !== null) return;
272 setBusyAction("detach");
273 await stopSession({
274 environmentId: props.environmentId,
275 input: { threadId: props.threadId },
276 });
277 setBusyAction(null);
278 };
279​
280 const parentTitle =
281 mergeTargetThreadId === null
282 ? null
283 : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null);
284​
285 return (
286 <ThreadDetailsSection
287 headingId="thread-details-lineage-heading"
288 title="Lineage"
289 data-thread-relationships-panel
290 actions={
291 canDetach ? (
292 <Menu>
293 <MenuTrigger
294 render={
295 <Button
296 size="icon-xs"
297 variant="ghost"
298 className={THREAD_DETAILS_PANEL_ICON_ACTION_CLASS}
299 aria-label="More thread actions"
300 disabled={busyAction !== null}
301 />
302 }
303 >
304 <MoreHorizontalIcon className="size-3.5" />
305 </MenuTrigger>
306 <MenuPopup align="end" className={THREAD_DETAILS_PANEL_MENU_POPUP_CLASS}>
307 <MenuItem onClick={() => void detach()}>
308 <UnplugIcon className="size-3.5" />
309 Disconnect agent session
310 </MenuItem>
311 </MenuPopup>
312 </Menu>
313 ) : null
314 }
315 >
316 {groups.map((group) => (
317 <ThreadLineageGroup key={`${scopedThreadKey(ref)}:${group.id}`} {...group}>
318 {(visibleRows) =>
319 visibleRows.map(({ threadId, edge }) => {
320 const node = graph.nodes.get(threadId);
321 const isSubagent = edge.kind === "subagent";
322 const isMergeTarget = threadId === mergeTargetThreadId;
323 const isParent = isParentThreadRelationship(edge, props.threadId);
324 const RelationshipIcon = isParent
325 ? CornerLeftUpIcon
326 : isSubagent
327 ? BotIcon
328 : GitForkIcon;
329 const relationship = relationshipLabel(edge, props.threadId);
330 const agent = isSubagent && !isParent ? subagentsByThreadId.get(threadId) : undefined;
331 const threadTitle = relationshipThreadTitle({
332 title: node?.thread?.title ?? agent?.title ?? threadId,
333 isSubagent,
334 });
335 const provider = providers?.find(
336 (entry) =>
337 entry.instanceId ===
338 (agent?.providerInstanceId ?? node?.thread?.providerInstanceId),
339 );
340 const providerDriver = agent?.driver ?? provider?.driver;
341 const project = projects.find((project) => project.id === node?.thread?.projectId);
342 const relationshipHint = node?.missing
343 ? "This related thread is unavailable"
344 : `Open ${relationship.toLowerCase()} in this chat`;
345 const relationshipTooltip = agent ? (
346 <SubagentTooltipContent
347 title={threadTitle}
348 model={agent.model}
349 provider={provider}
350 status={agent.status}
351 result={agent.result}
352 progress={agent.progress}
353 parentThread={currentThread ?? undefined}
354 childThread={node?.thread ?? undefined}
355 parentProject={currentProject}
356 childProject={project}
357 />
358 ) : (
359 relationshipHint
360 );
361 const relationshipContent = (
362 <>
363 <ThreadRelationshipIcon
364 driver={isSubagent && !isParent ? providerDriver : undefined}
365 provider={provider}
366 fallbackIcon={RelationshipIcon}
367 status={edge.status}
368 />
369 <span className="min-w-0 flex-1">
370 <span className="block truncate text-[13px] font-medium leading-4 text-foreground/85">
371 {threadTitle}
372 </span>
373 {agent ? <span className="sr-only">{agent.status}</span> : null}
374 </span>
375 {agent ? (
376 agent.startedAt ? (
377 <span className="shrink-0 text-[11px] font-normal tabular-nums text-muted-foreground">
378 <AgentElapsed agent={agent} />
379 </span>
380 ) : null
381 ) : (
382 <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
383 )}
384 </>
385 );
386 return (
387 <li key={threadId} className="group flex h-9 items-center rounded-lg">
388 {isMergeTarget ? (
389 <div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
390 <Tooltip>
391 <TooltipTrigger
392 render={
393 <Button
394 size="sm"
395 variant="ghost"
396 className={THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS}
397 disabled={node?.missing === true}
398 onClick={() => openThread(threadId)}
399 />
400 }
401 >
402 {relationshipContent}
403 </TooltipTrigger>
404 <TooltipPopup side="left">{relationshipTooltip}</TooltipPopup>
405 </Tooltip>
406 <span
407 aria-hidden="true"
408 className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS}
409 />
410 <Tooltip>
411 <TooltipTrigger
412 render={
413 <Button
414 size="sm"
415 variant="ghost"
416 className={THREAD_DETAILS_PANEL_LINK_SPLIT_SECONDARY_CLASS}
417 aria-label={
418 parentTitle
419 ? `Merge back to ${parentTitle}`
420 : "Merge back to source conversation"
421 }
422 disabled={!canMerge || busyAction !== null}
423 onClick={() => void merge()}
424 >
425 {busyAction === "merge" ? (
426 <LoaderCircleIcon className="size-3 animate-spin" />
427 ) : (
428 <PullRequestGlyph.merged className="size-3" />
429 )}
430 </Button>
431 }
432 />
433 <TooltipPopup side="left">
434 {latestMergeBackRun === null
435 ? "Complete a run in this fork before merging it back"
436 : parentTitle
437 ? `Merge this conversation back into ${parentTitle}`
438 : "Merge this conversation back into its source"}
439 </TooltipPopup>
440 </Tooltip>
441 </div>
442 ) : (
443 <Tooltip>
444 <TooltipTrigger
445 render={
446 <Button
447 size="sm"
448 variant="ghost"
449 disabled={node?.missing === true}
450 onClick={() => openThread(threadId)}
451 className={THREAD_DETAILS_PANEL_LINK_ROW_CLASS}
452 />
453 }
454 >
455 {relationshipContent}
456 </TooltipTrigger>
457 <TooltipPopup side="left">{relationshipTooltip}</TooltipPopup>
458 </Tooltip>
459 )}
460 </li>
461 );
462 })
463 }
464 </ThreadLineageGroup>
465 ))}
466 </ThreadDetailsSection>
467 );