Open-source, local-first AI agent for real work.
TypeScript agent-toolsai-agentbyokcoding-agentcross-platformdesktop-appdeveloper-toolselectronharnessknowledge-basellmwikilocal-firstmcpplugin-systemprivacy-firstskillstypescriptvettaworkflow-automation
import { Button } from "@vetta-org/ui/button";
import { cn } from "@vetta-org/ui/utils";
import { type JSX, useMemo, useRef, useState } from "react";
import { formatFileSize } from "../knowledge/types";
import { hatch } from "./StorageBar";
import { StorageReadout } from "./StorageReadout";
import { layoutTreemap, type TreemapTile } from "./storage-treemap-layout";
export interface StorageEntryView {
readonly name: string;
readonly bytes: number;
readonly directory: boolean;
/** 较大的子项,从大到小;没有时不能继续展开。 */
readonly children?: readonly StorageEntryView[];
}
export interface StorageOwnerView {
/** 相对数据目录的路径。 */
readonly id: string;
readonly kind: "conversations" | "projects";
readonly title: string;
readonly meta: string;
readonly bytes: number;
readonly children: readonly StorageEntryView[];
/** 有会话记录时才能打开。 */
readonly onOpen?: () => void;
/** 正在运行的对话没有。 */
readonly onDelete?: () => void;
}
export interface StorageExplorerLabels {
readonly scanning: string;
readonly rescan: string;
readonly open: string;
readonly reveal: string;
readonly delete: string;
readonly view: string;
readonly all: string;
readonly rest: string;
readonly empty: string;
readonly largestDescription: string;
}
export interface StorageExplorerProps {
readonly labels: StorageExplorerLabels;
/** owners 是全部对话与项目,从大到小。 */
readonly explorer: { readonly totalBytes: number; readonly owners: readonly StorageOwnerView[] } | null;
readonly scanning: boolean;
readonly cleaning: boolean;
readonly onRescan: () => void;
readonly onReveal: (path: string) => void;
}
type ItemKind = "conversations" | "projects" | "folder" | "file" | "rest";
interface Item {
readonly id: string;
readonly kind: ItemKind;
readonly title: string;
readonly meta?: string;
readonly bytes: number;
readonly color: string;
/** 下一层的内容;为空时不能展开。 */
readonly children: readonly Item[];
readonly owner?: StorageOwnerView;
}
interface Level {
readonly id: string;
readonly title: string;
readonly bytes: number;
readonly items: readonly Item[];
}
/** 正在离开的一层;缩放以被点开(或被收起)的那一块为中心。 */
interface Transition {
readonly leaving: Level;
readonly origin: string;
readonly deeper: boolean;
}
const STAGE_WIDTH = 616;
const STAGE_HEIGHT = 360;
const TILE_GAP = 4;
/** 每层先列这么多,其余合成一块,点开再看。 */
const LEVEL_LIMIT = 12;
/** 合并项展开后清单列出全部,图上只画这么多。 */
const TILE_LIMIT = 24;
const REST_ID = "#rest";
const REST_COLOR = "var(--muted-foreground)";
const OWNER_COLORS = { conversations: "var(--context-segment-1)", projects: "var(--context-segment-2)" } as const;
const ICONS: Record<ItemKind, string> = {
conversations: "icon-[solar--chat-round-line-linear]",
projects: "icon-[solar--folder-linear]",
folder: "icon-[solar--folder-linear]",
file: "icon-[solar--file-linear]",
rest: "icon-[solar--layers-minimalistic-linear]",
};
const percent = (value: number, whole: number) => `${(value / whole) * 100}%`;
function entryItems(
parentId: string,
parentBytes: number,
entries: readonly StorageEntryView[],
color: string,
restLabel: string,
): Item[] {
if (entries.length === 0) return [];
const items = entries.map((entry): Item => {
const id = `${parentId}/${entry.name}`;
return {
id,
kind: entry.directory ? "folder" : "file",
title: entry.name,
bytes: entry.bytes,
color,
children: entryItems(id, entry.bytes, entry.children ?? [], color, restLabel),
};
});
// 扫描只保留较大的子项,差额合成一块;它没有明细,不能展开。
const rest = parentBytes - items.reduce((sum, item) => sum + item.bytes, 0);
if (rest < parentBytes * 0.005) return items;
return [...items, restItem(`${parentId}/${REST_ID}`, restLabel, rest, [])];
}
const restItem = (id: string, title: string, bytes: number, children: readonly Item[]): Item => ({
id,
kind: "rest",
title,
bytes,
color: REST_COLOR,
children,
});
function rootLevel(explorer: NonNullable<StorageExplorerProps["explorer"]>, labels: StorageExplorerLabels): Level {
const owners = explorer.owners.map((owner): Item => {
const color = OWNER_COLORS[owner.kind];
return {
id: owner.id,
kind: owner.kind,
title: owner.title,
meta: owner.meta,
bytes: owner.bytes,
color,
children: entryItems(owner.id, owner.bytes, owner.children, color, labels.rest),
owner,
};
});
const small = owners.slice(LEVEL_LIMIT);
const items =
small.length > 1
? [...owners.slice(0, LEVEL_LIMIT), restItem(REST_ID, labels.rest, sumBytes(small), small)]
: owners;
return { id: "", title: labels.all, bytes: explorer.totalBytes, items };
}
const sumBytes = (items: readonly Item[]) => items.reduce((sum, item) => sum + item.bytes, 0);
/** 从「全部」到当前位置的每一层;重新计算后已经不存在的层自动略去。 */
function resolveLevels(root: Level, path: readonly string[]): Level[] {
const levels = [root];
for (const id of path) {
const parent = levels.at(-1)?.items.find((item) => item.id === id);
if (!parent || parent.children.length === 0) break;
levels.push({ id: parent.id, title: parent.title, bytes: parent.bytes, items: parent.children });
}
return levels;
}
/** 图上的块;超出上限的并成最后一块,它只示意,不能点。 */
function tilesOf(level: Level): { item: Item; tile: TreemapTile }[] {
const hidden = level.items.slice(TILE_LIMIT);
const shown =
hidden.length > 0
? [...level.items.slice(0, TILE_LIMIT), restItem(`${level.id}/#hidden`, "", sumBytes(hidden), [])]
: level.items;
// 画布各边多算一个间隙再从每块里扣掉,外缘就能与正文左右对齐。
const tiles = layoutTreemap(
shown.map((item) => item.bytes),
STAGE_WIDTH + TILE_GAP,
STAGE_HEIGHT + TILE_GAP,
);
return tiles.flatMap((tile, index) => {
const item = shown[index];
return item
? [{ item, tile: { ...tile, width: tile.width - TILE_GAP, height: tile.height - TILE_GAP } }]
: [];
});
}
/** 逐层查看对话与项目的占用:矩形越大占用越多,点开进入下一层。矩形是指针快捷方式,键盘与读屏走下面的清单。 */
export function StorageExplorer(props: StorageExplorerProps): JSX.Element {
const { labels, explorer, onReveal } = props;
const topRef = useRef<HTMLDivElement>(null);
const [path, setPath] = useState<readonly string[]>([]);
const [activeId, setActiveId] = useState<string | null>(null);
const [transition, setTransition] = useState<Transition | null>(null);
const root = useMemo(() => (explorer ? rootLevel(explorer, labels) : null), [explorer, labels]);
const levels = useMemo(() => (root ? resolveLevels(root, path) : []), [root, path]);
const level = levels.at(-1);
const active = level?.items.find((item) => item.id === activeId);
const goTo = (depth: number, next?: Item) => {
if (!level) return;
const target = levels[depth];
// 深入时从被点的那块放大;返回时向当前目录在上一层里的那块收拢。
const pivotLevel = next ? level : target;
const pivotId = next?.id ?? levels[depth + 1]?.id;
const pivot = pivotLevel && tilesOf(pivotLevel).find(({ item }) => item.id === pivotId)?.tile;
setTransition({
leaving: level,
origin: pivot ? `${percent(pivot.x + pivot.width / 2, STAGE_WIDTH)} ${percent(pivot.y + pivot.height / 2, STAGE_HEIGHT)}` : "50% 50%",
deeper: next !== undefined,
});
setPath([...levels.slice(1, depth + 1).map((item) => item.id), ...(next ? [next.id] : [])]);
setActiveId(null);
// 从清单下方点开时,图可能已经滚出视野。
topRef.current?.scrollIntoView?.({ block: "nearest" });
};
const select = (item: Item) => {
if (item.children.length > 0) goTo(levels.length - 1, item);
else if (item.kind !== "rest") onReveal(item.id);
};
return (
<>
<div ref={topRef} className="scroll-mt-8" />
<StorageReadout
title={
<nav className="flex min-w-0 items-center">
{levels.map((item, index) => {
const current = index === levels.length - 1;
return (
<span key={item.id} className="flex min-w-0 items-center">
{index > 0 && (
<span
aria-hidden="true"
className="icon-[solar--alt-arrow-right-linear] mx-1 h-3 w-3 shrink-0 opacity-50"
/>
)}
<Button
variant="link"
aria-current={current ? "page" : undefined}
disabled={current}
className={cn(
"h-5 min-w-0 shrink p-0 text-[12px] font-normal hover:text-foreground hover:no-underline disabled:opacity-100",
current && levels.length > 1 ? "text-foreground" : "text-muted-foreground",
)}
onClick={() => goTo(index)}
>
<span className="max-w-40 truncate">{item.title}</span>
</Button>
</span>
);
})}
</nav>
}
bytes={level ? (active?.bytes ?? level.bytes) : null}
share={active && level && level.bytes > 0 ? active.bytes / level.bytes : undefined}
hint={active?.title ?? (levels.length === 1 ? labels.largestDescription : "")}
scanning={props.scanning}
disabled={props.cleaning}
scanningLabel={labels.scanning}
rescanLabel={labels.rescan}
onRescan={props.onRescan}
/>
<div
aria-hidden="true"
className="relative mt-6 w-full overflow-clip [contain:layout] [overflow-clip-margin:24px]"
style={{ aspectRatio: `${STAGE_WIDTH} / ${STAGE_HEIGHT}` }}
onMouseLeave={() => setActiveId(null)}
>
{transition && (
<TileLayer
key={`leaving:${transition.leaving.id}`}
level={transition.leaving}
activeId={null}
origin={transition.origin}
className={cn(
"pointer-events-none animate-out fade-out-0 fill-mode-forwards motion-reduce:hidden",
transition.deeper ? "zoom-out-115" : "zoom-out-80",
)}
onAnimationEnd={() => setTransition((current) => (current === transition ? null : current))}
/>
)}
{level && (
<TileLayer
key={level.id}
level={level}
activeId={activeId}
origin={transition?.origin}
className={cn(
"animate-in fade-in-0 motion-reduce:animate-none",
transition && !transition.deeper ? "zoom-in-110" : "zoom-in-80",
)}
onActiveChange={setActiveId}
onSelect={select}
/>
)}
</div>
{level && level.items.length === 0 && (
<p className="text-center text-[12px] text-muted-foreground">{labels.empty}</p>
)}
<ul className="-mx-3 mt-6" onMouseLeave={() => setActiveId(null)}>
{level?.items.map((item) => (
<ItemRow
key={item.id}
item={item}
labels={labels}
active={item.id === activeId}
onActive={() => setActiveId(item.id)}
onSelect={() => select(item)}
onReveal={() => onReveal(item.id)}
/>
))}
</ul>
</>
);
}
/** 一层矩形。层切换只动整层的 transform 与 opacity,不给每块单独做动画。 */
function TileLayer({
level,
activeId,
origin,
className,
onAnimationEnd,
onActiveChange,
onSelect,
}: {
readonly level: Level;
readonly activeId: string | null;
readonly origin?: string;
readonly className: string;
readonly onAnimationEnd?: () => void;
readonly onActiveChange?: (id: string) => void;
readonly onSelect?: (item: Item) => void;
}): JSX.Element {
const tiles = useMemo(() => tilesOf(level), [level]);
return (
<div
className={cn("absolute inset-0 duration-300 ease-out", className)}
style={{ transformOrigin: origin }}
onAnimationEnd={onAnimationEnd}
>
{tiles.map(({ item, tile }) => {
const strength = item.id === activeId ? (item.kind === "rest" ? 22 : 46) : item.kind === "rest" ? 10 : 28;
const inert = item.kind === "rest" && item.children.length === 0;
return (
<Button
key={item.id}
variant="ghost"
tabIndex={-1}
className={cn(
"absolute h-auto flex-col items-start justify-start gap-0.5 overflow-hidden rounded-lg px-2.5 py-2 font-normal transition-colors duration-200 active:not-aria-[haspopup]:translate-y-0",
inert && "cursor-default",
)}
style={{
left: percent(tile.x, STAGE_WIDTH),
top: percent(tile.y, STAGE_HEIGHT),
width: percent(tile.width, STAGE_WIDTH),
height: percent(tile.height, STAGE_HEIGHT),
backgroundColor: `color-mix(in srgb, ${item.color} ${strength}%, var(--background))`,
...(item.kind === "rest"
? { backgroundImage: hatch(`color-mix(in srgb, ${item.color} 14%, transparent)`) }
: {}),
}}
onMouseEnter={() => onActiveChange?.(item.id)}
onClick={() => onSelect?.(item)}
>
{tile.width >= 56 && tile.height >= 32 && (
<span className="max-w-full truncate text-[12px] text-foreground">{item.title}</span>
)}
{tile.width >= 72 && tile.height >= 52 && (
<span className="text-[11px] text-muted-foreground tabular-nums">{formatFileSize(item.bytes)}</span>
)}
</Button>
);
})}
</div>
);
}
function ItemRow({
item,
labels,
active,
onActive,
onSelect,
onReveal,
}: {
readonly item: Item;
readonly labels: StorageExplorerLabels;
readonly active: boolean;
readonly onActive: () => void;
readonly onSelect: () => void;
readonly onReveal: () => void;
}): JSX.Element {
const expandable = item.children.length > 0;
const { owner } = item;
return (
<li
className={cn(
"group relative flex items-center gap-3.5 rounded-lg px-3 py-2.5 transition-colors duration-200",
active && "bg-accent/40",
)}
onMouseEnter={onActive}
onFocus={onActive}
>
<span aria-hidden="true" className={cn("h-[18px] w-[18px] shrink-0", ICONS[item.kind])} style={{ color: item.color }} />
<div className="min-w-0 flex-1">
{item.kind === "rest" && !expandable ? (
<span className="text-[13px] text-muted-foreground">{item.title}</span>
) : (
// 整行都能点:按钮的热区铺满整行,右侧操作浮在它上面。
<Button
variant="link"
className="h-auto max-w-full justify-start p-0 text-[13px] text-foreground after:absolute after:inset-0 hover:no-underline active:not-aria-[haspopup]:translate-y-0"
aria-label={`${expandable ? labels.view : labels.reveal} ${item.title}`}
onClick={onSelect}
>
<span className="truncate" title={item.title}>
{item.title}
</span>
</Button>
)}
{item.meta && <div className="mt-0.5 truncate text-[12px] text-muted-foreground">{item.meta}</div>}
</div>
<div className="relative flex shrink-0 items-center opacity-0 transition-opacity duration-200 group-focus-within:opacity-100 group-hover:opacity-100">
{owner?.onOpen && (
<RowAction
icon="icon-[solar--chat-round-line-linear]"
label={labels.open}
title={item.title}
onClick={owner.onOpen}
/>
)}
{expandable && item.kind !== "rest" && (
<RowAction
icon="icon-[solar--folder-open-linear]"
label={labels.reveal}
title={item.title}
onClick={onReveal}
/>
)}
{owner?.onDelete && (
<RowAction
icon="icon-[solar--trash-bin-trash-linear]"
label={labels.delete}
title={item.title}
onClick={owner.onDelete}
/>
)}
</div>
<span className="w-16 shrink-0 text-right text-[13px] font-medium text-foreground tabular-nums">
{formatFileSize(item.bytes)}
</span>
<span
aria-hidden="true"
className={cn(
"-mx-1.5 h-3.5 w-3.5 shrink-0 text-muted-foreground",
expandable && "icon-[solar--alt-arrow-right-linear]",
)}
/>
</li>
);
}
function RowAction({
icon,
label,
title,
onClick,
}: {
readonly icon: string;
readonly label: string;
readonly title: string;
readonly onClick: () => void;
}): JSX.Element {
return (
<Button variant="ghost" size="icon-sm" title={label} aria-label={`${label} ${title}`} onClick={onClick}>
<span aria-hidden="true" className={cn(icon, "h-4 w-4")} />
</Button>
);
}