import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; import { useNavigate } from "@tanstack/react-router"; import { ArrowRightIcon, BotIcon, GitBranchIcon, GitForkIcon, GitMergeIcon, LoaderCircleIcon, MoreHorizontalIcon, UnplugIcon, } from "lucide-react"; import { useState } from "react"; import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState"; import { deriveThreadRelationshipGraph, immediateThreadRelationships, resolveMergeBackTargetThreadId, type ThreadRelationshipEdge, } from "../../lib/threadRelationships"; import { newThreadId } from "../../lib/utils"; import { buildThreadRouteParams } from "../../threadRoutes"; import { useThreadProjection, useThreadShells } from "../../state/entities"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; import { cn } from "../../lib/utils"; import { Button } from "../ui/button"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) { if (edge.kind === "transfer") return "Context transfer"; if (edge.kind === "subagent") { return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent"; } return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread"; } function statusDotClass(status: string | null): string { if (status === "running" || status === "in_progress") return "bg-info"; if (status === "failed" || status === "error") return "bg-destructive"; if (status === "completed") return "bg-success"; return "bg-muted-foreground/45"; } const MAX_VISIBLE_RELATIONSHIPS = 5; export function ThreadRelationshipsPanel(props: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; }) { const ref = scopeThreadRef(props.environmentId, props.threadId); const projection = useThreadProjection(ref)?.projection ?? null; const threadShells = useThreadShells(); const activeShells = threadShells.filter( (thread) => thread.environmentId === props.environmentId, ); const archived = useArchivedThreadSnapshots([props.environmentId]); const archivedShells = archived.snapshots.find( (entry) => entry.environmentId === props.environmentId, )?.snapshot.threads; const shells: ReadonlyArray = [ ...activeShells.map((thread) => thread.source), ...(archivedShells ?? []), ]; const graph = deriveThreadRelationshipGraph({ threads: shells, projection }); const navigate = useNavigate(); const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun); const mergeBack = useAtomCommand(threadEnvironment.mergeBack); const stopSession = useAtomCommand(threadEnvironment.stopSession); const [busyAction, setBusyAction] = useState<"fork" | "merge" | "detach" | null>(null); const latestCompletedRun = projection?.runs.findLast((run) => run.status === "completed") ?? null; const sourceProviderThread = latestCompletedRun?.providerThreadId == null ? null : (projection?.providerThreads.find( (thread) => thread.id === latestCompletedRun.providerThreadId, ) ?? null); const capabilities = (sourceProviderThread === null ? null : projection?.providerSessions.find( (session) => session.id === sourceProviderThread.providerSessionId, )?.capabilities) ?? null; const canForkNatively = capabilities?.threads.canForkThread === true && capabilities.threads.canForkFromTurn === true && capabilities.identity.nativeThreadIds === "strong"; const canFork = latestCompletedRun !== null && (canForkNatively || capabilities?.context.supportsFullThreadHandoff === true); const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection); const relationshipRows = immediateThreadRelationships(graph, props.threadId).toSorted( (left, right) => Number(right.threadId === mergeTargetThreadId) - Number(left.threadId === mergeTargetThreadId), ); const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null; const canDetach = projection?.providerSessions.some( (session) => session.status !== "stopped" && session.status !== "error", ) ?? false; if (relationshipRows.length === 0 && !canFork && mergeTargetThreadId === null && !canDetach) { return null; } const openThread = (threadId: ThreadId) => { void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)), }); }; const fork = async () => { if (!latestCompletedRun || busyAction !== null) return; setBusyAction("fork"); const targetThreadId = newThreadId(); const result = await forkFromRun({ environmentId: props.environmentId, input: { sourceThreadId: props.threadId, targetThreadId, runId: latestCompletedRun.id, title: `${projection?.thread.title ?? "Thread"} fork`, }, }); setBusyAction(null); if (result._tag === "Success") openThread(targetThreadId); }; const merge = async () => { if (!latestCompletedRun || mergeTargetThreadId === null || busyAction !== null) return; setBusyAction("merge"); const result = await mergeBack({ environmentId: props.environmentId, input: { sourceThreadId: props.threadId, targetThreadId: mergeTargetThreadId, runId: latestCompletedRun.id, }, }); setBusyAction(null); if (result._tag === "Success") openThread(mergeTargetThreadId); }; const detach = async () => { if (!canDetach || busyAction !== null) return; setBusyAction("detach"); await stopSession({ environmentId: props.environmentId, input: { threadId: props.threadId }, }); setBusyAction(null); }; const visibleRows = relationshipRows.slice(0, MAX_VISIBLE_RELATIONSHIPS); const hiddenRelationshipCount = relationshipRows.length - visibleRows.length; const parentTitle = mergeTargetThreadId === null ? null : (graph.nodes.get(mergeTargetThreadId)?.thread?.title ?? null); return (

Lineage

{canFork ? ( ) : null} {canDetach ? ( } > void detach()}> Disconnect agent session ) : null}
{visibleRows.length > 0 ? ( ) : null} {hiddenRelationshipCount > 0 ? (

{hiddenRelationshipCount} more direct relationship {hiddenRelationshipCount === 1 ? "" : "s"}

) : null}
); }