feat(webui): inspect file context in a live graph sidebar (#6562)

* feat(webui): inspect file context in a live graph sidebar

* refactor(webui): place preview controls in the shared sidebar header

* fix(webui): synchronize npm lockfile for graph dependencies

* fix(webui): preserve compacted context and refine graph inspection

* fix(context): harden provenance, request usage, and drawer lifecycle

* fix(webui): align source skeleton and browser fixtures

* perf(context): reuse source analysis and capture request graphs once

* perf(webui): compact graph history and render graph motion on canvas

* fix(webui): remove redundant context sidebar header

* style(webui): clarify context replay icon

* perf(webui): pace context replay on an adaptive timeline

* feat(webui): briefly reveal labels for new context nodes

* fix(webui): reveal new labels only for loaded context files

* fix(webui): restart graph animation clock after idle

* fix(webui): reveal labels when replay reverses node exit

* refactor(context): project file-use facts without retention tracking

* refactor(context): observe file reads outside agent execution

* fix(webui): animate context sidebar closing

* refactor(context): remove unused graph and usage panel code

* refactor(context): isolate prompt observation from execution metadata

* fix(webui): clarify cache rate and show context token usage

* fix(webui): abbreviate context token counts in thousands

* fix(webui): omit token unit from context usage details

* fix(webui): restore large source preview highlighting and panel elevation

* fix(webui): distinguish modifier scrolling from keyboard focus

* fix(webui): align preview tab and panel corner radii

* fix(webui): attach file tabs to the header divider

* fix(webui): use one action to toggle file preview mode

* fix(webui): use hover hint for context replay

* fix(webui): share composer layout between graph and file sidebars

* fix(webui): align sidebar bottom with composer surface

* fix(webui): restore mobile graph drawing and touch file details

* test(webui): align legacy cache assertions with current label

* perf(context): retain source analysis and bound graph animation work

* style(webui): add light elevation to user messages

* test(webui): await lazy graph scene before replay assertions

* fix(webui): align preview skeleton and browser contracts
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-05 17:09:20 +08:00
1 parent 2b44088413
commit 519ed81132
132 files changed
+4673 -1159

No files matched your search

+3 -3
View File
@@ -59,7 +59,7 @@ const LazyHighlightedCode = lazy(async () => {
customStyle={{
background: "transparent",
margin: 0,
padding: chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",
padding: viewportHighlight ? "0.75rem 1rem 0.75rem 0.5rem" : chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",
fontFamily: "inherit",
fontSize: "inherit",
lineHeight: "inherit",
@@ -134,7 +134,7 @@ function CodeTextBlock({
showLineNumbers ? "whitespace-pre" : "whitespace-pre-wrap",
chrome === "default"
? "py-4 pl-5 pr-14"
: compact ? "px-4 py-3" : "p-3",
: compact ? "py-3 pl-2 pr-4" : "p-3",
className,
)}
data-testid={testId}
@@ -143,7 +143,7 @@ function CodeTextBlock({
{showLineNumbers && compact ? (
<span className="flex min-w-max">
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
style={{ minWidth: "4.25em" }}>{lines.map((_, index) => index + 1).join("\n")}</span>
style={{ minWidth: `calc(${String(lines.length).length}ch + 1.15rem)` }}>{lines.map((_, index) => index + 1).join("\n")}</span>
<span>{renderText(code)}</span>
</span>
) : showLineNumbers ? (
+20 -16
View File
@@ -1,10 +1,12 @@
import { useState } from "react";
import { surfaceFocusProps } from "@/lib/surface-focus";
import { useContext, useState } from "react";
import { createPortal } from "react-dom";
import { SidebarPanelActionsContext } from "@/components/ui/sidebar-panel";
import { useTranslation } from "react-i18next";
import { AlertCircle } from "lucide-react";
import { CodeBlock } from "@/components/CodeBlock";
import { MarkdownText } from "@/components/MarkdownText";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { ImageLightbox } from "@/components/ImageLightbox";
import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
import type { FilePreviewPayload } from "@/lib/types";
@@ -23,6 +25,7 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
onOpenFilePreview?: (path: string) => void;
}) {
const { t } = useTranslation();
const actionsHost = useContext(SidebarPanelActionsContext);
const [mode, setMode] = useState<"preview" | "source">("preview");
const previewKind = fileKindForPath(path);
const markdown = state.status === "ready" && state.payload.kind !== "image"
@@ -38,17 +41,18 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
: state.message ?? t("filePreview.failed", { defaultValue: "Could not preview this file." }))
: null;
const modeLabel = t(mode === "preview" ? "filePreview.source" : "filePreview.preview");
const modeControl = <button type="button" onClick={() => setMode(value => value === "preview" ? "source" : "preview")}
className="touch-target inline-flex h-8 items-center justify-center rounded-control px-3 text-xs text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{modeLabel}
</button>;
return (
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
{markdown ? (
<div className="flex shrink-0 items-center justify-end px-4 py-2">
<SegmentedControl value={mode} onChange={setMode} ariaLabel={t("filePreview.displayMode")}
options={[{ value: "preview", label: t("filePreview.preview") }, { value: "source", label: t("filePreview.source") }]}
itemClassName="px-3 [@media(pointer:coarse)]:min-h-9" />
</div>
) : null}
{markdown && (actionsHost ? createPortal(modeControl, actionsHost) : <div className="flex shrink-0 justify-end px-4 py-2">{modeControl}</div>)}
<div key={mode} data-file-preview-scroll tabIndex={0}
className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">
{...surfaceFocusProps}
className="min-h-0 flex-1 overflow-auto outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring/60">
{state.status === "loading" ? (
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
className="h-full" aria-busy="true">
@@ -57,9 +61,9 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
{previewKind === "image" ? <div className="flex h-full items-center justify-center p-4">
<div className="aspect-[8/5] w-full max-w-sm rounded-compact bg-muted/40" />
</div> : <>
{previewKind === "markdown" ? <div className="flex justify-end px-4 py-2">
<div className="inline-flex min-h-8 items-center gap-1 rounded-full bg-muted/40 p-1 text-ui-label">
{[t("filePreview.preview"), t("filePreview.source")].map((label) => <span key={label} className="invisible px-3 py-1 [@media(pointer:coarse)]:min-h-9">{label}</span>)}
{previewKind === "markdown" && !actionsHost ? <div className="flex justify-end px-4 py-2">
<div className="touch-target inline-flex h-8 items-center rounded-control bg-muted/40 px-3 text-xs">
<span className="invisible">{modeLabel}</span>
</div>
</div> : null}
{previewKind === "markdown" && mode === "preview" ? <div className="markdown-content px-5 pb-6 pt-1 sm:px-6">
@@ -67,10 +71,10 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
{["w-full", "w-5/6", "w-3/4"].map((width) => <div key={width} className="mt-4 flex h-[1lh] items-center">
<div className={`h-3 rounded bg-muted/40 ${width}`} />
</div>)}
</div> : <div className="px-4 py-3 font-mono text-code">
</div> : <div className="py-3 pl-2 pr-4 font-mono text-code">
{["w-2/3", "w-full", "w-5/6", "w-3/4", "w-1/2", "w-3/5"].map((width) => <div key={width} className="flex h-[1lh] items-center">
<div className="w-[4.25em] shrink-0 pr-[1.15rem]"><div className="ml-auto h-3 w-2 rounded bg-muted/40" /></div>
<div className={`h-3 max-w-[calc(100%-4.25em)] rounded bg-muted/40 ${width}`} />
<div className="w-[calc(1ch+1.15rem)] shrink-0 pr-[1.15rem]"><div className="ml-auto h-3 w-2 rounded bg-muted/40" /></div>
<div className={`h-3 max-w-[calc(100%-1ch-1.15rem)] rounded bg-muted/40 ${width}`} />
</div>)}
</div>}
</>}
@@ -1,3 +1,4 @@
import { surfaceFocusProps } from "@/lib/surface-focus";
import {
Children,
isValidElement,
@@ -686,7 +687,7 @@ export default function MarkdownTextRenderer({
void _node;
return (
<div
data-testid="markdown-data-table"
data-testid="markdown-data-table" {...surfaceFocusProps}
data-table-kind="data"
role="region"
tabIndex={0}
@@ -694,7 +695,7 @@ export default function MarkdownTextRenderer({
className={cn(
"not-prose mb-5 mt-3 w-full max-w-full overflow-x-auto rounded-lg",
"border border-border/65 bg-muted/20",
"overscroll-x-contain focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
"overscroll-x-contain outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-ring",
)}
>
<table
@@ -703,9 +704,9 @@ export default function MarkdownTextRenderer({
"[&_thead]:bg-muted/45 [&_thead]:text-muted-foreground",
"[&_th]:border-b [&_th]:border-border/65 [&_th]:px-3 [&_th]:py-2",
"[&_th]:text-left [&_th]:font-medium [&_th]:whitespace-normal",
"[&_th]:[overflow-wrap:anywhere]",
"[&_th]:[overflow-wrap:normal]",
"[&_td]:border-b [&_td]:border-border/55 [&_td]:px-3 [&_td]:py-2",
"[&_td]:whitespace-normal [&_td]:[overflow-wrap:anywhere]",
"[&_td]:whitespace-normal [&_td]:[overflow-wrap:normal]",
"[&_th:not(:last-child)]:border-r [&_th:not(:last-child)]:border-border/45",
"[&_td:not(:last-child)]:border-r [&_td:not(:last-child)]:border-border/45",
"[&_tbody_tr:last-child_td]:border-b-0",
+1 -1
View File
@@ -503,7 +503,7 @@ export function MessageBubble({
"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",
temporary
? "border border-dashed border-muted-foreground/40 bg-transparent"
: "bg-secondary/70",
: "user-message-surface bg-secondary/70",
)}
>
{messageText}
+18 -28
View File
@@ -1,4 +1,6 @@
import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react";
import { surfaceFocusProps } from "@/lib/surface-focus";
import { useEffect, useId, useRef, type PointerEvent, type ReactNode } from "react";
import { SidebarPanel } from "@/components/ui/sidebar-panel";
import { PanelRightClose, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { FileReferenceIcon, fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
@@ -6,6 +8,7 @@ import { FileActions } from "@/components/FileActions";
import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/components/SidebarSelectionHighlight";
import type { PreviewTab } from "@/hooks/useFilePreviewState";
import { cn } from "@/lib/utils";
import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface";
/** One stable sidebar shell: switching targets never replays its opening animation. */
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: {
@@ -21,14 +24,9 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
}) {
const { t } = useTranslation();
const id = useId();
const [entered, setEntered] = useState(false);
const buttons = useRef(new Map<string, HTMLButtonElement>());
const tabList = useRef<HTMLDivElement>(null);
const pendingFocus = useRef<string | null>(null);
useEffect(() => {
const frame = requestAnimationFrame(() => setEntered(true));
return () => cancelAnimationFrame(frame);
}, []);
useEffect(() => {
const revealActiveTab = () => buttons.current.get(activeId)?.parentElement?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
revealActiveTab();
@@ -48,29 +46,18 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onCloseTab(tab.id);
};
const iconButton = "touch-target inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return <aside aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
style={{
"--file-preview-width": `${width}px`,
"--file-preview-slot-width": !entered || isClosing ? "0px" : `${width}px`,
"--file-preview-mobile-width": !entered || isClosing ? "0px" : "100%",
} as CSSProperties}
className={cn("file-preview-pane absolute inset-y-0 right-0 z-30 w-[var(--file-preview-mobile-width)] overflow-hidden transition-[width] duration-300 ease-out motion-reduce:transition-none", isClosing && "pointer-events-none")}
>
<div className={cn("file-preview-content absolute inset-y-0 right-0 flex w-[100cqw] flex-col border-l border-border/60 bg-background pb-[env(safe-area-inset-bottom)] transition-opacity duration-200 motion-reduce:transition-none", !entered || isClosing ? "opacity-0" : "opacity-100")}>
<button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}
className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">
<span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
</button>
<div className="flex min-h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2">
return <SidebarPanel aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
width={width} isClosing={isClosing} contentClassName={sidePanelSurfaceClassName}
header={<>
<div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<SidebarSelectionHighlight activeId={activeId} scope="preview-tabs" targetSelector="[data-preview-tab-active]"
className="relative isolate flex w-max min-w-full items-center gap-1"
highlightClassName="rounded-compact">
highlightClassName="rounded-none rounded-t-2xl">
{tabs.map((tab, index) => {
const selected = tab.id === activeId;
const name = splitFilePath(tab.value).name;
const item = <div key={tab.id} role="presentation" data-preview-tab-active={selected ? "" : undefined}
className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-compact", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>
className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-t-2xl", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>
<button type="button" role="tab" id={`${id}-tab-${index}`} aria-selected={selected} aria-controls={`${id}-panel`}
tabIndex={selected ? 0 : -1} title={tab.value}
ref={(node) => { if (node) buttons.current.set(tab.id, node); else buttons.current.delete(tab.id); }}
@@ -87,7 +74,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onSelect(tabs[next].id);
buttons.current.get(tabs[next].id)?.focus();
}}
className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-compact pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-t-2xl pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
<span aria-hidden className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
<FileReferenceIcon kind={fileKindForPath(tab.value)} className="size-3.5" />
</span>
@@ -106,11 +93,14 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
{tabs.length > 1 ? <button type="button" className={iconButton} onClick={onClose} aria-label={t("previewTabs.closeAll")} title={t("previewTabs.closeAll")}>
<PanelRightClose className="size-4" aria-hidden />
</button> : null}
</div>
<div role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}
className="flex min-h-0 flex-1 flex-col focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
</>}>
<button type="button" aria-label={t("filePreview.resize")} onPointerDown={onResizeStart}
className="file-preview-resize group absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none justify-start focus-visible:outline-none">
<span aria-hidden className="h-full w-px bg-foreground/25 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
</button>
<div role="tabpanel" {...surfaceFocusProps} id={`${id}-panel`} aria-labelledby={`${id}-tab-${tabs.findIndex((tab) => tab.id === activeId)}`} tabIndex={0}
className="flex min-h-0 flex-1 flex-col outline-none data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring">
{children}
</div>
</div>
</aside>;
</SidebarPanel>;
}
+5 -3
View File
@@ -10,15 +10,16 @@ function textOf(node: Row): string {
return node.type === "text" ? String(node.value ?? "") : (node.children ?? []).map(textOf).join("");
}
const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted }: RowsProps & {
const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted, lineNumberWidth }: RowsProps & {
text: string;
start: number;
highlighted: boolean;
lineNumberWidth: string;
}) {
return (
<span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max">
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
style={{ minWidth: "4.25em" }}>
style={{ minWidth: lineNumberWidth }}>
{rows.map((_, index) => start + index + 1).join("\n")}
</span>
<span data-highlighted={highlighted}>
@@ -78,7 +79,8 @@ export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsProp
return (
<span ref={rootRef} className="block min-w-max" data-testid="viewport-code-rows">
{chunks.map((chunk, index) => <CodeChunk key={chunk.start} {...chunk}
stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)} />)}
stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)}
lineNumberWidth={`calc(${String(rows.length).length}ch + 1.15rem)`} />)}
</span>
);
}
@@ -388,8 +388,8 @@ function SkillDetailSheet({
"sm:right-3 sm:top-3",
)}
className={cn(
"w-full max-w-none gap-0 overflow-hidden border-l-0 p-0",
"sm:w-[min(34rem,calc(100vw-1rem))] sm:max-w-none sm:border-l",
"w-[calc(100vw-1rem)] max-w-none gap-0 p-0",
"sm:w-[min(34rem,calc(100vw-1rem))] sm:max-w-none",
)}
>
<div
@@ -1,82 +1,72 @@
import { Fragment, useCallback, useMemo, useRef, useState, type PointerEvent, type ReactNode } from "react";
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import { FloatingPortalContext } from "@/components/ui/floating-portal";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { formatCompactTokenCount } from "@/lib/format";
import { formatTurnLatency } from "@/lib/format-time";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { SidebarPanel } from "@/components/ui/sidebar-panel";
import { ContextInspector } from "./ContextInspector";
import type { ContextSnapshot } from "@/lib/types";
import { cn } from "@/lib/utils";
export interface ComposerContextUsage {
estimated?: boolean;
contextTokens: number;
contextWindowTokens?: number;
}
export interface ComposerRoundUsage {
id: string;
timestamp: number;
inputTokens: number;
outputTokens?: number;
cachedTokens?: number;
estimatedTokens?: number;
generationMs?: number;
}
interface NormalizedRoundUsage extends ComposerRoundUsage {
cachedTokens?: number;
outputTokens: number;
}
function normalizeRounds(
rounds: readonly ComposerRoundUsage[],
): NormalizedRoundUsage[] {
return rounds
.filter((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0)
.map((round) => ({
...round,
inputTokens: Math.max(0, round.inputTokens),
outputTokens: Number.isFinite(round.outputTokens)
? Math.max(0, round.outputTokens ?? 0)
: 0,
...(Number.isFinite(round.cachedTokens)
? { cachedTokens: Math.min(round.inputTokens, Math.max(0, round.cachedTokens ?? 0)) }
: {}),
}));
}
export function ComposerUsagePopover({
context,
rounds,
snapshots = [],
onOpenFile,
showLabel = false,
compactLabel = false,
bottomSheet = false,
sidebarHost,
triggerHost,
open: controlledOpen,
onOpenChange,
}: {
context: ComposerContextUsage | null;
rounds: readonly ComposerRoundUsage[];
snapshots?: readonly ContextSnapshot[];
onOpenFile?: (path: string) => void;
showLabel?: boolean;
compactLabel?: boolean;
bottomSheet?: boolean;
sidebarHost?: HTMLElement | null;
triggerHost?: HTMLElement | null;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const { t, i18n } = useTranslation();
const [open, setOpen] = useState(false);
const normalizedRounds = useMemo(() => normalizeRounds(rounds), [rounds]);
const { t } = useTranslation();
const [localOpen, setLocalOpen] = useState(false);
const open = controlledOpen ?? localOpen;
const interactedOutside = useRef(false);
const setOpen = (next: boolean) => { if (next) interactedOutside.current = false; setLocalOpen(next); onOpenChange?.(next); };
const triggerRef = useRef<HTMLButtonElement>(null);
const panelId = useId();
const [narrow, setNarrow] = useState(false);
useEffect(() => {
const measure = () => setNarrow((sidebarHost?.clientWidth ?? window.innerWidth) < 780);
measure();
const observer = new ResizeObserver(measure);
if (sidebarHost) observer.observe(sidebarHost);
window.addEventListener("resize", measure);
return () => { observer.disconnect(); window.removeEventListener("resize", measure); };
}, [sidebarHost]);
const close = () => { setOpen(false); requestAnimationFrame(() => triggerRef.current?.focus()); };
const hasRounds = rounds.some((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0);
const hasContext = !!context
&& Number.isFinite(context.contextTokens)
&& context.contextTokens >= 0
&& Number.isFinite(context.contextWindowTokens)
&& (context.contextWindowTokens ?? 0) > 0;
if (!hasContext && normalizedRounds.length === 0) {
if (!open && !hasContext && !hasRounds && !snapshots.length) {
return null;
}
@@ -99,37 +89,21 @@ export function ComposerUsagePopover({
? detailsLabel
: t("thread.composer.context.tooltip", {
defaultValue: "Context {{percent}}%",
percent: contextPercentage,
percent: `${context?.estimated ? "≈" : ""}${contextPercentage}`,
});
const triggerLabel = contextPercentage === null
? detailsLabel
: `${contextDescription}. ${detailsLabel}`;
const ringCircumference = 2 * Math.PI * 6;
const ringLength = ringCircumference * meterPercentage / 100;
const maxInputTokens = Math.max(0, ...normalizedRounds.map((round) => round.inputTokens));
const numberFormatter = new Intl.NumberFormat(i18n.language);
const percentageFormatter = new Intl.NumberFormat(i18n.language, {
style: "percent",
maximumFractionDigits: 0,
});
const roundDateFormatter = new Intl.DateTimeFormat(i18n.language, {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
const Root = bottomSheet ? Sheet : Popover;
const Trigger = bottomSheet ? SheetTrigger : PopoverTrigger;
const RoundRoot = bottomSheet ? Popover : Tooltip;
const RoundTrigger = bottomSheet ? PopoverTrigger : TooltipTrigger;
const RoundContent = bottomSheet ? PopoverContent : TooltipContent;
const RoundBar = bottomSheet ? "button" : "span";
const showTextLabel = showLabel && (!compactLabel || contextPercentage !== null);
const trigger = (
<Trigger asChild>
<button
type="button"
ref={triggerRef}
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-controls={open ? panelId : undefined}
data-testid="composer-context-usage"
aria-label={triggerLabel}
className={cn(
@@ -184,372 +158,43 @@ export function ComposerUsagePopover({
)}
{showTextLabel ? (
<span aria-hidden className="whitespace-nowrap tabular-nums">
{compactLabel && contextPercentage !== null ? `${contextPercentage}%` : contextDescription}
{compactLabel && contextPercentage !== null ? `${context?.estimated ? "≈" : ""}${contextPercentage}%` : contextDescription}
</span>
) : null}
</button>
</Trigger>
);
return (
<Root open={open} onOpenChange={setOpen}>
<TooltipProvider>
{bottomSheet ? trigger : (
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent
side="top"
align="center"
sideOffset={8}
className="w-fit max-w-[calc(100vw-2rem)] rounded-full border-border/70 px-2.5 py-1 text-xs font-medium shadow-[0_8px_24px_rgba(15,23,42,0.13)]"
>
<span className="whitespace-nowrap tabular-nums">{contextDescription}</span>
</TooltipContent>
</Tooltip>
)}
const triggerWithTooltip = <TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent side="top" className="text-xs">{contextDescription}</TooltipContent>
</Tooltip>
</TooltipProvider>;
<UsagePanel bottomSheet={bottomSheet} onDismiss={() => setOpen(false)}>
<div className="px-4 pb-4 pt-3.5">
{contextPercentage !== null ? (
<>
<div className="flex items-baseline justify-between gap-3">
<div className="flex min-w-0 items-baseline gap-2">
<span className={cn("shrink-0 font-medium text-foreground", bottomSheet ? "text-sm" : "text-[12px]")}>
{t("thread.composer.context.contextTitle", {
defaultValue: "Context",
})}
</span>
<span className={cn("truncate tabular-nums text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
{formatCompactTokenCount(context!.contextTokens)} / {formatCompactTokenCount(
context!.contextWindowTokens!,
)}
</span>
</div>
<span className={cn("shrink-0 tabular-nums text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
{contextPercentage}%
</span>
</div>
<div
role="progressbar"
aria-label={contextDescription}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={contextPercentage}
className="mt-2 h-1 overflow-hidden rounded-full bg-muted"
>
<div
className={cn(
"h-full rounded-full",
status === "critical" && "bg-destructive",
status === "caution" && "bg-amber-500",
status === "normal" && "bg-foreground/45",
)}
style={{ width: `${contextPercentage}%` }}
/>
</div>
</>
) : null}
{normalizedRounds.length > 0 ? (
<>
<div className={cn(
"flex items-baseline justify-between gap-3",
contextPercentage === null ? "mt-0" : "mt-5",
)}>
<span className={cn("font-medium text-foreground", bottomSheet ? "text-sm" : "text-[12px]")}>
{t("thread.composer.context.recentRounds", {
defaultValue: "Recent rounds",
})}
</span>
<span className={cn("text-muted-foreground", bottomSheet ? "text-xs" : "text-[11px]")}>
{t("thread.composer.context.inputTrend", {
defaultValue: "Input tokens",
})}
</span>
</div>
<div
role="group"
aria-label={t("thread.composer.context.inputTrend", {
defaultValue: "Input tokens",
})}
className="mt-2 flex h-28 items-end gap-1.5 border-b border-border/60"
>
{normalizedRounds.map((round, index) => {
const cachedKnown = typeof round.cachedTokens === "number";
const cachedTokens = round.cachedTokens ?? 0;
const notReusedTokens = Math.max(0, round.inputTokens - cachedTokens);
const cacheHitRate = cachedKnown
? percentageFormatter.format(cachedTokens / round.inputTokens)
: null;
const cachedHeight = cachedKnown
? cachedTokens / round.inputTokens * 100
: 0;
const barHeight = round.inputTokens / maxInputTokens * 108;
const timestampLabel = roundDateFormatter.format(round.timestamp);
const detailRows = [
{
key: "input",
label: t("thread.composer.context.input", {
defaultValue: "Input tokens",
}),
value: numberFormatter.format(round.inputTokens),
},
cachedKnown
? {
key: "cache-hit-rate",
label: t("thread.composer.context.cacheHitRate", {
defaultValue: "KV cache hit rate",
}),
value: cacheHitRate!,
}
: null,
{
key: "output",
label: t("thread.composer.context.output", {
defaultValue: "Output tokens",
}),
value: numberFormatter.format(round.outputTokens),
},
typeof round.generationMs === "number"
? {
key: "duration",
label: t("thread.composer.context.duration", {
defaultValue: "Generation time",
}),
value: formatTurnLatency(round.generationMs, i18n.language),
}
: null,
].filter((row): row is NonNullable<typeof row> => !!row);
const detailNote = (round.estimatedTokens ?? 0) > 0
? t("message.usage.estimated", {
defaultValue: "Includes estimated usage",
})
: null;
const detailLabel = [
timestampLabel,
...detailRows.map((row) => `${row.label} ${row.value}`),
detailNote,
].filter((part): part is string => !!part).join(". ");
return (
<span
key={round.id}
className={cn(
"flex h-full min-w-0 flex-1 items-end justify-center rounded-sm",
bottomSheet && "relative",
"opacity-70 transition-opacity hover:opacity-100",
index === 0 && "justify-start",
normalizedRounds.length > 1
&& index === normalizedRounds.length - 1
&& "justify-end",
index === normalizedRounds.length - 1 && "opacity-100",
)}
>
<RoundRoot>
<RoundTrigger asChild>
<RoundBar
type={bottomSheet ? "button" : undefined}
role={bottomSheet ? undefined : "img"}
tabIndex={0}
aria-label={detailLabel}
data-testid="round-usage-bar"
className={cn(
"flex w-full max-w-7 flex-col overflow-hidden rounded-t-[3px] bg-muted",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
// Let touch users hit the entire column, even when a
// round's proportional bar is less than a pixel high.
bottomSheet && "before:absolute before:inset-0 before:content-[''] data-[state=open]:ring-2 data-[state=open]:ring-foreground/20",
)}
style={{ height: `${barHeight}px` }}
>
{cachedKnown ? (
<>
{notReusedTokens > 0 ? (
<span
className="kv-cache-not-reused block w-full"
style={{ height: `${100 - cachedHeight}%` }}
/>
) : null}
{cachedTokens > 0 ? (
<span
className="kv-cache-reused block w-full"
style={{ height: `${cachedHeight}%` }}
/>
) : null}
</>
) : (
<span className="block h-full w-full bg-muted-foreground/25" />
)}
</RoundBar>
</RoundTrigger>
<RoundContent
side="top"
align="center"
className="max-w-72 px-3 py-2 text-[11px]"
{...(bottomSheet ? {
"aria-label": timestampLabel,
onOpenAutoFocus: (event: Event) => event.preventDefault(),
} : {})}
>
<span
className="block font-medium text-foreground"
>
{timestampLabel}
</span>
<span className="mt-1 grid grid-cols-[max-content_max-content] gap-x-3 gap-y-0.5">
{detailRows.map((row) => (
<Fragment key={row.key}>
<span className="text-muted-foreground">
{row.label}
</span>
<span className="text-end tabular-nums text-foreground">
{row.value}
</span>
</Fragment>
))}
</span>
{detailNote ? (
<span
className="mt-1 block text-muted-foreground"
>
{detailNote}
</span>
) : null}
</RoundContent>
</RoundRoot>
</span>
);
})}
</div>
</>
) : null}
</div>
</UsagePanel>
</TooltipProvider>
</Root>
);
}
function UsagePanel({ bottomSheet, onDismiss, children }: {
bottomSheet: boolean;
onDismiss: () => void;
children: ReactNode;
}) {
const { t } = useTranslation();
const panelRef = useRef<HTMLDivElement | null>(null);
const [panelNode, setPanelNode] = useState<HTMLDivElement | null>(null);
const sheetRef = useCallback((node: HTMLDivElement | null) => {
panelRef.current = node;
setPanelNode(node);
}, []);
const gesture = useRef<{ pointerId: number; x: number; y: number; time: number } | null>(null);
const suppressClick = useRef(false);
const [offset, setOffset] = useState(0);
const [dragging, setDragging] = useState(false);
const title = t("thread.composer.context.panelTitle", { defaultValue: "Context usage" });
const focusPanel = (event: Event) => {
event.preventDefault();
gesture.current = null;
suppressClick.current = false;
setOffset(0);
setDragging(false);
panelRef.current?.focus({ preventScroll: true });
};
const cancelDrag = (event: PointerEvent<HTMLButtonElement>) => {
if (gesture.current?.pointerId !== event.pointerId) return;
gesture.current = null;
suppressClick.current = true;
setDragging(false);
setOffset(0);
const inspector = <ContextInspector sidebar expandable={!narrow} context={context} rounds={rounds} snapshots={snapshots}
onOpenFile={onOpenFile ? (path) => { setOpen(false); onOpenFile(path); } : undefined} />;
const onPanelKeyDown = (event: KeyboardEvent<HTMLElement>) => {
if (event.key === "Escape" && !event.defaultPrevented) { event.preventDefault(); close(); }
};
if (bottomSheet) {
return (
<SheetContent
ref={sheetRef}
side="bottom"
aria-describedby={undefined}
showCloseButton={false}
onOpenAutoFocus={focusPanel}
style={{ translate: `0 ${offset}px`, ...(dragging ? { transition: "none" } : {}) }}
className={cn(
"mx-auto max-h-[60dvh] w-full max-w-md gap-0 rounded-t-3xl border-t border-border/60 p-0 shadow-xl outline-none",
"transition-[translate]",
"data-[state=open]:duration-300 data-[state=open]:ease-out data-[state=closed]:duration-200 data-[state=closed]:ease-in",
)}
>
<button
type="button"
aria-label={t("common.close")}
className="mx-auto flex h-11 w-24 shrink-0 touch-none select-none items-center justify-center rounded-full cursor-grab active:cursor-grabbing focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onPointerDown={(event) => {
if (event.button !== 0 || !event.isPrimary || gesture.current) return;
event.currentTarget.setPointerCapture(event.pointerId);
gesture.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, time: event.timeStamp };
suppressClick.current = false;
setDragging(true);
}}
onPointerMove={(event) => {
const start = gesture.current;
if (!start || start.pointerId !== event.pointerId) return;
const dy = event.clientY - start.y;
const dx = event.clientX - start.x;
if (Math.abs(dy) > 5 || Math.abs(dx) > 5) suppressClick.current = true;
setOffset(Math.max(0, dy));
}}
onPointerUp={(event) => {
const start = gesture.current;
if (!start || start.pointerId !== event.pointerId) return;
gesture.current = null;
const dy = Math.max(0, event.clientY - start.y);
const dx = Math.abs(event.clientX - start.x);
const threshold = Math.max(48, Math.min(96, (panelRef.current?.offsetHeight ?? 320) * 0.3));
const elapsed = Math.max(1, event.timeStamp - start.time);
const dismiss = dy > dx && (dy >= threshold || (dy > 20 && dy / elapsed > 0.5));
suppressClick.current ||= dy > 5 || dx > 5;
event.currentTarget.releasePointerCapture(event.pointerId);
setDragging(false);
if (dismiss) onDismiss();
else setOffset(0);
}}
onPointerCancel={cancelDrag}
onLostPointerCapture={cancelDrag}
onClick={(event) => {
// A completed drag also emits a click; don't close after a snap-back.
if (suppressClick.current && event.detail !== 0) {
event.preventDefault();
suppressClick.current = false;
return;
}
onDismiss();
}}
>
<span aria-hidden="true" className="h-1 w-8 rounded-full bg-foreground/15" />
</button>
<div className="shrink-0 px-5 pb-2">
<SheetTitle className="text-base font-medium">{title}</SheetTitle>
</div>
<div className="min-h-0 overflow-y-auto overscroll-contain px-1 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
<FloatingPortalContext.Provider value={panelNode}>
{children}
</FloatingPortalContext.Provider>
</div>
</SheetContent>
);
}
return (
<PopoverContent
ref={panelRef}
side="top"
align="end"
sideOffset={10}
onOpenAutoFocus={focusPanel}
aria-label={title}
className="w-[min(22rem,calc(100vw-1.5rem))] p-0"
>
{children}
</PopoverContent>
);
return <>
{triggerHost === undefined ? triggerWithTooltip : triggerHost && createPortal(triggerWithTooltip, triggerHost)}
{narrow ? <Dialog open={open} onOpenChange={setOpen} modal={!sidebarHost}>
<DialogContent portalContainer={sidebarHost} placement="bottom" id={panelId} aria-describedby={undefined}
data-testid="context-sidebar"
overlayClassName={cn("context-drawer-backdrop", sidebarHost && "absolute bg-black/25 backdrop-blur-[8px] sm:bg-transparent sm:backdrop-blur-none")}
className="context-drawer-panel flex h-[85%] min-h-0 max-w-none flex-col gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))]"
onCloseAutoFocus={(event) => { event.preventDefault(); if (!interactedOutside.current) triggerRef.current?.focus({ preventScroll: true }); }}
onInteractOutside={(event) => {
if (event.target instanceof Node && triggerRef.current?.contains(event.target)) event.preventDefault();
else interactedOutside.current = true;
}}>
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
{inspector}
</DialogContent>
</Dialog> : createPortal(<SidebarPanel open={open} width={420} floating={!sidebarHost} id={panelId}
aria-label={t("thread.composer.context.panelTitle")} data-testid="context-sidebar" onKeyDown={onPanelKeyDown}>
{inspector}
</SidebarPanel>, sidebarHost ?? document.body)}
</>;
}
@@ -0,0 +1,294 @@
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useReducedMotion } from "motion/react";
import { Maximize2, Minimize2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { formatCompactTokenCount } from "@/lib/format";
import { createGraphSimulation, updateGraphSimulation, advanceGraphSimulation, startGraphSettlement, type GraphParticle, type GraphPosition } from "@/lib/context-graph-layout";
import type { ContextGraph } from "@/lib/types";
import { createGraphPresentation } from "./graph-presentation";
import { paintGraph, readGraphPalette, type GraphPalette } from "./graph-canvas";
const surface = "context-inspector-surface select-none rounded-[20px] bg-card";
export const ContextGraphScene = memo(function ContextGraphScene({ graph, epoch, expanded, onExpand, onOpenFile, onReady, sidebar = false }: {
graph: ContextGraph; epoch?: string; expanded: boolean; onExpand?: () => void; onOpenFile?: (path: string) => void; onReady?: (graph: ContextGraph) => void; sidebar?: boolean;
}) {
const { t } = useTranslation();
const container = useRef<HTMLDivElement>(null);
const canvas = useRef<HTMLCanvasElement>(null);
const paletteProbe = useRef<HTMLSpanElement>(null);
const palette = useRef<GraphPalette>();
const nodeElements = useRef(new Map<string, HTMLButtonElement>());
const focused = useRef<string | null>(null);
const positions = useRef(new Map<string, GraphPosition>());
const particles = useRef(new Map<string, GraphParticle>());
const simulation = useRef<ReturnType<typeof createGraphSimulation>>();
const settlement = useRef<ReturnType<typeof startGraphSettlement> | null>(null);
const paintedGraph = useRef<ContextGraph>();
const [presentation] = useState(createGraphPresentation);
const [frame, setFrame] = useState(presentation.frame);
const [size, setSize] = useState({ width: 550, height: 300 });
const [active, setActive] = useState<string | null>(null);
const [hovered, setHovered] = useState<string | null>(null);
const currentNodes = useMemo(() => new Map(graph.nodes.map((node) => [node.path, node])), [graph]);
const discovered = useMemo(() => new Set(graph.nodes.filter((node) => node.state === "discovered").map((node) => node.path)), [graph]);
const selected = active ? currentNodes.get(active) : undefined;
const candidate = active ?? hovered;
const highlighted = candidate && currentNodes.has(candidate) ? candidate : null;
const reducedMotion = !!useReducedMotion();
const clock = useRef({ frame: 0, previous: 0, visible: true, geometry: true });
const draw = useRef<(time: number) => void>(() => {});
const view = useRef({ x: 0, y: 0, k: 1 });
const interacted = useRef(false);
const fittedSize = useRef("");
const layoutKey = useRef("");
const pruneEpoch = useRef(false);
const previousEpoch = useRef(epoch);
const pan = useRef<{ id: number; x: number; y: number } | null>(null);
const dragging = useRef<{ id: number; path: string; x: number; y: number; moved: boolean } | null>(null);
const restoreNodeFocus = useRef(false);
const schedule = useCallback(() => {
if (!clock.current.frame && clock.current.visible && !document.hidden) clock.current.frame = requestAnimationFrame((time) => draw.current(time));
}, []);
const setView = useCallback((next: typeof view.current) => {
view.current = next;
schedule();
}, [schedule]);
draw.current = (time) => {
const state = clock.current;
state.frame = 0;
if (!state.visible || document.hidden) return;
const elapsed = state.previous ? time - state.previous : 1000 / 60;
state.previous = time;
const sim = simulation.current;
if (settlement.current) {
if (!settlement.current()) { schedule(); return; }
settlement.current = null; state.geometry = true;
}
const running = !!sim && (sim.alpha() > sim.alphaMin() || sim.alphaTarget() > 0);
if (sim && running && !reducedMotion) { advanceGraphSimulation(sim, elapsed); state.geometry = true; }
const change = presentation.advance(elapsed, reducedMotion);
if (change.removed) {
setFrame(presentation.frame);
if (pruneEpoch.current) {
const retained = new Set(presentation.frame.nodes.map((node) => node.path));
for (const path of positions.current.keys()) if (!retained.has(path)) positions.current.delete(path);
}
}
if (!change.moving) pruneEpoch.current = false;
if (state.geometry && sim) for (const particle of sim.nodes()) {
const point = positions.current.get(particle.path);
if (point) { point.x = particle.x; point.y = particle.y; }
else positions.current.set(particle.path, { x: particle.x, y: particle.y });
}
const bitmap = canvas.current;
const context = bitmap?.getContext("2d");
if (bitmap && context && palette.current) {
// Keep motion within a pixel budget; the final stationary paint restores
// native resolution for crisp labels without paying that cost every frame.
const ratio = running || change.moving
? Math.min(window.devicePixelRatio || 1, 1.5, Math.sqrt(1_000_000 / (size.width * size.height)))
: window.devicePixelRatio || 1;
const width = Math.round(size.width * ratio), height = Math.round(size.height * ratio);
if (bitmap.width !== width || bitmap.height !== height) { bitmap.width = width; bitmap.height = height; }
paintGraph(context, presentation.frame, positions.current, view.current, palette.current, highlighted, focused.current,
size.width, size.height, ratio, discovered);
if (paintedGraph.current !== graph) { paintedGraph.current = graph; onReady?.(graph); }
}
state.geometry = false;
if (change.moving || (running && !reducedMotion)) schedule();
// The next animation starts a new clock; idle time must not consume its labels.
else state.previous = 0;
};
useEffect(() => {
if (previousEpoch.current === epoch) return;
previousEpoch.current = epoch;
pruneEpoch.current = true;
palette.current?.labels.clear();
const retained = new Set(graph.nodes.map((node) => node.path));
for (const node of presentation.frame.nodes) retained.add(node.path);
for (const path of positions.current.keys()) if (!retained.has(path)) positions.current.delete(path);
}, [epoch, graph, presentation]);
useEffect(() => {
const element = container.current;
if (!element) return;
const observer = new ResizeObserver(([entry]) => setSize({ width: entry.contentRect.width, height: entry.contentRect.height }));
observer.observe(element);
const visibility = () => { clock.current.previous = 0; if (document.hidden) { cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; } else schedule(); };
document.addEventListener("visibilitychange", visibility);
window.addEventListener("resize", schedule);
const intersection = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => {
// Drawer entry can batch offscreen and onscreen records together. The
// newest record owns visibility; the first can leave painting suspended.
const entry = entries[entries.length - 1];
clock.current.visible = entry.isIntersecting;
if (entry.isIntersecting) { clock.current.previous = 0; schedule(); }
else { cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; clock.current.previous = 0; }
});
intersection?.observe(element);
return () => { observer.disconnect(); intersection?.disconnect(); document.removeEventListener("visibilitychange", visibility); window.removeEventListener("resize", schedule); cancelAnimationFrame(clock.current.frame); clock.current.frame = 0; simulation.current?.stop(); };
}, [schedule]);
useEffect(() => {
const sim = simulation.current ?? createGraphSimulation(graph, positions.current, size.width, size.height);
if (simulation.current) updateGraphSimulation(sim, graph, positions.current, size.width, size.height);
simulation.current = sim.stop();
particles.current = new Map(sim.nodes().map((node) => [node.path, node]));
const nextLayout = JSON.stringify([graph.nodes.map((node) => node.path), graph.edges, size]);
settlement.current = reducedMotion && (layoutKey.current !== nextLayout || sim.alpha() > sim.alphaMin()) ? startGraphSettlement(sim) : null;
if (!reducedMotion && layoutKey.current !== nextLayout) sim.alpha(Math.max(sim.alpha(), 0.3));
layoutKey.current = nextLayout;
clock.current.geometry = true;
const key = `${size.width}:${size.height}`;
if (!interacted.current && graph.nodes.length && fittedSize.current !== key) {
const radius = Math.sqrt(graph.nodes.length * (60 * 0.36) ** 2 / Math.PI);
const k = Math.max(0.01, Math.min(1, (size.width - 100) / Math.max(1, radius * 6), (size.height - 80) / Math.max(1, radius * 6)));
setView({ k, x: size.width / 2 * (1 - k), y: size.height / 2 * (1 - k) });
fittedSize.current = key;
}
schedule();
}, [graph, size, reducedMotion, schedule, setView]);
useEffect(() => {
setActive((path) => path && currentNodes.has(path) ? path : null);
setHovered((path) => path && currentNodes.has(path) ? path : null);
}, [currentNodes]);
useEffect(() => {
setFrame(presentation.update(graph, highlighted));
schedule();
}, [graph, highlighted, presentation, schedule]);
useLayoutEffect(() => { clock.current.geometry = true; schedule(); }, [frame, schedule]);
useEffect(() => {
const element = container.current;
if (!element) return;
const wheel = (event: WheelEvent) => {
event.preventDefault(); interacted.current = true;
const rect = element.getBoundingClientRect();
const x = event.clientX - rect.left, y = event.clientY - rect.top, old = view.current;
const k = Math.max(0.25, Math.min(4, old.k * Math.exp(-event.deltaY * 0.002)));
setView({ k, x: x - (x - old.x) * k / old.k, y: y - (y - old.y) * k / old.k });
setActive(null);
};
element.addEventListener("wheel", wheel, { passive: false });
return () => element.removeEventListener("wheel", wheel);
}, [setView]);
const anchor = useRef({ getBoundingClientRect: () => new DOMRect() });
anchor.current.getBoundingClientRect = () => {
const rect = container.current?.getBoundingClientRect(), point = active ? positions.current.get(active) : undefined;
return new DOMRect((rect?.x ?? 0) + (point?.x ?? 0) * view.current.k + view.current.x - 22,
(rect?.y ?? 0) + (point?.y ?? 0) * view.current.k + view.current.y - 22, 44, 44);
};
const endDrag = (id: number, cancelled: boolean) => {
const drag = dragging.current;
if (!drag || drag.id !== id) return;
const particle = particles.current.get(drag.path);
if (particle) {
if (particle.fx != null) particle.x = particle.fx;
if (particle.fy != null) particle.y = particle.fy;
particle.fx = null; particle.fy = null;
clock.current.geometry = true;
}
simulation.current?.alphaTarget(0);
if (!cancelled && !drag.moved) setActive((path) => path === drag.path ? null : drag.path);
dragging.current = null;
schedule();
};
const nodeAt = (clientX: number, clientY: number, radius: number) => {
const rect = container.current?.getBoundingClientRect();
if (!rect) return null;
const x = clientX - rect.left, y = clientY - rect.top;
let closest: string | null = null;
let distance = Infinity;
for (let index = presentation.frame.nodes.length - 1; index >= 0; index--) {
const node = presentation.frame.nodes[index], point = positions.current.get(node.path);
if (!point || !currentNodes.has(node.path)) continue;
const candidateDistance = Math.hypot(point.x * view.current.k + view.current.x - x, point.y * view.current.k + view.current.y - y);
if (candidateDistance <= Math.max(radius, node.radius) && candidateDistance < distance) { closest = node.path; distance = candidateDistance; }
}
return closest;
};
useLayoutEffect(() => {
const update = () => { if (paletteProbe.current) palette.current = readGraphPalette(paletteProbe.current); schedule(); };
update();
const observer = new MutationObserver(update);
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style"] });
return () => observer.disconnect();
}, [schedule]);
const controls = useMemo(() => (<div className="sr-only">
{graph.nodes.map((node) => <button key={node.path} type="button" data-context-node={node.path} aria-label={node.name} aria-expanded={active === node.path} aria-haspopup="dialog"
ref={(element) => { if (element) nodeElements.current.set(node.path, element); else nodeElements.current.delete(node.path); }}
onFocus={(e) => { focused.current = e.currentTarget.matches(":focus-visible") ? node.path : null; setHovered(node.path); schedule(); }}
onKeyDown={() => { focused.current = node.path; schedule(); }}
onBlur={() => { focused.current = null; setHovered(null); schedule(); }}
onClick={() => setActive((path) => path === node.path ? null : node.path)}>{node.name}</button>)}
</div>), [graph.nodes, active, schedule]);
return <div ref={container} className={cn(surface, "relative isolate overflow-clip touch-none cursor-grab active:cursor-grabbing", sidebar ? "min-h-0 flex-1" : expanded ? "h-[min(65dvh,600px)]" : "h-[300px]")}
onPointerDown={(e) => {
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
if (e.button !== 0 || !e.isPrimary || (e.target instanceof Element && e.target.closest("button"))) return;
// Keep the node's managed focus. Touch compatibility mouse events would
// otherwise focus the drawer and immediately dismiss its node popover.
e.preventDefault();
interacted.current = true;
const path = nodeAt(e.clientX, e.clientY, e.pointerType === "mouse" ? 12 : 22);
if (path) {
nodeElements.current.get(path)?.focus({ preventScroll: true });
dragging.current = { id: e.pointerId, path, x: e.clientX, y: e.clientY, moved: false };
pan.current = null;
} else { pan.current = { id: e.pointerId, x: e.clientX, y: e.clientY }; setActive(null); }
e.currentTarget.setPointerCapture(e.pointerId);
}}
onPointerMove={(e) => {
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
const drag = dragging.current;
if (drag && drag.id === e.pointerId) {
const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
if (!drag.moved && Math.hypot(dx, dy) < 5) return;
drag.moved = true; drag.x = e.clientX; drag.y = e.clientY; setActive(null); setHovered(drag.path);
const particle = particles.current.get(drag.path);
if (particle) {
particle.fx = (particle.fx ?? particle.x) + dx / view.current.k; particle.fy = (particle.fy ?? particle.y) + dy / view.current.k;
if (reducedMotion) { particle.x = particle.fx; particle.y = particle.fy; clock.current.geometry = true; }
else simulation.current?.alphaTarget(0.25);
schedule();
}
} else if (pan.current?.id === e.pointerId) {
const old = view.current, previous = pan.current;
setView({ ...old, x: old.x + e.clientX - previous.x, y: old.y + e.clientY - previous.y });
pan.current = { id: e.pointerId, x: e.clientX, y: e.clientY };
} else if (e.pointerType === "mouse") setHovered(nodeAt(e.clientX, e.clientY, 12));
}}
onPointerLeave={() => { if (!dragging.current) setHovered(null); }}
onPointerUp={(e) => { endDrag(e.pointerId, false); if (pan.current?.id === e.pointerId) pan.current = null; }}
onPointerCancel={(e) => { endDrag(e.pointerId, true); if (pan.current?.id === e.pointerId) pan.current = null; }}
onLostPointerCapture={(e) => { endDrag(e.pointerId, true); if (pan.current?.id === e.pointerId) pan.current = null; }}
onDoubleClick={(e) => {
if (!(e.target instanceof Node) || !e.currentTarget.contains(e.target)) return;
if ((e.target instanceof Element && e.target.closest("button")) || nodeAt(e.clientX, e.clientY, 22)) return;
const points = [...particles.current.values()];
if (!points.length) return;
const xs = points.map((p) => p.x), ys = points.map((p) => p.y);
const left = Math.min(...xs), right = Math.max(...xs), top = Math.min(...ys), bottom = Math.max(...ys);
const k = Math.max(0.01, Math.min(1, (size.width - 140) / Math.max(1, right - left), (size.height - 110) / Math.max(1, bottom - top)));
interacted.current = false; setView({ k, x: size.width / 2 - (left + right) / 2 * k, y: (size.height + 22) / 2 - (top + bottom) / 2 * k });
}}>
<span ref={paletteProbe} aria-hidden className="invisible absolute bg-background text-muted-foreground" />
{onExpand && <button type="button" onClick={onExpand} aria-label={t(expanded ? "thread.composer.context.collapse" : "thread.composer.context.expand")}
className="absolute right-2 top-2 z-10 flex size-9 items-center justify-center rounded-full bg-background/90 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{expanded ? <Minimize2 size={15} /> : <Maximize2 size={15} />}
</button>}
{!graph.nodes.length && !frame.nodes.length && <p className="absolute inset-0 flex items-center justify-center px-6 text-center text-xs text-muted-foreground">{t("thread.composer.context.noFiles")}</p>}
<canvas ref={canvas} aria-hidden="true" className="absolute inset-0 size-full" />
{controls}
<Popover open={!!selected} onOpenChange={(open) => { if (!open) setActive(null); }}>
<PopoverAnchor virtualRef={anchor} />
{selected && <PopoverContent updatePositionStrategy="always" side="bottom" sideOffset={12} collisionPadding={12} onOpenAutoFocus={(e) => e.preventDefault()}
onEscapeKeyDown={() => { restoreNodeFocus.current = true; }}
onCloseAutoFocus={(e) => { e.preventDefault(); if (restoreNodeFocus.current) nodeElements.current.get(selected.path)?.focus(); restoreNodeFocus.current = false; }} onInteractOutside={(e) => { if (e.target instanceof Element && container.current?.contains(e.target) && e.target.closest("[data-context-node],canvas")) e.preventDefault(); }} className="flex w-auto select-none items-center gap-4 rounded-xl px-3 py-2.5 font-sans text-ui-label">
<span className="text-muted-foreground">{t(selected.state === "loaded" ? "thread.composer.context.loaded" : "thread.composer.context.unloaded")}</span>
{selected.state === "loaded" && <span className="tabular-nums text-muted-foreground">{t("thread.composer.context.estimatedNodeTokens", { value: formatCompactTokenCount(selected.tokens) })}</span>}
{onOpenFile && <button type="button" className="min-h-8 font-sans text-ui-label text-orange-600 dark:text-orange-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" onClick={() => onOpenFile(selected.path)}>{t("thread.composer.context.openFile")}</button>}
</PopoverContent>}
</Popover>
</div>;
});
@@ -0,0 +1,99 @@
import { lazy, Suspense, useCallback, useEffect, useId, useRef, useState } from "react";
import { LayoutGroup, motion, useReducedMotion } from "motion/react";
import { useTranslation } from "react-i18next";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { formatTurnLatency } from "@/lib/format-time";
import type { ContextGraph, ContextSnapshot } from "@/lib/types";
import type { ComposerContextUsage, ComposerRoundUsage } from "./ComposerUsagePopover";
import { ContextReplayButton } from "./ContextReplayButton";
const ContextGraphScene = lazy(() => import("./ContextGraphScene").then(module => ({ default: module.ContextGraphScene })));
const EMPTY_GRAPH: ContextGraph = { nodes: [], edges: [] };
const surface = "context-inspector-surface select-none rounded-[20px] bg-card";
export function ContextInspector({ context, rounds, snapshots, onOpenFile, sidebar = false, expandable = true }: {
context: ComposerContextUsage | null; rounds: readonly ComposerRoundUsage[];
snapshots: readonly ContextSnapshot[]; onOpenFile?: (path: string) => void; sidebar?: boolean; expandable?: boolean;
}) {
const { t, i18n } = useTranslation();
const layoutId = useId();
const reducedMotion = useReducedMotion();
const [expanded, setExpanded] = useState(false);
const [replay, setReplay] = useState<{ frames: readonly ContextSnapshot[]; index: number; startedAt: number; interval: number } | null>(null);
const [readyGraph, setReadyGraph] = useState<ContextGraph | null>(null);
const [meterHover, setMeterHover] = useState(false);
const epoch = snapshots[0]?.id;
useEffect(() => { setReplay(null); }, [epoch]);
useEffect(() => {
if (!replay || readyGraph !== replay.frames[replay.index].graph) return;
// Keep a shared timeline instead of adding rendering time to every step.
// Advance only after painting each snapshot, even when catching up.
const remaining = replay.startedAt + (replay.index + 1) * replay.interval - performance.now();
const timer = window.setTimeout(() => setReplay((current) => current && current.index + 1 < current.frames.length
? { ...current, index: current.index + 1 } : null), Math.max(0, remaining));
return () => window.clearTimeout(timer);
}, [replay, readyGraph]);
const snapshot = replay ? replay.frames[replay.index] : snapshots.at(-1);
const latestRound = rounds.at(-1);
const tokens = snapshot ? snapshot.estimatedTokens ?? snapshot.usage?.context_tokens ?? snapshot.usage?.prompt_tokens : context?.contextTokens;
const estimated = snapshot?.estimatedTokens !== undefined || (!snapshot?.usage && context?.estimated);
const windowTokens = snapshot?.contextWindowTokens ?? context?.contextWindowTokens;
const tokenNumbers = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 1 });
const hasTokenUsage = tokens !== undefined || !!windowTokens;
const used = tokens !== undefined && windowTokens ? Math.min(100, tokens / windowTokens * 100) : null;
const cached = snapshot ? snapshot.usage?.cached_tokens : latestRound?.cachedTokens;
const input = snapshot ? snapshot.usage?.prompt_tokens : latestRound?.inputTokens;
const cachedWidth = cached !== undefined && windowTokens ? Math.min(used ?? 0, cached / windowTokens * 100) : 0;
const duration = snapshot ? snapshot.usage?.generation_ms : latestRound?.generationMs;
const toggleExpanded = useCallback(() => setExpanded((value) => !value), []);
const openFileCallback = useRef(onOpenFile);
openFileCallback.current = onOpenFile;
const openFile = useCallback((path: string) => { setExpanded(false); openFileCallback.current?.(path); }, []);
const content = (large: boolean) => <motion.div layoutId={layoutId} transition={{ duration: reducedMotion ? 0 : 0.25, ease: [0.2, 0, 0, 1] }} className={cn("flex flex-col gap-3", sidebar && !large && "h-full min-h-0")}>
<Suspense fallback={<div aria-busy="true" className={cn(surface, "min-h-[300px]", sidebar && !large && "min-h-0 flex-1")} />}>
<ContextGraphScene graph={snapshot?.graph ?? EMPTY_GRAPH} epoch={epoch} onReady={setReadyGraph} expanded={large} sidebar={sidebar && !large} onExpand={expandable ? toggleExpanded : undefined} onOpenFile={onOpenFile ? openFile : undefined} />
</Suspense>
<div className="flex shrink-0 items-center gap-3">
<div onPointerEnter={() => setMeterHover(true)} onPointerLeave={() => setMeterHover(false)} className={cn(surface, "relative flex h-14 min-w-0 flex-1 items-center gap-4 px-4 transition-transform duration-150 ease-out motion-reduce:transition-none", meterHover && "scale-[1.015]")}>
<div className="flex h-11 flex-1 items-center">
<div role="progressbar" aria-label={t("thread.composer.context.contextTitle")} aria-valuemin={0} aria-valuemax={100} aria-valuenow={used === null ? undefined : Math.round(used)} className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
<span className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground/45 transition-[width] duration-150 ease-out motion-reduce:transition-none" style={{ width: `${used ?? 0}%` }} />
<span className="absolute inset-y-0 left-0 rounded-full bg-orange-500 transition-[width] duration-150 ease-out motion-reduce:transition-none" style={{ width: `${cachedWidth}%` }} />
</div>
</div>
<span className="text-sm tabular-nums">{used === null ? "—" : `${estimated ? "≈" : ""}${Math.round(used)}%`}</span>
{meterHover && (hasTokenUsage || cached !== undefined || duration !== undefined || replay !== null) && <div className="pointer-events-none absolute bottom-full right-0 z-20 mb-2 min-w-48 rounded-xl bg-popover px-3 py-2.5 font-sans text-xs font-normal leading-5 shadow-lg">
<dl className="grid grid-cols-[auto_auto] items-baseline gap-x-6 gap-y-1">
{hasTokenUsage && <><dt className="whitespace-nowrap text-muted-foreground">{t("thread.composer.context.panelTitle")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{t("thread.composer.context.tokenUsage", {
used: tokens === undefined ? "—" : `${estimated ? "≈" : ""}${tokenNumbers.format(tokens / 1000)}k`,
limit: windowTokens ? `${tokenNumbers.format(windowTokens / 1000)}k` : "—",
})}</dd></>}
{cached !== undefined && !!input && <><dt className="text-muted-foreground">{t("thread.composer.context.cacheHitRate")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{Math.round(cached / input * 100)}%</dd></>}
{duration !== undefined && <><dt className="text-muted-foreground">{t("thread.composer.context.duration")}</dt><dd className="whitespace-nowrap text-right tabular-nums text-popover-foreground">{formatTurnLatency(duration)}</dd></>}
{replay && <><dt className="text-muted-foreground">{t("thread.composer.context.history")}</dt>
<dd className="text-right tabular-nums text-muted-foreground">{replay.index + 1}/{replay.frames.length}</dd></>}
</dl>
</div>}
</div>
<ContextReplayButton disabled={replay !== null || snapshots.length < 2}
onPlay={() => {
setMeterHover(false);
// Scale by request count: our replay unit is a snapshot, not a graph edge.
const stepsPerSecond = Math.min(20, Math.max(5, 0.5 * Math.sqrt(snapshots.length)));
setReplay({ frames: [...snapshots], index: 0, startedAt: performance.now(), interval: 1000 / stepsPerSecond });
}} />
</div>
</motion.div>;
return <LayoutGroup>
{!expanded && content(false)}
<Dialog open={expanded} onOpenChange={setExpanded}>
<DialogContent showCloseButton={false} aria-describedby={undefined} overlayClassName="context-expanded-overlay bg-background/30 backdrop-blur-md" className="w-[min(960px,calc(100vw-2rem))] max-w-none border-0 bg-transparent p-0 shadow-none !animate-none">
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
{content(true)}
</DialogContent>
</Dialog>
</LayoutGroup>;
}
@@ -0,0 +1,12 @@
import { RotateCcw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { HoverHint } from "@/components/ui/tooltip";
export function ContextReplayButton({ disabled, onPlay }: { disabled: boolean; onPlay: () => void }) {
const { t } = useTranslation();
const label = t("thread.composer.context.playHistory");
return <HoverHint content={label} side="top" enabled={!disabled}><button type="button" aria-label={label} disabled={disabled} onClick={onPlay}
className="context-inspector-surface grid size-14 shrink-0 place-items-center rounded-[20px] bg-card text-foreground/80 transition-colors enabled:hover:bg-muted enabled:hover:text-orange-500 disabled:cursor-default disabled:text-foreground/45 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<RotateCcw className="size-[18px]" strokeWidth={2.25} aria-hidden="true" />
</button></HoverHint>;
}
+62 -27
View File
@@ -1,17 +1,12 @@
import {
PromptNavigationIcon,
} from "@/components/icons/product-icons";
import { useMemo, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Search } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { SearchInput } from "@/components/ui/input";
import {
Sheet,
SheetContent,
SheetTitle,
} from "@/components/ui/sheet";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import {
type PromptAnchor,
userPromptAnchors,
@@ -24,14 +19,16 @@ interface PromptNavigatorProps {
messages: UIMessage[];
prompts?: PromptAnchor[];
onJumpToPrompt: (promptId: string) => void;
shortcutEnabled?: boolean;
}
const ROW_HEIGHT = 88;
const ROW_HEIGHT = 64;
export function PromptNavigator({
messages,
prompts: suppliedPrompts,
onJumpToPrompt,
shortcutEnabled = true,
}: PromptNavigatorProps) {
const { i18n, t } = useTranslation();
const prompts = useMemo(() => suppliedPrompts ?? userPromptAnchors(messages), [suppliedPrompts, messages]);
@@ -39,6 +36,23 @@ export function PromptNavigator({
const [query, setQuery] = useState("");
const listRef = useRef<HTMLDivElement>(null);
const [listTop, setListTop] = useState(0);
const [highlighted, setHighlighted] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
const keyDown = (event: KeyboardEvent) => {
if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing
|| event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return;
if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || document.querySelector("[role=dialog][data-state=open]"))) return;
event.preventDefault();
setListTop(0); setOpen(true);
inputRef.current?.focus(); inputRef.current?.select();
};
window.addEventListener("keydown", keyDown);
return () => window.removeEventListener("keydown", keyDown);
}, [shortcutEnabled, prompts.length, open]);
useEffect(() => { if (open) { setQuery(""); setHighlighted(0); setListTop(0); } }, [open]);
const filteredPrompts = useMemo(() => {
const needle = query.trim().toLocaleLowerCase();
@@ -60,6 +74,7 @@ export function PromptNavigator({
return (
<>
<Button
ref={triggerRef}
type="button"
variant="ghost"
size="icon"
@@ -68,41 +83,53 @@ export function PromptNavigator({
"hover:text-foreground",
)}
aria-label={t("thread.promptNavigator.open")}
aria-keyshortcuts="Control+F Meta+F"
onClick={() => { setListTop(0); setOpen(true); }}
>
<PromptNavigationIcon className="h-4 w-4" />
</Button>
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent
side="right"
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent
showCloseButton={false}
aria-describedby={undefined}
className="w-[min(92vw,24rem)] gap-0 p-0 sm:max-w-[24rem]"
onOpenAutoFocus={(event) => { event.preventDefault(); inputRef.current?.focus(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}
className="session-search-dialog flex max-h-[min(40rem,100%)] w-[calc(100vw-2rem)] max-w-[42rem] flex-col gap-0 overflow-hidden p-0"
>
<div className="border-b px-5 pb-4 pt-5">
<SheetTitle className="text-base font-medium">
<DialogTitle className="sr-only">
{t("thread.promptNavigator.title")}
</SheetTitle>
<div className="relative mt-4">
</DialogTitle>
<div className="session-search-input flex h-[62px] shrink-0 items-center gap-3 border-b border-border px-[18px]">
<Search
aria-hidden
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
className="h-[18px] w-[18px] shrink-0 text-muted-foreground"
/>
<SearchInput
<input
ref={inputRef}
value={query}
onChange={(event) => {
setQuery(event.target.value);
setListTop(0);
setHighlighted(0);
if (listRef.current) listRef.current.scrollTop = 0;
}}
aria-label={t("thread.promptNavigator.search")}
placeholder={t("thread.promptNavigator.search")}
className="h-10 rounded-full border-border bg-background pl-9 pr-3 text-sm transition-colors"
onKeyDown={(event) => {
if (event.key === "Enter" && filteredPrompts[highlighted]) { event.preventDefault(); jump(filteredPrompts[highlighted].id); }
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && filteredPrompts.length) {
event.preventDefault();
const next = (highlighted + (event.key === "ArrowDown" ? 1 : -1) + filteredPrompts.length) % filteredPrompts.length;
setHighlighted(next);
if (listRef.current) { listRef.current.scrollTop = next * ROW_HEIGHT; setListTop(next * ROW_HEIGHT); }
}
}}
className="h-full min-w-0 flex-1 bg-transparent text-[19px] font-normal leading-none text-foreground outline-none placeholder:text-muted-foreground"
/>
</div>
</div>
<div ref={listRef} className="min-h-0 flex-1 overflow-y-auto px-2 py-2"
<div ref={listRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent"
onScroll={(event) => setListTop(event.currentTarget.scrollTop)}
onKeyDown={(event) => {
const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-prompt-row]");
@@ -125,6 +152,8 @@ export function PromptNavigator({
<PromptNavigatorRow
key={prompt.id}
row={firstRow + offset}
highlighted={highlighted === firstRow + offset}
onHighlight={() => setHighlighted(firstRow + offset)}
locale={i18n.resolvedLanguage || i18n.language}
prompt={prompt}
onJump={jump}
@@ -137,8 +166,8 @@ export function PromptNavigator({
</div>
)}
</div>
</SheetContent>
</Sheet>
</DialogContent>
</Dialog>
</>
);
}
@@ -148,6 +177,8 @@ interface PromptNavigatorRowProps {
locale: string;
onJump: (promptId: string) => void;
prompt: PromptAnchor;
highlighted: boolean;
onHighlight: () => void;
}
function PromptNavigatorRow({
@@ -155,6 +186,8 @@ function PromptNavigatorRow({
locale,
onJump,
prompt,
highlighted,
onHighlight,
}: PromptNavigatorRowProps) {
const { t } = useTranslation();
const timestamp = fmtDateTime(prompt.createdAt, locale);
@@ -163,17 +196,19 @@ function PromptNavigatorRow({
type="button"
data-prompt-row={row}
className={cn(
"h-[88px] w-full overflow-hidden rounded-control px-3 py-3 text-left transition",
"hover:bg-accent focus-visible:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",
"h-16 w-full overflow-hidden rounded-control px-3 py-2 text-left transition-colors",
"hover:bg-muted focus-visible:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",
highlighted && "bg-muted",
)}
aria-label={t("thread.promptNavigator.jumpTo", { label: prompt.label })}
onClick={() => onJump(prompt.id)}
onMouseEnter={onHighlight}
>
<div className="line-clamp-2 whitespace-pre-wrap break-words text-sm leading-5 text-foreground">
<div className="truncate text-[14px] font-medium leading-5 text-foreground">
{prompt.preview}
</div>
{timestamp ? (
<div className="mt-1 text-[10px] leading-4 text-muted-foreground/75">
<div className="mt-1 text-[12px] leading-4 text-muted-foreground">
{timestamp}
</div>
) : null}
@@ -11,16 +11,15 @@ interface SessionInfoPopoverProps {
client: WebUIMutationTransport;
sessionKey: string;
token: string;
title: string;
}
export function SessionInfoPopover({ client, sessionKey, token, title }: SessionInfoPopoverProps) {
export function SessionInfoPopover({ client, sessionKey, token }: SessionInfoPopoverProps) {
const [surfacesOpen, setSurfacesOpen] = useState(false);
const { jobs, loading, loadFailed, now } = useSessionAutomationJobs(surfacesOpen, token, sessionKey);
const act = useCallback(async (action: AutomationAction, job: SessionAutomationJob) =>
(await runAutomationAction(client, action, job.id)).jobs, [client]);
const edit = useCallback(async (job: SessionAutomationJob, values: AutomationUpdatePayload) =>
(await updateAutomation(client, job.id, values)).jobs, [client]);
return <SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}
return <SessionInfoPopoverView jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}
onAction={act} onEdit={edit} onSurfacesOpenChange={setSurfacesOpen} calendarHref="#/automations" />;
}
@@ -49,9 +49,8 @@ const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
[Number.POSITIVE_INFINITY, "year"],
];
export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now, onAction, onEdit,
export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onAction, onEdit,
onSurfacesOpenChange, calendarHref, onOpenCalendar }: {
title: string;
jobs: SessionAutomationJob[];
loading: boolean;
loadFailed: boolean;
@@ -201,16 +200,7 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,
>
<div className="flex max-h-[min(var(--radix-popover-content-available-height),32rem)] flex-col">
<div className="px-4 pb-3 pt-3.5">
<div className="min-w-0">
<div className="text-[12px] font-normal text-muted-foreground/75">
{t("thread.sessionInfo.title")}
</div>
<div className="mt-0.5 truncate text-[14px] font-medium text-foreground">
{title || t("thread.sessionInfo.untitled")}
</div>
</div>
<div className="mt-3 flex items-center justify-between gap-3 border-t border-border/45 pt-3">
<div className="flex items-center justify-between gap-3">
<span className="truncate text-[13px] font-medium text-foreground">
{t("thread.sessionInfo.automations")}
</span>
@@ -157,8 +157,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
{children}
<Sheet open={!!selected} onOpenChange={(open) => { if (!open) setSelectedId(null); }}>
<SheetContent ref={detailPanel} tabIndex={-1}
className="w-full gap-0 overflow-hidden border-l p-0 outline-none sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"
overlayClassName="bg-black/20 backdrop-blur-[8px]"
className="w-[calc(100vw-1rem)] gap-0 p-0 sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"
closeButtonClassName="right-2 top-2 grid h-11 w-11 place-items-center rounded-full sm:right-3 sm:top-3 sm:h-9 sm:w-9"
onOpenAutoFocus={(event) => {
event.preventDefault();
+16 -4
View File
@@ -241,6 +241,11 @@ interface ThreadComposerProps {
onManageModels?: () => void;
contextUsage?: ComposerContextUsage | null;
recentRoundUsage?: readonly ComposerRoundUsage[];
contextSnapshots?: readonly import("@/lib/types").ContextSnapshot[];
onOpenContextFile?: (path: string) => void;
contextSidebarHost?: HTMLElement | null;
contextSidebarOpen?: boolean;
onContextSidebarOpenChange?: (open: boolean) => void;
variant?: "thread" | "hero";
slashCommands?: SlashCommand[];
onMentionSearch?: () => void;
@@ -1080,6 +1085,11 @@ export function ThreadComposer({
onManageModels,
contextUsage = null,
recentRoundUsage = [],
contextSnapshots = [],
onOpenContextFile,
contextSidebarHost,
contextSidebarOpen,
onContextSidebarOpenChange,
variant = "thread",
slashCommands = [],
onMentionSearch,
@@ -1169,6 +1179,7 @@ export function ThreadComposer({
const formRef = useRef<HTMLFormElement>(null);
const tabFocusRequested = useRef(false);
const [compactControls, setCompactControls] = useState(false);
const [usageTriggerHost, setUsageTriggerHost] = useState<HTMLSpanElement | null>(null);
useEffect(() => {
// Automatic session focus should not open the hint; keyboard navigation should.
@@ -2588,8 +2599,8 @@ export function ThreadComposer({
/>
) : null;
const usageInMeta = mobileWorkspaceControls || compactControls;
const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length) ? (
<ComposerUsagePopover context={contextUsage} rounds={recentRoundUsage} showLabel={usageInMeta} compactLabel={mobileWorkspaceControls} bottomSheet={usageInMeta} />
const usageControl = !voiceRecorder.isRecording && (contextUsage || recentRoundUsage.length || contextSnapshots.length) ? (
<ComposerUsagePopover triggerHost={usageTriggerHost} context={contextUsage} rounds={recentRoundUsage} snapshots={contextSnapshots} onOpenFile={onOpenContextFile} showLabel={usageInMeta} compactLabel={mobileWorkspaceControls} sidebarHost={contextSidebarHost} open={contextSidebarOpen} onOpenChange={onContextSidebarOpenChange} />
) : null;
const inputTextClasses = cn(
// Keep the overlay's CJK/Latin spacing aligned with the native textarea caret.
@@ -2904,7 +2915,7 @@ export function ThreadComposer({
)}
>
{modelControl}
{!usageInMeta ? usageControl : null}
{!usageInMeta && usageControl ? <span className="contents" ref={setUsageTriggerHost} /> : null}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
@@ -2981,12 +2992,13 @@ export function ThreadComposer({
</div>
{usageInMeta && usageControl || mobileWorkspaceControls && accessControl ? (
<div className={cn("ml-auto flex shrink-0 items-center gap-1", mobileWorkspaceControls && "h-11 max-w-[calc(100%-3rem)]")}>
{usageInMeta ? usageControl : null}
{usageInMeta && usageControl ? <span className="contents" ref={setUsageTriggerHost} /> : null}
{mobileWorkspaceControls ? accessControl : null}
</div>
) : null}
</div>
) : null}
{usageControl}
</form>
);
}
@@ -466,7 +466,7 @@ function MessageBlockMenu({
data-message-block-menu data-message-mobile-sheet data-message-context-menu-block={contextBlockKey}
className="gap-2 p-4 pt-5 pb-[max(1rem,env(safe-area-inset-bottom))] outline-none"
onCloseAutoFocus={(event) => { if (activity?.expanded) event.preventDefault(); }}>
<DialogTitle className="px-2 pb-2 pe-10 text-sm font-medium text-muted-foreground">{label}</DialogTitle>
<DialogTitle className="px-2 pb-2 text-sm font-medium text-muted-foreground">{label}</DialogTitle>
{actions}
</DialogContent>
</Dialog>
+80 -18
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
import type { CSSProperties, PointerEvent as ReactPointerEvent, ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request";
@@ -76,13 +76,16 @@ import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { providerDisplayLabel } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
import { composerContextSnapshots } from "@/lib/context-graph";
import { useClient } from "@/providers/ClientProvider";
function latestComposerContextUsage(messages: ComposerUsageSnapshot[]): ComposerContextUsage | null {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message.compacted) {
return null;
return message.estimatedContextTokens !== undefined
? { contextTokens: message.estimatedContextTokens, contextWindowTokens: message.contextWindowTokens, estimated: true }
: null;
}
const contextTokens = message.usage?.context_tokens;
if (
@@ -107,6 +110,7 @@ function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRo
const seenTurns = new Set<string>();
for (let index = messages.length - 1; index >= 0 && recent.length < 8; index -= 1) {
const message = messages[index];
if (message.compacted) break;
const turnKey = message.turnId || message.id;
if (seenTurns.has(turnKey)) {
continue;
@@ -126,23 +130,13 @@ function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRo
) {
continue;
}
const outputTokens = round.completion_tokens;
const cachedTokens = round.cached_tokens;
const estimatedTokens = round.estimated_tokens;
const generationMs = round.generation_ms;
recent.push({
id: `${turnKey}:${roundIndex}`,
timestamp: message.completedAt ?? message.createdAt,
inputTokens,
...(typeof outputTokens === "number" && Number.isFinite(outputTokens)
? { outputTokens }
: {}),
...(typeof cachedTokens === "number" && Number.isFinite(cachedTokens)
? { cachedTokens }
: {}),
...(typeof estimatedTokens === "number" && Number.isFinite(estimatedTokens)
? { estimatedTokens }
: {}),
...(typeof generationMs === "number" && Number.isFinite(generationMs)
? { generationMs }
: {}),
@@ -540,11 +534,36 @@ export function ThreadShell({
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
const { state: previewState, openFile, resolveFile, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
useFilePreviewState(previewSessionKey, filePreviewStore);
const [contextSidebarOpen, setContextSidebarOpen] = useState(false);
const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0);
const [contextSidebarHost, setContextSidebarHost] = useState<HTMLElement | null>(null);
const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []);
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey;
const visiblePreview = filePreviewClosing ? closingPreview.state : previewState;
const activePreview = visiblePreview.tabs.find((tab) => tab.id === visiblePreview.activeId);
const previewOpen = Boolean(activePreview);
const sidebarOpen = previewOpen || contextSidebarOpen;
const [localComposerHost, setLocalComposerHost] = useState<HTMLDivElement | null>(null);
const [composerMount] = useState(() => document.createElement("div"));
const inlineComposer = composerPortalTarget === undefined || (sidebarOpen && composerActive);
const composerDestination = inlineComposer ? localComposerHost : composerPortalTarget;
useLayoutEffect(() => {
// The inline host ref arrives on the next render. Keep the focused input
// attached until that destination is ready.
if (!composerDestination) { if (!inlineComposer) composerMount.remove(); return; }
if (composerMount.parentElement === composerDestination) return;
// Move the host, not the React subtree: drafts, graph replay and exit presence survive.
const focused = document.activeElement instanceof HTMLElement && composerMount.contains(document.activeElement)
? document.activeElement : null;
const selection = document.getSelection();
const range = focused && selection?.rangeCount && composerMount.contains(selection.getRangeAt(0).commonAncestorContainer)
? selection.getRangeAt(0).cloneRange() : null;
composerDestination.appendChild(composerMount);
focused?.focus({ preventScroll: true });
if (range && selection) { selection.removeAllRanges(); selection.addRange(range); }
}, [composerDestination, composerMount, inlineComposer]);
useLayoutEffect(() => () => composerMount.remove(), [composerMount]);
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");
@@ -560,6 +579,23 @@ export function ThreadShell({
const shellRef = useRef<HTMLElement | null>(null);
const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);
const composerSurfaceRef = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const shell = contextSidebarHost;
const surface = composerSurfaceRef.current;
if (!sidebarOpen || !inlineComposer || !shell || !surface) return;
// Metadata can wrap below the input card. Align sidebars to the visible
// surface, rather than assuming a fixed composer/footer padding.
const alignSidebar = () => {
const inset = shell.getBoundingClientRect().bottom - surface.getBoundingClientRect().bottom;
shell.style.setProperty("--sidebar-bottom-inset", `${Math.max(0, inset)}px`);
};
alignSidebar();
const observer = new ResizeObserver(alignSidebar);
observer.observe(shell);
observer.observe(composerMount);
observer.observe(surface);
return () => observer.disconnect();
}, [contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount]);
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
const filePreviewCloseTimerRef = useRef<number | null>(null);
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
@@ -704,6 +740,9 @@ export function ThreadShell({
() => recentComposerRoundUsage(usageSnapshots),
[usageSnapshots],
);
const contextGraphSnapshots = useMemo(
() => composerContextSnapshots(messages, modelRequests), [messages, modelRequests],
);
const currentGoalState = messagesReady ? goalState : undefined;
// Recovery decisions gate queued input, not the ledger-owned run state.
const recoveryNeedsDecision = recoveryState?.status === "awaiting_user"
@@ -1132,10 +1171,20 @@ export function ThreadShell({
}, []);
const handleOpenFilePreview = useCallback((path: string) => {
setSidebarEnterWidth(shellRef.current?.querySelector(".file-preview-pane")?.getBoundingClientRect().width ?? 0);
setContextSidebarOpen(false);
cancelPreviewClose();
openFile(path);
}, [cancelPreviewClose, openFile]);
const handleContextSidebarOpenChange = useCallback((open: boolean) => {
if (open) {
setSidebarEnterWidth(previewOpen ? filePreviewWidth : 0);
cancelPreviewClose(); closePreview();
}
setContextSidebarOpen(open);
}, [previewOpen, filePreviewWidth, cancelPreviewClose, closePreview]);
const handleClosePreviewTab = useCallback((id: string) => {
if (previewState.tabs.length === 1) handleCloseFilePreview();
else {
@@ -1325,7 +1374,13 @@ export function ThreadShell({
onManageModels={onOpenModelSettings}
contextUsage={composerContextUsage}
recentRoundUsage={composerRoundUsage}
contextSnapshots={contextGraphSnapshots}
onOpenContextFile={handleOpenFilePreview}
contextSidebarHost={contextSidebarHost}
contextSidebarOpen={contextSidebarOpen}
onContextSidebarOpenChange={handleContextSidebarOpenChange}
variant={composerVariant}
surfaceRef={composerSurfaceRef}
slashCommands={availableSlashCommands}
onMentionSearch={requestMentionCatalogs}
cliApps={cliApps}
@@ -1379,6 +1434,11 @@ export function ThreadShell({
onManageModels={onOpenModelSettings}
contextUsage={composerContextUsage}
recentRoundUsage={composerRoundUsage}
contextSnapshots={contextGraphSnapshots}
onOpenContextFile={handleOpenFilePreview}
contextSidebarHost={contextSidebarHost}
contextSidebarOpen={contextSidebarOpen}
onContextSidebarOpenChange={handleContextSidebarOpenChange}
variant="hero"
slashCommands={availableSlashCommands}
onMentionSearch={requestMentionCatalogs}
@@ -1420,10 +1480,11 @@ export function ThreadShell({
</div>
);
const sessionInfoAction = historyKey ? (
<SessionInfoPopover client={client} sessionKey={historyKey} token={token} title={title} />
<SessionInfoPopover client={client} sessionKey={historyKey} token={token} />
) : undefined;
const promptNavigatorAction = historyKey ? (
<PromptNavigator
shortcutEnabled={composerActive}
messages={displayMessages}
prompts={promptNavigation.prompts}
onJumpToPrompt={(promptId) => viewportRef.current?.jumpToUserPrompt(promptId)}
@@ -1460,7 +1521,7 @@ export function ThreadShell({
historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}
active={composerActive}
enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
<section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
<section ref={setSidebarHost} style={{ "--sidebar-enter-width": `${sidebarEnterWidth}px`, "--sidebar-enter-mobile-width": sidebarEnterWidth ? "100%" : "0px" } as CSSProperties} data-preview-open={sidebarOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
<div ref={setConversationElement} className={cn(
"thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",
headerPortalTarget === undefined && !hideHeader && "thread-workspace",
@@ -1496,7 +1557,7 @@ export function ThreadShell({
retryStatus={retryStatus}
emptyState={emptyState}
initialLoading={initialHistoryLoading}
composer={composerPortalTarget === undefined ? composer : null}
composer={inlineComposer ? <div ref={setLocalComposerHost} /> : null}
activeTurnId={viewportTurnId}
activeTurnStartedHere={activeTurnStartedHere}
conversationKey={historyKey}
@@ -1523,16 +1584,17 @@ export function ThreadShell({
{headerPortalTarget && headerActive
? createPortal(threadHeader, headerPortalTarget)
: null}
{composerPortalTarget ? createPortal(
{createPortal(
<div
hidden={!composerActive}
aria-hidden={!composerActive}
data-testid={composerActive ? "active-pane-composer" : undefined}
data-active-composer={composerActive || undefined}
>
{composer}
</div>,
composerPortalTarget,
) : null}
composerMount,
)}
{activePreview && previewSessionKey ? (
<FileActionsProvider key={previewSessionKey} value={fileActions}>
<PreviewPane
@@ -1,3 +1,4 @@
import { surfaceFocusProps } from "@/lib/surface-focus";
import { FullAccessIcon, RestrictedAccessIcon, WorkspaceIcon } from "@/components/icons/product-icons";
import type { HTMLAttributes, ReactElement, RefObject } from "react";
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -636,8 +637,8 @@ export function WorkspaceProjectPicker({ disabled, scope, defaultScope, controls
</nav>}
<div className={cn("mr-[var(--picker-toolbar-inset)] flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[var(--picker-field-radius)] bg-[#fcfcfc] dark:bg-muted", compact && showLocations && canBrowse && "hidden")}>
<div ref={attachColumns} data-workspace-columns className="sidebar-scrollbar flex flex-1 min-h-0 min-w-0 overflow-x-auto overscroll-x-contain">
{columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && <WorkspaceDirectoryColumn key={columnIndex} options={column.options} selectedPath={column.selectedPath} initialScrollTop={previewingPath ? 0 : currentVisit.scrollTops[columnIndex] ?? 0} visitRevision={history.revision} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}
id={`${optionsId}-${columnIndex}`} data-workspace-column={columnIndex} data-current-directory={columnIndex === currentColumnIndex ? "" : undefined} role="listbox" tabIndex={0} aria-activedescendant={highlightActive && columnIndex === activeColumn && column.options.length ? `${optionsId}-${columnIndex}-${activeOption}` : undefined} aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === currentColumnIndex && loading} style={{ width: `${compact ? 100 : 100 / columnCount}%` }} className="sidebar-scrollbar relative min-w-0 shrink-0 overflow-x-hidden overflow-y-auto px-2 outline-none [scrollbar-gutter:stable] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50"
{columns.map((column, columnIndex) => (!compact || columnIndex === currentColumnIndex) && <WorkspaceDirectoryColumn key={columnIndex} {...surfaceFocusProps} options={column.options} selectedPath={column.selectedPath} initialScrollTop={previewingPath ? 0 : currentVisit.scrollTops[columnIndex] ?? 0} visitRevision={history.revision} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}
id={`${optionsId}-${columnIndex}`} data-workspace-column={columnIndex} data-current-directory={columnIndex === currentColumnIndex ? "" : undefined} role="listbox" tabIndex={0} aria-activedescendant={highlightActive && columnIndex === activeColumn && column.options.length ? `${optionsId}-${columnIndex}-${activeOption}` : undefined} aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === currentColumnIndex && loading} style={{ width: `${compact ? 100 : 100 / columnCount}%` }} className="sidebar-scrollbar relative min-w-0 shrink-0 overflow-x-hidden overflow-y-auto px-2 outline-none [scrollbar-gutter:stable] data-[keyboard-focus]:ring-2 data-[keyboard-focus]:ring-inset data-[keyboard-focus]:ring-ring/50"
onFocus={event => { if (event.target === event.currentTarget) { setActiveColumn(columnIndex); setActiveIndex(0); } }}
onKeyDown={event => {
if (event.target !== event.currentTarget || event.altKey || event.metaKey || event.ctrlKey || pickingFolder) return;
@@ -0,0 +1,94 @@
import type { GraphPosition } from "@/lib/context-graph-layout";
import type { GraphPresentation } from "./graph-presentation";
type RGB = readonly [number, number, number];
export interface GraphPalette { background: RGB; foreground: string; muted: RGB; font: string; labels: Map<string, string> }
interface GraphCamera { x: number; y: number; k: number }
const orange: RGB = [249, 115, 22];
const blend = (a: RGB, b: RGB, amount: number): RGB => [a[0] + (b[0] - a[0]) * amount, a[1] + (b[1] - a[1]) * amount, a[2] + (b[2] - a[2]) * amount];
const rgb = (value: RGB) => `rgb(${value.map(Math.round).join(" ")})`;
export function readGraphPalette(element: HTMLElement): GraphPalette {
const style = getComputedStyle(element);
const parse = (color: string): RGB => {
const values = color.match(/[\d.]+/g)?.map(Number) ?? [];
return [values[0] ?? 0, values[1] ?? 0, values[2] ?? 0];
};
return { background: parse(style.backgroundColor), muted: parse(style.color), foreground: getComputedStyle(element.parentElement!).color, font: `10px ${style.fontFamily}`, labels: new Map() };
}
export function fitGraphLabel(name: string, measure: (text: string) => number, maxWidth = 128): string {
if (measure(name) <= maxWidth) return name;
const characters = Array.from(name);
let start = 0, end = characters.length;
while (start < end) {
const middle = Math.ceil((start + end) / 2);
if (measure(`${characters.slice(0, middle).join("")}…`) <= maxWidth) start = middle;
else end = middle - 1;
}
return `${characters.slice(0, start).join("")}…`;
}
/** One bitmap paint; neither force ticks nor camera movement mutate per-node DOM. */
export function paintGraph(context: CanvasRenderingContext2D, frame: GraphPresentation, positions: ReadonlyMap<string, GraphPosition>,
view: GraphCamera, palette: GraphPalette, highlighted: string | null, focused: string | null,
width: number, height: number, pixelRatio: number, discovered: ReadonlySet<string>) {
context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
context.clearRect(0, 0, width, height);
const groups = new Map<string, { opacity: number; dashed: boolean; edges: GraphPresentation["edges"] }>();
for (const edge of frame.edges) {
const opacity = edge.presence * edge.emphasis * 0.7;
const dashed = discovered.has(edge.target);
const key = `${opacity}:${dashed}`;
let group = groups.get(key);
if (!group) { group = { opacity, dashed, edges: [] }; groups.set(key, group); }
group.edges.push(edge);
}
context.strokeStyle = "#f97316";
context.lineWidth = 1;
for (const group of groups.values()) {
context.globalAlpha = group.opacity;
context.setLineDash(group.dashed ? [3, 5] : []);
context.beginPath();
for (const edge of group.edges) {
const a = positions.get(edge.source), b = positions.get(edge.target);
if (!a || !b) continue;
context.moveTo(a.x * view.k + view.x, a.y * view.k + view.y);
context.lineTo(b.x * view.k + view.x, b.y * view.k + view.y);
}
context.stroke();
}
context.setLineDash([]);
context.font = palette.font;
context.textAlign = "center";
context.textBaseline = "middle";
for (const node of frame.nodes) {
const point = positions.get(node.path);
if (!point) continue;
const x = point.x * view.k + view.x, y = point.y * view.k + view.y;
const alpha = node.presence * node.emphasis;
const color = blend(palette.muted, orange, node.focus);
context.globalAlpha = alpha;
context.strokeStyle = rgb(color);
context.fillStyle = rgb(blend(palette.background, color, node.loaded));
context.beginPath(); context.arc(x, y, node.radius - 0.5, 0, Math.PI * 2); context.fill(); context.stroke();
if (node.path === focused) {
context.strokeStyle = palette.foreground;
context.lineWidth = 2;
context.beginPath(); context.roundRect(x - 22, y - 22, 44, 44, 4); context.stroke();
context.lineWidth = 1;
}
// Introduce newly loaded files for one second, then fade to the usual zoom visibility.
const labelOpacity = node.path === highlighted ? 1 : Math.max(0, Math.min(1, (view.k - 1) / 3.75), Math.min(1, node.labelRemaining / 600));
if (labelOpacity > 0) {
context.globalAlpha = alpha * labelOpacity;
context.fillStyle = palette.foreground;
let label = palette.labels.get(node.name);
if (label === undefined) {
label = fitGraphLabel(node.name, (text) => context.measureText(text).width);
palette.labels.set(node.name, label);
}
context.fillText(label, x, y + 24);
}
}
context.globalAlpha = 1;
}
@@ -0,0 +1,77 @@
import { nodeRadius } from "@/lib/context-graph-layout";
import type { ContextGraph, ContextGraphNode } from "@/lib/types";
type PresentedNode = ContextGraphNode & { presence: number; emphasis: number; focus: number; radius: number; loaded: number; labelRemaining: number };
type PresentedEdge = ContextGraph["edges"][number] & { presence: number; emphasis: number };
export type GraphPresentation = { nodes: PresentedNode[]; edges: PresentedEdge[] };
const edgeKey = (edge: ContextGraph["edges"][number]) => JSON.stringify([edge.source, edge.target]);
/** Mutable animation state; request graphs remain immutable. The caller owns its clock. */
export function createGraphPresentation() {
const nodes = new Map<string, PresentedNode>();
const edges = new Map<string, PresentedEdge>();
let wanted = new Set<string>();
let wantedEdges = new Set<string>();
let related = new Set<string | null>();
let highlighted: string | null = null;
let frame: GraphPresentation = { nodes: [], edges: [] };
let moving = false;
return {
get frame() { return frame; },
update(graph: ContextGraph, focus: string | null) {
highlighted = focus;
const previouslyWanted = wanted;
wanted = new Set(graph.nodes.map((node) => node.path));
wantedEdges = new Set(graph.edges.map(edgeKey));
related = new Set([focus]);
for (const edge of graph.edges) {
if (edge.source === focus) related.add(edge.target);
if (edge.target === focus) related.add(edge.source);
}
for (const node of graph.nodes) {
const previous = nodes.get(node.path);
if (previous) {
if (node.state !== "loaded") previous.labelRemaining = 0;
// A replay can reintroduce a node before its exit animation removes it.
else if (previous.state !== "loaded" || !previouslyWanted.has(node.path)) previous.labelRemaining = 1600;
Object.assign(previous, node);
}
else nodes.set(node.path, { ...node, presence: 0, emphasis: 1, focus: 0, radius: nodeRadius(node), loaded: Number(node.state === "loaded"), labelRemaining: node.state === "loaded" ? 1600 : 0 });
}
for (const edge of graph.edges) if (!edges.has(edgeKey(edge))) edges.set(edgeKey(edge), { ...edge, presence: 0, emphasis: 1 });
frame = { nodes: [...nodes.values()], edges: [...edges.values()] };
moving = true;
return frame;
},
advance(elapsed: number, reducedMotion: boolean) {
if (!moving) return { moving: false, removed: false };
const amount = reducedMotion ? 1 : 1 - Math.pow(0.9, Math.min(64, Math.max(0, elapsed)) / (1000 / 60));
moving = false;
let removed = false;
const approach = (value: number, target: number) => {
const next = value + (target - value) * amount;
if (Math.abs(next - target) < 0.005) return target;
moving = true;
return next;
};
for (const [path, node] of nodes) {
// Keep the clock alive after the layout settles so new labels can fade out.
node.labelRemaining = Math.max(0, node.labelRemaining - Math.max(0, elapsed));
if (node.labelRemaining > 0) moving = true;
node.presence = approach(node.presence, wanted.has(path) ? 1 : 0);
node.emphasis = approach(node.emphasis, highlighted && !related.has(path) ? 0.2 : 1);
node.focus = approach(node.focus, path === highlighted ? 1 : 0);
node.radius = approach(node.radius, nodeRadius(node));
node.loaded = approach(node.loaded, Number(node.state === "loaded"));
if (!wanted.has(path) && node.presence === 0) { nodes.delete(path); removed = true; }
}
for (const [key, edge] of edges) {
edge.presence = approach(edge.presence, wantedEdges.has(key) ? 1 : 0);
edge.emphasis = approach(edge.emphasis, highlighted && edge.source !== highlighted && edge.target !== highlighted ? 0.2 : 1);
if (!wantedEdges.has(key) && edge.presence === 0) { edges.delete(key); removed = true; }
}
if (removed) frame = { nodes: [...nodes.values()], edges: [...edges.values()] };
return { moving, removed };
},
};
}
+124 -11
View File
@@ -41,26 +41,29 @@ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogPositionedContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
contained?: boolean;
positionerStyle?: React.CSSProperties;
placement?: "center" | "bottom";
overlayClassName?: string;
}
>(({ positionerStyle, placement, overlayClassName, ...props }, ref) => (
<DialogOverlay forceMount className={overlayClassName}>
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overflow-y-auto overscroll-contain", placement !== "bottom" && "p-4")} style={{
>(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => {
const Overlay = contained ? "div" : DialogOverlay;
return <Overlay data-dialog-backdrop {...(contained ? {} : { forceMount: true })} className={cn(contained && "absolute inset-0 z-50", overlayClassName)}>
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overscroll-contain", placement === "bottom" ? "overflow-clip" : "overflow-y-auto p-4", contained && "absolute")} style={{
top: "var(--app-viewport-top, 0px)",
height: "var(--app-viewport-height, 100%)",
bottom: "auto",
...positionerStyle,
...(contained ? { top: 0, height: "100%" } : positionerStyle),
}}>
<DialogPrimitive.Content ref={ref} {...props} />
</div>
</DialogOverlay>
));
</Overlay>;
});
DialogPositionedContent.displayName = "DialogPositionedContent";
interface DialogContentProps
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
portalContainer?: HTMLElement | null;
showCloseButton?: boolean;
overlayClassName?: string;
layoutAnchor?: HTMLElement | null;
@@ -71,10 +74,73 @@ interface DialogContentProps
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {
>(({ className, children, portalContainer, showCloseButton = true, overlayClassName, placement = "center", layoutAnchor: explicitLayoutAnchor, centerInLayoutAnchor = false, onOpenAutoFocus, ...props }, ref) => {
const { t } = useTranslation();
const [container, setContainer] = React.useState<HTMLDivElement | null>(null);
const contentNode = React.useRef<HTMLDivElement | null>(null);
const gesture = React.useRef<{ id: number; start: number; y: number; time: number; speed: number; moved: boolean } | null>(null);
const suppressClick = React.useRef(false);
const settleAnimation = React.useRef<Animation | null>(null);
const backdropFrame = React.useRef<number | null>(null);
const dragBackdrop = React.useRef<{ node: HTMLElement; color: string; blur: number } | null>(null);
const paintBackdrop = (distance: number, height: number) => {
const backdrop = dragBackdrop.current;
if (!backdrop) return;
const remaining = 1 - Math.min(1, Math.max(0, distance) / Math.max(1, height));
backdrop.node.style.backgroundColor = `color-mix(in srgb, ${backdrop.color} ${remaining * 100}%, transparent)`;
backdrop.node.style.backdropFilter = `blur(${backdrop.blur * remaining}px)`;
};
const cancelBackdropFrame = () => {
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
backdropFrame.current = null;
};
React.useEffect(() => () => {
settleAnimation.current?.cancel();
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
}, []);
const finishDrag = (button: HTMLButtonElement, pointerId: number, cancelled: boolean) => {
const drag = gesture.current;
const node = contentNode.current;
if (!drag || drag.id !== pointerId || !node) return;
gesture.current = null;
suppressClick.current = drag.moved;
if (!drag.moved) {
if (dragBackdrop.current) {
const style = dragBackdrop.current.node.style;
for (const property of ["background-color", "backdrop-filter", "transition"]) style.removeProperty(property);
dragBackdrop.current = null;
}
return;
}
const distance = Math.max(0, drag.y - drag.start);
const dismiss = !cancelled && (distance > Math.min(120, node.offsetHeight * 0.22)
|| (distance > 24 && drag.speed > 0.65 && performance.now() - drag.time < 100));
const destination = dismiss ? node.offsetHeight : 0;
const animation = node.animate([{ translate: `0 ${distance}px` }, { translate: `0 ${destination}px` }], {
duration: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : dismiss ? 180 : 260,
easing: "cubic-bezier(0.2, 0, 0, 1)", fill: "forwards",
});
settleAnimation.current = animation;
const follow = () => {
paintBackdrop(parseFloat(getComputedStyle(node).getPropertyValue("translate").split(" ")[1]) || 0, node.offsetHeight);
backdropFrame.current = requestAnimationFrame(follow);
};
backdropFrame.current = requestAnimationFrame(follow);
animation.onfinish = () => {
cancelBackdropFrame();
node.style.translate = `0 ${destination}px`;
paintBackdrop(destination, node.offsetHeight);
if (!dismiss && dragBackdrop.current) {
const style = dragBackdrop.current.node.style;
for (const property of ["background-color", "backdrop-filter", "transition"]) style.removeProperty(property);
dragBackdrop.current = null;
}
animation.cancel();
settleAnimation.current = null;
if (dismiss) { suppressClick.current = false; button.click(); }
};
};
const inheritedLayoutAnchor = React.useContext(DialogLayoutContext);
const layoutAnchor = explicitLayoutAnchor ?? inheritedLayoutAnchor;
const [layout, setLayout] = React.useState<React.CSSProperties>();
@@ -114,13 +180,22 @@ const DialogContent = React.forwardRef<
}, [layoutAnchor, placement, centerInLayoutAnchor]);
const contentRef = React.useCallback((node: HTMLDivElement | null) => {
contentNode.current = node;
if (!node) {
settleAnimation.current?.cancel();
settleAnimation.current = null;
if (backdropFrame.current !== null) cancelAnimationFrame(backdropFrame.current);
backdropFrame.current = null;
dragBackdrop.current = null;
gesture.current = null;
}
setContainer(node);
if (typeof ref === "function") ref(node);
else if (ref) ref.current = node;
}, [ref]);
return (
<DialogPortal>
<DialogPortal container={portalContainer}>
<DialogPositionedContent
contained={!!portalContainer}
positionerStyle={layout}
placement={placement}
overlayClassName={overlayClassName}
@@ -136,9 +211,10 @@ const DialogContent = React.forwardRef<
modalSurfaceClassName,
"relative grid w-full max-w-lg gap-4 p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 motion-reduce:animate-none",
placement === "bottom"
? "mt-auto max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-4 data-[state=closed]:slide-out-to-bottom-4"
? "mt-auto max-h-[85dvh] overflow-y-auto overscroll-contain rounded-t-modal pb-[max(1rem,env(safe-area-inset-bottom))] data-[state=open]:slide-in-from-bottom-full data-[state=closed]:slide-out-to-bottom-full ease-[cubic-bezier(0.2,0,0,1)] duration-300"
: "my-auto origin-center rounded-modal data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className,
placement === "bottom" && "pt-9 transition-none",
)}
{...props}
>
@@ -146,8 +222,45 @@ const DialogContent = React.forwardRef<
{children}
</FloatingPortalContext.Provider>
{showCloseButton ? (
<DialogPrimitive.Close className={cn("absolute right-2.5 top-2.5 grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "h-11 w-11" : "h-7 w-7")}>
<X className="h-4 w-4" />
<DialogPrimitive.Close
onPointerDown={(event) => {
if (placement !== "bottom" || !event.isPrimary || event.button !== 0) return;
const node = contentNode.current;
const offset = node ? parseFloat(getComputedStyle(node).getPropertyValue("translate").split(" ")[1]) || 0 : 0;
cancelBackdropFrame();
settleAnimation.current?.cancel();
if (node) node.style.translate = `0 ${offset}px`;
const backdrop = node?.closest<HTMLElement>("[data-dialog-backdrop]");
if (backdrop && !dragBackdrop.current) {
const style = getComputedStyle(backdrop);
dragBackdrop.current = { node: backdrop, color: style.backgroundColor,
blur: parseFloat(style.getPropertyValue("backdrop-filter").match(/blur\(([^)]+)/)?.[1] ?? "0") || 0 };
backdrop.style.transition = "none";
backdrop.style.animation = "none";
}
suppressClick.current = false;
gesture.current = { id: event.pointerId, start: event.clientY - offset, y: event.clientY, time: performance.now(), speed: 0, moved: offset > 5 };
event.currentTarget.setPointerCapture(event.pointerId);
}}
onPointerMove={(event) => {
const drag = gesture.current;
if (!drag || drag.id !== event.pointerId) return;
const now = performance.now();
drag.speed = (event.clientY - drag.y) / Math.max(1, now - drag.time);
drag.y = event.clientY; drag.time = now;
drag.moved ||= Math.abs(drag.y - drag.start) > 5;
if (contentNode.current) {
const distance = Math.max(0, drag.y - drag.start);
contentNode.current.style.translate = `0 ${distance}px`;
paintBackdrop(distance, contentNode.current.offsetHeight);
}
}}
onPointerUp={(event) => finishDrag(event.currentTarget, event.pointerId, false)}
onPointerCancel={(event) => finishDrag(event.currentTarget, event.pointerId, true)}
onLostPointerCapture={(event) => finishDrag(event.currentTarget, event.pointerId, true)}
onClick={(event) => { if (suppressClick.current) { event.preventDefault(); suppressClick.current = false; } }}
className={cn("absolute grid place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none", placement === "bottom" ? "left-1/2 top-0 h-8 w-16 -translate-x-1/2 touch-none cursor-grab active:cursor-grabbing" : "right-2.5 top-2.5 h-7 w-7")}>
{placement === "bottom" ? <span aria-hidden="true" className="h-1 w-9 rounded-full bg-current opacity-40" /> : <X className="h-4 w-4" />}
<span className="sr-only">{t("common.close")}</span>
</DialogPrimitive.Close>
) : null}
@@ -12,6 +12,9 @@ export const modalOverlayClassName =
export const modalSurfaceClassName =
"outline-none bg-background text-foreground shadow-[0_12px_36px_rgba(15,23,42,0.12)] dark:bg-popover dark:shadow-[0_18px_44px_rgba(0,0,0,0.32)]";
export const sidePanelSurfaceClassName =
"side-panel-surface outline-none bg-background text-foreground dark:bg-popover overflow-hidden rounded-[24px]";
export const floatingSurfaceClassName =
`${floatingSurfaceVisualClassName} z-50 overflow-x-hidden overflow-y-auto overscroll-contain scrollbar-thin`;
+3 -2
View File
@@ -1,3 +1,4 @@
import { surfaceFocusProps } from "@/lib/surface-focus";
import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react";
import { Minus, Plus } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -121,8 +122,8 @@ export function ImageViewport({
const buttonClass = "grid size-9 shrink-0 place-items-center rounded-full transition-colors hover:text-foreground disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return <>
<div ref={viewport} data-testid={testId} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}
<div ref={viewport} data-testid={testId} {...surfaceFocusProps} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden outline-none data-[keyboard-focus]:ring-1 data-[keyboard-focus]:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}
onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={endPointer} onPointerCancel={endPointer} onLostPointerCapture={endPointer}
onDoubleClick={(event) => zoom(viewRef.current.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })}
onKeyDown={(event) => {
+11 -8
View File
@@ -5,6 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface";
const Sheet = DialogPrimitive.Root;
const SheetTrigger = DialogPrimitive.Trigger;
@@ -29,7 +30,7 @@ const SheetOverlay = React.forwardRef<
SheetOverlay.displayName = DialogPrimitive.Overlay.displayName;
const sheetVariants = cva(
"fixed z-50 flex flex-col gap-4 bg-background outline-none transition ease-in-out",
"fixed z-50 flex flex-col gap-4 bg-background outline-none ease-out",
{
variants: {
side: {
@@ -42,12 +43,14 @@ const sheetVariants = cva(
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
),
left: cn(
"inset-y-0 left-0 h-full w-3/4 sm:max-w-sm",
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",
"inset-y-2 left-2 w-3/4 max-w-[calc(100vw-1rem)] sm:max-w-sm",
sidePanelSurfaceClassName,
"data-[state=closed]:slide-out-to-left-4 data-[state=open]:slide-in-from-left-4",
),
right: cn(
"inset-y-0 right-0 h-full w-3/4 sm:max-w-sm",
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",
"inset-y-2 right-2 w-3/4 max-w-[calc(100vw-1rem)] sm:max-w-sm",
sidePanelSurfaceClassName,
"data-[state=closed]:slide-out-to-right-4 data-[state=open]:slide-in-from-right-4",
),
},
},
@@ -83,13 +86,13 @@ const SheetContent = React.forwardRef<
const { t } = useTranslation();
return (
<SheetPortal>
<SheetOverlay className={overlayClassName} />
<SheetOverlay className={cn((side === "right" || side === "left") && modalOverlayClassName, overlayClassName)} />
<DialogPrimitive.Content
ref={ref}
className={cn(
sheetVariants({ side }),
"data-[state=open]:animate-in data-[state=closed]:animate-out",
"duration-300 motion-reduce:transition-none",
"data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 duration-200 motion-reduce:transition-none",
"motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none",
className,
)}
@@ -99,7 +102,7 @@ const SheetContent = React.forwardRef<
{showCloseButton ? (
<DialogPrimitive.Close
className={cn(
"absolute right-4 top-4 rounded-mark opacity-70 ring-offset-background transition-opacity",
"absolute right-2 top-2 grid size-10 place-items-center rounded-full opacity-70 ring-offset-background transition-opacity",
"hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
"disabled:pointer-events-none",
closeButtonClassName,
+68
View File
@@ -0,0 +1,68 @@
import { createContext, forwardRef, useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type HTMLAttributes, type ReactNode } from "react";
import { useReducedMotion } from "motion/react";
import { cn } from "@/lib/utils";
interface SidebarPanelProps extends HTMLAttributes<HTMLElement> {
header?: ReactNode;
width: number;
isClosing?: boolean;
open?: boolean;
floating?: boolean;
contentClassName?: string;
}
export const SidebarPanelActionsContext = createContext<HTMLElement | null>(null);
/** Retain the same surface through exit, including an interrupted close. */
export const SidebarPanel = forwardRef<HTMLElement, SidebarPanelProps>(function SidebarPanel({
open = true, isClosing, ...props
}, ref) {
const [present, setPresent] = useState(open);
const reducedMotion = useReducedMotion();
useEffect(() => {
if (open) { setPresent(true); return; }
const timer = window.setTimeout(() => setPresent(false), reducedMotion ? 0 : 300);
return () => window.clearTimeout(timer);
}, [open, reducedMotion]);
return open || present ? <SidebarPanelContent {...props} ref={ref} isClosing={isClosing || !open} /> : null;
});
/** Shared nonmodal side slot. Contents keep their final width while the slot opens. */
const SidebarPanelContent = forwardRef<HTMLElement, SidebarPanelProps>(function SidebarPanelContent({
width, isClosing = false, floating = false, header, contentClassName, className, style, children, ...props
}, forwardedRef) {
const panel = useRef<HTMLElement | null>(null);
const [entered, setEntered] = useState(false);
const [actionsHost, setActionsHost] = useState<HTMLElement | null>(null);
const setPanel = useCallback((node: HTMLElement | null) => {
panel.current = node;
if (typeof forwardedRef === "function") forwardedRef(node);
else if (forwardedRef) forwardedRef.current = node;
}, [forwardedRef]);
useLayoutEffect(() => {
// Commit the outgoing slot width before transitioning to the replacement width.
panel.current?.getBoundingClientRect();
let frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => setEntered(true)); });
return () => cancelAnimationFrame(frame);
}, []);
return <aside {...props} ref={setPanel} data-closing={isClosing || undefined}
style={{
"--file-preview-width": `${width}px`,
"--file-preview-slot-width": isClosing ? "0px" : !entered ? "var(--sidebar-enter-width, 0px)" : `${width}px`,
"--file-preview-mobile-width": isClosing ? "0px" : !entered ? "var(--sidebar-enter-mobile-width, 0px)" : "100%",
...style,
} as CSSProperties}
className={cn("file-preview-pane z-30 min-h-0 w-[var(--file-preview-mobile-width)] overflow-hidden duration-300 ease-[cubic-bezier(0.2,0,0,1)] motion-reduce:transition-none",
entered ? "transition-[width]" : "transition-none",
floating ? "fixed inset-y-2 right-2 max-w-[420px]" : "absolute inset-y-0 right-0", isClosing && "pointer-events-none", className)}>
<div className={cn("file-preview-content absolute inset-y-2 right-2 flex min-h-0 w-[calc(100cqw-1rem)] flex-col pb-[env(safe-area-inset-bottom)] transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none",
floating && "w-[calc(min(420px,100vw)-1rem)]",
!entered || isClosing ? "translate-x-2 opacity-0" : "translate-x-0 opacity-100", contentClassName)}>
{header && <div className="flex min-h-10 shrink-0 items-center gap-1 border-b border-border/40 px-2 pt-2">
{header}
<div ref={setActionsHost} className="shrink-0" />
</div>}
<SidebarPanelActionsContext.Provider value={actionsHost}>{children}</SidebarPanelActionsContext.Provider>
</div>
</aside>;
});
@@ -25,10 +25,8 @@ import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { HoverHint } from "@/components/ui/tooltip";
@@ -634,10 +632,6 @@ export function PaneWorkbench({
align="end"
onCloseAutoFocus={(event) => event.preventDefault()}
>
<DropdownMenuLabel>
{t("workbench.layout", { defaultValue: "Pane layout" })}
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuRadioGroup
value={layout}
onValueChange={(value) => {
@@ -701,8 +695,8 @@ export function PaneWorkbench({
data-testid="pane-grid"
data-layout={effectiveLayout}
className={cn(
"grid h-full min-h-0 min-w-0 overflow-hidden",
chrome && displayedPanes.length > 1 && "gap-px bg-border/55",
"grid h-full min-h-0 min-w-0 overflow-hidden bg-background",
chrome && displayedPanes.length > 1 && "gap-px",
)}
style={gridStyle}
>
@@ -723,7 +717,10 @@ export function PaneWorkbench({
data-testid={`workbench-pane-${pane.key}`}
onPointerDownCapture={(event) => handlePanePointerDown(pane.key, event)}
onFocusCapture={(event) => handlePaneFocus(pane.key, event)}
className="workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background"
className={cn(
"workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background",
chrome && displayedPanes.length > 1 && "shadow-[0_0_0_1px_hsl(var(--border)/0.55)]",
)}
style={layoutGeometry.paneStyles[index]}
>
{renderPane(pane, {
+2 -2
View File
@@ -65,7 +65,7 @@ function SessionPreview() {
}}>
<StatePicker label={t("previews.session.state")} value={mode} options={["ready", "loading", "error", "empty", "action_error"]}
onChange={(next) => { setMode(next); setJobs(exampleJobs(now)); setAction(null); }} />
<SessionInfoPopoverView title="组件设计" jobs={mode === "ready" || mode === "action_error" ? displayJobs(jobs) : []} loading={mode === "loading"} loadFailed={mode === "error"} now={now}
<SessionInfoPopoverView jobs={mode === "ready" || mode === "action_error" ? displayJobs(jobs) : []} loading={mode === "loading"} loadFailed={mode === "error"} now={now}
onOpenCalendar={() => setAction({ key: "previews.session.openedCalendar" })}
onAction={(operation, job) => {
if (mode === "action_error") return Promise.reject(new Error(t("previews.session.actionError")));
@@ -106,7 +106,7 @@ export const contentExamples: ComponentExample[] = [
code: '<FilePreviewPanelView path={path} state={previewState} imageOpen={imageOpen} onImageOpenChange={setImageOpen} onImageError={reportImageError} />' },
{ title: "previews.session.title", files: ["webui/src/components/thread/SessionInfoPopoverView.tsx"], Preview: SessionPreview,
description: "previews.session.description", options: "previews.session.options",
code: '<SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },
code: '<SessionInfoPopoverView jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },
{ title: "previews.subagent.title", files: ["webui/src/components/thread/SubagentThreadView.tsx"], Preview: SubagentPreview,
description: "previews.subagent.description", options: "previews.subagent.options",
code: '<SubagentThreadView messages={messages} loading={loading} error={error} isStreaming={running} runStartedAt={startedAt} onRetry={retry} />' },
+23 -6
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
import { ComposerUsagePopover, type ComposerRoundUsage } from "@/components/thread/ComposerUsagePopover";
import type { ContextSnapshot } from "@/lib/types";
import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { ModelPresetBadge, type ModelPresetOption } from "@/components/thread/ModelPresetBadge";
@@ -30,9 +31,9 @@ const presets: ModelPresetOption[] = [
{ name: "推理", provider: "anthropic", model: "claude-sonnet-4", reasoningEffort: "high", contextWindowTokens: 200_000 },
];
const rounds: ComposerRoundUsage[] = [
{ id: "gallery-round-1", timestamp: createdAt, inputTokens: 8_200, cachedTokens: 6_000, outputTokens: 620, generationMs: 3_100 },
{ id: "gallery-round-2", timestamp: createdAt + 60_000, inputTokens: 12_000, cachedTokens: 8_200, outputTokens: 980, generationMs: 5_400 },
{ id: "gallery-round-3", timestamp: createdAt + 120_000, inputTokens: 18_500, cachedTokens: 12_000, outputTokens: 1_240, generationMs: 7_200 },
{ inputTokens: 8_200, cachedTokens: 6_000, generationMs: 3_100 },
{ inputTokens: 12_000, cachedTokens: 8_200, generationMs: 5_400 },
{ inputTokens: 18_500, cachedTokens: 12_000, generationMs: 7_200 },
];
const commands: SlashCommand[] = [
{ command: "/status", title: "previews.composer.statusCommand", description: "previews.composer.statusDescription", icon: "activity", lifecycle: "side_channel", acceptsArgs: false },
@@ -102,14 +103,30 @@ function ModelPresetPreview() {
</div>;
}
const contextSnapshots: ContextSnapshot[] = [0, 1, 2].map((round) => ({
id: `context-example-${round}`, contextWindowTokens: 128000,
usage: { prompt_tokens: 28000 + round * 7300, context_tokens: 28000 + round * 7300, cached_tokens: 20000 + round * 7000, generation_ms: 8200 },
graph: {
nodes: [
{ path: "/workspace/MEMORY.md", name: "MEMORY.md", state: "loaded", tokens: 2100 },
{ path: "/workspace/SOUL.md", name: "SOUL.md", state: "loaded", tokens: 380 },
{ path: "/workspace/AGENTS.md", name: "AGENTS.md", state: "loaded", tokens: 1400 },
{ path: "/workspace/skills/nanobot-document/SKILL.md", name: "nanobot-document", state: "loaded", tokens: 550 },
{ path: "/workspace/skills/nanobot-document/references/architecture.md", name: "architecture.md", state: round ? "loaded" : "discovered", tokens: round * 1600 },
{ path: "/workspace/skills/nanobot-document/references/configuration.md", name: "configuration.md", state: "discovered", tokens: 0 },
],
edges: ["architecture.md", "configuration.md"].map((name) => ({ source: "/workspace/skills/nanobot-document/SKILL.md", target: `/workspace/skills/nanobot-document/references/${name}` })),
},
}));
function UsagePreview() {
const { t } = useGalleryTranslation();
const [mode, setMode] = useState<"normal" | "caution" | "critical" | "rounds_only" | "sheet">("normal");
const [mode, setMode] = useState<"normal" | "caution" | "critical" | "rounds_only">("normal");
const tokens = mode === "critical" ? 192_000 : mode === "caution" ? 162_000 : 18_500;
return <div className="space-y-4">
<StatePicker label={t("previews.usage.state")} value={mode} options={["normal", "caution", "critical", "rounds_only", "sheet"]} onChange={setMode} />
<StatePicker label={t("previews.usage.state")} value={mode} options={["normal", "caution", "critical", "rounds_only"]} onChange={setMode} />
<ComposerUsagePopover context={mode === "rounds_only" ? null : { contextTokens: tokens, contextWindowTokens: 200_000 }}
rounds={rounds} showLabel bottomSheet={mode === "sheet"} />
rounds={rounds} snapshots={contextSnapshots} showLabel />
<p className="text-sm text-muted-foreground">{t("previews.usage.hint")}</p>
</div>;
}
+17
View File
@@ -1,4 +1,5 @@
import { useState } from "react";
import { SidebarPanel } from "@/components/ui/sidebar-panel";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -250,7 +251,23 @@ function ImageViewports() {
}
const base = "webui/src/components/ui/";
function Sidebars() {
const { t } = useGalleryTranslation();
const [open, setOpen] = useState(true);
return <div className="space-y-3">
<Button onClick={() => setOpen(!open)}>{t("controls.sidebarPanel.toggle")}</Button>
<div className="thread-preview-layout relative h-64 overflow-hidden rounded-xl border">
{open && <SidebarPanel width={320} header={<span>{t("controls.sidebarPanel.title")}</span>}>
<p className="p-4 text-sm">{t("controls.sidebarPanel.content")}</p>
</SidebarPanel>}
</div>
</div>;
}
export const foundationExamples: ComponentExample[] = [
{ title: "controls.sidebarPanel.title", files: ["sidebar-panel"], Preview: Sidebars,
description: "controls.sidebarPanel.description", options: "controls.sidebarPanel.options",
code: '<SidebarPanel width={320} header={<span>Details</span>}>{children}</SidebarPanel>' },
{ title: "controls.button.title", files: ["button"], Preview: Buttons,
description: "controls.button.description",
options: "controls.button.options",
@@ -504,5 +504,12 @@
"view": "View invitation",
"dismissed": "Never remind again selected in preview",
"starred": "GitHub link selected in preview"
},
"sidebarPanel": {
"title": "Sidebar panel",
"toggle": "Toggle sidebar",
"content": "Details stay inside the current pane.",
"description": "A nonmodal side panel with a shared opening transition.",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "Ver invitación",
"dismissed": "Se eligió no volver a recordar en la vista previa",
"starred": "Se eligió el enlace de GitHub en la vista previa"
},
"sidebarPanel": {
"title": "Panel lateral",
"toggle": "Mostrar u ocultar panel",
"content": "Los detalles permanecen en el panel actual.",
"description": "Un panel lateral no modal con una transición de apertura compartida.",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "Voir l’invitation",
"dismissed": "Ne plus rappeler sélectionné dans l’aperçu",
"starred": "Lien GitHub sélectionné dans l’aperçu"
},
"sidebarPanel": {
"title": "Panneau latéral",
"toggle": "Afficher ou masquer le panneau",
"content": "Les détails restent dans le volet actuel.",
"description": "Un panneau latéral non modal avec une transition d’ouverture commune.",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "Lihat undangan",
"dismissed": "Jangan ingatkan lagi dipilih dalam pratinjau",
"starred": "Tautan GitHub dipilih dalam pratinjau"
},
"sidebarPanel": {
"title": "Panel samping",
"toggle": "Tampilkan atau sembunyikan panel",
"content": "Detail tetap berada di panel saat ini.",
"description": "Panel samping nonmodal dengan transisi pembukaan bersama.",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "招待を表示",
"dismissed": "プレビューで今後表示しないを選択しました",
"starred": "プレビューで GitHub リンクを選択しました"
},
"sidebarPanel": {
"title": "サイドパネル",
"toggle": "パネルの表示を切り替え",
"content": "詳細は現在のペイン内に表示されます。",
"description": "共通の開くアニメーションを持つ非モーダルのサイドパネル。",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "안내 보기",
"dismissed": "미리보기에서 다시 알리지 않기를 선택했습니다",
"starred": "미리보기에서 GitHub 링크를 선택했습니다"
},
"sidebarPanel": {
"title": "사이드 패널",
"toggle": "패널 표시 전환",
"content": "세부 정보는 현재 창 안에 표시됩니다.",
"description": "공통 열기 전환 효과를 사용하는 비모달 사이드 패널입니다.",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "Ver convite",
"dismissed": "Nunca mais lembrar selecionado na prévia",
"starred": "Link do GitHub selecionado na prévia"
},
"sidebarPanel": {
"title": "Painel lateral",
"toggle": "Alternar painel",
"content": "Os detalhes permanecem no painel atual.",
"description": "Um painel lateral não modal com uma transição de abertura compartilhada.",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "Xem lời mời",
"dismissed": "Đã chọn không nhắc lại trong bản xem trước",
"starred": "Đã chọn liên kết GitHub trong bản xem trước"
},
"sidebarPanel": {
"title": "Bảng bên",
"toggle": "Ẩn hoặc hiện bảng",
"content": "Chi tiết nằm trong ngăn hiện tại.",
"description": "Bảng bên không khóa giao diện với hiệu ứng mở dùng chung.",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "查看邀请",
"dismissed": "预览中选择了不再提醒",
"starred": "预览中选择了 GitHub 链接"
},
"sidebarPanel": {
"title": "侧边面板",
"toggle": "切换侧边面板",
"content": "详情保留在当前窗格内。",
"description": "非模态侧边面板,使用统一的展开动画。",
"options": "width, header, isClosing, floating, contentClassName"
}
}
@@ -504,5 +504,12 @@
"view": "查看邀請",
"dismissed": "已在預覽中選取不再提醒",
"starred": "已在預覽中選取 GitHub 連結"
},
"sidebarPanel": {
"title": "側邊面板",
"toggle": "切換側邊面板",
"content": "詳細資訊保留在目前的窗格內。",
"description": "非模態側邊面板,使用統一的展開動畫。",
"options": "width, header, isClosing, floating, contentClassName"
}
}
+61 -7
View File
@@ -855,9 +855,32 @@
.thread-preview-layout {
container: thread-preview-layout / inline-size;
}
.context-expanded-overlay[data-state="open"] {
animation: context-backdrop-in 250ms ease-out;
}
.context-expanded-overlay[data-state="closed"] {
animation: context-backdrop-in 250ms ease-out reverse;
}
@keyframes context-backdrop-in {
from { opacity: 0; backdrop-filter: blur(0); }
to { opacity: 1; backdrop-filter: blur(12px); }
}
@media (prefers-reduced-motion: reduce) {
.context-expanded-overlay { animation: none !important; }
}
/* Sidebars share the full pane height with a local conversation composer. */
.workbench-composer-footer:not(:has([data-active-composer])) {
display: none;
}
/* A split needs 420px for the conversation plus 360px for the preview.
Narrow workbench panes use the same contained overlay as a phone. */
@container thread-preview-layout (min-width: 780px) {
/* A replacement owns the slot while the outgoing surface fades over it. */
.thread-preview-layout:has(> .file-preview-pane:not([data-closing])) > .file-preview-pane[data-closing] {
position: absolute;
width: var(--file-preview-width);
z-index: 30;
}
.file-preview-pane {
position: relative;
z-index: auto;
@@ -866,7 +889,8 @@
flex-shrink: 0;
}
.file-preview-content {
width: var(--file-preview-width);
width: calc(var(--file-preview-width) - 1rem);
bottom: var(--sidebar-bottom-inset, calc(1.125rem + env(safe-area-inset-bottom)));
padding-bottom: 0;
}
.file-preview-resize {
@@ -879,6 +903,27 @@
visibility: hidden;
}
}
@media (max-width: 639px) {
.context-drawer-backdrop {
animation: context-drawer-backdrop-in 150ms cubic-bezier(0.2, 0, 0, 1);
transition: background-color 150ms cubic-bezier(0.2, 0, 0, 1), backdrop-filter 150ms cubic-bezier(0.2, 0, 0, 1);
}
.context-drawer-backdrop:has(.context-drawer-panel[data-state="closed"]) {
animation: none;
background-color: transparent;
backdrop-filter: blur(0px);
}
}
@keyframes context-drawer-backdrop-in {
from { background-color: transparent; backdrop-filter: blur(0px); }
to { background-color: rgb(0 0 0 / 0.25); backdrop-filter: blur(8px); }
}
@media (prefers-reduced-motion: reduce) {
.context-drawer-backdrop { animation: none; transition: none; }
}
.thread-preview-layout:has(.context-drawer-panel) > .thread-conversation {
visibility: visible;
}
.thread-preview-layout[data-preview-open] > .thread-conversation {
--thread-header-position: relative;
}
@@ -947,9 +992,8 @@
display: inline;
}
/* Markdown tables wrap cell text to fit the conversation column. The
renderer's overflow-x:auto wrapper remains a fallback for content that
cannot shrink. */
/* Markdown table cells retain whole-word minimum widths. The renderer's
overflow-x:auto wrapper contains tables wider than the preview or chat. */
.thread-viewport-scrollbar {
overflow-x: hidden;
@@ -1184,16 +1228,25 @@
}
}
.thread-composer-surface {
.thread-composer-surface,
.context-inspector-surface,
.user-message-surface,
.side-panel-surface {
--composer-shadow-color: 240 10% 16%;
--tw-shadow: inset 0 0 0 1px hsl(var(--border) / 0.75), 0 4px 18px -8px hsl(var(--composer-shadow-color) / 0.12);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}
.thread-composer-surface {
transition: var(--theme-paint-transition, background-color 160ms ease-out, box-shadow 160ms ease-out), opacity 160ms ease-out;
container-name: thread-composer;
container-type: inline-size;
}
.dark .thread-composer-surface {
.dark .thread-composer-surface,
.dark .context-inspector-surface,
.dark .user-message-surface,
.dark .side-panel-surface {
--composer-shadow-color: 240 12% 3%;
}
@@ -1202,8 +1255,9 @@
}
@media (forced-colors: active) {
.thread-composer-surface { outline: 1px solid CanvasText; }
.thread-composer-surface, .context-inspector-surface, .user-message-surface, .side-panel-surface { outline: 1px solid CanvasText; }
.thread-composer-surface:focus-within { outline: 2px solid Highlight; }
[data-keyboard-focus] { outline: 2px solid Highlight; outline-offset: -2px; }
}
.thread-composer-footer-actions {
+12 -9
View File
@@ -2064,8 +2064,6 @@
"sessionInfo": "Session details"
},
"sessionInfo": {
"title": "Session",
"untitled": "Untitled topic",
"automations": "Automations",
"count": "{{count}}",
"loading": "Loading automations...",
@@ -2117,15 +2115,21 @@
"reauthFallback": "A fallback model handled this response.",
"reauthSettings": "Open model settings",
"context": {
"loaded": "Loaded",
"unloaded": "Not loaded",
"expand": "Expand context panel",
"collapse": "Collapse context panel",
"noFiles": "No context recorded yet",
"estimatedNodeTokens": "About {{value}} tokens",
"openFile": "Open file",
"history": "Context history",
"playHistory": "Play context history",
"tooltip": "Context {{percent}}%",
"detailsLabel": "Open context usage",
"panelTitle": "Context usage",
"contextTitle": "Context",
"recentRounds": "Recent rounds",
"inputTrend": "Input tokens",
"input": "Input tokens",
"cacheHitRate": "KV cache hit rate",
"output": "Output tokens",
"cacheHitRate": "Cache hit rate",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "Generation time"
},
"queued": {
@@ -2533,8 +2537,7 @@
"fileEditDiffTruncated": "Diff truncated. Open the file for the full change.",
"usage": {
"context": "Context now: {{tokens}}{{capacity}}",
"requests": "{{count}} calls this turn",
"estimated": "Includes estimated usage"
"requests": "{{count}} calls this turn"
}
},
"recovery": {
+12 -9
View File
@@ -1859,8 +1859,6 @@
"sessionInfo": "Detalles de la sesión"
},
"sessionInfo": {
"title": "Sesión",
"untitled": "Tema sin título",
"automations": "Automatizaciones",
"count": "{{count}}",
"loading": "Cargando automatizaciones...",
@@ -1912,15 +1910,21 @@
"reauthFallback": "Un modelo alternativo respondió esta vez.",
"reauthSettings": "Abrir ajustes del modelo",
"context": {
"loaded": "Cargado",
"unloaded": "Sin cargar",
"expand": "Ampliar contexto",
"collapse": "Reducir contexto",
"noFiles": "Aún no hay contexto registrado",
"estimatedNodeTokens": "Unos {{value}} tokens",
"openFile": "Abrir archivo",
"history": "Historial de contexto",
"playHistory": "Reproducir historial del contexto",
"tooltip": "Contexto {{percent}}%",
"detailsLabel": "Abrir uso del contexto",
"panelTitle": "Uso del contexto",
"contextTitle": "Contexto",
"recentRounds": "Rondas recientes",
"inputTrend": "Tokens de entrada",
"input": "Tokens de entrada",
"cacheHitRate": "Tasa de aciertos de KV Cache",
"output": "Tokens de salida",
"cacheHitRate": "Tasa de aciertos de caché",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "Tiempo de generación"
},
"queued": {
@@ -2148,8 +2152,7 @@
"fileEditDiffTruncated": "Diferencias truncadas. Abre el archivo para ver el cambio completo.",
"usage": {
"context": "Contexto más reciente: {{tokens}}{{capacity}} tokens",
"requests": "{{count}} solicitudes al modelo",
"estimated": "Incluye uso estimado"
"requests": "{{count}} solicitudes al modelo"
},
"activityThinkingFor": "Pensando durante {{duration}}",
"activityThought": "Pensamiento completado",
+12 -9
View File
@@ -1858,8 +1858,6 @@
"sessionInfo": "Détails de la session"
},
"sessionInfo": {
"title": "Session",
"untitled": "Sujet sans titre",
"automations": "Automatisations",
"count": "{{count}}",
"loading": "Chargement des automatisations...",
@@ -1911,15 +1909,21 @@
"reauthFallback": "Un modèle de secours a traité cette réponse.",
"reauthSettings": "Ouvrir les paramètres du modèle",
"context": {
"loaded": "Chargé",
"unloaded": "Non chargé",
"expand": "Agrandir le contexte",
"collapse": "Réduire le contexte",
"noFiles": "Aucun contexte enregistré pour le moment",
"estimatedNodeTokens": "Environ {{value}} tokens",
"openFile": "Ouvrir le fichier",
"history": "Historique du contexte",
"playHistory": "Lire l’historique du contexte",
"tooltip": "Contexte {{percent}} %",
"detailsLabel": "Ouvrir l’utilisation du contexte",
"panelTitle": "Utilisation du contexte",
"contextTitle": "Contexte",
"recentRounds": "Tours récents",
"inputTrend": "Jetons d’entrée",
"input": "Jetons d’entrée",
"cacheHitRate": "Taux de succès du cache KV",
"output": "Jetons de sortie",
"cacheHitRate": "Taux de réussite du cache",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "Temps de génération"
},
"queued": {
@@ -2147,8 +2151,7 @@
"fileEditDiffTruncated": "Différences tronquées. Ouvrez le fichier pour voir la modification complète.",
"usage": {
"context": "Dernier contexte : {{tokens}}{{capacity}} tokens",
"requests": "{{count}} requêtes au modèle",
"estimated": "Inclut une estimation de l’utilisation"
"requests": "{{count}} requêtes au modèle"
},
"activityThinkingFor": "Réflexion pendant {{duration}}",
"activityThought": "Réflexion terminée",
+12 -9
View File
@@ -1858,8 +1858,6 @@
"sessionInfo": "Detail sesi"
},
"sessionInfo": {
"title": "Sesi",
"untitled": "Topik tanpa judul",
"automations": "Otomasi",
"count": "{{count}}",
"loading": "Memuat otomasi...",
@@ -1911,15 +1909,21 @@
"reauthFallback": "Model cadangan menangani respons ini.",
"reauthSettings": "Buka pengaturan model",
"context": {
"loaded": "Dimuat",
"unloaded": "Belum dimuat",
"expand": "Perbesar konteks",
"collapse": "Perkecil konteks",
"noFiles": "Belum ada konteks yang tercatat",
"estimatedNodeTokens": "Sekitar {{value}} token",
"openFile": "Buka berkas",
"history": "Riwayat konteks",
"playHistory": "Putar riwayat konteks",
"tooltip": "Konteks {{percent}}%",
"detailsLabel": "Buka penggunaan konteks",
"panelTitle": "Penggunaan konteks",
"contextTitle": "Konteks",
"recentRounds": "Putaran terbaru",
"inputTrend": "Token masukan",
"input": "Token masukan",
"cacheHitRate": "Rasio hit KV cache",
"output": "Token keluaran",
"cacheHitRate": "Rasio cache hit",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "Waktu pembuatan"
},
"queued": {
@@ -2147,8 +2151,7 @@
"fileEditDiffTruncated": "Perbedaan dipotong. Buka file untuk melihat perubahan lengkap.",
"usage": {
"context": "Konteks terbaru: {{tokens}}{{capacity}} token",
"requests": "{{count}} permintaan model",
"estimated": "Termasuk penggunaan perkiraan"
"requests": "{{count}} permintaan model"
},
"activityThinkingFor": "Berpikir selama {{duration}}",
"activityThought": "Selesai berpikir",
+12 -9
View File
@@ -1858,8 +1858,6 @@
"sessionInfo": "セッション詳細"
},
"sessionInfo": {
"title": "セッション",
"untitled": "無題のトピック",
"automations": "自動タスク",
"count": "{{count}}",
"loading": "自動タスクを読み込み中...",
@@ -1911,15 +1909,21 @@
"reauthFallback": "今回の応答には代替モデルを使用しました。",
"reauthSettings": "モデル設定を開く",
"context": {
"loaded": "読み込み済み",
"unloaded": "未読み込み",
"expand": "コンテキストを拡大",
"collapse": "コンテキストを縮小",
"noFiles": "コンテキストはまだ記録されていません",
"estimatedNodeTokens": "約 {{value}} トークン",
"openFile": "ファイルを開く",
"history": "コンテキスト履歴",
"playHistory": "コンテキストの変化を再生",
"tooltip": "コンテキスト {{percent}}%",
"detailsLabel": "コンテキスト使用量を開く",
"panelTitle": "コンテキスト使用量",
"contextTitle": "コンテキスト",
"recentRounds": "最近のラウンド",
"inputTrend": "入力トークン",
"input": "入力トークン",
"cacheHitRate": "KV キャッシュヒット率",
"output": "出力トークン",
"cacheHitRate": "キャッシュヒット率",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "生成時間"
},
"queued": {
@@ -2147,8 +2151,7 @@
"fileEditDiffTruncated": "差分は切り詰められました。完全な変更はファイルを開いて確認してください。",
"usage": {
"context": "最新のコンテキスト: {{tokens}}{{capacity}} トークン",
"requests": "モデルリクエスト {{count}} 回",
"estimated": "推定使用量を含みます"
"requests": "モデルリクエスト {{count}} 回"
},
"activityThinkingFor": "{{duration}}考えています",
"activityThought": "思考しました",
+12 -9
View File
@@ -1858,8 +1858,6 @@
"sessionInfo": "세션 세부 정보"
},
"sessionInfo": {
"title": "세션",
"untitled": "제목 없는 주제",
"automations": "자동화",
"count": "{{count}}",
"loading": "자동화를 불러오는 중...",
@@ -1911,15 +1909,21 @@
"reauthFallback": "이번 응답은 대체 모델이 처리했습니다.",
"reauthSettings": "모델 설정 열기",
"context": {
"loaded": "불러옴",
"unloaded": "불러오지 않음",
"expand": "컨텍스트 확대",
"collapse": "컨텍스트 축소",
"noFiles": "아직 기록된 컨텍스트가 없습니다",
"estimatedNodeTokens": "약 {{value}} 토큰",
"openFile": "파일 열기",
"history": "컨텍스트 기록",
"playHistory": "컨텍스트 기록 재생",
"tooltip": "컨텍스트 {{percent}}%",
"detailsLabel": "컨텍스트 사용량 열기",
"panelTitle": "컨텍스트 사용량",
"contextTitle": "컨텍스트",
"recentRounds": "최근 라운드",
"inputTrend": "입력 토큰",
"input": "입력 토큰",
"cacheHitRate": "KV 캐시 적중률",
"output": "출력 토큰",
"cacheHitRate": "캐시 적중률",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "생성 시간"
},
"queued": {
@@ -2147,8 +2151,7 @@
"fileEditDiffTruncated": "변경 사항의 일부만 표시됩니다. 전체 내용은 파일을 열어 확인하세요.",
"usage": {
"context": "최근 컨텍스트: {{tokens}}{{capacity}} 토큰",
"requests": "모델 요청 {{count}}회",
"estimated": "예상 사용량 포함"
"requests": "모델 요청 {{count}}회"
},
"activityThinkingFor": "{{duration}} 동안 생각 중",
"activityThought": "생각함",
+12 -9
View File
@@ -1872,8 +1872,6 @@
"sessionInfo": "Detalhes da sessão"
},
"sessionInfo": {
"title": "Sessão",
"untitled": "Tópico sem título",
"automations": "Automações",
"count": "{{count}}",
"loading": "Carregando automações...",
@@ -1925,15 +1923,21 @@
"reauthFallback": "Um modelo alternativo respondeu desta vez.",
"reauthSettings": "Abrir configurações do modelo",
"context": {
"loaded": "Carregado",
"unloaded": "Não carregado",
"expand": "Expandir contexto",
"collapse": "Recolher contexto",
"noFiles": "Nenhum contexto registrado ainda",
"estimatedNodeTokens": "Cerca de {{value}} tokens",
"openFile": "Abrir arquivo",
"history": "Histórico de contexto",
"playHistory": "Reproduzir histórico do contexto",
"tooltip": "Contexto {{percent}}%",
"detailsLabel": "Abrir uso do contexto",
"panelTitle": "Uso do contexto",
"contextTitle": "Contexto",
"recentRounds": "Rodadas recentes",
"inputTrend": "Tokens de entrada",
"input": "Tokens de entrada",
"cacheHitRate": "Taxa de acertos do cache KV",
"output": "Tokens de saída",
"cacheHitRate": "Taxa de acertos de cache",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "Tempo de geração"
},
"queued": {
@@ -2341,8 +2345,7 @@
"fileEditDiffTruncated": "Diferenças truncadas. Abra o arquivo para ver a alteração completa.",
"usage": {
"context": "Contexto atual: {{tokens}}{{capacity}}",
"requests": "{{count}} chamadas nesta rodada",
"estimated": "Inclui uso estimado"
"requests": "{{count}} chamadas nesta rodada"
}
},
"recovery": {
+12 -9
View File
@@ -1858,8 +1858,6 @@
"sessionInfo": "Chi tiết phiên"
},
"sessionInfo": {
"title": "Phiên",
"untitled": "Chủ đề chưa đặt tên",
"automations": "Tự động hóa",
"count": "{{count}}",
"loading": "Đang tải tự động hóa...",
@@ -1911,15 +1909,21 @@
"reauthFallback": "Mô hình dự phòng đã xử lý phản hồi này.",
"reauthSettings": "Mở cài đặt mô hình",
"context": {
"loaded": "Đã tải",
"unloaded": "Chưa tải",
"expand": "Mở rộng ngữ cảnh",
"collapse": "Thu gọn ngữ cảnh",
"noFiles": "Chưa có ngữ cảnh được ghi nhận",
"estimatedNodeTokens": "Khoảng {{value}} token",
"openFile": "Mở tệp",
"history": "Lịch sử ngữ cảnh",
"playHistory": "Phát lịch sử ngữ cảnh",
"tooltip": "Ngữ cảnh {{percent}}%",
"detailsLabel": "Mở mức sử dụng ngữ cảnh",
"panelTitle": "Mức sử dụng ngữ cảnh",
"contextTitle": "Ngữ cảnh",
"recentRounds": "Các lượt gần đây",
"inputTrend": "Token đầu vào",
"input": "Token đầu vào",
"cacheHitRate": "Tỷ lệ hit KV cache",
"output": "Token đầu ra",
"cacheHitRate": "Tỷ lệ trúng bộ nhớ đệm",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "Thời gian tạo"
},
"queued": {
@@ -2147,8 +2151,7 @@
"fileEditDiffTruncated": "Chỉ hiển thị một phần thay đổi. Mở tệp để xem nội dung đầy đủ.",
"usage": {
"context": "Ngữ cảnh gần nhất: {{tokens}}{{capacity}} token",
"requests": "{{count}} yêu cầu mô hình",
"estimated": "Bao gồm mức sử dụng ước tính"
"requests": "{{count}} yêu cầu mô hình"
},
"activityThinkingFor": "Đang suy nghĩ trong {{duration}}",
"activityThought": "Đã suy nghĩ",
+12 -9
View File
@@ -2064,8 +2064,6 @@
"sessionInfo": "会话详情"
},
"sessionInfo": {
"title": "会话",
"untitled": "未命名话题",
"automations": "自动任务",
"count": "{{count}}",
"loading": "正在加载自动任务...",
@@ -2116,15 +2114,21 @@
"reauthFallback": "本次已由备用模型继续回复。",
"reauthSettings": "打开模型设置",
"context": {
"loaded": "已加载",
"unloaded": "未加载",
"expand": "展开上下文面板",
"collapse": "收起上下文面板",
"noFiles": "暂无上下文记录",
"estimatedNodeTokens": "约 {{value}} tokens",
"openFile": "打开文件",
"history": "上下文历史",
"playHistory": "播放上下文演变",
"tooltip": "上下文 {{percent}}%",
"detailsLabel": "打开上下文用量",
"panelTitle": "上下文用量",
"contextTitle": "上下文",
"recentRounds": "最近轮次",
"inputTrend": "输入 Token",
"input": "输入 Token",
"cacheHitRate": "KV Cache 命中率",
"output": "输出 Token",
"cacheHitRate": "缓存命中率",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "生成耗时"
},
"queued": {
@@ -2533,8 +2537,7 @@
"fileEditDiffTruncated": "仅显示部分差异,打开文件可查看完整内容。",
"usage": {
"context": "当前上下文:{{tokens}}{{capacity}}",
"requests": "本轮 {{count}} 次模型调用",
"estimated": "包含估算用量"
"requests": "本轮 {{count}} 次模型调用"
}
},
"recovery": {
+12 -9
View File
@@ -1858,8 +1858,6 @@
"sessionInfo": "對話詳細資料"
},
"sessionInfo": {
"title": "對話",
"untitled": "未命名話題",
"automations": "自動任務",
"count": "{{count}}",
"loading": "正在載入自動任務…",
@@ -1911,15 +1909,21 @@
"reauthFallback": "本次已由備用模型繼續回覆。",
"reauthSettings": "開啟模型設定",
"context": {
"loaded": "已載入",
"unloaded": "未載入",
"expand": "展開上下文面板",
"collapse": "收合上下文面板",
"noFiles": "暫無上下文紀錄",
"estimatedNodeTokens": "約 {{value}} tokens",
"openFile": "開啟檔案",
"history": "上下文歷史",
"playHistory": "播放上下文演變",
"tooltip": "上下文 {{percent}}%",
"detailsLabel": "開啟上下文用量",
"panelTitle": "上下文用量",
"contextTitle": "上下文",
"recentRounds": "最近輪次",
"inputTrend": "輸入 Token",
"input": "輸入 Token",
"cacheHitRate": "KV Cache 命中率",
"output": "輸出 Token",
"cacheHitRate": "快取命中率",
"tokenUsage": "{{used}} / {{limit}}",
"duration": "生成耗時"
},
"queued": {
@@ -2146,8 +2150,7 @@
"fileEditDiffTruncated": "僅顯示部分差異,請開啟檔案查看完整內容。",
"usage": {
"context": "目前上下文:{{tokens}}{{capacity}} tokens",
"requests": "{{count}} 次模型請求",
"estimated": "包含估算用量"
"requests": "{{count}} 次模型請求"
},
"activityThinkingFor": "思考中,已 {{duration}}",
"activityThought": "已思考",
+59 -8
View File
@@ -1,3 +1,4 @@
import { isContextGraph, isContextInspection } from "@/lib/context-graph";
import { isCompactionPhase, isCompactionReason } from "../../../packages/client-events/notifications";
import type {
ApiServicePayload,
@@ -10,6 +11,7 @@ import type {
ChannelConnectPayload,
ChannelValidationPayload,
ChatSummary,
ContextGraph,
CliAppsPayload,
FilePreviewPayload,
FileReferenceMetadata,
@@ -315,7 +317,7 @@ function isProjectionTraceDetail(value: unknown): boolean {
&& value.traceCount >= 0;
}
function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
function parseThreadProjectionEvent(value: unknown, validatedGraphs: ReadonlySet<unknown> = new Set()): ThreadProjectionEvent {
if (!isRecord(value) || typeof value.event !== "string" || typeof value.chat_id !== "string") {
throw new Error("Invalid WebUI thread event");
}
@@ -383,11 +385,13 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
if (value.text !== undefined && typeof value.text !== "string") break;
return value as unknown as ThreadProjectionEvent;
case "context_compaction":
if (value.context_snapshot !== undefined && !isContextInspection(value.context_snapshot, (graph): graph is ContextGraph => validatedGraphs.has(graph) || isContextGraph(graph))) break;
if (typeof value.compaction_id !== "string" || !value.compaction_id
|| !isCompactionPhase(value.phase)
|| (value.reason !== undefined && !isCompactionReason(value.reason))) break;
return value as unknown as ThreadProjectionEvent;
case "model_request": {
if (value.context_graph !== undefined && !validatedGraphs.has(value.context_graph) && !isContextGraph(value.context_graph)) break;
const isUsage = (usage: unknown) => isRecord(usage)
&& Object.values(usage).every((count) => typeof count === "number" && Number.isFinite(count) && count >= 0);
if (typeof value.request_id !== "string" || !value.request_id
@@ -395,6 +399,7 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|| !Number.isSafeInteger(value.sequence) || Number(value.sequence) < 0
|| !["started", "completed", "failed", "cancelled"].includes(String(value.phase))
|| (value.usage !== undefined && !isUsage(value.usage))
|| (value.request_usage != null && !isUsage(value.request_usage))
|| (value.round_usages !== undefined && (!Array.isArray(value.round_usages) || !value.round_usages.every(isUsage)))
|| (value.context_window_tokens !== undefined && (typeof value.context_window_tokens !== "number"
|| !Number.isFinite(value.context_window_tokens) || value.context_window_tokens < 0))) break;
@@ -413,12 +418,57 @@ export function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPay
if (value.projection !== "events" || !Array.isArray(value.events)) {
throw new Error("Invalid WebUI thread events");
}
const events = value.events.map(parseThreadProjectionEvent);
return {
...value,
projection: "events",
events,
} as unknown as WebuiThreadPersistedPayload;
const graphs = new Map<string, ContextGraph>();
if (value.context_graphs !== undefined) {
if (!isRecord(value.context_graphs)) throw new Error("Invalid context graph dictionary");
const table = { nodes: value.context_graph_nodes, edges: value.context_graph_edges };
if (!isContextGraph(table)) throw new Error("Invalid context graph entity table");
const resolveIndex = <T,>(entries: readonly T[], index: unknown): T => {
if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= entries.length) {
throw new Error("Unknown context graph entity reference");
}
return entries[index];
};
for (const [key, descriptor] of Object.entries(value.context_graphs)) {
if (!isRecord(descriptor) || !Array.isArray(descriptor.nodes) || !Array.isArray(descriptor.edges)) {
throw new Error("Invalid context graph dictionary entry");
}
const nodes = descriptor.nodes.map((index: unknown) => resolveIndex(table.nodes, index));
const paths = new Set(nodes.map((node) => node.path));
const edges = descriptor.edges.map((index: unknown) => {
const edge = resolveIndex(table.edges, index);
if (!paths.has(edge.source) || !paths.has(edge.target)) throw new Error("Invalid context graph edge reference");
return edge;
});
graphs.set(key, { nodes, edges });
}
}
const validatedGraphs = new Set(graphs.values());
const resolveGraph = (key: unknown): ContextGraph => {
const graph = typeof key === "string" ? graphs.get(key) : undefined;
if (!graph) throw new Error("Unknown context graph reference");
return graph;
};
const events = value.events.map((raw) => {
if (!isRecord(raw)) return parseThreadProjectionEvent(raw);
const event = { ...raw };
if (event.context_graph_ref !== undefined) {
if (event.context_graph !== undefined) throw new Error("Ambiguous context graph reference");
event.context_graph = resolveGraph(event.context_graph_ref);
delete event.context_graph_ref;
}
if (isRecord(event.context_snapshot) && event.context_snapshot.graph_ref !== undefined) {
if (event.context_snapshot.graph !== undefined) throw new Error("Ambiguous context graph reference");
const { graph_ref, ...snapshot } = event.context_snapshot;
event.context_snapshot = { ...snapshot, graph: resolveGraph(graph_ref) };
}
return parseThreadProjectionEvent(event, validatedGraphs);
});
const body: Record<string, unknown> = { ...value, projection: "events", events };
delete body.context_graphs;
delete body.context_graph_nodes;
delete body.context_graph_edges;
return body as unknown as WebuiThreadPersistedPayload;
}
function parseWebuiThreadTraceDetailPayload(value: unknown): WebuiThreadTraceDetailPayload {
@@ -432,7 +482,7 @@ function parseWebuiThreadTraceDetailPayload(value: unknown): WebuiThreadTraceDet
}
return {
message_id: value.message_id,
events: value.events.map(parseThreadProjectionEvent),
events: value.events.map((event) => parseThreadProjectionEvent(event)),
};
}
@@ -450,6 +500,7 @@ export async function fetchWebuiThread(
if (options?.before) params.set("before", options.before);
if (options?.after) params.set("after", options.after);
params.set("include_model_requests", "1");
params.set("context_graph_encoding", "references-v1");
const query = params.toString();
const suffix = query ? `?${query}` : "";
const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;
+100
View File
@@ -0,0 +1,100 @@
import type { ContextGraph, ContextGraphNode } from "@/lib/types";
import { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY, type SimulationNodeDatum } from "d3-force";
export interface GraphPosition { x: number; y: number }
export interface GraphParticle extends SimulationNodeDatum { path: string; radius: number; x: number; y: number }
// Obsidian display settings: center 0.52, repel 10, link strength 1, distance 250.
// Use 0.36 world units per reference unit to fit the compact panel.
const GRAPH_SCALE = 0.36;
const CENTER_STRENGTH = (Math.pow(0.01, 1 - 0.52) - 0.01) / 0.99;
/** Keep mutable simulation particles separate from immutable request snapshots. */
export function createGraphSimulation(graph: ContextGraph, previous: ReadonlyMap<string, GraphPosition>, width: number, height: number) {
const simulation = forceSimulation<GraphParticle>()
.alphaDecay(1 - Math.pow(0.001, 1 / 300)).velocityDecay(0.4)
// Force order matters: each force reads velocities written by the previous one.
.force("x", forceX<GraphParticle>(width / 2).strength(CENTER_STRENGTH))
.force("y", forceY<GraphParticle>(height / 2).strength(CENTER_STRENGTH))
.force("link", forceLink<GraphParticle, { source: string; target: string }>().id((node) => node.path).distance(250 * GRAPH_SCALE))
.force("charge", forceManyBody<GraphParticle>().strength(-Math.pow(10, 3) * GRAPH_SCALE ** 2))
.force("collision", forceCollide<GraphParticle>().radius(60 * GRAPH_SCALE).strength(0.5));
updateGraphSimulation(simulation, graph, previous, width, height);
return simulation;
}
export function updateGraphSimulation(simulation: ReturnType<typeof forceSimulation<GraphParticle>>, graph: ContextGraph,
previous: ReadonlyMap<string, GraphPosition>, width: number, height: number) {
const existing = new Map(simulation.nodes().map((node) => [node.path, node]));
const placed = new Map<string, GraphPosition>(existing);
const addedCount = graph.nodes.filter((node) => !existing.has(node.path)).length;
const area = (60 * GRAPH_SCALE) ** 2 * addedCount;
const outerRadius = Math.max(0, ...[...existing.values()].map((node) => Math.hypot(node.x - width / 2, node.y - height / 2)));
const ringWidth = Math.sqrt(area / Math.PI + outerRadius ** 2) - outerRadius;
const spread = Math.sqrt(area);
const adjacent = new Map<string, string[]>();
for (const edge of graph.edges) {
const sources = adjacent.get(edge.source) ?? [];
sources.push(edge.target); adjacent.set(edge.source, sources);
const targets = adjacent.get(edge.target) ?? [];
targets.push(edge.source); adjacent.set(edge.target, targets);
}
const nodes = graph.nodes.map((node): GraphParticle => {
const retained = existing.get(node.path);
if (retained) return retained;
const neighbours = (adjacent.get(node.path) ?? [])
.map((path) => placed.get(path)).filter((point): point is GraphPosition => !!point);
let position = previous.get(node.path);
if (!position && neighbours.length) position = {
x: neighbours.reduce((sum, point) => sum + point.x, 0) / neighbours.length + (Math.random() - 0.5) * spread,
y: neighbours.reduce((sum, point) => sum + point.y, 0) / neighbours.length + (Math.random() - 0.5) * spread,
};
if (!position) {
const angle = Math.random() * Math.PI * 2;
const radius = outerRadius + Math.sqrt(Math.random()) * ringWidth;
position = { x: width / 2 + Math.cos(angle) * radius, y: height / 2 + Math.sin(angle) * radius };
}
placed.set(node.path, position);
return { path: node.path, radius: 60 * GRAPH_SCALE, ...position };
});
const link = simulation.force<ReturnType<typeof forceLink<GraphParticle, { source: string; target: string }>>>("link")!;
// Clear old links before removing particles; D3 initializes forces inside nodes().
link.links([]);
simulation.nodes(nodes);
link.links(graph.edges.map((edge) => ({ ...edge })));
simulation.force<ReturnType<typeof forceCollide<GraphParticle>>>("collision")!.radius((node) => node.radius);
simulation.force<ReturnType<typeof forceX<GraphParticle>>>("x")!.x(width / 2);
simulation.force<ReturnType<typeof forceY<GraphParticle>>>("y")!.y(height / 2);
}
/** Preserve the simulation steps while bounding work per animated frame. */
export function advanceGraphSimulation(simulation: ReturnType<typeof createGraphSimulation>, elapsedMs: number, budgetMs = 8) {
// Advance physical time independently of painting cadence, but never spend an
// unbounded frame catching up after a hidden tab or a busy main thread.
const steps = Math.max(1, Math.floor(Math.min(elapsedMs, 100) * 240 / 1000));
const deadline = performance.now() + budgetMs;
for (let step = 0; step < steps; step++) {
if (simulation.alpha() <= simulation.alphaMin() && simulation.alphaTarget() === 0) break;
simulation.tick();
if (performance.now() >= deadline) break;
}
}
/** Finish the same finite layout in short slices without painting intermediate positions. */
export function startGraphSettlement(simulation: ReturnType<typeof createGraphSimulation>) {
simulation.stop().alpha(1).alphaTarget(0);
let remaining = Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay()));
return (budgetMs = 4) => {
const deadline = performance.now() + budgetMs;
do { simulation.tick(); remaining--; } while (remaining > 0 && performance.now() < deadline);
if (remaining > 0) return false;
for (const node of simulation.nodes()) { node.vx = 0; node.vy = 0; }
simulation.alpha(0);
return true;
};
}
export function nodeRadius(node: ContextGraphNode): number {
return node.state === "discovered" ? 3.5 : Math.max(4, Math.min(12.5, Math.sqrt(node.tokens) * 0.215));
}
+47
View File
@@ -0,0 +1,47 @@
import type { ContextGraph, ContextGraphNode, ContextInspection, ContextSnapshot, UIMessage, UIModelRequestSnapshot } from "@/lib/types";
export function isContextGraph(value: unknown): value is ContextGraph {
if (!value || typeof value !== "object") return false;
const graph = value as Record<string, unknown>;
if (!Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) return false;
if (!graph.nodes.every((n: unknown) => {
if (!n || typeof n !== "object") return false;
const node = n as Record<string, unknown>;
return typeof node.path === "string" && typeof node.name === "string"
&& (node.state === "loaded" || node.state === "discovered")
&& typeof node.tokens === "number" && Number.isFinite(node.tokens) && node.tokens >= 0;
})) return false;
const paths = new Set(graph.nodes.map((n: ContextGraphNode) => n.path));
return graph.edges.every((e: unknown) => {
if (!e || typeof e !== "object") return false;
const edge = e as Record<string, unknown>;
return typeof edge.source === "string" && typeof edge.target === "string"
&& paths.has(edge.source) && paths.has(edge.target);
});
}
export function isContextInspection(value: unknown, validateGraph: typeof isContextGraph = isContextGraph): value is ContextInspection {
return typeof value === "object" && value !== null
&& "graph" in value && validateGraph(value.graph)
&& "estimated_tokens" in value && typeof value.estimated_tokens === "number"
&& Number.isFinite(value.estimated_tokens) && value.estimated_tokens >= 0
&& "context_window_tokens" in value && typeof value.context_window_tokens === "number"
&& Number.isFinite(value.context_window_tokens) && value.context_window_tokens > 0;
}
export function composerContextSnapshots(
messages: UIMessage[], requests: ReadonlyMap<string, UIModelRequestSnapshot>,
): ContextSnapshot[] {
const boundary = messages.filter((message) => message.compaction?.phase === "succeeded").at(-1);
const baseline = boundary?.compaction?.contextSnapshot;
const snapshots = Array.from(requests.entries()).sort((a, b) => a[1].createdAt - b[1].createdAt)
.flatMap(([turnId, request]) => (request.contextSnapshots ?? []).filter((snapshot) => {
if (!boundary) return true;
if (turnId === boundary.turnId) {
return snapshot.turnSeq !== undefined && boundary.compaction?.turnSeq !== undefined
&& snapshot.turnSeq > boundary.compaction.turnSeq;
}
return request.createdAt > boundary.createdAt;
}));
return [...(baseline ? [baseline] : []), ...snapshots];
}
+10 -2
View File
@@ -2,7 +2,7 @@ import type { UIMessage, UIModelRequestSnapshot } from "@/lib/types";
export type ComposerUsageSnapshot = Pick<UIMessage,
"id" | "turnId" | "createdAt" | "completedAt" | "usage" | "roundUsages" | "contextWindowTokens"
> & { compacted?: boolean };
> & { compacted?: boolean; estimatedContextTokens?: number };
export function reconcileModelRequest(
current: UIModelRequestSnapshot | undefined,
@@ -44,12 +44,20 @@ export function composerUsageSnapshots(
const compactionSeq = compactions.get(row.turnId!);
const compacted = compactions.has(row.turnId!) && !(snapshot.usageTurnSeq !== undefined
&& compactionSeq !== undefined && snapshot.usageTurnSeq > compactionSeq);
if (compacted) {
const baseline = messages.filter((message) => message.turnId === row.turnId
&& message.compaction?.phase === "succeeded").at(-1)?.compaction?.contextSnapshot;
return [{ id: row.id, turnId: row.turnId, createdAt: row.createdAt, compacted: true,
estimatedContextTokens: baseline?.estimatedTokens, contextWindowTokens: baseline?.contextWindowTokens }];
}
return [{ id: row.id, turnId: row.turnId, createdAt: row.createdAt, compacted,
completedAt: snapshot.completedAt ?? row.completedAt, usage: snapshot.usage,
roundUsages: snapshot.roundUsages, contextWindowTokens: snapshot.contextWindowTokens }];
}
if (row.kind === "compaction" && row.compaction?.phase === "succeeded") {
return [{ id: row.id, createdAt: row.createdAt, compacted: true }];
return [{ id: row.id, createdAt: row.createdAt, compacted: true,
estimatedContextTokens: row.compaction.contextSnapshot?.estimatedTokens,
contextWindowTokens: row.compaction.contextSnapshot?.contextWindowTokens }];
}
if (row.role !== "assistant" || row.kind === "trace" || row.isStreaming) return [];
return [row];
+22
View File
@@ -0,0 +1,22 @@
import type { HTMLAttributes } from "react";
const MODIFIER_KEYS = new Set(["Shift", "Control", "Alt", "Meta", "CapsLock"]);
/** Preserve keyboard focus cues without treating Shift + wheel as navigation. */
export const surfaceFocusProps = {
onFocusCapture(event) {
if (event.target !== event.currentTarget) return;
if (event.currentTarget.matches(":focus-visible")) event.currentTarget.dataset.keyboardFocus = "true";
else delete event.currentTarget.dataset.keyboardFocus;
},
onBlurCapture(event) {
if (event.target === event.currentTarget) delete event.currentTarget.dataset.keyboardFocus;
},
onPointerDownCapture(event) {
delete event.currentTarget.dataset.keyboardFocus;
},
onKeyDownCapture(event) {
if (event.target === event.currentTarget && !MODIFIER_KEYS.has(event.key)
&& !event.ctrlKey && !event.metaKey && !event.altKey) event.currentTarget.dataset.keyboardFocus = "true";
},
} satisfies HTMLAttributes<HTMLElement>;
+14
View File
@@ -885,6 +885,11 @@ export function projectThreadEvent(
...(event.usage !== undefined ? { usage: event.usage } : {}),
...(event.round_usages !== undefined ? { roundUsages: event.round_usages.slice(-8) } : {}),
...(event.context_window_tokens !== undefined ? { contextWindowTokens: event.context_window_tokens } : {}),
...(event.context_graph ? { contextSnapshots: [
...(previousRequest?.contextSnapshots ?? []).filter((s) => s.id !== event.request_id),
{ id: event.request_id, turnSeq: event.turn_seq, graph: event.context_graph, usage: event.request_usage === undefined
? (event.phase === "completed" ? event.round_usages?.at(-1) : undefined) : event.request_usage ?? undefined, contextWindowTokens: event.context_window_tokens },
] } : {}),
};
state.modelRequests = new Map(state.modelRequests).set(event.turn_id, modelRequest);
return state;
@@ -1024,6 +1029,10 @@ export function projectThreadEvent(
if (event.event === "context_compaction") {
Object.assign(state, closeThreadProjectionAnswer(state));
if (event.phase === "succeeded") {
state.modelRequests = new Map(Array.from(state.modelRequests, ([turn, request]) =>
[turn, { ...request, contextSnapshots: [] }]));
}
const id = `compaction-${event.compaction_id}`;
const existing = state.messages.findIndex((message) => message.id === id);
const message: UIMessage = {
@@ -1037,6 +1046,11 @@ export function projectThreadEvent(
phase: event.phase,
turnSeq: event.turn_seq,
reason: event.reason,
...(event.context_snapshot ? { contextSnapshot: {
id, graph: event.context_snapshot.graph,
estimatedTokens: event.context_snapshot.estimated_tokens,
contextWindowTokens: event.context_snapshot.context_window_tokens,
} } : {}),
...(!options.persisted ? { announce: true } : {}),
},
...positionedTurnFields(state.messages[existing], turnFieldsForProjection(state, event, "activity"), options),
+33 -1
View File
@@ -8,6 +8,7 @@ type Role = "user" | "assistant" | "tool" | "system";
type MessageKind = "message" | "trace" | "compaction";
export interface UIContextCompaction extends ContextCompaction {
contextSnapshot?: ContextSnapshot;
/** Lifecycle event sequence, independent of the row's display position. */
turnSeq?: number;
/** Live wire transitions announce; hydrated transcript rows stay silent. */
@@ -183,7 +184,35 @@ export interface UIMessage {
}
/** Turn-owned telemetry, not a transcript row or body-history source. */
export interface ContextGraphNode {
path: string;
name: string;
state: "loaded" | "discovered";
tokens: number;
}
export interface ContextGraph {
nodes: ContextGraphNode[];
edges: { source: string; target: string }[];
}
export interface ContextInspection {
graph: ContextGraph;
estimated_tokens: number;
context_window_tokens: number;
}
export interface ContextSnapshot {
turnSeq?: number;
estimatedTokens?: number;
id: string;
graph: ContextGraph;
usage?: TurnUsage;
contextWindowTokens?: number;
}
export interface UIModelRequestSnapshot {
contextSnapshots?: ContextSnapshot[];
runId: string;
sequence: number;
turnSeq?: number;
@@ -1546,7 +1575,8 @@ export type InboundEvent =
/** Optional structured payload on progress frames (channel-specific). */
agent_ui?: AgentUIBlob;
} & InboundTurnMetadata)
| (NotificationEvent & InboundTurnMetadata)
| (Exclude<NotificationEvent, { event: "context_compaction" }> & InboundTurnMetadata)
| (Extract<NotificationEvent, { event: "context_compaction" }> & InboundTurnMetadata & { context_snapshot?: ContextInspection })
| ({
event: "file_edit";
chat_id: string;
@@ -1603,6 +1633,8 @@ export type InboundEvent =
}
| ({
event: "model_request";
request_usage?: TurnUsage | null;
context_graph?: ContextGraph;
chat_id: string;
request_id: string;
run_id: string;
+49 -2
View File
@@ -1,7 +1,54 @@
import { MemoryLruCache } from "./memory-lru-cache";
import { parseWebuiThreadPayload } from "./api";
import { readReloadCache, removeReloadCache, writeReloadCache } from "./reload-cache";
import type { WebuiThreadPersistedPayload } from "./types";
import type { ContextGraph, WebuiThreadPersistedPayload } from "./types";
/** Persist shared graph entities instead of expanding them in every replay frame. */
function reloadPayload(body: WebuiThreadPersistedPayload): unknown {
function table<T extends object>(key: (value: T) => string) {
const values: T[] = [];
const identities = new Map<T, number>();
const keys = new Map<string, number>();
return { values, index(value: T): number {
const known = identities.get(value);
if (known !== undefined) return known;
const valueKey = key(value);
let index = keys.get(valueKey);
if (index === undefined) {
index = values.length;
values.push(value);
keys.set(valueKey, index);
}
identities.set(value, index);
return index;
} };
}
const nodes = table<ContextGraph["nodes"][number]>((node) => JSON.stringify([node.path, node.name, node.tokens, node.state]));
const edges = table<ContextGraph["edges"][number]>((edge) => JSON.stringify([edge.source, edge.target]));
const references = new Map<ContextGraph, string>();
const graphs: Record<string, { nodes: number[]; edges: number[] }> = {};
const reference = (graph: ContextGraph): string => {
const known = references.get(graph);
if (known !== undefined) return known;
const key = String(references.size);
references.set(graph, key);
graphs[key] = { nodes: graph.nodes.map(nodes.index), edges: graph.edges.map(edges.index) };
return key;
};
const events = body.events.map((event) => {
if (event.event === "model_request" && event.context_graph) {
const { context_graph, ...rest } = event;
return { ...rest, context_graph_ref: reference(context_graph) };
}
if (event.event === "context_compaction" && event.context_snapshot) {
const { graph, ...snapshot } = event.context_snapshot;
return { ...event, context_snapshot: { ...snapshot, graph_ref: reference(graph) } };
}
return event;
});
return references.size ? { ...body, events, context_graphs: graphs,
context_graph_nodes: nodes.values, context_graph_edges: edges.values } : body;
}
/** Bounded canonical replay cache; the most recent snapshot also survives tab reloads. */
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
@@ -32,7 +79,7 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload
override set(key: string, body: WebuiThreadPersistedPayload): void {
super.set(key, body);
if (super.get(key)) writeReloadCache("thread", { key, body });
if (super.get(key)) writeReloadCache("thread", { key, body: reloadPayload(body) });
for (const listener of this.listeners.get(key) ?? []) listener(body);
}
+57 -3
View File
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
changeAutomationChat,
parseWebuiThreadPayload,
cancelMcpOAuth,
configureChannel,
completeMcpOAuth,
@@ -110,7 +111,7 @@ describe("webui API helpers", () => {
await fetchWebuiThread("tok", "websocket:chat-1");
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1",
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -126,7 +127,7 @@ describe("webui API helpers", () => {
});
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&include_model_requests=1",
"/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -172,7 +173,7 @@ describe("webui API helpers", () => {
})).resolves.toBe(cached);
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1",
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({
headers: {
Authorization: "Bearer tok",
@@ -1423,3 +1424,56 @@ describe("webui API helpers", () => {
);
});
});
describe("context graph response dictionaries", () => {
const graph = { nodes: [{ path: "/guide.md", name: "guide.md", tokens: 10, state: "loaded" }], edges: [] };
const request = (id: string, fields: Record<string, unknown>) => ({
event: "model_request", chat_id: "chat", request_id: id, run_id: "run", sequence: 2,
phase: "completed", ...fields,
});
const payload = (events: unknown[], fields: Record<string, unknown> = {}) => ({ schemaVersion: 3, projection: "events", events, ...fields });
it("resolves repeated graphs and checkpoint graphs into shared domain objects", () => {
const result = parseWebuiThreadPayload(payload([
request("one", { context_graph_ref: "0", request_usage: { context_tokens: 20 } }),
request("two", { context_graph_ref: "0", request_usage: null }),
{ event: "context_compaction", chat_id: "chat", compaction_id: "compact", phase: "succeeded",
context_snapshot: { graph_ref: "0", estimated_tokens: 10, context_window_tokens: 100 } },
], { context_graphs: { "0": { nodes: [0], edges: [] } }, context_graph_nodes: graph.nodes, context_graph_edges: graph.edges }));
const requests = result.events.filter((event) => event.event === "model_request");
expect(requests[0].context_graph).toBe(requests[1].context_graph);
expect(requests[0].context_graph).toEqual(graph);
expect(requests[1].request_usage).toBeNull();
expect(result.events[2]).toMatchObject({ context_snapshot: { graph } });
});
it("preserves a growing timeline while sharing unchanged node and edge entities", () => {
const nodes = Array.from({ length: 300 }, (_, index) => ({ path: `/${index}.md`, name: `${index}.md`, tokens: 10, state: "loaded" }));
const edges = nodes.slice(1).map((node, index) => ({ source: nodes[index].path, target: node.path }));
const descriptors = Object.fromEntries(Array.from({ length: 50 }, (_, index) => [String(index), {
nodes: Array.from({ length: 251 + index }, (_, n) => n),
edges: Array.from({ length: 250 + index }, (_, n) => n),
}]));
const result = parseWebuiThreadPayload(payload(Array.from({ length: 50 }, (_, index) => request(String(index), { context_graph_ref: String(index) })), {
context_graphs: descriptors, context_graph_nodes: nodes, context_graph_edges: edges,
}));
const requests = result.events.filter((event) => event.event === "model_request");
for (let index = 0; index < requests.length; index += 1) {
expect(requests[index].context_graph?.nodes).toEqual(nodes.slice(0, 251 + index));
expect(requests[index].context_graph?.edges).toEqual(edges.slice(0, 250 + index));
}
expect(requests[0].context_graph).not.toBe(requests[1].context_graph);
expect(requests[0].context_graph?.nodes[0]).toBe(requests[49].context_graph?.nodes[0]);
expect(requests[0].context_graph?.edges[0]).toBe(requests[49].context_graph?.edges[0]);
});
it("continues to accept inline graphs from older hosts", () => {
const result = parseWebuiThreadPayload(payload([request("one", { context_graph: graph })]));
expect(result.events[0]).toMatchObject({ context_graph: graph });
});
it("rejects unknown references and invalid dictionary entries", () => {
expect(() => parseWebuiThreadPayload(payload([request("one", { context_graph_ref: "missing" })], { context_graphs: {}, context_graph_nodes: [], context_graph_edges: [] }))).toThrow("Unknown context graph reference");
expect(() => parseWebuiThreadPayload(payload([], { context_graphs: { "0": { nodes: [], edges: [0] } }, context_graph_nodes: [], context_graph_edges: [{ source: "missing", target: "missing" }] }))).toThrow("Invalid context graph entity table");
});
});
+7
View File
@@ -65,6 +65,13 @@ describe("CodeBlock", () => {
expect(container.querySelectorAll("*").length).toBeLessThan(10);
});
it("keeps a Python module beyond the preview budget available as complete plain text", () => {
const code = Array.from({ length: 2800 }, (_, index) => `def function_${index}(): return "a realistic source line"`).join("\n");
render(<CodeBlock code={code} language="python" chrome="none"
showLineNumbers wrapLongLines={false} viewportHighlight />);
expect(screen.getByTestId("plain-code-fallback").querySelector("code > span > span:last-child")?.textContent).toBe(code);
});
it("paints large preview text before enhancing it, and cancels enhancement on unmount", async () => {
const callbacks = new Map<number, FrameRequestCallback>();
let next = 0;
+75 -165
View File
@@ -1,181 +1,91 @@
import { createEvent, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover";
import type { ContextSnapshot } from "@/lib/types";
function pointer(
target: HTMLElement,
type: "pointerDown" | "pointerMove" | "pointerUp" | "pointerCancel" | "lostPointerCapture",
{ y, x = 160, time = 1000, id = 1 }: { y: number; x?: number; time?: number; id?: number },
) {
const event = createEvent[type](target, {
pointerId: id, pointerType: "touch", isPrimary: true, button: 0, clientX: x, clientY: y,
});
Object.defineProperty(event, "timeStamp", { value: time });
fireEvent(target, event);
}
const first: ContextSnapshot = { id: "1", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 },
graph: { nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [] } };
async function openSheet() {
const user = userEvent.setup();
render(
<ComposerUsagePopover
bottomSheet
showLabel
context={{ contextTokens: 10000, contextWindowTokens: 200000 }}
rounds={[
{ id: "round", timestamp: 0, inputTokens: 10000, cachedTokens: 8000 },
{ id: "round-2", timestamp: 60000, inputTokens: 14000, outputTokens: 280 },
]}
/>,
);
const trigger = screen.getByTestId("composer-context-usage");
await user.click(trigger);
const sheet = screen.getByRole("dialog", { name: "Context usage" });
const handle = within(sheet).getByRole("button", { name: "Close" });
return { user, trigger, sheet, handle };
}
describe("Mobile context usage sheet", () => {
it("keeps tiny rounds tappable without exaggerating their visual token usage", async () => {
describe("Context sidebar", () => {
it("stays open while writing a message and updates the graph as new snapshots arrive", async () => {
const user = userEvent.setup();
render(<ComposerUsagePopover bottomSheet context={null} rounds={[
{ id: "small", timestamp: 0, inputTokens: 1000 },
{ id: "large", timestamp: 60000, inputTokens: 500000 },
]} />);
const content = (snapshots: ContextSnapshot[]) => <><textarea aria-label="Message" />
<ComposerUsagePopover context={null} rounds={[]} snapshots={snapshots} /></>;
const view = render(content([first]));
await user.click(screen.getByTestId("composer-context-usage"));
const [small, large] = screen.getAllByTestId("round-usage-bar");
for (const bar of [small, large]) {
expect(bar.parentElement).toHaveClass("relative", "h-full", "flex-1");
expect(bar).toHaveClass("before:absolute", "before:inset-0");
}
expect(small).toHaveStyle({ height: "0.216px" });
expect(large).toHaveStyle({ height: "108px" });
await user.pointer([{ keys: "[TouchA>]", target: small }, { keys: "[/TouchA]", target: small }]);
expect(within(screen.getByRole("dialog", { name: "Context usage" })).getByRole("dialog"))
.toHaveTextContent("1,000");
const sidebar = screen.getByRole("complementary", { name: "Context usage" });
await user.type(screen.getByRole("textbox"), "Continue reading");
expect(sidebar).toBeVisible();
expect(screen.getByRole("textbox")).toHaveValue("Continue reading");
view.rerender(content([first, { ...first, id: "2", usage: { prompt_tokens: 2000 }, graph: {
nodes: [...first.graph.nodes, { path: "/b.md", name: "b.md", state: "loaded", tokens: 200 }], edges: [],
} }]));
expect(await within(sidebar).findByRole("button", { name: "b.md" })).toBeInTheDocument();
expect(within(sidebar).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");
expect(screen.getByRole("textbox")).toHaveFocus();
await user.click(within(sidebar).getByRole("button", { name: "Expand context panel" }));
const expanded = await screen.findByRole("dialog", { name: "Context usage" });
expect(within(expanded).getByRole("button", { name: "b.md" })).toBeInTheDocument();
expect(within(expanded).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "20");
await user.click(within(expanded).getByRole("button", { name: "Collapse context panel" }));
expect(within(sidebar).getByRole("button", { name: "Expand context panel" })).toBeVisible();
await user.click(screen.getByTestId("composer-context-usage"));
await waitFor(() => expect(screen.getByTestId("composer-context-usage")).toHaveFocus());
});
it("replaces the X with a keyboard-accessible drag handle", async () => {
const { user, handle, sheet, trigger } = await openSheet();
expect(within(sheet).getAllByRole("button", { name: "Close" })).toEqual([handle]);
expect(handle.querySelector("svg")).toBeNull();
expect(handle).toHaveClass("touch-none", "h-11");
handle.focus();
await user.keyboard("{Enter}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(trigger).toHaveFocus();
});
it("keeps tapped round details open, switches rounds, and toggles the same bar closed", async () => {
const { user, sheet } = await openSheet();
const [first, second] = within(sheet).getAllByTestId("round-usage-bar");
const tap = (target: HTMLElement) => user.pointer([
{ keys: "[TouchA>]", target },
{ keys: "[/TouchA]", target },
]);
expect(first.tagName).toBe("BUTTON");
await tap(first);
const details = within(sheet).getByRole("dialog");
expect(details).toHaveTextContent("10,000");
expect(details).toHaveTextContent("80%");
expect(first).toHaveAttribute("aria-expanded", "true");
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
fireEvent.pointerLeave(first, { pointerType: "touch" });
expect(details).toBeVisible();
await tap(second);
await waitFor(() => expect(within(sheet).getAllByRole("dialog")).toHaveLength(1));
expect(within(sheet).getByRole("dialog")).toHaveTextContent("14,000");
expect(within(sheet).getByRole("dialog")).toHaveTextContent("280");
expect(first).toHaveAttribute("aria-expanded", "false");
expect(second).toHaveAttribute("aria-expanded", "true");
await tap(second);
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
expect(sheet).toBeVisible();
await tap(first);
await tap(within(sheet).getByRole("heading", { name: "Context usage" }));
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
expect(sheet).toBeVisible();
});
it("dismisses nested round details with Escape before the sheet, and supports dragging with details open", async () => {
const { user, sheet, handle, trigger } = await openSheet();
const first = within(sheet).getAllByTestId("round-usage-bar")[0];
first.focus();
await user.keyboard("{Enter}");
expect(within(sheet).getByRole("dialog")).toBeVisible();
it("mounts in the conversation's side slot and closes with Escape from its controls", async () => {
const user = userEvent.setup();
const host = document.createElement("section");
Object.defineProperty(host, "clientWidth", { value: 900 });
document.body.append(host);
const view = render(<ComposerUsagePopover sidebarHost={host} context={null} rounds={[]} snapshots={[first]} />);
await user.click(screen.getByTestId("composer-context-usage"));
const sidebar = within(host).getByRole("complementary");
act(() => within(sidebar).getByRole("button", { name: "Expand context panel" }).focus());
await user.keyboard("{Escape}");
await waitFor(() => expect(within(sheet).queryByRole("dialog")).not.toBeInTheDocument());
expect(sheet).toBeVisible();
expect(first).toHaveFocus();
await user.click(first);
pointer(handle, "pointerDown", { y: 400 });
pointer(handle, "pointerMove", { y: 520, time: 1400 });
pointer(handle, "pointerUp", { y: 520, time: 1500 });
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
expect(trigger).toHaveFocus();
await waitFor(() => expect(screen.getByTestId("composer-context-usage")).toHaveFocus());
expect(screen.getByTestId("composer-context-usage")).toHaveAttribute("aria-expanded", "false");
view.unmount(); host.remove();
});
it("keeps the open sidebar and playback when its trigger moves between responsive slots", async () => {
const user = userEvent.setup();
const toolbar = document.createElement("span");
const footer = document.createElement("span");
document.body.append(toolbar, footer);
const content = (host: HTMLElement) => <ComposerUsagePopover triggerHost={host} context={null} rounds={[]}
snapshots={[first, { ...first, id: "2", usage: { prompt_tokens: 2000 } }]} />;
const view = render(content(toolbar));
await user.click(within(toolbar).getByTestId("composer-context-usage"));
const sidebar = screen.getByRole("complementary");
await user.click(within(sidebar).getByRole("button", { name: "Play context history" }));
view.rerender(content(footer));
expect(screen.getByRole("complementary")).toBe(sidebar);
expect(within(sidebar).getByRole("progressbar")).toHaveAttribute("aria-valuenow", "10");
expect(within(footer).getByTestId("composer-context-usage")).toHaveAttribute("aria-expanded", "true");
await user.click(within(footer).getByTestId("composer-context-usage"));
expect(screen.getByRole("complementary")).toBe(sidebar);
expect(sidebar.style.getPropertyValue("--file-preview-slot-width")).toBe("0px");
// Reopening during exit retains the graph instead of remounting it.
await user.click(within(footer).getByTestId("composer-context-usage"));
expect(screen.getByRole("complementary")).toBe(sidebar);
await user.click(within(footer).getByTestId("composer-context-usage"));
await waitFor(() => expect(screen.queryByRole("complementary")).not.toBeInTheDocument());
view.unmount(); toolbar.remove(); footer.remove();
});
it.each([
[100, 500],
[32, 40],
])("dismisses after dragging %dpx in %dms and opens at the original position", async (distance, duration) => {
const { user, handle, sheet, trigger } = await openSheet();
pointer(handle, "pointerDown", { y: 400 });
pointer(handle, "pointerMove", { y: 400 + distance, time: 1000 + duration });
// happy-dom doesn't expose individual transforms through getComputedStyle.
expect(sheet.style.translate).toBe(`0 ${distance}px`);
expect(sheet).toHaveStyle({ transition: "none" });
pointer(handle, "pointerUp", { y: 400 + distance, time: 1000 + duration });
it("opens a pane-contained drawer with a visible close control on narrow panes", async () => {
const user = userEvent.setup();
const host = document.createElement("section");
Object.defineProperty(host, "clientWidth", { value: 600 });
document.body.append(host);
const view = render(<ComposerUsagePopover sidebarHost={host} context={null} rounds={[]} snapshots={[first]} />);
await user.click(screen.getByTestId("composer-context-usage"));
const drawer = within(host).getByRole("dialog", { name: "Context usage" });
await user.click(within(drawer).getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
expect(trigger).toHaveFocus();
await user.click(trigger);
expect(screen.getByRole("dialog").style.translate).toBe("0 0px");
expect(screen.getByTestId("composer-context-usage")).toHaveFocus();
view.unmount(); host.remove();
});
it.each([
{ end: "pointerUp" as const, y: 432, x: 160 },
{ end: "pointerUp" as const, y: 370, x: 160 },
{ end: "pointerUp" as const, y: 460, x: 260 },
{ end: "pointerCancel" as const, y: 500, x: 160 },
{ end: "lostPointerCapture" as const, y: 500, x: 160 },
])("snaps back without a click-through on $end at ($x, $y)", async ({ end, y, x }) => {
const { user, handle, sheet } = await openSheet();
pointer(handle, "pointerDown", { y: 400 });
pointer(handle, "pointerMove", { y, x, time: 1400 });
pointer(handle, end, { y, x, time: 1500 });
expect(sheet.style.translate).toBe("0 0px");
expect(sheet.style.transition).toBe("");
fireEvent.click(handle, { detail: 1 });
expect(screen.getByRole("dialog")).toBeVisible();
await user.click(handle);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
});
it("does not capture content scrolling or let another pointer finish the drag", async () => {
const { user, handle, sheet } = await openSheet();
const content = within(sheet).getByRole("group", { name: "Input tokens" });
pointer(content, "pointerDown", { y: 480 });
pointer(content, "pointerMove", { y: 580 });
pointer(content, "pointerUp", { y: 580, time: 1500 });
expect(sheet.style.translate).toBe("0 0px");
pointer(handle, "pointerDown", { y: 400 });
pointer(handle, "pointerMove", { y: 412 });
pointer(handle, "pointerDown", { y: 412, id: 2 });
pointer(handle, "pointerUp", { y: 600, id: 2 });
expect(sheet.style.translate).toBe("0 12px");
pointer(handle, "pointerUp", { y: 412, time: 1500 });
expect(sheet.style.translate).toBe("0 0px");
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
});
@@ -0,0 +1,11 @@
import { expect, it, vi } from "vitest";
import { fitGraphLabel } from "@/components/thread/graph-canvas";
it("fits long Unicode labels with bounded measurements and complete code points", () => {
const name = "😀".repeat(255);
const measure = vi.fn((text: string) => Array.from(text).length);
const fitted = fitGraphLabel(name, measure);
expect(fitted).toBe(`${"😀".repeat(127)}…`);
expect(measure.mock.calls.length).toBeLessThanOrEqual(10);
expect(fitGraphLabel("a.md", measure)).toBe("a.md");
});
@@ -0,0 +1,119 @@
import { describe, expect, it } from "vitest";
import { createGraphSimulation, updateGraphSimulation, advanceGraphSimulation, startGraphSettlement } from "@/lib/context-graph-layout";
import { createGraphPresentation } from "@/components/thread/graph-presentation";
import type { ContextGraph } from "@/lib/types";
const first: ContextGraph = { nodes: [{ path: "a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [] };
const next: ContextGraph = { nodes: [...first.nodes, { path: "b.md", name: "b.md", state: "discovered", tokens: 0 }],
edges: [{ source: "a.md", target: "b.md" }] };
describe("context graph continuity", () => {
it("reintroduces a loaded filename when fast replay reverses its unfinished exit", () => {
const presentation = createGraphPresentation();
const loaded: ContextGraph = { nodes: [{ path: "loop.py", name: "loop.py", state: "loaded", tokens: 200 }], edges: [] };
presentation.update(loaded, null);
presentation.advance(2000, true);
presentation.update({ nodes: [], edges: [] }, null);
presentation.advance(200, false);
const exiting = presentation.frame.nodes[0];
expect(exiting.presence).toBeGreaterThan(0);
expect(exiting.labelRemaining).toBe(0);
presentation.update(loaded, null);
expect(presentation.frame.nodes[0]).toBe(exiting);
expect(exiting.labelRemaining).toBe(1600);
presentation.advance(300, false);
presentation.update(loaded, "loop.py");
expect(exiting.labelRemaining).toBe(1300);
});
it("briefly introduces new labels without restarting existing labels on graph or focus updates", () => {
const presentation = createGraphPresentation();
presentation.update(first, null);
presentation.advance(1000, false);
expect(presentation.frame.nodes[0].labelRemaining).toBe(600);
presentation.update(next, "a.md");
presentation.advance(300, false);
expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([300, 0]);
const loaded: ContextGraph = { ...next, nodes: next.nodes.map((node) => ({ ...node, state: "loaded" })) };
presentation.update(loaded, null);
presentation.advance(300, false);
expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([0, 1300]);
presentation.update(loaded, "b.md");
presentation.advance(300, false);
expect(presentation.frame.nodes[1].labelRemaining).toBe(1000);
// Replaying an earlier, unloaded state ends the automatic label reveal.
presentation.update(next, null);
expect(presentation.advance(0, true).moving).toBe(false);
expect(presentation.frame.nodes.map((node) => node.labelRemaining)).toEqual([0, 0]);
});
it("retains existing particles and grows a linked node near its neighbour", () => {
const sim = createGraphSimulation(first, new Map(), 600, 300).stop();
const original = sim.nodes()[0];
original.x = 100; original.y = 100; original.vx = 2;
updateGraphSimulation(sim, next, new Map(), 600, 300);
expect(sim.nodes()[0]).toBe(original);
expect(original.vx).toBe(2);
expect(Math.hypot(sim.nodes()[1].x - 100, sim.nodes()[1].y - 100)).toBeLessThan(20);
const cache = new Map(sim.nodes().map((node) => [node.path, { x: node.x, y: node.y }]));
updateGraphSimulation(sim, first, cache, 600, 300);
updateGraphSimulation(sim, next, cache, 600, 300);
expect(sim.nodes()[1].x).toBe(cache.get("b.md")!.x);
expect(sim.nodes()[1].y).toBe(cache.get("b.md")!.y);
sim.stop();
});
it("settles reduced motion in slices to the same finite layout", () => {
const previous = new Map([["a.md", { x: 50, y: 80 }], ["b.md", { x: 150, y: 130 }]]);
const reference = createGraphSimulation(next, previous, 600, 300).stop();
const sliced = createGraphSimulation(next, previous, 600, 300).stop();
reference.alpha(1).alphaTarget(0).tick(300);
const advance = startGraphSettlement(sliced);
expect(advance(0)).toBe(false);
let slices = 1;
while (!advance(0)) slices++;
expect(slices).toBe(299);
expect(sliced.nodes().map(({ x, y }) => ({ x, y }))).toEqual(reference.nodes().map(({ x, y }) => ({ x, y })));
expect(sliced.nodes().every((node) => node.vx === 0 && node.vy === 0)).toBe(true);
expect(sliced.alpha()).toBe(0);
});
it("reaches the same layout at slow and fast paint rates without stretching physical time", () => {
const previous = new Map([["a.md", { x: 50, y: 80 }], ["b.md", { x: 150, y: 130 }]]);
const simulate = (frameMs: number) => {
const sim = createGraphSimulation(next, previous, 600, 300).stop();
let elapsed = 0;
while (sim.alpha() > sim.alphaMin()) {
advanceGraphSimulation(sim, frameMs, Infinity);
elapsed += frameMs;
}
return { elapsed, positions: sim.nodes().map(({ x, y }) => ({ x, y })) };
};
const fast = simulate(1000 / 60), slow = simulate(50);
expect(slow.positions).toEqual(fast.positions);
expect(Math.abs(slow.elapsed - fast.elapsed)).toBeLessThan(51);
// A constrained frame still makes progress, rather than queuing an unbounded catch-up.
const bounded = createGraphSimulation(next, previous, 600, 300).stop();
const reference = createGraphSimulation(next, previous, 600, 300).stop().tick();
advanceGraphSimulation(bounded, 10_000, 0);
expect(bounded.nodes().map(({ x, y }) => ({ x, y }))).toEqual(reference.nodes().map(({ x, y }) => ({ x, y })));
});
it("reverses an in-flight exit from its current opacity when a graph returns", () => {
const presentation = createGraphPresentation();
presentation.update(next, null);
for (let index = 0; index < 20; index++) presentation.advance(1000 / 60, false);
const node = () => presentation.frame.nodes.find((item) => item.path === "b.md")!;
expect(node().presence).toBeGreaterThan(0.7);
presentation.update(first, null);
for (let index = 0; index < 8; index++) presentation.advance(1000 / 60, false);
const fading = node().presence;
expect(fading).toBeGreaterThan(0);
expect(fading).toBeLessThan(0.5);
presentation.update(next, null);
expect(node().presence).toBe(fading);
for (let index = 0; index < 20; index++) presentation.advance(1000 / 60, false);
expect(node().presence).toBeGreaterThan(0.9);
expect(presentation.frame.edges).toHaveLength(1);
});
});
@@ -0,0 +1,70 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { ContextInspector } from "@/components/thread/ContextInspector";
import type { ContextSnapshot } from "@/lib/types";
const snapshots: ContextSnapshot[] = [
{ id: "first", contextWindowTokens: 10000, usage: { prompt_tokens: 1000 }, graph: {
nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }], edges: [],
} },
{ id: "second", contextWindowTokens: 10000, usage: { prompt_tokens: 2000, cached_tokens: 800 }, graph: {
nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 100 }, { path: "/b.md", name: "b.md", state: "discovered", tokens: 0 }],
edges: [{ source: "/a.md", target: "/b.md" }],
} },
];
describe("Context inspector", () => {
it("exposes every graph node as a named keyboard control", async () => {
const user = userEvent.setup();
render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
const node = await screen.findByRole("button", { name: "a.md" });
expect(screen.getByRole("button", { name: "b.md" })).toBeInTheDocument();
act(() => node.focus());
await user.keyboard("{Enter}");
expect(await screen.findByText("About 100 tokens")).toBeVisible();
expect(node).toHaveFocus();
});
it("opens the selected file through the supplied preview action without loading its context", async () => {
const open = vi.fn();
const user = userEvent.setup();
render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} onOpenFile={open} />);
const node = await screen.findByRole("button", { name: "a.md" });
await user.hover(node);
expect(screen.queryByText("About 100 tokens")).not.toBeInTheDocument();
await user.click(node);
expect(await screen.findByText("About 100 tokens")).toBeVisible();
expect(open).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Open file" }));
expect(open).toHaveBeenCalledWith("/a.md");
expect(snapshots[1].graph.nodes[1].state).toBe("discovered");
});
});
it("stops playback at compaction and shows the new baseline", async () => {
const { rerender } = render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
fireEvent.click(screen.getByRole("button", { name: "Play context history" }));
const compacted: ContextSnapshot = { id: "compacted", graph: { nodes: [{ path: "/system.md", name: "system.md", state: "loaded", tokens: 300 }], edges: [] },
estimatedTokens: 1500, contextWindowTokens: 10000 };
rerender(<ContextInspector context={null} rounds={[]} snapshots={[compacted]} />);
expect(screen.getByRole("progressbar")).toHaveAttribute("aria-valuenow", "15");
expect(screen.getByText("≈15%")).toBeVisible();
await waitFor(() => expect(screen.queryByRole("button", { name: "a.md" })).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "system.md" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();
});
it("shows token usage from the displayed snapshot, including estimates without cache data", () => {
const { rerender } = render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
const meter = screen.getByRole("progressbar").parentElement!.parentElement!;
fireEvent.pointerEnter(meter);
expect(screen.getByText("2k / 10k")).toBeVisible();
expect(screen.getByText("40%")).toBeVisible();
rerender(<ContextInspector context={null} rounds={[]} snapshots={[{
id: "compacted", estimatedTokens: 1500, contextWindowTokens: 10000, graph: { nodes: [], edges: [] },
}]} />);
expect(screen.getByText("≈1.5k / 10k")).toBeVisible();
});
+62
View File
@@ -0,0 +1,62 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { ContextInspector } from "@/components/thread/ContextInspector";
import type { ContextGraph, ContextSnapshot } from "@/lib/types";
// Painting is explicit here so slow rendering can be exercised without a canvas.
vi.mock("@/components/thread/ContextGraphScene", () => ({
ContextGraphScene: ({ graph, onReady }: { graph: ContextGraph; onReady: (graph: ContextGraph) => void }) =>
<button onClick={() => onReady(graph)}>Paint snapshot</button>,
}));
afterEach(() => vi.useRealTimers());
async function start(count: number) {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
const snapshots: ContextSnapshot[] = Array.from({ length: count }, (_, index) => ({
id: String(index), contextWindowTokens: 10000,
usage: { prompt_tokens: (index + 1) * 100 }, graph: { nodes: [], edges: [] },
}));
await act(async () => {
render(<ContextInspector context={null} rounds={[]} snapshots={snapshots} />);
await vi.dynamicImportSettled();
});
const play = screen.getByRole("button", { name: "Play context history" });
fireEvent.click(play);
return play;
}
const paint = () => fireEvent.click(screen.getByRole("button", { name: "Paint snapshot" }));
const progress = () => screen.getByRole("progressbar").getAttribute("aria-valuenow");
it("replays short histories at five steps per second and can restart", async () => {
const play = await start(2);
expect(play).toBeDisabled();
expect(progress()).toBe("1");
paint();
act(() => vi.advanceTimersByTime(200));
expect(progress()).toBe("2");
paint();
act(() => vi.advanceTimersByTime(200));
expect(play).toBeEnabled();
fireEvent.click(play);
expect(progress()).toBe("1");
});
it("speeds up longer histories without dropping unpainted snapshots", async () => {
await start(400);
// A delayed first paint does not skip intermediate request states.
act(() => vi.advanceTimersByTime(350));
expect(progress()).toBe("1");
paint();
act(() => vi.advanceTimersByTime(1));
expect(progress()).toBe("2");
paint();
act(() => vi.advanceTimersByTime(1));
expect(progress()).toBe("3");
paint();
act(() => vi.advanceTimersByTime(1));
expect(progress()).toBe("4");
paint();
// The fourth deadline remains at 400ms, not 100ms after its late paint.
act(() => vi.advanceTimersByTime(47));
expect(progress()).toBe("5");
});
+61
View File
@@ -0,0 +1,61 @@
import { act, createEvent, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
const originalAnimate = Object.getOwnPropertyDescriptor(Element.prototype, "animate");
let finish: (() => void) | null = null;
beforeEach(() => {
// happy-dom has no WAAPI timeline; explicitly finish the browser-owned settlement.
Object.defineProperty(Element.prototype, "animate", { configurable: true, value: () => ({
cancel: vi.fn(),
set onfinish(callback: () => void) { finish = callback; },
}) });
});
afterEach(() => {
if (originalAnimate) Object.defineProperty(Element.prototype, "animate", originalAnimate);
else Reflect.deleteProperty(Element.prototype, "animate");
finish = null;
});
function pointer(target: HTMLElement, type: "pointerDown" | "pointerMove" | "pointerUp" | "pointerCancel" | "lostPointerCapture", y: number, id = 1) {
fireEvent(target, createEvent[type](target, { pointerId: id, pointerType: "touch", isPrimary: id === 1, button: 0, clientY: y }));
}
function openDrawer() {
render(<Dialog><DialogTrigger>Open drawer</DialogTrigger><DialogContent placement="bottom" aria-describedby={undefined}>
<DialogTitle>Details</DialogTitle>
</DialogContent></Dialog>);
fireEvent.click(screen.getByRole("button", { name: "Open drawer" }));
const drawer = screen.getByRole("dialog");
Object.defineProperty(drawer, "offsetHeight", { configurable: true, value: 500 });
return { drawer, handle: screen.getByRole("button", { name: "Close" }) };
}
describe("shared bottom dialog drag", () => {
it.each(["pointerUp", "pointerCancel", "lostPointerCapture"] as const)("rebounds without click-through after %s", (end) => {
const { drawer, handle } = openDrawer();
pointer(handle, "pointerDown", 100);
pointer(handle, "pointerMove", end === "pointerUp" ? 115 : 260);
pointer(handle, end, end === "pointerUp" ? 115 : 260);
fireEvent.click(handle, { detail: 1 });
expect(screen.getByRole("dialog")).toBe(drawer);
act(() => finish?.());
expect(drawer.style.translate).toBe("0 0px");
expect(screen.getByRole("dialog")).toBe(drawer);
fireEvent.click(handle);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it("ignores another touch ending over the handle while the first touch drags", () => {
const { drawer, handle } = openDrawer();
pointer(handle, "pointerDown", 100);
pointer(handle, "pointerMove", 115);
pointer(handle, "pointerDown", 115, 2);
pointer(handle, "pointerUp", 200, 2);
expect(finish).toBeNull();
pointer(handle, "pointerMove", 120);
expect(drawer.style.translate).toBe("0 20px");
pointer(handle, "pointerCancel", 120);
act(() => finish?.());
expect(drawer.style.translate).toBe("0 0px");
});
});
+4 -3
View File
@@ -227,7 +227,7 @@ describe("FilePreviewPanel", () => {
await setAppLanguage("zh-CN");
});
expect(screen.getByRole("button", { name: "预览" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("heading", { name: "Notes" })).toBeVisible();
expect(screen.getByRole("button", { name: "原文" })).toBeInTheDocument();
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
});
@@ -246,7 +246,7 @@ describe("FilePreviewPanel", () => {
source.focus();
fireEvent.click(source);
expect(source).toHaveFocus();
expect(source).toHaveAttribute("aria-pressed", "true");
expect(source).toHaveAccessibleName("Preview");
expect(screen.getByTestId("mock-code-block").textContent).toBe(content);
expect(CodeBlock).toHaveBeenLastCalledWith(expect.objectContaining({
code: content, chrome: "none", showLineNumbers: true, wrapLongLines: false, viewportHighlight: true,
@@ -267,7 +267,8 @@ describe("FilePreviewPanel", () => {
await screen.findByRole("heading", { name: "Notes" });
fireEvent.click(screen.getByRole("button", { name: "Source" }));
rerender(view("notes.md", "a", "new"));
expect(screen.getByRole("button", { name: "Source" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("button", { name: "Preview" })).toBeVisible();
expect(screen.getByTestId("mock-code-block")).toHaveTextContent("# Notes");
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
rerender(view("other.md"));
await screen.findByRole("heading", { name: "Notes" });
@@ -43,7 +43,7 @@ describe("shared latest thread requests", () => {
const surviving = fetchLatestWebuiThread(client, "token", KEY);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
"/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest&include_model_requests=1",
"/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest&include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({ headers: { Authorization: "Bearer token", "If-None-Match": '"cached"' } }),
);
const rejected = expect(first).rejects.toMatchObject({ name: "AbortError" });
@@ -742,9 +742,9 @@ describe("MarkdownTextRenderer", () => {
expect(table).toHaveTextContent("nanobot");
expect(table).toHaveClass(
"[&_th]:whitespace-normal",
"[&_th]:[overflow-wrap:anywhere]",
"[&_th]:[overflow-wrap:normal]",
"[&_td]:whitespace-normal",
"[&_td]:[overflow-wrap:anywhere]",
"[&_td]:[overflow-wrap:normal]",
);
expect(container.firstElementChild).toHaveClass("space-y-4");
expect(container.firstElementChild).not.toHaveClass("space-y-0");
+2 -2
View File
@@ -372,7 +372,7 @@ describe("MessageBubble", () => {
rerender(<MessageBubble message={message} />);
expect(bubble).not.toHaveClass("border-dashed");
expect(bubble).toHaveClass("bg-secondary/70");
expect(bubble).toHaveClass("user-message-surface", "bg-secondary/70");
});
it("renders completed message branches with static wrapper classes", async () => {
@@ -538,7 +538,7 @@ describe("MessageBubble", () => {
expect(command.firstElementChild).toHaveClass("opacity-90");
expect(command.className).not.toMatch(/(?:^|\s)(?:bg-|border|ring|rounded)/);
expect(command.parentElement).toHaveTextContent("/model gpt-5");
expect(command.parentElement).toHaveClass("rounded-floating", "bg-secondary/70");
expect(command.parentElement).toHaveClass("rounded-floating", "user-message-surface", "bg-secondary/70");
});
it("keeps unknown and invalid slash commands as plain message text", () => {
+57 -3
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { parseWebuiThreadPayload } from "@/lib/api";
import { composerContextSnapshots } from "@/lib/context-graph";
import { composerUsageSnapshots } from "@/lib/model-request";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadTranscript } from "@/lib/thread-transcript";
@@ -18,6 +19,20 @@ function project(transcript: ThreadTranscript, event: ThreadProjectionEvent, per
}
describe("model request snapshots", () => {
it("replays each request's matching file graph and usage after reload", () => {
const transcript = new ThreadTranscript();
const first = { nodes: [{ path: "/a.md", name: "a.md", state: "loaded" as const, tokens: 100 }], edges: [] };
const second = { nodes: [...first.nodes, { path: "/b.md", name: "b.md", state: "discovered" as const, tokens: 0 }], edges: [{ source: "/a.md", target: "/b.md" }] };
for (const event of [
request(1, { request_id: "first", context_graph: first }),
request(2, { request_id: "first", phase: "completed", context_graph: first, round_usages: rounds(1) }),
request(3, { request_id: "second", context_graph: second }),
request(4, { request_id: "second", phase: "completed", context_graph: second, round_usages: rounds(2) }),
]) project(transcript, event, true);
expect(transcript.modelRequests.get("turn")?.contextSnapshots?.map((snapshot) => ({
graph: snapshot.graph, tokens: snapshot.usage?.prompt_tokens,
}))).toEqual([{ graph: first, tokens: 100 }, { graph: second, tokens: 101 }]);
});
it("validates request identity, phase, sequence, and usage at the history boundary", () => {
for (const invalid of [{ phase: "unknown" }, { sequence: -1 }, { run_id: null }, { usage: { context_tokens: "123" } }]) {
expect(() => parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...request(1), ...invalid }] })).toThrow();
@@ -60,10 +75,10 @@ describe("model request snapshots", () => {
expect(latest().compacted).toBe(false);
send({ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 3 });
expect(latest().compacted).toBe(true);
expect(latest().roundUsages).toEqual(rounds(1));
expect(latest().roundUsages).toBeUndefined();
send(request(4, { usage: usage(1), round_usages: rounds(1) }));
expect(latest().compacted).toBe(true);
expect(latest().roundUsages).toEqual(rounds(1));
expect(latest().roundUsages).toBeUndefined();
expect(projectWebuiThreadMessages(transcript.messages).map((row) => row.kind)).toEqual(["compaction"]);
const smaller = { ...usage(2), context_tokens: 50 };
send(request(5, { request_id: "request-4", phase: "completed", usage: smaller, round_usages: rounds(2) }));
@@ -86,7 +101,7 @@ describe("model request snapshots", () => {
] as ThreadProjectionEvent[]) project(transcript, event, persisted);
const snapshot = composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)!;
expect(snapshot.compacted).toBe(true);
expect(snapshot.roundUsages).toEqual(rounds(1));
expect(snapshot.roundUsages).toBeUndefined();
});
it("preserves legacy compaction invalidation and historical rounds without request events", () => {
@@ -203,3 +218,42 @@ describe("model request snapshots", () => {
expect(snapshot.roundUsages?.[0].prompt_tokens).toBe(102);
});
});
it.each([false, true])("starts a new graph history and estimated meter at compaction (persisted=%s)", (persisted) => {
const transcript = new ThreadTranscript();
const oldGraph = { nodes: [{ path: "/read.md", name: "read.md", state: "loaded" as const, tokens: 300 }], edges: [] };
const systemGraph = { nodes: [{ path: "/SOUL.md", name: "SOUL.md", state: "loaded" as const, tokens: 40 }], edges: [] };
project(transcript, request(1, { context_graph: oldGraph, phase: "completed", usage: usage(1) }), persisted);
const event = parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...envelope, event: "context_compaction", compaction_id: "boundary",
phase: "succeeded", turn_seq: 2, context_snapshot: { graph: systemGraph, estimated_tokens: 1200, context_window_tokens: 10000 } }] }).events[0];
expect(event).not.toBeNull();
if (!event) throw new Error("Compaction snapshot rejected");
project(transcript, event, persisted);
expect(composerContextSnapshots(transcript.messages, transcript.modelRequests)).toEqual([
{ id: "compaction-boundary", graph: systemGraph, estimatedTokens: 1200, contextWindowTokens: 10000 },
]);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)).toMatchObject({
compacted: true, estimatedContextTokens: 1200, contextWindowTokens: 10000,
});
const reloadedRequests = new Map(transcript.modelRequests);
reloadedRequests.set("older-turn", {
...transcript.modelRequests.get("turn")!, createdAt: 0,
contextSnapshots: [{ id: "older-request", graph: oldGraph, turnSeq: 1 }],
});
expect(composerContextSnapshots(transcript.messages, reloadedRequests).map((s) => s.id))
.toEqual(["compaction-boundary"]);
project(transcript, request(3, { context_graph: systemGraph, phase: "completed", usage: { context_tokens: 1300, request_count: 2 } }), persisted);
expect(composerContextSnapshots(transcript.messages, transcript.modelRequests).map((s) => s.id)).toEqual(["compaction-boundary", "request-3"]);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)).toMatchObject({ compacted: false, usage: { context_tokens: 1300 } });
});
it.each(["failed", "cancelled", "completed"] as const)("does not borrow previous usage for a %s request without measurement", (phase) => {
const transcript = new ThreadTranscript();
const graph = { nodes: [{ path: "/a.md", name: "a.md", state: "loaded" as const, tokens: 20 }], edges: [] };
project(transcript, request(1, { phase: "completed", context_graph: graph, request_usage: usage(1), round_usages: rounds(1) }));
project(transcript, request(2, { phase, context_graph: graph, request_usage: null, round_usages: rounds(1) }));
const frames = composerContextSnapshots(transcript.messages, transcript.modelRequests);
expect(frames[0].usage).toEqual(usage(1));
expect(frames[1].usage).toBeUndefined();
});
+16 -1
View File
@@ -1,4 +1,4 @@
import { render, screen, waitFor } from "@testing-library/react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
@@ -12,6 +12,21 @@ beforeEach(() => {
afterEach(() => restoreBrowserFocus());
it("opens Ctrl+F only in the active pane and selects a filtered message with Enter", async () => {
const user = userEvent.setup();
const jump = vi.fn();
const props = { messages: [{ id: "one", role: "user" as const, content: "alpha", createdAt: 1 }], onJumpToPrompt: jump };
const view = render(<PromptNavigator {...props} shortcutEnabled={false} />);
fireEvent.keyDown(window, { key: "f", ctrlKey: true });
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
view.rerender(<PromptNavigator {...props} shortcutEnabled />);
fireEvent.keyDown(window, { key: "f", ctrlKey: true });
const input = await screen.findByRole("textbox", { name: "Search messages" });
await waitFor(() => expect(input).toHaveFocus());
await user.keyboard("alpha{Enter}");
expect(jump).toHaveBeenCalledWith("one");
});
it("keeps a long searchable index windowed and keyboard-reachable", async () => {
const user = userEvent.setup();
const jump = vi.fn();
+49
View File
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { activateReloadCache, clearReloadCache, readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
import { parseWebuiThreadPayload } from "@/lib/api";
import { WebuiThreadCache } from "@/lib/webui-thread-cache";
import { canonicalThreadPayload } from "./thread-test-payload";
@@ -19,6 +20,54 @@ describe("tab reload cache", () => {
expect(new WebuiThreadCache().get("websocket:b")).toBeUndefined();
});
it.each(["inline", "references"])("restores all 50 growing graph frames from compact tab storage (%s)", (format) => {
activateReloadCache("ws://localhost:8765/?token=first");
const nodes = Array.from({ length: 300 }, (_, index) => ({
path: `/workspace/${index}.md`, name: `${index}.md`, tokens: 256, state: "loaded",
}));
const edges = nodes.flatMap((node, source) => [1, 2, 3].flatMap((offset) => source + offset < nodes.length
? [{ source: node.path, target: nodes[source + offset].path }] : []));
const graphs = Array.from({ length: 50 }, (_, index) => {
const count = 251 + index;
const paths = new Set(nodes.slice(0, count).map((node) => node.path));
return { nodes: nodes.slice(0, count), edges: edges.filter((edge) => paths.has(edge.source) && paths.has(edge.target)) };
});
const table = Object.fromEntries(graphs.map((graph, index) => [String(index), {
nodes: graph.nodes.map((node) => nodes.indexOf(node)), edges: graph.edges.map((edge) => edges.indexOf(edge)),
}]));
const events = graphs.map((graph, index) => ({
event: "model_request", chat_id: "growing", request_id: String(index), run_id: "run", sequence: index + 1,
phase: "completed", request_usage: { context_tokens: 10000 + index },
...(format === "inline" ? { context_graph: structuredClone(graph) } : { context_graph_ref: String(index) }),
}));
const body = parseWebuiThreadPayload({ schemaVersion: 3, sessionKey: "websocket:growing", revision: "growing-50",
projection: "events", active_turn_id: null, page: { before_cursor: "older", has_more_before: true },
events: [{ event: "context_compaction", chat_id: "growing", compaction_id: "checkpoint", phase: "succeeded",
context_snapshot: { estimated_tokens: 100, context_window_tokens: 100000,
...(format === "inline" ? { graph: structuredClone(graphs[0]) } : { graph_ref: "0" }) } }, ...events],
...(format === "references" ? { context_graphs: table, context_graph_nodes: nodes, context_graph_edges: edges } : {}),
});
const cache = new WebuiThreadCache();
cache.set("websocket:growing", body);
expect(cache.get("websocket:growing")).toBe(body);
const raw = sessionStorage.getItem("nanobot.reload.v1.thread");
expect(raw).not.toBeNull();
expect(raw!.length).toBeLessThanOrEqual(512 * 1024);
const restored = new WebuiThreadCache().get("websocket:growing");
expect(restored).toEqual(body);
expect(restored).not.toHaveProperty("context_graphs");
expect(restored).not.toHaveProperty("context_graph_nodes");
expect(restored).not.toHaveProperty("context_graph_edges");
const frames = restored!.events.filter((event) => event.event === "model_request");
expect(frames).toHaveLength(50);
for (let index = 0; index < frames.length; index += 1) {
expect(frames[index].context_graph).toEqual(graphs[index]);
expect(frames[index].request_usage?.context_tokens).toBe(10000 + index);
}
expect(frames[0].context_graph?.nodes[0]).toBe(frames[49].context_graph?.nodes[0]);
expect(frames[0].context_graph?.edges[0]).toBe(frames[49].context_graph?.edges[0]);
});
it("does not restore another gateway's data or data after logout", () => {
activateReloadCache("ws://localhost:8765/");
new WebuiThreadCache().set("websocket:a", thread);
@@ -26,8 +26,7 @@ async function loadView(fail = false) {
await initializeI18n();
await loadAllLocaleResources();
const { SessionInfoPopoverView } = await import("@/components/thread/SessionInfoPopoverView");
render(<><textarea aria-label="Unsent draft" defaultValue="Keep this draft" /><SessionInfoPopoverView
title="Release work" jobs={[job]} loading={false} loadFailed={false} now={Date.now()}
render(<><textarea aria-label="Unsent draft" defaultValue="Keep this draft" /><SessionInfoPopoverView jobs={[job]} loading={false} loadFailed={false} now={Date.now()}
onAction={async () => []} onEdit={async () => [job]}
/></>);
return loaded;
+3 -12
View File
@@ -58,7 +58,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -93,7 +92,7 @@ describe("SessionInfoPopover", () => {
let finish!: (response: Response) => void;
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
const user = userEvent.setup();
const view = render(<SessionInfoPopover client={client} sessionKey="websocket:chat-1" token="tok" title="Release work" />);
const view = render(<SessionInfoPopover client={client} sessionKey="websocket:chat-1" token="tok" />);
await user.click(screen.getByRole("button", { name: "Session details" }));
expect(screen.getByRole("status", { name: "Loading automations..." })).toHaveAttribute("aria-busy", "true");
await act(async () => finish(automationsResponse([automationJob()])));
@@ -107,7 +106,7 @@ describe("SessionInfoPopover", () => {
await act(async () => fail(new Error("Refresh failed")));
expect(screen.getByRole("button", { name: /Morning check/ })).toBeVisible();
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
view.rerender(<SessionInfoPopover client={client} sessionKey="websocket:chat-2" token="tok" title="Other project" />);
view.rerender(<SessionInfoPopover client={client} sessionKey="websocket:chat-2" token="tok" />);
expect(screen.queryByRole("button", { name: /Morning check/ })).not.toBeInTheDocument();
expect(screen.getByRole("status", { name: "Loading automations..." })).toBeVisible();
await act(async () => finish(automationsResponse([])));
@@ -128,7 +127,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -165,7 +163,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -189,14 +186,12 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="@hyperframes 使用指南"
/>,
);
await user.click(screen.getByRole("button", { name: "会话详情" }));
expect(await screen.findByText("会话")).toBeInTheDocument();
expect(screen.getByText("自动任务")).toBeInTheDocument();
expect(await screen.findByText("自动任务")).toBeInTheDocument();
expect(screen.getByText("Morning check")).toBeInTheDocument();
expect(screen.getByText(/下次/)).toBeInTheDocument();
expect(screen.queryByText("Session")).not.toBeInTheDocument();
@@ -217,7 +212,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -255,7 +249,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -284,7 +277,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
@@ -314,7 +306,6 @@ describe("SessionInfoPopover", () => {
client={client}
sessionKey="websocket:chat-1"
token="tok"
title="Release work"
/>,
);
+54 -128
View File
@@ -672,130 +672,54 @@ describe("ThreadComposer", () => {
fireEvent.focus(context);
const tooltip = await screen.findByRole("tooltip");
expect(tooltip).toHaveTextContent("Context 7%");
expect(tooltip.parentElement).toHaveClass("rounded-full", "px-2.5", "py-1");
expect(tooltip.parentElement).not.toHaveTextContent("Available");
});
it("opens an input-token chart with one bar for each logical round", () => {
render(
<ThreadComposer
onSend={vi.fn()}
modelLabel="gpt-5.6-sol"
modelPreset="gpt-5-6-sol"
modelProvider="openai_codex"
contextUsage={{
contextTokens: 14_700,
contextWindowTokens: 200_000,
}}
recentRoundUsage={[
{
id: "turn-1",
timestamp: Date.UTC(2026, 8, 3, 7, 20),
inputTokens: 18_000,
outputTokens: 280,
cachedTokens: 12_000,
generationMs: 12_000,
},
{
id: "turn-2",
timestamp: Date.UTC(2026, 8, 3, 8, 22),
inputTokens: 29_400,
outputTokens: 416,
cachedTokens: 26_180,
generationMs: 40_000,
},
]}
placeholder="Ask anything..."
/>,
);
it("opens the current graph and replays its request snapshots from the beginning", async () => {
// Happy DOM has no canvas renderer; supply the operations used by graph paint
// so replay can receive the same painted-frame acknowledgement as a browser.
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
setTransform: vi.fn(), clearRect: vi.fn(), setLineDash: vi.fn(), beginPath: vi.fn(),
moveTo: vi.fn(), lineTo: vi.fn(), stroke: vi.fn(), arc: vi.fn(), fill: vi.fn(),
roundRect: vi.fn(), fillText: vi.fn(), measureText: (text: string) => ({ width: text.length * 6 }),
} as unknown as CanvasRenderingContext2D);
render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 200, contextWindowTokens: 1000 }}
contextSnapshots={[
{ id: "first", contextWindowTokens: 1000, usage: { prompt_tokens: 100 }, graph: { nodes: [{ path: "/a.md", name: "a.md", state: "loaded", tokens: 40 }], edges: [] } },
{ id: "second", contextWindowTokens: 1000, usage: { prompt_tokens: 200 }, graph: { nodes: [{ path: "/b.md", name: "b.md", state: "loaded", tokens: 60 }], edges: [] } },
]} />);
fireEvent.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByText("Context")).toBeInTheDocument();
expect(screen.getByText("14.7K / 200K")).toBeInTheDocument();
expect(screen.getByText("Recent rounds")).toBeInTheDocument();
expect(screen.getByText("Input tokens")).toBeInTheDocument();
expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(2);
const [smallerBar, largerBar] = screen.getAllByTestId("round-usage-bar");
expect(
Number.parseFloat(smallerBar.style.height) / Number.parseFloat(largerBar.style.height),
).toBeCloseTo(18_000 / 29_400, 5);
expect(largerBar.querySelector(".kv-cache-reused")).toBeInTheDocument();
expect(largerBar.querySelector(".kv-cache-not-reused")).toBeInTheDocument();
expect(screen.queryByText("Reused")).not.toBeInTheDocument();
expect(screen.queryByText("Not reused")).not.toBeInTheDocument();
expect(screen.getByRole("img", {
name: /input tokens 29,400.*KV cache hit rate 89%.*output tokens 416.*generation time 40/i,
})).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "b.md" })).toBeInTheDocument();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");
const replay = screen.getByRole("button", { name: "Play context history" });
fireEvent.click(replay);
expect(replay).toBeDisabled();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "10");
expect(await screen.findByRole("button", { name: "a.md" })).toBeInTheDocument();
await waitFor(() => expect(replay).toBeEnabled(), { timeout: 2500 });
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");
});
it("uses each visible bar as its round detail trigger", async () => {
const user = userEvent.setup();
render(
<ThreadComposer
onSend={vi.fn()}
contextUsage={{ contextTokens: 14_700, contextWindowTokens: 200_000 }}
recentRoundUsage={[
{
id: "turn-1",
timestamp: Date.UTC(2026, 8, 3, 7, 20),
inputTokens: 18_000,
outputTokens: 280,
cachedTokens: 12_000,
},
{
id: "turn-2",
timestamp: Date.UTC(2026, 8, 3, 8, 22),
inputTokens: 29_400,
outputTokens: 416,
cachedTokens: 26_180,
},
]}
placeholder="Ask anything..."
/>,
);
await user.click(screen.getByTestId("composer-context-usage"));
const firstBar = screen.getByRole("img", { name: /input tokens 18,000/i });
const secondBar = screen.getByRole("img", { name: /input tokens 29,400/i });
expect(firstBar).toHaveAttribute("data-testid", "round-usage-bar");
expect(secondBar).toHaveAttribute("data-testid", "round-usage-bar");
await user.hover(firstBar);
const firstTooltip = await screen.findByRole("tooltip");
expect(within(firstTooltip).getByText("Input tokens")).toBeInTheDocument();
expect(within(firstTooltip).getByText("18,000")).toBeInTheDocument();
await user.click(firstBar);
await user.unhover(firstBar);
await user.hover(secondBar);
const secondTooltip = await screen.findByRole("tooltip");
expect(within(secondTooltip).getByText("Input tokens")).toBeInTheDocument();
expect(within(secondTooltip).getByText("29,400")).toBeInTheDocument();
it("shows the latest round cache metrics when inspecting legacy history", () => {
render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 14700, contextWindowTokens: 200000 }}
recentRoundUsage={[{ inputTokens: 18000, cachedTokens: 12000 },
{ inputTokens: 29400, cachedTokens: 26180 }]} />);
fireEvent.click(screen.getByTestId("composer-context-usage"));
const meter = screen.getByRole("progressbar", { name: "Context" });
fireEvent.pointerEnter(meter.parentElement!.parentElement!);
expect(screen.getByText("Cache hit rate")).toBeInTheDocument();
expect(screen.getByText("89%")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();
});
it("keeps context usage visible when the provider omits cache metrics", () => {
render(
<ThreadComposer
onSend={() => {}}
contextUsage={{ contextTokens: 14_700, contextWindowTokens: 200_000 }}
recentRoundUsage={[{
id: "turn-without-cache-metrics",
timestamp: new Date(2026, 8, 3, 16, 22).getTime(),
inputTokens: 29_400,
outputTokens: 416,
}]}
placeholder="Ask anything..."
/>,
);
render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 14700, contextWindowTokens: 200000 }}
recentRoundUsage={[{ inputTokens: 29400 }]} />);
fireEvent.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByRole("progressbar", { name: "Context 7%" })).toHaveAttribute(
"aria-valuenow",
"7",
);
const [bar] = screen.getAllByTestId("round-usage-bar");
expect(bar.firstElementChild).toHaveClass("bg-muted-foreground/25");
expect(screen.queryByText("Reused")).not.toBeInTheDocument();
const meter = screen.getByRole("progressbar", { name: "Context" });
expect(meter).toHaveAttribute("aria-valuenow", "7");
fireEvent.pointerEnter(meter.parentElement!.parentElement!);
expect(screen.queryByText("Cache hit rate")).not.toBeInTheDocument();
});
it("keeps the thread composer compact while matching the hero style", () => {
@@ -1292,6 +1216,7 @@ describe("ThreadComposer", () => {
it.each(["thread", "hero"] as const)("keeps narrow %s permissions inline and usage below without losing the draft", async (variant) => {
let width = 390;
vi.stubGlobal("innerWidth", width);
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(
() => rect({ width, height: 160 }),
);
@@ -1323,6 +1248,7 @@ describe("ThreadComposer", () => {
// A narrow desktop panel uses the same layout; resizing must not replace the textarea.
width = 800;
vi.stubGlobal("innerWidth", width);
fireEvent(window, new Event("resize"));
expect(form).not.toHaveAttribute("data-compact-controls");
expect(primary).toContainElement(access);
@@ -1374,6 +1300,7 @@ describe("ThreadComposer", () => {
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockReturnValue(
rect({ width: 390, height: 160 }),
);
vi.stubGlobal("innerWidth", 390);
const user = userEvent.setup();
const onSend = vi.fn();
render(
@@ -1381,10 +1308,7 @@ describe("ThreadComposer", () => {
onSend={onSend}
contextUsage={{ contextTokens: 10000, contextWindowTokens: 200000 }}
recentRoundUsage={[{
id: "turn-1",
timestamp: Date.UTC(2026, 8, 13, 7, 20),
inputTokens: 10000,
outputTokens: 280,
cachedTokens: 8000,
}]}
/>,
@@ -1392,12 +1316,11 @@ describe("ThreadComposer", () => {
const trigger = screen.getByTestId("composer-context-usage");
await user.click(trigger);
const sheet = screen.getByRole("dialog", { name: "Context usage" });
expect(sheet).toHaveClass("bottom-0", "max-h-[60dvh]");
expect(sheet).toHaveFocus();
expect(within(sheet).getByRole("heading", { name: "Context usage" })).toBeVisible();
expect(within(sheet).getByText("10K / 200K")).toBeVisible();
expect(within(sheet).getByTestId("round-usage-bar")).toBeVisible();
expect(sheet).toContainElement(within(sheet).getByRole("group", { name: "Input tokens" }));
expect(sheet).toHaveClass("mt-auto", "h-[85%]");
expect(sheet.contains(document.activeElement)).toBe(true);
expect(within(sheet).getByRole("heading", { name: "Context usage" })).toBeInTheDocument();
expect(within(sheet).getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "5");
expect(within(sheet).getByRole("button", { name: "Play context history" })).toBeDisabled();
expect(document.body).toHaveStyle({ pointerEvents: "none" });
if (dismissal === "Escape") await user.keyboard("{Escape}");
@@ -1410,23 +1333,24 @@ describe("ThreadComposer", () => {
expect(onSend).toHaveBeenCalledWith("still works", undefined, undefined);
});
it("releases the mobile sheet when resizing to desktop and keeps the desktop popover", async () => {
it("releases the mobile modal lock when resizing and keeps the desktop sidebar open", async () => {
let width = 390;
vi.stubGlobal("innerWidth", width);
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(
() => rect({ width, height: 160 }),
);
const user = userEvent.setup();
render(<ThreadComposer onSend={vi.fn()} contextUsage={{ contextTokens: 500, contextWindowTokens: 1000 }} />);
await user.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByRole("dialog")).toHaveClass("bottom-0");
expect(screen.getByRole("dialog")).toHaveClass("mt-auto");
width = 800;
vi.stubGlobal("innerWidth", width);
fireEvent(window, new Event("resize"));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(document.body).not.toHaveStyle({ pointerEvents: "none" });
await user.click(screen.getByTestId("composer-context-usage"));
expect(screen.getByRole("dialog", { name: "Context usage" })).not.toHaveClass("bottom-0");
expect(screen.getByRole("progressbar", { name: "Context 50%" })).toBeVisible();
expect(screen.getByRole("complementary", { name: "Context usage" })).toBeInTheDocument();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "50");
});
it.each([
@@ -1640,6 +1564,7 @@ describe("ThreadComposer", () => {
it("keeps the inline permission menu and directory picker mounted across composer widths", () => {
let width = 390;
vi.stubGlobal("innerWidth", width);
vi.spyOn(HTMLFormElement.prototype, "getBoundingClientRect").mockImplementation(() => rect({ width, height: 160 }));
const defaultScope = { project_path: "/srv/workspace", project_name: "workspace", access_mode: "full" as const };
const { container } = render(<ThreadComposer variant="hero" onSend={vi.fn()} workspaceScope={defaultScope}
@@ -1652,6 +1577,7 @@ describe("ThreadComposer", () => {
expect(row.querySelector(".thread-composer-workspace-group")).toContainElement(trigger);
expect(container.querySelector(".thread-composer-footer-primary")).toContainElement(access);
width = 800;
vi.stubGlobal("innerWidth", width);
fireEvent(window, new Event("resize"));
expect(container.querySelector(".thread-composer-meta")).toBe(row);
expect(screen.getByRole("button", { name: "Switch directory" })).toBe(trigger);
+36 -11
View File
@@ -947,7 +947,7 @@ describe("ThreadShell", () => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("renders each logical round in a completed turn as its own usage bar", async () => {
it("shows legacy history usage and clears it after successful compaction", async () => {
const client = makeClient();
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
if (String(input).includes("websocket%3Ausage-chart/webui-thread")) {
@@ -1013,10 +1013,8 @@ describe("ThreadShell", () => {
const trigger = await screen.findByTestId("composer-context-usage");
fireEvent.click(trigger);
expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(4);
expect(screen.getByRole("img", {
name: /input tokens 16,400.*KV cache hit rate 99%.*output tokens 236/i,
})).toBeInTheDocument();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "22");
expect(screen.getByRole("button", { name: "Play context history" })).toBeDisabled();
expect(screen.getByTestId("composer-context-meter")).toBeInTheDocument();
for (const phase of ["started", "failed"] as const) {
act(() => client._emitChat("usage-chart", {
@@ -1028,8 +1026,7 @@ describe("ThreadShell", () => {
event: "context_compaction", chat_id: "usage-chart",
compaction_id: "success", phase: "succeeded",
}));
expect(trigger).toHaveAccessibleName("Open context usage");
expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(4);
await waitFor(() => expect(screen.queryByTestId("composer-context-usage")).not.toBeInTheDocument());
});
it("updates composer usage from active model snapshots without changing the body", async () => {
@@ -1041,7 +1038,10 @@ describe("ThreadShell", () => {
events: [{ ...envelope, event: "user_message", text: "Waiting for answer", starts_turn: true, turn_seq: 0 }] })
: { ok: false, status: 404, json: async () => ({}) },
)));
render(wrap(client, <ThreadShell
const footer = document.createElement("div");
document.body.append(footer);
const view = render(wrap(client, <ThreadShell
composerPortalTarget={footer}
session={session("live-usage")} title="Live usage" onToggleSidebar={() => {}}
settingsSnapshot={modelSettings("test-model", "deepseek")}
/>));
@@ -1050,6 +1050,7 @@ describe("ThreadShell", () => {
phase: "completed", sequence: 1, turn_seq: 1, context_window_tokens: 1000,
usage: { prompt_tokens: 100, completion_tokens: 10, context_tokens: 100, request_count: 1 },
round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }],
context_graph: { nodes: [{ path: "/first.md", name: "first.md", state: "loaded", tokens: 40 }], edges: [] },
}));
const trigger = await screen.findByTestId("composer-context-usage");
expect(trigger).toHaveAccessibleName("Context 10%. Open context usage");
@@ -1057,11 +1058,34 @@ describe("ThreadShell", () => {
phase: "completed", sequence: 2, turn_seq: 2, context_window_tokens: 1000,
usage: { prompt_tokens: 300, completion_tokens: 20, context_tokens: 200, request_count: 2 },
round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }, { prompt_tokens: 200, completion_tokens: 10 }],
context_graph: { nodes: [{ path: "/second.md", name: "second.md", state: "loaded", tokens: 60 }], edges: [] },
}));
expect(trigger).toHaveAccessibleName("Context 20%. Open context usage");
const input = screen.getByRole("textbox");
expect(footer).toContainElement(input);
fireEvent.change(input, { target: { value: "Preserve this draft" } });
const host = document.querySelector(".thread-preview-layout")!;
Object.defineProperty(host, "clientWidth", { value: 1000 });
fireEvent(window, new Event("resize"));
act(() => input.focus());
fireEvent.click(trigger);
expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(2);
expect(host.querySelector(".thread-conversation")).toContainElement(input);
expect(footer).not.toContainElement(input);
expect(input).toHaveValue("Preserve this draft");
expect(input).toHaveFocus();
expect(screen.getByRole("progressbar", { name: "Context" })).toHaveAttribute("aria-valuenow", "20");
expect(await screen.findByRole("button", { name: "second.md" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Play context history" })).toBeEnabled();
expect(screen.getByText("Waiting for answer")).toBeInTheDocument();
const sidebar = screen.getByTestId("context-sidebar");
fireEvent.click(trigger);
expect(screen.getByTestId("context-sidebar")).toBe(sidebar);
expect(sidebar).toHaveAttribute("data-closing");
expect(footer).toContainElement(input);
expect(input).toHaveValue("Preserve this draft");
await waitFor(() => expect(screen.queryByTestId("context-sidebar")).not.toBeInTheDocument());
view.unmount();
footer.remove();
});
it.each([false, true])("restores context after compaction only with newer usage (%s)", async (newReply) => {
@@ -1090,11 +1114,12 @@ describe("ThreadShell", () => {
session={session("compact-usage")} title="Compact usage" onToggleSidebar={() => {}}
settingsSnapshot={modelSettings("test-model", "deepseek")}
/>));
const trigger = await screen.findByTestId("composer-context-usage");
await screen.findByText("Before compact");
if (newReply) {
const trigger = await screen.findByTestId("composer-context-usage");
expect(trigger).toHaveAccessibleName("Context 2%. Open context usage");
} else {
expect(trigger).toHaveAccessibleName("Open context usage");
expect(screen.queryByTestId("composer-context-usage")).not.toBeInTheDocument();
}
});
+2 -1
View File
@@ -30,7 +30,8 @@ describe("UI shape system", () => {
<DialogDescription>Content that can outgrow a keyboard-fitted frame.</DialogDescription>
</DialogContent></Dialog>);
const dialog = screen.getByRole("dialog");
expect(dialog.parentElement).toHaveClass("items-start", "overflow-y-auto");
expect(dialog.parentElement).toHaveClass("items-start", placement === "bottom" ? "overflow-clip" : "overflow-y-auto");
if (placement === "bottom") expect(dialog).toHaveClass("overflow-y-auto");
// The scroll owner stays inside Radix's overlay/scroll-lock boundary.
expect(dialog.parentElement?.parentElement).toHaveAttribute("data-state", "open");
expect(dialog).toHaveClass(placement === "bottom" ? "mt-auto" : "my-auto");
+1 -1
View File
@@ -306,7 +306,7 @@ describe("durable run recovery", () => {
await reopen();
expect(fetchMock).toHaveBeenCalledWith(
"/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1",
"/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1&context_graph_encoding=references-v1",
expect.objectContaining({ headers: { Authorization: "Bearer renewed-token" } }),
);
expect(client.getRunStartedAt("inactive")).toBeNull();