feat(desktop): add tooltip provider and model management

This commit is contained in:
leokun committed 2026-09-04 21:58:24 +08:00
1 parent 37f9c4c4c8
commit 4700d3abc0
25 files changed
+717 -262

No files matched your search

+25 -7
View File
@@ -15,6 +15,25 @@ import { useI18n } from "../../i18n/store";
type TimeRange = { startMs: number; endMs: number };
const CALENDAR_DAYS = 365;
const DAY_MS = 24 * 60 * 60_000;
function contributionCalendarData(overview: Overview, endMs: number) {
const tokensByDate = new Map<string, number>();
for (const bucket of overview.token_usage_series) {
const date = new Date(bucket.bucket_start_ms).toISOString().slice(0, 10);
const tokens = bucket.input_tokens + bucket.cache_read_tokens + bucket.cache_write_tokens + bucket.output_tokens;
tokensByDate.set(date, (tokensByDate.get(date) ?? 0) + tokens);
}
const lastDay = new Date(Math.max(0, endMs - 1));
lastDay.setUTCHours(0, 0, 0, 0);
const firstDayMs = lastDay.getTime() - (CALENDAR_DAYS - 1) * DAY_MS;
return Array.from({ length: CALENDAR_DAYS }, (_, offset) => {
const date = new Date(firstDayMs + offset * DAY_MS).toISOString().slice(0, 10);
return { date, tokens: tokensByDate.get(date) ?? 0 };
});
}
function presetRange(preset: Exclude<OverviewRangePreset, "custom">, now = new Date()): TimeRange {
const endMs = now.getTime();
if (preset === "today") {
@@ -74,10 +93,7 @@ export function HomePage() {
cacheWriteTokens: bucket.cache_write_tokens,
outputTokens: bucket.output_tokens,
}));
const contribution = overview.token_usage_series.map((bucket) => ({
date: new Date(bucket.bucket_start_ms).toISOString().slice(0, 10),
tokens: bucket.input_tokens + bucket.cache_read_tokens + bucket.cache_write_tokens + bucket.output_tokens,
}));
const contribution = contributionCalendarData(filteredOverview, selectedRange?.endMs ?? Date.now());
const metrics = {
llmCalls: filteredOverview.metrics.llm_calls,
successfulCalls: filteredOverview.metrics.successful_calls,
@@ -107,13 +123,15 @@ export function HomePage() {
setCustomOpen(false);
};
const selectQuick = (durationMs: number, bucketMs?: number) => {
const endMs = Date.now();
setCustomRange({ startMs: endMs - durationMs, endMs });
const end = new Date();
const start = new Date(end.getTime() - durationMs);
setCustomStart(formatTimeInput(start));
setCustomEnd(formatTimeInput(end));
setCustomRange({ startMs: start.getTime(), endMs: end.getTime() });
setAppliedModels(selectedModels);
setQuick(durationMs === 4 * 60 * 60_000 ? "four-hours" : "twenty-four-hours");
setFourHourBucket(durationMs === 4 * 60 * 60_000 ? bucketMs : undefined);
setPreset("custom");
setCustomOpen(false);
};
const selectPreset = (value: Exclude<OverviewRangePreset, "custom">) => {
setPreset(value);
@@ -2,7 +2,7 @@ import { useLayoutEffect, useMemo, useRef, useState } from "react";
import { init, Rect, type ElementEvent } from "zrender";
import type { Locale } from "../../../i18n/runtime";
import { useI18n } from "../../../i18n/store";
import { Tooltip, type TooltipAnchor } from "../../../shared/ui/Tooltip";
import { useTooltip, type TooltipAnchor } from "../../../shared/ui/Tooltip";
import styles from "./ContributionCalendarChart.module.scss";
export type ContributionDay = {
@@ -28,12 +28,6 @@ type CellExtra = CalendarCell & {
height: number;
};
type TooltipState = {
date: string;
tokens: number;
anchor: TooltipAnchor;
};
type AxisLabel = {
key: string;
text: string;
@@ -101,7 +95,7 @@ export function ContributionCalendarChart({ data }: ContributionCalendarChartPro
const canvasRef = useRef<HTMLDivElement>(null);
const layoutRef = useRef<ReturnType<typeof buildCalendarLayout>>(null);
const scheduleDrawRef = useRef<() => void>(() => undefined);
const [tooltip, setTooltip] = useState<TooltipState | null>(null);
const { show: showTooltip, hide: hideTooltip } = useTooltip();
const [axisLabels, setAxisLabels] = useState<AxisLabel[]>([]);
const layout = useMemo(() => buildCalendarLayout(data, locale), [data, locale]);
const tokenFormatter = useMemo(() => new Intl.NumberFormat(locale), [locale]);
@@ -129,10 +123,13 @@ export function ContributionCalendarChart({ data }: ContributionCalendarChartPro
return new DOMRect(bounds.left + extra.x, bounds.top + extra.y, extra.width, extra.height);
},
};
setTooltip({ date: extra.date, tokens: extra.tokens, anchor });
showTooltip(anchor, undefined, <div className={styles.tooltipContent}>
<strong>{extra.date}</strong>
<span>{t("Token 用量:{tokens}", { tokens: tokenFormatter.format(extra.tokens) })}</span>
</div>);
};
const handleMouseOut = (event: ElementEvent) => {
if (isCellExtra(event.target?.extra)) setTooltip(null);
if (isCellExtra(event.target?.extra)) hideTooltip();
};
chart.on("mouseover", handleMouseOver);
@@ -226,7 +223,7 @@ export function ContributionCalendarChart({ data }: ContributionCalendarChartPro
cellRects.set(cell.date, rect);
chart.add(rect);
}
setTooltip(null);
hideTooltip();
};
const scheduleDraw = () => {
window.cancelAnimationFrame(drawFrame);
@@ -264,12 +261,6 @@ export function ContributionCalendarChart({ data }: ContributionCalendarChartPro
{axisLabels.map((label) => <span key={label.key} style={{ left: label.left }}>{label.text}</span>)}
</div>
</div>
<Tooltip anchor={tooltip?.anchor ?? null}>
<div className={styles.tooltipContent}>
<strong>{tooltip?.date}</strong>
<span>{t("Token 用量:{tokens}", { tokens: tokenFormatter.format(tooltip?.tokens ?? 0) })}</span>
</div>
</Tooltip>
</section>
);
}
@@ -1,7 +1,6 @@
import { useState } from "react";
import { formatCompactInteger, formatInteger } from "../../../shared/utils/numberFormat";
import { Icon } from "../../../shared/ui/Icon";
import { Tooltip, type TooltipAnchor } from "../../../shared/ui/Tooltip";
import { useTooltip, type TooltipAnchor } from "../../../shared/ui/Tooltip";
import { informationOutlineIcon } from "../../../shared/ui/icons";
import { CacheHitRateChart } from "./CacheHitRateChart";
import styles from "./HomeMetrics.module.scss";
@@ -53,22 +52,17 @@ function elementAnchor(element: HTMLElement): TooltipAnchor {
}
function InfoTooltip({ content }: { content: string }) {
const [anchor, setAnchor] = useState<TooltipAnchor | null>(null);
const { show, hide } = useTooltip();
return <>
<button
type="button"
className={styles.info}
aria-label={t("查看说明")}
onMouseEnter={(event) => setAnchor(elementAnchor(event.currentTarget))}
onMouseLeave={() => setAnchor(null)}
onFocus={(event) => setAnchor(elementAnchor(event.currentTarget))}
onBlur={() => setAnchor(null)}
><Icon icon={informationOutlineIcon} size="1.1em" /></button>
<Tooltip anchor={anchor}>
<div className={styles.tooltipText}>{content}</div>
</Tooltip>
</>;
return <button
type="button"
className={styles.info}
aria-label={t("查看说明")}
onMouseEnter={(event) => show(elementAnchor(event.currentTarget), undefined, <div className={styles.tooltipText}>{content}</div>)}
onMouseLeave={hide}
onFocus={(event) => show(elementAnchor(event.currentTarget), undefined, <div className={styles.tooltipText}>{content}</div>)}
onBlur={hide}
><Icon icon={informationOutlineIcon} size="1.1em" /></button>;
}
export function HomeMetrics({ data, refreshVersion = 0 }: { data: HomeMetricsData; refreshVersion?: number }) {
@@ -157,7 +157,10 @@ export function OverviewTimeRangeFilter({ value, quick, fourHourBucket, customOp
aria-controls={granularityOpen ? granularityMenuId : undefined}
aria-expanded={granularityOpen}
aria-pressed={quick === "four-hours"}
onClick={() => setGranularityOpen((current) => !current)}
onClick={() => {
onQuickSelect(4 * 60 * 60_000, fourHourBucket);
setGranularityOpen((current) => !current);
}}
>{preset.label}</button>
: <button
key={preset.value}
@@ -85,6 +85,50 @@
}
}
.modelToolbar {
display: flex;
gap: 8px;
}
.modelTableWrap {
min-width: min(520px, 70vw);
}
.modelTable {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
th,
td {
padding: 10px 12px;
border-bottom: 1px solid var(--vscode-sideBar-border);
text-align: left;
}
th:last-child,
td:last-child {
width: 72px;
text-align: center;
}
td:first-child {
min-width: 0;
}
.modelName {
min-width: 0;
display: flex;
flex-direction: column;
gap: 3px;
}
td span {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.resourceSection {
display: flex;
flex-direction: column;
@@ -14,6 +14,8 @@ import { appStore } from "../../shared/store/appStore";
import { Button } from "../../shared/ui/Button";
import { Card } from "../../shared/ui/Card";
import { FormField, TextInput } from "../../shared/ui/FormControls";
import { Modal } from "../../shared/ui/Modal";
import { Switch } from "../../shared/ui/Switch";
import styles from "./PluginResourcePanels.module.scss";
const PAGE_SIZE = 10;
@@ -142,6 +144,8 @@ function OAuthMethodCard({ pluginId, resourceType, method, onConfigured }: {
export function PluginSettingsPanel({ plugin }: { plugin: PluginDescriptor }) {
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [modelProviderId, setModelProviderId] = useState<string | null>(null);
const modelProvider = modelProviderId ? plugin.providers.find((provider) => provider.id === modelProviderId) ?? null : null;
const run = async (key: string, task: () => Promise<void>) => {
setBusy(key);
@@ -162,6 +166,7 @@ export function PluginSettingsPanel({ plugin }: { plugin: PluginDescriptor }) {
provider={provider}
busy={busy !== null}
syncing={busy === `sync:${provider.id}`}
onManageModels={() => setModelProviderId(provider.id)}
onSync={() => void run(`sync:${provider.id}`, async () => {
await api.syncPluginModels(plugin.id, provider.id);
})}
@@ -178,13 +183,25 @@ export function PluginSettingsPanel({ plugin }: { plugin: PluginDescriptor }) {
})}
/>)}
{error && <span className={styles.error} role="alert">{error}</span>}
{modelProvider && <ModelManagementModal
provider={modelProvider}
busy={busy !== null}
onClose={() => setModelProviderId(null)}
onSubmit={(enabledByModel) => void run("models", async () => {
for (const model of modelProvider.models) {
const enabled = enabledByModel[model.id] ?? model.enabled;
if (model.enabled !== enabled) await api.setPluginModelEnabled(plugin.id, modelProvider.id, model.modelId, enabled);
}
})}
/>}
</div>;
}
function ProviderRow({ provider, busy, syncing, onSync }: {
function ProviderRow({ provider, busy, syncing, onManageModels, onSync }: {
provider: PluginProviderDescriptor;
busy: boolean;
syncing: boolean;
onManageModels: () => void;
onSync: () => void;
}) {
const { locale } = useI18n();
@@ -199,12 +216,68 @@ function ProviderRow({ provider, busy, syncing, onSync }: {
{provider.configured ? t("可调用") : t("未就绪")}
</span>
</div>
{provider.hasModels && <Button size="small" disabled={busy} onClick={onSync}>
{syncing ? t("正在同步…") : t("同步模型")}
</Button>}
{provider.hasModels && <div className={styles.actions}>
<Button size="small" disabled={busy || provider.models.length === 0} onClick={onManageModels}>{t("模型管理")}</Button>
<Button size="small" disabled={busy} onClick={onSync}>
{syncing ? t("正在同步…") : t("同步模型")}
</Button>
</div>}
</Card>;
}
function ModelManagementModal({ provider, busy, onClose, onSubmit }: {
provider: PluginProviderDescriptor;
busy: boolean;
onClose: () => void;
onSubmit: (enabledByModel: Record<string, boolean>) => void;
}) {
const { locale } = useI18n();
const [enabledByModel, setEnabledByModel] = useState<Record<string, boolean>>({});
useEffect(() => {
setEnabledByModel(Object.fromEntries(provider.models.map((model) => [model.id, model.enabled])));
}, [provider.models]);
const setAll = (enabled: boolean) => {
setEnabledByModel(Object.fromEntries(provider.models.map((model) => [model.id, enabled])));
};
return <Modal
fullHeight
open
title={t("{name} 模型管理", { name: pluginText(provider.displayName, locale) })}
busy={busy}
onClose={onClose}
onSubmit={() => onSubmit(enabledByModel)}
submitLabel={t("确定")}
>
<div className={styles.modelToolbar}>
<Button size="small" disabled={busy || provider.models.length === 0} onClick={() => setAll(true)}>{t("全选")}</Button>
<Button size="small" disabled={busy || provider.models.length === 0} onClick={() => setAll(false)}>{t("全不选")}</Button>
</div>
<div className={styles.modelTableWrap}>
<table className={styles.modelTable}>
<thead><tr><th scope="col">{t("模型名称")}</th><th scope="col">{t("启用")}</th></tr></thead>
<tbody>
{provider.models.map((model) => <tr key={model.id}>
<td><div className={styles.modelName}>
<strong>{model.displayName}</strong>
{model.description && <span>{model.description}</span>}
</div></td>
<td><Switch
checked={enabledByModel[model.id] ?? model.enabled}
disabled={busy}
label={t("启用 {model}", { model: model.displayName })}
onChange={(enabled) => setEnabledByModel((current) => ({ ...current, [model.id]: enabled }))}
/></td>
</tr>)}
</tbody>
</table>
{provider.models.length === 0 && <span className={styles.empty}>{t("尚未同步模型")}</span>}
</div>
</Modal>;
}
function ResourceList({ resource, busy, onRefresh, onDelete }: {
resource: PluginResourceDescriptor;
busy: boolean;