Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
perf: split web studio heavy chunks (#2886)
yufeng83cba39b9cdd
diff --git a/web-studio/src/components/app-devtools.tsx b/web-studio/src/components/app-devtools.tsxnew file mode 100644index 000000000..15da43f56--- /dev/null+++ b/web-studio/src/components/app-devtools.tsx@@ -0,0 +1,18 @@+import { TanStackDevtools } from '@tanstack/react-devtools'+import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'++export function AppDevtools() {+ return (+ <TanStackDevtools+ config={{+ position: 'bottom-right',+ }}+ plugins={[+ {+ name: 'TanStack Router',+ render: <TanStackRouterDevtoolsPanel />,+ },+ ]}+ />+ )+}diff --git a/web-studio/src/routes/__root.tsx b/web-studio/src/routes/__root.tsxindex cf2a4cc90..69d08b67f 100644--- a/web-studio/src/routes/__root.tsx+++ b/web-studio/src/routes/__root.tsx@@ -1,8 +1,7 @@+import { lazy, Suspense } from 'react'import { RotateCcwIcon, TriangleAlertIcon } from 'lucide-react'import { Outlet, createRootRoute } from '@tanstack/react-router'import type { ErrorComponentProps } from '@tanstack/react-router'-import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'-import { TanStackDevtools } from '@tanstack/react-devtools'import { useTranslation } from 'react-i18next'import { AppShell } from '#/components/app-shell'@@ -18,6 +17,14 @@ import {import { Toaster } from '#/components/ui/sonner'import '../styles.css'+const AppDevtools = import.meta.env.DEV+ ? lazy(() =>+ import('#/components/app-devtools').then((module) => ({+ default: module.AppDevtools,+ })),+ )+ : null+export const Route = createRootRoute({component: RootComponent,errorComponent: RootErrorComponent,@@ -30,21 +37,21 @@ function RootComponent() {<Outlet /></AppShell><Toaster />- <TanStackDevtools- config={{- position: 'bottom-right',- }}- plugins={[- {- name: 'TanStack Router',- render: <TanStackRouterDevtoolsPanel />,- },- ]}- />+ <DevtoolsSlot /></>)}+function DevtoolsSlot() {+ if (!AppDevtools) return null++ return (+ <Suspense fallback={null}>+ <AppDevtools />+ </Suspense>+ )+}+function RootErrorComponent({ error, reset }: ErrorComponentProps) {const { t } = useTranslation('common')const message = error instanceof Error ? error.message : 'Unknown error'@@ -76,17 +83,7 @@ function RootErrorComponent({ error, reset }: ErrorComponentProps) {</CardFooter></Card></div>- <TanStackDevtools- config={{- position: 'bottom-right',- }}- plugins={[- {- name: 'TanStack Router',- render: <TanStackRouterDevtoolsPanel />,- },- ]}- />+ <DevtoolsSlot /></>)}diff --git a/web-studio/src/routes/home/-components/context-commits-heatmap.tsx b/web-studio/src/routes/home/-components/context-commits-heatmap.tsxnew file mode 100644index 000000000..f44f14965--- /dev/null+++ b/web-studio/src/routes/home/-components/context-commits-heatmap.tsx@@ -0,0 +1,280 @@+import { useEffect, useLayoutEffect, useRef, useState } from 'react'+import { createPortal } from 'react-dom'+import HeatMap from '@uiw/react-heat-map'++import {+ HEATMAP_COLOR_STOPS,+ HEATMAP_EMPTY_COLOR,+ HEATMAP_MONTH_LABELS,+ HEATMAP_WEEK_LABELS,+} from '../-constants/dashboard'+import type {+ CommitHeatmapStats,+ CommitTooltip,+ HeatMapDayValue,+ HomeT,+} from '../-types/dashboard'+import { asNumber, formatNumber, formatShortDate } from '../-lib/format'+import { getHeatmapFillColor } from '../-lib/normalize'++export function ContextCommitsHeatmap({+ endDate,+ items,+ panelColors,+ startDate,+ stats,+ t,+}: {+ endDate: Date+ items: HeatMapDayValue[]+ panelColors: Record<number, string>+ startDate: Date+ stats: CommitHeatmapStats+ t: HomeT+}) {+ const [tooltip, setTooltip] = useState<CommitTooltip | null>(null)+ const heatmapScrollRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ const el = heatmapScrollRef.current+ if (!el) return+ // Align the viewport to the newest rendered cell after HeatMap layout.+ const raf = requestAnimationFrame(() => {+ const node = heatmapScrollRef.current+ if (!node) return+ const rects = node.querySelectorAll<SVGRectElement>('svg rect')+ let cellsRight = node.scrollWidth+ if (rects.length > 0) {+ const last = rects[rects.length - 1]+ const bbox = last.getBoundingClientRect()+ const containerLeft = node.getBoundingClientRect().left+ cellsRight = bbox.right - containerLeft + node.scrollLeft+ }+ node.scrollLeft = Math.max(0, cellsRight - node.clientWidth)+ })+ return () => cancelAnimationFrame(raf)+ }, [items])++ return (+ <>+ <div className="grid gap-4 xl:grid-cols-[minmax(820px,auto)_minmax(180px,1fr)]">+ <div className="min-w-0">+ <div ref={heatmapScrollRef} className="overflow-x-auto">+ <HeatMap+ className="[--heatmap-empty:oklch(0.92_0_0)] text-muted-foreground dark:[--heatmap-empty:oklch(0.31_0_0)] [&_.w-heatmap-month]:fill-current [&_.w-heatmap-week]:fill-current"+ endDate={endDate}+ height={128}+ legendCellSize={0}+ monthLabels={HEATMAP_MONTH_LABELS}+ panelColors={panelColors}+ rectProps={{ rx: 2 }}+ rectRender={(props, item) => {+ const value = item as Partial<HeatMapDayValue>+ const heatmapItem = value.details+ ? (value as HeatMapDayValue)+ : null+ const count = asNumber(value.count)+ const fill = getHeatmapFillColor(count, panelColors)+ return (+ <rect+ {...props}+ fill={fill}+ onMouseEnter={(event) => {+ if (!heatmapItem) return+ const rect = (+ event.target as SVGRectElement+ ).getBoundingClientRect()+ setTooltip({+ item: heatmapItem,+ x: rect.left + rect.width / 2,+ y: rect.top,+ })+ }}+ onMouseLeave={() => setTooltip(null)}+ style={{+ ...props.style,+ cursor: heatmapItem ? 'pointer' : 'default',+ fill,+ transition: 'fill 0.15s, opacity 0.15s',+ }}+ />+ )+ }}+ rectSize={11}+ space={3}+ startDate={startDate}+ value={items}+ weekLabels={HEATMAP_WEEK_LABELS}+ width={820}+ />+ </div>++ <div className="-mt-1 flex justify-end text-xs text-muted-foreground">+ <div className="flex items-center gap-1.5">+ <span className="mr-0.5">{t('contextCommits.legend.none')}</span>+ <span+ className="size-3 rounded-[2px]"+ style={{ backgroundColor: HEATMAP_EMPTY_COLOR }}+ />+ {HEATMAP_COLOR_STOPS.map((color, index) => (+ <span+ key={`${color}-${index}`}+ className="size-3 rounded-[2px]"+ style={{ backgroundColor: color }}+ />+ ))}+ <span className="ml-0.5">{t('contextCommits.legend.more')}</span>+ </div>+ </div>+ </div>++ <div className="grid content-start border-t border-border/60 pt-3 sm:grid-cols-3 xl:border-l xl:border-t-0 xl:pl-5 xl:pt-5">+ <ContextCommitStat+ label={t('contextCommits.stats.activeDays')}+ value={formatNumber(stats.activeDays)}+ />+ <ContextCommitStat+ label={t('contextCommits.stats.peakDay')}+ value={formatNumber(stats.peakCount)}+ />+ <ContextCommitStat+ label={t('contextCommits.stats.recentDay')}+ value={stats.recentDate ? formatShortDate(stats.recentDate) : '--'}+ />+ </div>+ </div>++ {tooltip && typeof document !== 'undefined'+ ? createPortal(+ <CommitTooltipView+ item={tooltip.item}+ t={t}+ x={tooltip.x}+ y={tooltip.y}+ />,+ document.body,+ )+ : null}+ </>+ )+}++function ContextCommitStat({ label, value }: { label: string; value: string }) {+ return (+ <div className="border-b border-border/60 py-2 last:border-b-0 sm:border-b-0 sm:border-r sm:px-4 sm:last:border-r-0 xl:border-b xl:border-r-0 xl:px-0 xl:last:border-b-0">+ <div className="text-[11px] leading-none text-muted-foreground">+ {label}+ </div>+ <div className="mt-1.5 text-lg font-semibold leading-none tabular-nums">+ {value}+ </div>+ </div>+ )+}++function CommitTooltipView({+ item,+ t,+ x,+ y,+}: {+ item: HeatMapDayValue+ t: HomeT+ x: number+ y: number+}) {+ const details = item.details+ const rows = [+ {+ label: t('contextCommits.operations.addResource'),+ value: details.add_resource,+ },+ {+ label: t('contextCommits.operations.addSkill'),+ value: details.add_skill,+ },+ {+ label: t('contextCommits.operations.sessionAddMessage'),+ value: details.session_add_message,+ },+ {+ label: t('contextCommits.operations.sessionCommit'),+ value: details.session_commit,+ },+ ]++ // Clamp the tooltip into the viewport so it never overflows on narrow screens.+ const tooltipRef = useRef<HTMLDivElement>(null)+ const [horizontalShift, setHorizontalShift] = useState(0)++ useLayoutEffect(() => {+ const el = tooltipRef.current+ if (!el) return+ const margin = 8+ const rect = el.getBoundingClientRect()+ const viewportWidth =+ window.innerWidth || document.documentElement.clientWidth+ let shift = 0+ if (rect.right > viewportWidth - margin) {+ shift = viewportWidth - margin - rect.right+ } else if (rect.left < margin) {+ shift = margin - rect.left+ }+ setHorizontalShift(shift)+ }, [item, x, y])++ return (+ <div+ ref={tooltipRef}+ className="pointer-events-none fixed z-50 w-64 max-w-[calc(100vw-1rem)] rounded-xl border border-border/70 bg-popover/95 px-3.5 py-3 text-xs text-popover-foreground shadow-2xl shadow-black/10 ring-1 ring-foreground/5 backdrop-blur-md dark:shadow-black/35"+ style={{+ left: x,+ top: y - 12,+ transform: `translate(calc(-50% + ${horizontalShift}px), -100%)`,+ }}+ >+ <div className="flex items-start justify-between gap-4">+ <div>+ <div className="font-medium tabular-nums">{details.date}</div>+ <div className="mt-0.5 text-[11px] text-muted-foreground">+ {t('contextCommits.tooltip.total')}+ </div>+ </div>+ <div className="rounded-md bg-[oklch(0.68_0.12_232_/_0.14)] px-2 py-1 text-sm font-semibold tabular-nums text-[oklch(0.45_0.13_242)] dark:bg-[oklch(0.68_0.14_232_/_0.18)] dark:text-[oklch(0.76_0.14_232)]">+ {details.total}+ </div>+ </div>++ <div className="mt-3 space-y-2 border-t border-border/70 pt-3">+ {rows.map((row, index) => (+ <div+ key={row.label}+ className="grid grid-cols-[auto_1fr_auto] items-center gap-2"+ >+ <span+ className="size-1.5 rounded-full"+ style={{+ backgroundColor:+ HEATMAP_COLOR_STOPS[+ Math.min(index, HEATMAP_COLOR_STOPS.length - 1)+ ],+ opacity: row.value > 0 ? 1 : 0.35,+ }}+ />+ <span className="min-w-0 truncate text-muted-foreground">+ {row.label}+ </span>+ <span className="font-medium tabular-nums">+ {formatNumber(row.value)}+ </span>+ </div>+ ))}+ </div>++ <span+ className="absolute top-full size-2.5 -translate-x-1/2 -translate-y-1/2 rotate-45 border-b border-r border-border/70 bg-popover/95"+ style={{ left: `calc(50% - ${horizontalShift}px)` }}+ />+ </div>+ )+}diff --git a/web-studio/src/routes/home/-components/context-commits-panel.tsx b/web-studio/src/routes/home/-components/context-commits-panel.tsxindex 7bc8cba90..bee751068 100644--- a/web-studio/src/routes/home/-components/context-commits-panel.tsx+++ b/web-studio/src/routes/home/-components/context-commits-panel.tsx@@ -1,27 +1,15 @@-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'-import { createPortal } from 'react-dom'-import HeatMap from '@uiw/react-heat-map'+import { lazy, Suspense, useMemo } from 'react'import { Skeleton } from '#/components/ui/skeleton'-import {- COMMIT_SERIES_DAYS,- HEATMAP_COLOR_STOPS,- HEATMAP_EMPTY_COLOR,- HEATMAP_MONTH_LABELS,- HEATMAP_WEEK_LABELS,-} from '../-constants/dashboard'+import { COMMIT_SERIES_DAYS } from '../-constants/dashboard'import type {- CommitTooltip,ConsoleSeries,ContextCommitItem,- HeatMapDayValue,HomeT,} from '../-types/dashboard'import {- asNumber,formatNumber,- formatShortDate,getLastDaysRange,isDisabledPayload,parseDateKey,@@ -29,23 +17,15 @@ import {import {buildHeatmapPanelColors,computeCommitHeatmapStats,- getHeatmapFillColor,normalizeCommitHeatmapData,} from '../-lib/normalize'import { EmptyState, Panel, SectionHeading } from './panel'-function ContextCommitStat({ label, value }: { label: string; value: string }) {- return (- <div className="border-b border-border/60 py-2 last:border-b-0 sm:border-b-0 sm:border-r sm:px-4 sm:last:border-r-0 xl:border-b xl:border-r-0 xl:px-0 xl:last:border-b-0">- <div className="text-[11px] leading-none text-muted-foreground">- {label}- </div>- <div className="mt-1.5 text-lg font-semibold leading-none tabular-nums">- {value}- </div>- </div>- )-}+const ContextCommitsHeatmap = lazy(() =>+ import('./context-commits-heatmap').then((module) => ({+ default: module.ContextCommitsHeatmap,+ })),+)export function ContextCommitsPanel({data,@@ -60,35 +40,10 @@ export function ContextCommitsPanel({isLoading: booleant: HomeT}) {- const [tooltip, setTooltip] = useState<CommitTooltip | null>(null)- const heatmapScrollRef = useRef<HTMLDivElement>(null)const items = useMemo(() => normalizeCommitHeatmapData(data?.items),[data?.items],)-- useEffect(() => {- const el = heatmapScrollRef.current- if (!el) return- // Wait one frame for HeatMap to lay out, then align the viewport's- // right edge with the rightmost rendered cell (not the SVG's trailing- // padding). Finds the last <rect> on the heatmap to compute the- // actual content edge.- const raf = requestAnimationFrame(() => {- const node = heatmapScrollRef.current- if (!node) return- const rects = node.querySelectorAll<SVGRectElement>('svg rect')- let cellsRight = node.scrollWidth- if (rects.length > 0) {- const last = rects[rects.length - 1]- const bbox = last.getBoundingClientRect()- const containerLeft = node.getBoundingClientRect().left- cellsRight = bbox.right - containerLeft + node.scrollLeft- }- node.scrollLeft = Math.max(0, cellsRight - node.clientWidth)- })- return () => cancelAnimationFrame(raf)- }, [items])const panelColors = useMemo(() => buildHeatmapPanelColors(items), [items])const totalCommits = useMemo(() => items.reduce((total, item) => total + item.count, 0),@@ -131,222 +86,17 @@ export function ContextCommitsPanel({) : items.length === 0 ? (<EmptyState>{t('contextCommits.empty')}</EmptyState>) : (- <>- <div className="grid gap-4 xl:grid-cols-[minmax(820px,auto)_minmax(180px,1fr)]">- <div className="min-w-0">- <div ref={heatmapScrollRef} className="overflow-x-auto">- <HeatMap- className="[--heatmap-empty:oklch(0.92_0_0)] text-muted-foreground dark:[--heatmap-empty:oklch(0.31_0_0)] [&_.w-heatmap-month]:fill-current [&_.w-heatmap-week]:fill-current"- endDate={endDate}- height={128}- legendCellSize={0}- monthLabels={HEATMAP_MONTH_LABELS}- panelColors={panelColors}- rectProps={{ rx: 2 }}- rectRender={(props, item) => {- const value = item as Partial<HeatMapDayValue>- const heatmapItem = value.details- ? (value as HeatMapDayValue)- : null- const count = asNumber(value.count)- const fill = getHeatmapFillColor(count, panelColors)- return (- <rect- {...props}- fill={fill}- onMouseEnter={(event) => {- if (!heatmapItem) return- const rect = (- event.target as SVGRectElement- ).getBoundingClientRect()- setTooltip({- item: heatmapItem,- x: rect.left + rect.width / 2,- y: rect.top,- })- }}- onMouseLeave={() => setTooltip(null)}- style={{- ...props.style,- cursor: heatmapItem ? 'pointer' : 'default',- fill,- transition: 'fill 0.15s, opacity 0.15s',- }}- />- )- }}- rectSize={11}- space={3}- startDate={startDate}- value={items}- weekLabels={HEATMAP_WEEK_LABELS}- width={820}- />- </div>-- <div className="-mt-1 flex justify-end text-xs text-muted-foreground">- <div className="flex items-center gap-1.5">- <span className="mr-0.5">- {t('contextCommits.legend.none')}- </span>- <span- className="size-3 rounded-[2px]"- style={{ backgroundColor: HEATMAP_EMPTY_COLOR }}- />- {HEATMAP_COLOR_STOPS.map((color, index) => (- <span- key={`${color}-${index}`}- className="size-3 rounded-[2px]"- style={{ backgroundColor: color }}- />- ))}- <span className="ml-0.5">- {t('contextCommits.legend.more')}- </span>- </div>- </div>- </div>-- <div className="grid content-start border-t border-border/60 pt-3 sm:grid-cols-3 xl:border-l xl:border-t-0 xl:pl-5 xl:pt-5">- <ContextCommitStat- label={t('contextCommits.stats.activeDays')}- value={formatNumber(stats.activeDays)}- />- <ContextCommitStat- label={t('contextCommits.stats.peakDay')}- value={formatNumber(stats.peakCount)}- />- <ContextCommitStat- label={t('contextCommits.stats.recentDay')}- value={- stats.recentDate ? formatShortDate(stats.recentDate) : '--'- }- />- </div>- </div>- </>+ <Suspense fallback={<Skeleton className="h-72 w-full" />}>+ <ContextCommitsHeatmap+ endDate={endDate}+ items={items}+ panelColors={panelColors}+ startDate={startDate}+ stats={stats}+ t={t}+ />+ </Suspense>)}-- {tooltip && typeof document !== 'undefined'- ? createPortal(- <CommitTooltipView- item={tooltip.item}- t={t}- x={tooltip.x}- y={tooltip.y}- />,- document.body,- )- : null}</Panel>)}--function CommitTooltipView({- item,- t,- x,- y,-}: {- item: HeatMapDayValue- t: HomeT- x: number- y: number-}) {- const details = item.details- const rows = [- {- label: t('contextCommits.operations.addResource'),- value: details.add_resource,- },- {- label: t('contextCommits.operations.addSkill'),- value: details.add_skill,- },- {- label: t('contextCommits.operations.sessionAddMessage'),- value: details.session_add_message,- },- {- label: t('contextCommits.operations.sessionCommit'),- value: details.session_commit,- },- ]-- // Clamp the tooltip into the viewport so it never overflows on narrow- // (mobile) screens. We render once with the centered transform, then- // measure and re-apply a clamped horizontal offset.- const tooltipRef = useRef<HTMLDivElement>(null)- const [horizontalShift, setHorizontalShift] = useState(0)-- useLayoutEffect(() => {- const el = tooltipRef.current- if (!el) return- const margin = 8- const rect = el.getBoundingClientRect()- const viewportWidth =- window.innerWidth || document.documentElement.clientWidth- let shift = 0- if (rect.right > viewportWidth - margin) {- shift = viewportWidth - margin - rect.right- } else if (rect.left < margin) {- shift = margin - rect.left- }- setHorizontalShift(shift)- }, [item, x, y])-- return (- <div- ref={tooltipRef}- className="pointer-events-none fixed z-50 w-64 max-w-[calc(100vw-1rem)] rounded-xl border border-border/70 bg-popover/95 px-3.5 py-3 text-xs text-popover-foreground shadow-2xl shadow-black/10 ring-1 ring-foreground/5 backdrop-blur-md dark:shadow-black/35"- style={{- left: x,- top: y - 12,- transform: `translate(calc(-50% + ${horizontalShift}px), -100%)`,- }}- >- <div className="flex items-start justify-between gap-4">- <div>- <div className="font-medium tabular-nums">{details.date}</div>- <div className="mt-0.5 text-[11px] text-muted-foreground">- {t('contextCommits.tooltip.total')}- </div>- </div>- <div className="rounded-md bg-[oklch(0.68_0.12_232_/_0.14)] px-2 py-1 text-sm font-semibold tabular-nums text-[oklch(0.45_0.13_242)] dark:bg-[oklch(0.68_0.14_232_/_0.18)] dark:text-[oklch(0.76_0.14_232)]">- {details.total}- </div>- </div>-- <div className="mt-3 space-y-2 border-t border-border/70 pt-3">- {rows.map((row, index) => (- <div- key={row.label}- className="grid grid-cols-[auto_1fr_auto] items-center gap-2"- >- <span- className="size-1.5 rounded-full"- style={{- backgroundColor:- HEATMAP_COLOR_STOPS[- Math.min(index, HEATMAP_COLOR_STOPS.length - 1)- ],- opacity: row.value > 0 ? 1 : 0.35,- }}- />- <span className="min-w-0 truncate text-muted-foreground">- {row.label}- </span>- <span className="font-medium tabular-nums">- {formatNumber(row.value)}- </span>- </div>- ))}- </div>-- <span- className="absolute top-full size-2.5 -translate-x-1/2 -translate-y-1/2 rotate-45 border-b border-r border-border/70 bg-popover/95"- style={{ left: `calc(50% - ${horizontalShift}px)` }}- />- </div>- )-}diff --git a/web-studio/src/routes/home/-components/token-trend-chart.tsx b/web-studio/src/routes/home/-components/token-trend-chart.tsxnew file mode 100644index 000000000..98ebc70be--- /dev/null+++ b/web-studio/src/routes/home/-components/token-trend-chart.tsx@@ -0,0 +1,226 @@+import {+ Area,+ AreaChart,+ CartesianGrid,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from 'recharts'++import { TOKEN_COLORS } from '../-constants/dashboard'+import type {+ HomeT,+ TokenSeriesItem,+ TokenTrendPayload,+} from '../-types/dashboard'+import { formatNumber, formatShortDate } from '../-lib/format'++export function TokenTrendChart({+ items,+ t,+}: {+ items: Array<Required<TokenSeriesItem>>+ t: HomeT+}) {+ return (+ <>+ <div className="h-72 min-h-72 min-w-0 w-full">+ <ResponsiveContainer+ width="100%"+ height="100%"+ initialDimension={{ width: 720, height: 288 }}+ minWidth={1}+ minHeight={1}+ >+ <AreaChart+ data={items}+ margin={{ bottom: 0, left: 0, right: 12, top: 8 }}+ >+ <defs>+ <linearGradient+ id="tokenTrendVlmInput"+ x1="0"+ x2="0"+ y1="0"+ y2="1"+ >+ <stop+ offset="5%"+ stopColor={TOKEN_COLORS.input}+ stopOpacity={0.52}+ />+ <stop+ offset="95%"+ stopColor={TOKEN_COLORS.input}+ stopOpacity={0.14}+ />+ </linearGradient>+ <linearGradient+ id="tokenTrendVlmOutput"+ x1="0"+ x2="0"+ y1="0"+ y2="1"+ >+ <stop+ offset="5%"+ stopColor={TOKEN_COLORS.output}+ stopOpacity={0.46}+ />+ <stop+ offset="95%"+ stopColor={TOKEN_COLORS.output}+ stopOpacity={0.11}+ />+ </linearGradient>+ <linearGradient+ id="tokenTrendEmbedding"+ x1="0"+ x2="0"+ y1="0"+ y2="1"+ >+ <stop+ offset="5%"+ stopColor={TOKEN_COLORS.embedding}+ stopOpacity={0.36}+ />+ <stop+ offset="95%"+ stopColor={TOKEN_COLORS.embedding}+ stopOpacity={0.08}+ />+ </linearGradient>+ </defs>+ <CartesianGrid+ stroke="currentColor"+ strokeOpacity={0.08}+ vertical={false}+ />+ <XAxis+ axisLine={false}+ className="text-muted-foreground"+ dataKey="date"+ tick={{ fill: 'currentColor', fontSize: 12 }}+ tickFormatter={formatShortDate}+ tickLine={false}+ />+ <YAxis+ axisLine={false}+ className="text-muted-foreground"+ tick={{ fill: 'currentColor', fontSize: 12 }}+ tickFormatter={(value) => Number(value).toLocaleString()}+ tickLine={false}+ width={64}+ />+ <Tooltip+ cursor={{ stroke: 'currentColor', strokeOpacity: 0.12 }}+ content={<TokenTrendTooltip t={t} />}+ />+ <Area+ dataKey="vlm_input"+ fill="url(#tokenTrendVlmInput)"+ name="vlm_input"+ stackId="tokens"+ stroke={TOKEN_COLORS.input}+ strokeWidth={2}+ type="monotone"+ />+ <Area+ dataKey="vlm_output"+ fill="url(#tokenTrendVlmOutput)"+ name="vlm_output"+ stackId="tokens"+ stroke={TOKEN_COLORS.output}+ strokeWidth={2}+ type="monotone"+ />+ <Area+ dataKey="embedding_input"+ fill="url(#tokenTrendEmbedding)"+ name="embedding_input"+ stackId="tokens"+ stroke={TOKEN_COLORS.embedding}+ strokeWidth={2}+ type="monotone"+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ <div className="mt-4 flex flex-wrap gap-4 text-sm text-muted-foreground">+ <LegendDot+ color={TOKEN_COLORS.input}+ label={t('todayTokens.vlmInput')}+ />+ <LegendDot+ color={TOKEN_COLORS.output}+ label={t('todayTokens.vlmOutput')}+ />+ <LegendDot+ color={TOKEN_COLORS.embedding}+ label={t('todayTokens.embeddingInput')}+ />+ </div>+ </>+ )+}++function LegendDot({ color, label }: { color: string; label: string }) {+ return (+ <span className="inline-flex items-center gap-2">+ <span+ className="size-2.5 rounded-full"+ style={{ backgroundColor: color }}+ />+ <span>{label}</span>+ </span>+ )+}++function TokenTrendTooltip({+ active,+ label,+ payload,+ t,+}: {+ active?: boolean+ label?: string | number+ payload?: TokenTrendPayload[]+ t: HomeT+}) {+ if (!active || !payload?.length) return null++ const labelForKey = (key: string | undefined) => {+ if (key === 'vlm_input') return t('todayTokens.vlmInput')+ if (key === 'vlm_output') return t('todayTokens.vlmOutput')+ return t('todayTokens.embeddingInput')+ }++ return (+ <div className="min-w-56 rounded-xl border border-border/70 bg-popover/95 px-3.5 py-3 text-xs text-popover-foreground shadow-2xl shadow-black/10 ring-1 ring-foreground/5 backdrop-blur-md dark:shadow-black/35">+ <div className="font-medium tabular-nums text-foreground">+ {String(label ?? '')}+ </div>+ <div className="mt-3 space-y-2 border-t border-border/70 pt-3">+ {payload.map((item) => (+ <div+ key={item.dataKey ?? item.name}+ className="grid grid-cols-[auto_1fr_auto] items-center gap-2"+ >+ <span+ className="size-2 rounded-full"+ style={{ backgroundColor: item.color }}+ />+ <span className="min-w-0 truncate text-muted-foreground">+ {labelForKey(item.dataKey ?? item.name)}+ </span>+ <span className="font-medium tabular-nums text-foreground">+ {formatNumber(item.value)}+ </span>+ </div>+ ))}+ </div>+ </div>+ )+}diff --git a/web-studio/src/routes/home/-components/token-trend-panel.tsx b/web-studio/src/routes/home/-components/token-trend-panel.tsxindex 3b0e64680..8b94bf023 100644--- a/web-studio/src/routes/home/-components/token-trend-panel.tsx+++ b/web-studio/src/routes/home/-components/token-trend-panel.tsx@@ -1,31 +1,19 @@-import {- Area,- AreaChart,- CartesianGrid,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts'+import { lazy, Suspense } from 'react'import { Skeleton } from '#/components/ui/skeleton'-import { TOKEN_COLORS, TOKEN_SERIES_DAYS } from '../-constants/dashboard'-import type {- ConsoleSeries,- HomeT,- TokenSeriesItem,- TokenTrendPayload,-} from '../-types/dashboard'-import {- formatNumber,- formatShortDate,- getLastDaysRange,- isDisabledPayload,-} from '../-lib/format'+import { TOKEN_SERIES_DAYS } from '../-constants/dashboard'+import type { ConsoleSeries, HomeT, TokenSeriesItem } from '../-types/dashboard'+import { getLastDaysRange, isDisabledPayload } from '../-lib/format'import { normalizeTokenSeries } from '../-lib/normalize'import { EmptyState, Panel, SectionHeading } from './panel'+const TokenTrendChart = lazy(() =>+ import('./token-trend-chart').then((module) => ({+ default: module.TokenTrendChart,+ })),+)+export function TokenTrendPanel({data,disabled: disabledProp,@@ -67,205 +55,10 @@ export function TokenTrendPanel({) : items.length === 0 ? (<EmptyState>{t('tokenTrend.empty')}</EmptyState>) : (- <>- <div className="h-72 min-h-72 min-w-0 w-full">- <ResponsiveContainer- width="100%"- height="100%"- initialDimension={{ width: 720, height: 288 }}- minWidth={1}- minHeight={1}- >- <AreaChart- data={items}- margin={{ bottom: 0, left: 0, right: 12, top: 8 }}- >- <defs>- <linearGradient- id="tokenTrendVlmInput"- x1="0"- x2="0"- y1="0"- y2="1"- >- <stop- offset="5%"- stopColor={TOKEN_COLORS.input}- stopOpacity={0.52}- />- <stop- offset="95%"- stopColor={TOKEN_COLORS.input}- stopOpacity={0.14}- />- </linearGradient>- <linearGradient- id="tokenTrendVlmOutput"- x1="0"- x2="0"- y1="0"- y2="1"- >- <stop- offset="5%"- stopColor={TOKEN_COLORS.output}- stopOpacity={0.46}- />- <stop- offset="95%"- stopColor={TOKEN_COLORS.output}- stopOpacity={0.11}- />- </linearGradient>- <linearGradient- id="tokenTrendEmbedding"- x1="0"- x2="0"- y1="0"- y2="1"- >- <stop- offset="5%"- stopColor={TOKEN_COLORS.embedding}- stopOpacity={0.36}- />- <stop- offset="95%"- stopColor={TOKEN_COLORS.embedding}- stopOpacity={0.08}- />- </linearGradient>- </defs>- <CartesianGrid- stroke="currentColor"- strokeOpacity={0.08}- vertical={false}- />- <XAxis- axisLine={false}- className="text-muted-foreground"- dataKey="date"- tick={{ fill: 'currentColor', fontSize: 12 }}- tickFormatter={formatShortDate}- tickLine={false}- />- <YAxis- axisLine={false}- className="text-muted-foreground"- tick={{ fill: 'currentColor', fontSize: 12 }}- tickFormatter={(value) => Number(value).toLocaleString()}- tickLine={false}- width={64}- />- <Tooltip- cursor={{ stroke: 'currentColor', strokeOpacity: 0.12 }}- content={<TokenTrendTooltip t={t} />}- />- <Area- dataKey="vlm_input"- fill="url(#tokenTrendVlmInput)"- name="vlm_input"- stackId="tokens"- stroke={TOKEN_COLORS.input}- strokeWidth={2}- type="monotone"- />- <Area- dataKey="vlm_output"- fill="url(#tokenTrendVlmOutput)"- name="vlm_output"- stackId="tokens"- stroke={TOKEN_COLORS.output}- strokeWidth={2}- type="monotone"- />- <Area- dataKey="embedding_input"- fill="url(#tokenTrendEmbedding)"- name="embedding_input"- stackId="tokens"- stroke={TOKEN_COLORS.embedding}- strokeWidth={2}- type="monotone"- />- </AreaChart>- </ResponsiveContainer>- </div>- <div className="mt-4 flex flex-wrap gap-4 text-sm text-muted-foreground">- <LegendDot- color={TOKEN_COLORS.input}- label={t('todayTokens.vlmInput')}- />- <LegendDot- color={TOKEN_COLORS.output}- label={t('todayTokens.vlmOutput')}- />- <LegendDot- color={TOKEN_COLORS.embedding}- label={t('todayTokens.embeddingInput')}- />- </div>- </>+ <Suspense fallback={<Skeleton className="h-72 w-full" />}>+ <TokenTrendChart items={items} t={t} />+ </Suspense>)}</Panel>)}--function LegendDot({ color, label }: { color: string; label: string }) {- return (- <span className="inline-flex items-center gap-2">- <span- className="size-2.5 rounded-full"- style={{ backgroundColor: color }}- />- <span>{label}</span>- </span>- )-}--function TokenTrendTooltip({- active,- label,- payload,- t,-}: {- active?: boolean- label?: string | number- payload?: TokenTrendPayload[]- t: HomeT-}) {- if (!active || !payload?.length) return null-- const labelForKey = (key: string | undefined) => {- if (key === 'vlm_input') return t('todayTokens.vlmInput')- if (key === 'vlm_output') return t('todayTokens.vlmOutput')- return t('todayTokens.embeddingInput')- }-- return (- <div className="min-w-56 rounded-xl border border-border/70 bg-popover/95 px-3.5 py-3 text-xs text-popover-foreground shadow-2xl shadow-black/10 ring-1 ring-foreground/5 backdrop-blur-md dark:shadow-black/35">- <div className="font-medium tabular-nums text-foreground">- {String(label ?? '')}- </div>- <div className="mt-3 space-y-2 border-t border-border/70 pt-3">- {payload.map((item) => (- <div- key={item.dataKey ?? item.name}- className="grid grid-cols-[auto_1fr_auto] items-center gap-2"- >- <span- className="size-2 rounded-full"- style={{ backgroundColor: item.color }}- />- <span className="min-w-0 truncate text-muted-foreground">- {labelForKey(item.dataKey ?? item.name)}- </span>- <span className="font-medium tabular-nums text-foreground">- {formatNumber(item.value)}- </span>- </div>- ))}- </div>- </div>- )-}diff --git a/web-studio/src/routes/playground/route.tsx b/web-studio/src/routes/playground/route.tsxindex 0a7bc4c74..ff004bf14 100644--- a/web-studio/src/routes/playground/route.tsx+++ b/web-studio/src/routes/playground/route.tsx@@ -18,9 +18,9 @@ import {DialogHeader,DialogTitle,} from '#/components/ui/dialog'-import { FilePreview } from '#/routes/resources/-components/file-preview'import { AddResourceForm } from '#/routes/resources/-components/add-resource-page'import { UploadTaskDialog } from '#/routes/resources/-components/upload-task-dialog'+import { LazyFilePreview } from '#/routes/resources/-components/lazy-file-preview'import {ResourceUploadProvider,useResourceUpload,@@ -568,7 +568,7 @@ function PlaygroundWorkbench() {</div></div><div className="min-h-0 flex-1">- <FilePreview+ <LazyFilePreviewfile={selectedFile}hideDirectoryHeaderonClose={() => setSelectedFile(null)}diff --git a/web-studio/src/routes/resources/-components/dir-browser.tsx b/web-studio/src/routes/resources/-components/dir-browser.tsxindex bbfbde067..7a22ed712 100644--- a/web-studio/src/routes/resources/-components/dir-browser.tsx+++ b/web-studio/src/routes/resources/-components/dir-browser.tsx@@ -8,8 +8,8 @@ import { cn } from '#/lib/utils'import { normalizeDirUri, fileNameFromUri } from '../-lib/normalize'import { useVikingFsList, useDebouncedValue } from '../-hooks/viking-fm'import type { VikingFsEntry } from '../-types/viking-fm'-import { FilePreview } from './file-preview'import { ItemColumn } from './item-column'+import { LazyFilePreview } from './lazy-file-preview'const VIKING_ROOT_URI = 'viking://'@@ -174,7 +174,7 @@ function DetailPane({switch (detail.kind) {case 'preview':return (- <FilePreview+ <LazyFilePreviewfile={detail.file}onClose={() => {}}showCloseButton={false}diff --git a/web-studio/src/routes/resources/-components/find-palette.tsx b/web-studio/src/routes/resources/-components/find-palette.tsxindex feefd39fc..2aaaf7829 100644--- a/web-studio/src/routes/resources/-components/find-palette.tsx+++ b/web-studio/src/routes/resources/-components/find-palette.tsx@@ -35,8 +35,8 @@ import {} from '../-hooks/viking-fm'import { useListNavigation } from '../-hooks/use-list-navigation'import type { VikingFsEntry } from '../-types/viking-fm'-import { FilePreview } from './file-preview'import { DirBrowser } from './dir-browser'+import { LazyFilePreview } from './lazy-file-preview'interface FindPaletteProps {open: boolean@@ -535,7 +535,7 @@ export function FindPalette({{/* Preview pane */}{showPreview && (<div className="animate-palette-preview flex h-full w-[32rem] flex-col overflow-hidden">- <FilePreview+ <LazyFilePreviewfile={previewEntry}onClose={() => setIndex(-1)}showCloseButton={false}diff --git a/web-studio/src/routes/resources/-components/lazy-file-preview.tsx b/web-studio/src/routes/resources/-components/lazy-file-preview.tsxnew file mode 100644index 000000000..a53fcf55e--- /dev/null+++ b/web-studio/src/routes/resources/-components/lazy-file-preview.tsx@@ -0,0 +1,39 @@+import { lazy, Suspense } from 'react'+import { Loader2 } from 'lucide-react'++import type { VikingFsEntry } from '../-types/viking-fm'++const FilePreview = lazy(() =>+ import('./file-preview').then((module) => ({+ default: module.FilePreview,+ })),+)++export function LazyFilePreview({+ file,+ hideDirectoryHeader,+ onClose,+ showCloseButton,+}: {+ file: VikingFsEntry | null+ hideDirectoryHeader?: boolean+ onClose: () => void+ showCloseButton?: boolean+}) {+ return (+ <Suspense+ fallback={+ <div className="flex min-h-0 flex-1 items-center justify-center">+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ </div>+ }+ >+ <FilePreview+ file={file}+ hideDirectoryHeader={hideDirectoryHeader}+ onClose={onClose}+ showCloseButton={showCloseButton}+ />+ </Suspense>+ )+}