import { IconChartTreemap, IconInfoCircle, IconList, IconLock, } from "@tabler/icons-react"; import { useMemo, useState } from "react"; import type { ContextManifest, ContextManifestSystemSection, ContextPreview, } from "../../shared/context-xray.js"; import { manifestConversationTokens } from "../../shared/context-xray.js"; import { ContextMeter } from "../context-xray/ContextMeter.js"; import { ContextTreemap } from "../context-xray/ContextTreemap.js"; import { formatTokens, resolveContextWindow } from "../context-xray/format.js"; import { useT } from "../i18n.js"; import { useActionQuery } from "../use-action.js"; import { useChatThreads, type ChatThreadSummary } from "../use-chat-threads.js"; import { cn } from "../utils.js"; import { AgentTabFrame } from "./AgentTabFrame.js"; import type { AgentPageTabProps } from "./types.js"; type PreviewQuery = { data?: ContextPreview; isLoading?: boolean; error?: unknown; }; type ManifestQuery = { data?: ContextManifest; isLoading?: boolean }; export function mostRecentlyUpdatedThread( threads: ChatThreadSummary[], ): ChatThreadSummary | undefined { return threads.reduce( (latest, thread) => !latest || thread.updatedAt > latest.updatedAt ? thread : latest, undefined, ); } const PROVENANCE_ORDER = [ "framework-core", "actions-prompt", "enterprise-workspace-core", "template", "sql-workspace", "legacy-app-default", "organization", "personal", "memory", "db-schema", "tools", "model-overlay", "runtime-context", ] as const; type Translate = (key: string, options?: Record) => string; function provenanceLabel( provenance: ContextManifestSystemSection["provenance"], t: Translate, ): string { switch (provenance) { case "framework-core": return t("contextXray.provenance.frameworkCore", { defaultValue: "Framework", }); case "actions-prompt": return t("contextXray.provenance.actionsPrompt", { defaultValue: "Actions", }); case "template": return t("contextXray.provenance.template", { defaultValue: "Template", }); case "enterprise-workspace-core": return t("contextXray.provenance.enterpriseWorkspaceCore", { defaultValue: "Enterprise workspace core", }); case "sql-workspace": return t("contextXray.provenance.sqlWorkspace", { defaultValue: "Workspace", }); case "legacy-app-default": return t("contextXray.provenance.legacyAppDefault", { defaultValue: "App defaults", }); case "organization": return t("contextXray.provenance.organization", { defaultValue: "Organization", }); case "personal": return t("contextXray.provenance.personal", { defaultValue: "Personal", }); case "memory": return t("contextXray.provenance.memory", { defaultValue: "Memory", }); case "db-schema": return t("contextXray.provenance.dbSchema", { defaultValue: "SQL schema", }); case "tools": return t("contextXray.provenance.tools", { defaultValue: "Tools" }); case "model-overlay": return t("contextXray.provenance.modelOverlay", { defaultValue: "Model overlay", }); case "runtime-context": return t("contextXray.provenance.runtimeContext", { defaultValue: "Runtime context", }); } } function governanceLabel( governance: ContextManifestSystemSection["governance"], t: Translate, ): string { switch (governance) { case "required": return t("contextXray.governance.required", { defaultValue: "Required", }); case "inherited": return t("contextXray.governance.inherited", { defaultValue: "Inherited", }); case "user": return t("contextXray.governance.user", { defaultValue: "Your context", }); } } function sourceLabel(section: ContextManifestSystemSection): string { return ( section.sourceRef?.path ?? section.sourceRef?.resourceId ?? section.sourceRef?.scope ?? "framework" ); } function previewAsManifest(preview: ContextPreview): ContextManifest { return { threadId: "context-preview", computedAt: preview.computedAt, ...(preview.model ? { model: preview.model } : {}), totalTokens: preview.totalTokens, rawTokens: preview.totalTokens, reclaimedTokens: 0, tokenCountMethod: preview.tokenCountMethod, conversationTokens: 0, systemTokens: preview.systemTokens, source: "preview", enforceable: false, segments: [], systemSections: preview.sections, }; } function ContextSplitMeter({ manifest, budget, }: { manifest: ContextManifest; budget: number; }) { const t = useT(); const systemTokens = manifest.systemTokens ?? 0; const conversationTokens = manifestConversationTokens(manifest); const total = Math.max(1, systemTokens + conversationTokens); return (
{t("contextXray.system", { defaultValue: "System" })}{" "} {formatTokens(systemTokens)} {t("contextXray.conversation", { defaultValue: "Conversation" })}{" "} {formatTokens(conversationTokens)} {formatTokens(Math.max(0, budget - manifest.totalTokens))}{" "} {t("contextXray.free", { defaultValue: "free" })}
); } function SystemSectionList({ sections, totalTokens, }: { sections: ContextManifestSystemSection[]; totalTokens: number; }) { const t = useT(); const grouped = useMemo(() => { const map = new Map< ContextManifestSystemSection["provenance"], ContextManifestSystemSection[] >(); for (const section of sections) { const items = map.get(section.provenance) ?? []; items.push(section); map.set(section.provenance, items); } return PROVENANCE_ORDER.flatMap((provenance) => { const items = map.get(provenance); return items && items.length > 0 ? [{ provenance, items }] : []; }); }, [sections]); return (
{grouped.map((group) => { const tokens = group.items.reduce( (sum, item) => sum + item.tokenCount, 0, ); return (

{provenanceLabel(group.provenance, t)}

{governanceLabel( group.items[0]?.governance ?? "inherited", t, )}
{formatTokens(tokens)} ·{" "} {totalTokens > 0 ? Math.round((tokens / totalTokens) * 100) : 0} %
{group.items .slice() .sort((a, b) => b.tokenCount - a.tokenCount) .map((section) => (
{section.label}
{formatTokens(section.tokenCount)} ·{" "} {totalTokens > 0 ? Math.round( (section.tokenCount / totalTokens) * 100, ) : 0} %
{sourceLabel(section)} {section.tokenMethod === "estimate" ? " · estimated" : ""}
{section.preview ? (
{section.preview}
) : null}
))}
); })} {grouped.length === 0 ? (
{t("contextXray.noSystemContext", { defaultValue: "No system context is available for this scope yet.", })}
) : null}
); } export function AgentContextTab({ scope }: AgentPageTabProps) { const t = useT(); const [view, setView] = useState<"list" | "map">("list"); const previewQuery = useActionQuery( "context-preview-get", { scope }, { staleTime: 5_000 }, ) as PreviewQuery; const threads = useChatThreads(undefined, "agent-context-page", null, { autoCreate: false, restoreActiveThread: false, }); const latestThread = mostRecentlyUpdatedThread(threads.threads); const liveManifestQuery = useActionQuery( "context-manifest-get", latestThread ? { threadId: latestThread.id } : undefined, { enabled: Boolean(latestThread), staleTime: 1_000 }, ) as ManifestQuery; const preview = previewQuery.data; const previewManifest = preview ? previewAsManifest(preview) : null; const budget = resolveContextWindow(preview?.model); const title = t("contextXray.snapshotsTitle", { defaultValue: "Snapshots", }); const description = t("contextXray.headerDescription", { defaultValue: "Inspect the latest combined snapshot of what the agent loaded and why.", }); return ( ) : null } >
{previewManifest ? ( ) : null}
{previewQuery.isLoading ? (
{t("contextXray.loadingPreview", { defaultValue: "Loading recent snapshot…", })}
) : previewQuery.error ? (
{t("contextXray.previewUnavailable", { defaultValue: "A recent snapshot is not available yet.", })}
) : previewManifest ? ( view === "map" ? ( ) : ( ) ) : (
{t("contextXray.noPreview", { defaultValue: "No recent snapshot is available for this scope yet.", })}
)}

{t("contextXray.liveThread", { defaultValue: "Live thread" })}

{t("contextXray.liveThreadDescription", { defaultValue: "The latest thread snapshot, when one exists. This is a single current snapshot, not an append-only history.", })}

{latestThread && liveManifestQuery.data ? (
{latestThread.title || latestThread.preview || t("contextXray.latestThread", { defaultValue: "Latest thread", })}
{formatTokens(liveManifestQuery.data.totalTokens)} tokens ·{" "} {latestThread.id}
) : (
{t("contextXray.noLiveThread", { defaultValue: "No live thread snapshot is available yet.", })}
)}

{t("contextXray.orderedTokensTitle", { defaultValue: "Snapshots show ordered tokens, not weighted tokens.", })}

{t("contextXray.orderedTokensDescription", { defaultValue: "Required framework and enterprise policy come first, followed by inherited template, workspace, and organization instructions. Personal instructions and memory arrive later and can narrow or override earlier guidance where the prompt permits. These system sections are not evictable; only run-local conversation segments support pin, evict, and restore.", })}

); }