refactor: align project directory architecture

This commit is contained in:
leookun committed 2026-08-29 20:45:51 +08:00
1 parent 88f258f184
commit 279e6bb07c
236 files changed
+1982 -57487

No files matched your search

@@ -0,0 +1,38 @@
@use "../../styles/typography" as type;
.root {
section { min-width: 0; }
h4 { margin: 12px 0 6px; color: var(--vscode-descriptionForeground); font-size: type.$font-size-xs; font-weight: 500; }
}
.details {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1px;
padding: 1px;
margin: 0;
overflow: hidden;
background: var(--vscode-sideBar-border);
border-radius: 6px;
> div {
min-width: 0;
display: grid;
grid-template-columns: 132px minmax(0, 1fr);
gap: 10px;
padding: 8px 10px;
background: var(--vscode-editorWidget-background);
}
dt { color: var(--vscode-descriptionForeground); font-size: type.$font-size-xs; }
dd { min-width: 0; margin: 0; overflow-wrap: anywhere; }
code { white-space: pre-wrap; font-family: var(--oa-code-font); font-size: type.$font-size-xs; }
}
.meta{
margin-bottom: 10px;
}
.meta,
.empty {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
@@ -0,0 +1,82 @@
import type { CallDetail } from "../../shared/api";
import { JsonEditor } from "../../shared/ui/JsonEditor";
import { Tabs, type TabItem } from "../../shared/ui/Tabs";
import styles from "./CallDetails.module.scss";
const show = (value: string | number | null) => value ?? "-";
const timing = (value: number | null) => value == null ? "-" : `${value} ms`;
export function CallDetails({ detail }: { detail: CallDetail }) {
const { call, request, response_chunks: chunks, cursor_trace: cursorTrace } = detail;
const responseBody = chunks.map((chunk) => chunk.data).join("");
const responseBytes = chunks.reduce((total, chunk) => total + chunk.byte_count, 0);
const fields: Array<[string, string | number]> = [
["Call ID", call.call_id],
[t("调用类型"), call.call_kind === "cursor_official" ? t("Cursor 官方") : "LLM"],
[t("路由"), call.route === "cursor_official" ? t("Cursor 官方") : "BYOK"],
["Run ID", call.run_id],
["Conversation ID", call.conversation_id],
[t("上游调用序号"), call.provider_call_index],
["Model Hash", show(call.model_hash)],
[t("上游类型"), call.provider_type],
[t("上游地址"), call.provider_url],
[t("最终请求类型"), call.request_type],
[t("最终请求地址"), call.request_url],
["Model ID", call.model_id],
[t("显示名称"), call.display_name],
[t("思考强度"), show(call.reasoning_effort)],
["Fast", call.fast == null ? "-" : call.fast ? t("是") : t("否")],
[t("状态"), call.status],
["Finish Reason", show(call.finish_reason)],
["HTTP Status", show(call.http_status)],
["Created At", `${call.created_at_ms} · ${new Date(call.created_at_ms).toLocaleString()}`],
[t("耗时"), timing(call.duration_ms)],
["TTFB", timing(call.ttfb_ms)],
["TTFR", timing(call.ttfr_ms)],
["TTFT", timing(call.ttft_ms)],
["Input Token", show(call.input_tokens)],
["Output Token", show(call.output_tokens)],
["Total Token", show(call.total_tokens)],
["Cache Read Token", show(call.cache_read_tokens)],
["Cache Write Token", show(call.cache_write_tokens)],
["Reasoning Token", show(call.reasoning_tokens)],
[t("消息数"), call.message_count],
[t("工具数"), call.tool_count],
[t("详细记录"), call.detailed ? t("是") : t("否")],
["Error Kind", show(call.error_kind)],
["Error Message", show(call.error_message)],
];
const tabs: TabItem[] = [
{ value: "call", label: t("调用信息"), content: <section>
<dl className={styles.details}>{fields.map(([label, value]) => <div key={label}><dt>{label}</dt><dd><code>{value}</code></dd></div>)}</dl>
</section> },
{ value: "request", label: t("请求"), content: <section>
{request ? <>
<div className={styles.meta}>{t("字节数")}:{request.byte_count}</div>
<h4>{t("请求头")}</h4><JsonEditor ariaLabel={t("请求头")} value={JSON.stringify(request.headers)} readOnly />
<h4>{t("请求体")}</h4><JsonEditor ariaLabel={t("请求体")} value={JSON.stringify(request.body)} readOnly detail />
</> : <div className={styles.empty}>{t("未记录请求内容,请开启详细记录后重试。")}</div>}
</section> },
{ value: "response", label: t("响应流"), content: <section>
{chunks.length > 0 ? <>
<div className={styles.meta}>{t("分块数")}:{chunks.length} · {t("字节数")}:{responseBytes}</div>
<JsonEditor ariaLabel={t("响应流")} value={responseBody} readOnly detail />
</> : <div className={styles.empty}>{t("未记录响应内容,请开启详细记录后重试。")}</div>}
</section> },
];
if (cursorTrace) tabs.push({ value: "cursor-trace", label: t("Cursor 追踪"), content: <section>
<div className={styles.meta}>
Request ID:{cursorTrace.trace.request_id} · {t("工件数")}:{cursorTrace.artifacts.length}
</div>
<JsonEditor
ariaLabel={t("Cursor 追踪")}
value={JSON.stringify({ trace: cursorTrace.trace, artifacts: cursorTrace.artifacts })}
readOnly
detail
/>
</section> });
return <div className={styles.root}><Tabs items={tabs} /></div>;
}
@@ -0,0 +1,27 @@
@use "../../styles/typography" as type;
.root {
width: 100%;
height: 100%;
overflow: hidden;
background: var(--vscode-editor-background);
}
.scroller {
width: 100%;
height: 100%;
}
.content {
width: calc(100% - 36px);
max-width: var(--app-page-max-width);
padding: 28px 0 40px;
margin-right: auto;
margin-left: auto;
h1 {
margin: 0 0 20px;
font-size: type.$font-size-lg;
font-weight: 630;
}
}
@@ -0,0 +1,40 @@
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { api, type CallDetail } from "../../shared/api";
import { CallDetails } from "./CallDetails";
import { TitledCard } from "../../shared/ui/TitledCard";
import styles from "./CallDetailsPage.module.scss";
import { ScrollableContent } from "../../shared/virtual/ScrollableContent";
export function CallDetailsPage() {
const { callId = "" } = useParams();
const [detail, setDetail] = useState<CallDetail | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
setDetail(null);
setError(null);
void api.call(callId).then((value) => {
if (!cancelled) setDetail(value);
}).catch((cause) => {
if (!cancelled) setError(cause instanceof Error ? cause.message : String(cause));
});
return () => {
cancelled = true;
};
}, [callId]);
const content = error
? <TitledCard title={t("无法加载调用详情")}><div style={{ padding: 16 }}>{error}</div></TitledCard>
: detail
? <CallDetails detail={detail} />
: <TitledCard title={t("调用详情")}><div style={{ padding: 16 }}>{t("正在加载调用详情…")}</div></TitledCard>;
return <main className={styles.root}>
<ScrollableContent className={styles.scroller} contentClassName={styles.content}>
<h1>{detail?.call.display_name ?? t("调用详情")}</h1>
{content}
</ScrollableContent>
</main>;
}
@@ -0,0 +1,12 @@
@use "../../styles/typography" as type;
.status {
padding: 3px 7px;
color: var(--vscode-descriptionForeground);
background: var(--vscode-input-background);
border-radius: 99px;
font-size: type.$font-size-xs;
}
.completed { color: #56b870; }
.failed { color: var(--vscode-errorForeground, #f48771); }
@@ -0,0 +1,199 @@
import type { LlmCall } from "../../shared/api";
import controls from "../../shared/ui/Controls.module.scss";
import { DataTable, type DataTableColumn } from "../../shared/ui/DataTable";
import { Icon } from "../../shared/ui/Icon";
import { TooltipTrigger } from "../../shared/ui/TooltipTrigger";
import { eyeIcon } from "../../shared/ui/icons";
import styles from "./CallTable.module.scss";
const value = (input: string | number | null) => input ?? "-";
const milliseconds = (input: number | null) => input == null ? "-" : `${input} ms`;
export function CallTable({ calls, onDetails }: { calls: LlmCall[]; onDetails: (call: LlmCall) => void }) {
const columns: DataTableColumn<LlmCall>[] = [
{
key: "status",
header: t("状态"),
render: (call) => (
<span
className={[styles.status, styles[call.status]]
.filter(Boolean)
.join(" ")}
>
{call.status}
</span>
),
},
{
key: "display_name",
header: t("显示名称"),
render: (call) => call.display_name,
title: (call) => call.display_name,
},
{
key: "created_at",
header: t("时间"),
render: (call) => new Date(call.created_at_ms).toLocaleString(),
},
{
key: "model_id",
header: t("模型名称"),
render: (call) => call.model_id,
title: (call) => call.model_id,
},
{
key: "reasoning_effort",
header: t("思考强度"),
render: (call) => value(call.reasoning_effort),
},
{
key: "fast",
header: "Fast",
render: (call) => call.fast == null ? "-" : call.fast ? t("是") : t("否"),
},
{
key: "call_kind",
header: t("调用类型"),
render: (call) =>
call.call_kind === "cursor_official" ? t("Cursor 官方") : "LLM",
},
{
key: "route",
header: t("路由"),
render: (call) =>
call.route === "cursor_official" ? t("Cursor 官方") : "BYOK",
},
// { key: "model_hash", header: "Model Hash", render: (call) => value(call.model_hash), title: (call) => call.model_hash ?? undefined },
// { key: "provider_type", header: t("供应商类型"), render: (call) => call.provider_type },
// { key: "provider_url", header: t("供应商地址"), render: (call) => call.provider_url, title: (call) => call.provider_url },
// { key: "request_type", header: t("最终请求类型"), render: (call) => call.request_type },
// { key: "request_url", header: t("最终请求地址"), render: (call) => call.request_url, title: (call) => call.request_url },
{
key: "finish_reason",
header: "Finish Reason",
render: (call) => value(call.finish_reason),
},
{ key: "http", header: "HTTP", render: (call) => value(call.http_status) },
{
key: "duration",
header: t("耗时"),
render: (call) => milliseconds(call.duration_ms),
},
{
key: "ttfb",
header: "TTFB",
render: (call) => milliseconds(call.ttfb_ms),
},
{
key: "ttfr",
header: "TTFR",
render: (call) => milliseconds(call.ttfr_ms),
},
{
key: "ttft",
header: "TTFT",
render: (call) => milliseconds(call.ttft_ms),
},
{
key: "input_tokens",
header: "Input Token",
render: (call) => value(call.input_tokens),
},
{
key: "output_tokens",
header: "Output Token",
render: (call) => value(call.output_tokens),
},
{
key: "total_tokens",
header: "Total Token",
render: (call) => value(call.total_tokens),
},
{
key: "cache_read",
header: "Cache Read",
render: (call) => value(call.cache_read_tokens),
},
{
key: "cache_write",
header: "Cache Write",
render: (call) => value(call.cache_write_tokens),
},
{
key: "reasoning_tokens",
header: "Reasoning Token",
render: (call) => value(call.reasoning_tokens),
},
{
key: "message_count",
header: t("消息数"),
render: (call) => call.message_count,
},
{
key: "tool_count",
header: t("工具数"),
render: (call) => call.tool_count,
},
{
key: "detailed",
header: t("详细记录"),
render: (call) => (call.detailed ? t("是") : t("否")),
},
{
key: "error_kind",
header: "Error Kind",
render: (call) => value(call.error_kind),
title: (call) => call.error_kind ?? undefined,
},
{
key: "error_message",
header: "Error Message",
render: (call) => value(call.error_message),
title: (call) => call.error_message ?? undefined,
},
{
key: "call_id",
header: "Call ID",
render: (call) => call.call_id,
title: (call) => call.call_id,
},
{
key: "run_id",
header: "Run ID",
render: (call) => call.run_id,
title: (call) => call.run_id,
},
{
key: "conversation_id",
header: "Conversation ID",
render: (call) => call.conversation_id,
title: (call) => call.conversation_id,
},
{
key: "call_index",
header: "Call Index",
render: (call) => call.provider_call_index,
},
{
key: "actions",
header: t("操作"),
sticky: "right",
render: (call) => (
<TooltipTrigger label={t("查看详情")}>
<button
className={controls.iconButton}
aria-label={t("查看详情")}
onClick={() => onDetails(call)}
>
<Icon icon={eyeIcon} size="1.1em" />
</button>
</TooltipTrigger>
),
},
];
return <DataTable rows={calls} columns={columns} rowKey={(call) => call.call_id} minWidth={4180} />;
}
@@ -0,0 +1,11 @@
.pageContent {
height: 100%;
}
.page {
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
display: flex;
}
@@ -0,0 +1,34 @@
import { useEffect } from "react";
import { CallTable } from "./CallTable";
import { PageContent } from "../../shell/layout/PageContent";
import { appStore, useAppStore } from "../../shared/store/appStore";
import styles from "./CallsPage.module.scss";
const CALL_REFRESH_INTERVAL_MS = 2_000;
export function CallsPage() {
const { calls } = useAppStore();
useEffect(() => {
let disposed = false;
const refreshCalls = () => {
if (!disposed && document.visibilityState === "visible") {
void appStore.refreshCalls();
}
};
refreshCalls();
const interval = window.setInterval(refreshCalls, CALL_REFRESH_INTERVAL_MS);
window.addEventListener("focus", refreshCalls);
document.addEventListener("visibilitychange", refreshCalls);
return () => {
disposed = true;
window.clearInterval(interval);
window.removeEventListener("focus", refreshCalls);
document.removeEventListener("visibilitychange", refreshCalls);
};
}, []);
const content = <div className={styles.page}><CallTable calls={calls} onDetails={(call) => void appStore.openCallDetails(call.call_id)} /></div>;
return <PageContent fixed title={t("调用")} contentClassName={styles.pageContent} sections={[{ key: "calls", estimatedHeight: 720, content }]} />;
}
+150
View File
@@ -0,0 +1,150 @@
import { useEffect, useState } from "react";
import { api, type Overview } from "../../shared/api";
import { ContributionCalendarChart } from "./charts/ContributionCalendarChart";
import { DailyTokenUsageChart } from "./charts/DailyTokenUsageChart";
import { HomeMetrics } from "./metrics/HomeMetrics";
import { PageContent } from "../../shell/layout/PageContent";
import type { VirtualPageSection } from "../../shell/layout/VirtualPage";
import { OverviewTimeRangeFilter, type OverviewRangePreset } from "./overview/OverviewTimeRangeFilter";
import { PageActions } from "../../shell/PageActions";
import { appStore, useAppStore } from "../../shared/store/appStore";
import { formatTimeInput, parseTimeInput } from "../../shared/utils/parseTimeInput";
import { claudeIcon, openAiIcon } from "../../shared/ui/icons";
type TimeRange = { startMs: number; endMs: number };
function presetRange(preset: Exclude<OverviewRangePreset, "custom">, now = new Date()): TimeRange {
const endMs = now.getTime();
if (preset === "today") {
const start = new Date(now);
start.setHours(0, 0, 0, 0);
return { startMs: start.getTime(), endMs };
}
if (preset === "month") {
const start = new Date(now);
start.setMonth(start.getMonth() - 1);
return { startMs: start.getTime(), endMs };
}
const duration = preset === "ten-minutes" ? 10 * 60_000 : preset === "hour" ? 60 * 60_000 : 7 * 24 * 60 * 60_000;
return { startMs: now.getTime() - duration, endMs };
}
export function HomePage() {
const { overview, busy, models } = useAppStore();
const [preset, setPreset] = useState<OverviewRangePreset>("month");
const [customRange, setCustomRange] = useState<TimeRange | null>(null);
const [customOpen, setCustomOpen] = useState(false);
const [customStart, setCustomStart] = useState("");
const [customEnd, setCustomEnd] = useState("");
const [selectedModels, setSelectedModels] = useState<string[]>([]);
const [appliedModels, setAppliedModels] = useState<string[]>([]);
const [rangeOverview, setRangeOverview] = useState<Overview | null>(null);
const [rangeBusy, setRangeBusy] = useState(false);
const [refreshVersion, setRefreshVersion] = useState(0);
const selectedRange = preset === "custom" ? customRange : presetRange(preset);
useEffect(() => {
if (!selectedRange) return;
let active = true;
setRangeBusy(true);
void api.overview({
...selectedRange,
modelHashes: appliedModels,
}).then((next) => {
if (active) setRangeOverview(next);
}).finally(() => {
if (active) setRangeBusy(false);
});
return () => { active = false; };
}, [preset, customRange, overview, refreshVersion, appliedModels]);
const filteredOverview = rangeOverview ?? overview;
const dailyTokenUsage = filteredOverview.token_usage_series.map((bucket) => ({
bucketStartMs: bucket.bucket_start_ms,
inputTokens: bucket.input_tokens,
cacheReadTokens: bucket.cache_read_tokens,
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 metrics = {
llmCalls: filteredOverview.metrics.llm_calls,
successfulCalls: filteredOverview.metrics.successful_calls,
failedCalls: filteredOverview.metrics.failed_calls,
tokenUsage: filteredOverview.metrics.token_usage,
promptTokens: filteredOverview.metrics.prompt_tokens,
cacheReadTokens: filteredOverview.metrics.cache_read_tokens,
cacheWriteTokens: filteredOverview.metrics.cache_write_tokens,
};
const openCustom = (open: boolean) => {
if (open && !customStart && !customEnd) {
const now = new Date();
setCustomEnd(formatTimeInput(now));
setCustomStart(formatTimeInput(new Date(now.getTime() - 60 * 60_000)));
}
setCustomOpen(open);
};
const applyCustom = () => {
const startMs = parseTimeInput(customStart);
const endMs = parseTimeInput(customEnd);
if (startMs === null || endMs === null || startMs >= endMs) return;
setCustomRange({ startMs, endMs });
setAppliedModels(selectedModels);
setPreset("custom");
setCustomOpen(false);
};
const refresh = async () => {
await appStore.refresh();
setRefreshVersion((version) => version + 1);
};
const iconFor = (type: string) => type === "anthropic" ? claudeIcon : openAiIcon;
const modelOptions = models.map((model) => ({
value: model.model_hash,
label: model.display_name,
icon: iconFor(model.type),
}));
const sections: VirtualPageSection[] = [
{
key: "daily-token-usage",
estimatedHeight: 240,
content: <DailyTokenUsageChart
data={dailyTokenUsage}
granularity={filteredOverview.token_usage_granularity}
/>,
},
{
key: "metrics",
estimatedHeight: 130,
content: <HomeMetrics data={metrics} refreshVersion={refreshVersion} />,
},
{
key: "activity",
estimatedHeight: 106,
content: <ContributionCalendarChart data={contribution} />,
},
];
return <>
<PageActions><OverviewTimeRangeFilter
value={preset}
customOpen={customOpen}
customStart={customStart}
customEnd={customEnd}
modelOptions={modelOptions}
selectedModels={selectedModels}
busy={busy || rangeBusy}
onSelect={(value) => { setPreset(value); setCustomOpen(false); }}
onCustomOpenChange={openCustom}
onCustomStartChange={setCustomStart}
onCustomEndChange={setCustomEnd}
onSelectedModelsChange={setSelectedModels}
onCustomApply={applyCustom}
onRefresh={() => void refresh()}
/></PageActions>
<PageContent title={t("概览")} sections={sections} />
</>;
}
@@ -0,0 +1,36 @@
@use "../../../styles/typography" as type;
.root {
width: 100%;
}
.scroller {
width: 100%;
overflow: hidden;
}
.canvas {
width: 100%;
flex: 0 0 auto;
}
.axis {
position: relative;
width: 100%;
height: 18px;
margin-top: 10px;
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-2xs;
span {
position: absolute;
top: 0;
width: 28px;
white-space: nowrap;
}
}
.tooltipContent {
display: flex;
flex-direction: column;
}
@@ -0,0 +1,275 @@
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 styles from "./ContributionCalendarChart.module.scss";
export type ContributionDay = {
date: string;
tokens: number;
};
type ContributionCalendarChartProps = {
data: ContributionDay[];
};
type CalendarCell = ContributionDay & {
column: number;
row: number;
level: number;
};
type CellExtra = CalendarCell & {
kind: "calendar-cell";
x: number;
y: number;
width: number;
height: number;
};
type TooltipState = {
date: string;
tokens: number;
anchor: TooltipAnchor;
};
type AxisLabel = {
key: string;
text: string;
left: number;
};
const levelColors = [
"rgba(139, 148, 158, 0.20)",
"#9be9a8",
"#40c463",
"#30a14e",
"#216e39",
];
const DAY_IN_MS = 24 * 60 * 60 * 1000;
const CALENDAR_CONFIG = {
cellAspectRatio: 0.9,
cellGap: 3,
resizeTransitionMs: 180,
rowCount: 7,
axisLabelGap: 8,
axisLabelWidth: 28,
} as const;
function parseDate(date: string) {
return new Date(`${date}T00:00:00Z`);
}
function mondayIndex(date: Date) {
return (date.getUTCDay() + 6) % 7;
}
function cellOffset(index: number, cellSize: number) {
return index * (cellSize + CALENDAR_CONFIG.cellGap);
}
function isCellExtra(value: unknown): value is CellExtra {
return typeof value === "object" && value !== null && (value as CellExtra).kind === "calendar-cell";
}
function buildCalendarLayout(data: ContributionDay[], locale: Locale) {
if (data.length === 0) return null;
const monthFormatter = new Intl.DateTimeFormat(locale, { month: "short", timeZone: "UTC" });
const maximum = Math.max(1, ...data.map(({ tokens }) => tokens));
const firstDate = parseDate(data[0].date);
const calendarStart = new Date(firstDate.getTime() - mondayIndex(firstDate) * DAY_IN_MS);
const cells: CalendarCell[] = data.map((day) => {
const date = parseDate(day.date);
const daysFromStart = Math.round((date.getTime() - calendarStart.getTime()) / DAY_IN_MS);
const level = day.tokens === 0 ? 0 : Math.max(1, Math.ceil((day.tokens / maximum) * 4));
return { ...day, column: Math.floor(daysFromStart / 7), row: mondayIndex(date), level };
});
const columnCount = cells.at(-1)!.column + 1;
const monthTicks = cells.reduce<Array<{ key: string; text: string; column: number }>>((ticks, cell) => {
const date = parseDate(cell.date);
const key = `${date.getUTCFullYear()}-${date.getUTCMonth()}`;
if (ticks.at(-1)?.key !== key) ticks.push({ key, text: monthFormatter.format(date), column: cell.column });
return ticks;
}, []);
return { cells, columnCount, monthTicks };
}
export function ContributionCalendarChart({ data }: ContributionCalendarChartProps) {
const { locale } = useI18n();
const scrollerRef = useRef<HTMLDivElement>(null);
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 [axisLabels, setAxisLabels] = useState<AxisLabel[]>([]);
const layout = useMemo(() => buildCalendarLayout(data, locale), [data, locale]);
const tokenFormatter = useMemo(() => new Intl.NumberFormat(locale), [locale]);
layoutRef.current = layout;
useLayoutEffect(() => {
const scroller = scrollerRef.current;
const node = canvasRef.current;
if (!scroller || !node) return;
const chart = init(node, {
renderer: "canvas",
width: 1,
height: 1,
useDirtyRect: true,
});
const handleMouseOver = (event: ElementEvent) => {
const extra = event.target?.extra;
if (!isCellExtra(extra)) return;
const anchor: TooltipAnchor = {
contextElement: node,
getBoundingClientRect: () => {
const bounds = node.getBoundingClientRect();
return new DOMRect(bounds.left + extra.x, bounds.top + extra.y, extra.width, extra.height);
},
};
setTooltip({ date: extra.date, tokens: extra.tokens, anchor });
};
const handleMouseOut = (event: ElementEvent) => {
if (isCellExtra(event.target?.extra)) setTooltip(null);
};
chart.on("mouseover", handleMouseOver);
chart.on("mouseout", handleMouseOut);
const cellRects = new Map<string, Rect>();
let drawFrame = 0;
let lastAvailableWidth = -1;
let lastCanvasHeight = -1;
let lastLayout: typeof layout = null;
const draw = () => {
const currentLayout = layoutRef.current;
if (!currentLayout) return;
const availableWidth = Math.floor(scroller.getBoundingClientRect().width);
if (availableWidth <= 0 || (availableWidth === lastAvailableWidth && currentLayout === lastLayout)) return;
const gapsWidth = (currentLayout.columnCount - 1) * CALENDAR_CONFIG.cellGap;
const cellWidth = Math.max(0, (availableWidth - gapsWidth) / currentLayout.columnCount);
const cellHeight = cellWidth / CALENDAR_CONFIG.cellAspectRatio;
const width = availableWidth;
const height = CALENDAR_CONFIG.rowCount * cellHeight
+ (CALENDAR_CONFIG.rowCount - 1) * CALENDAR_CONFIG.cellGap;
let lastLabelEnd = -Infinity;
const nextAxisLabels = currentLayout.monthTicks.flatMap((tick) => {
const left = Math.min(
cellOffset(tick.column, cellWidth),
availableWidth - CALENDAR_CONFIG.axisLabelWidth,
);
if (left < lastLabelEnd + CALENDAR_CONFIG.axisLabelGap) return [];
lastLabelEnd = left + CALENDAR_CONFIG.axisLabelWidth;
return [{ ...tick, left }];
});
setAxisLabels(nextAxisLabels);
if (availableWidth !== lastAvailableWidth || height !== lastCanvasHeight) {
node.style.width = "100%";
node.style.height = `${height}px`;
chart.resize({ width, height });
lastAvailableWidth = availableWidth;
lastCanvasHeight = height;
}
lastLayout = currentLayout;
const currentDates = new Set(currentLayout.cells.map((cell) => cell.date));
for (const [date, rect] of cellRects) {
if (currentDates.has(date)) continue;
chart.remove(rect);
cellRects.delete(date);
}
for (const cell of currentLayout.cells) {
const x = cellOffset(cell.column, cellWidth);
const y = cellOffset(cell.row, cellHeight);
const shape = {
x,
y,
width: cellWidth,
height: cellHeight,
r: Math.min(3, Math.min(cellWidth, cellHeight) / 4),
};
const extra = {
...cell,
kind: "calendar-cell" as const,
x,
y,
width: cellWidth,
height: cellHeight,
} satisfies CellExtra;
const current = cellRects.get(cell.date);
if (current) {
current.extra = extra;
current.stopAnimation();
current.animateTo(
{ shape, style: { fill: levelColors[cell.level] } },
{ duration: CALENDAR_CONFIG.resizeTransitionMs, easing: "cubicOut" },
);
continue;
}
const rect = new Rect({
shape,
style: {
fill: levelColors[cell.level],
stroke: "rgba(139, 148, 158, 0.10)",
lineWidth: 1,
},
cursor: "default",
extra,
});
cellRects.set(cell.date, rect);
chart.add(rect);
}
setTooltip(null);
};
const scheduleDraw = () => {
window.cancelAnimationFrame(drawFrame);
drawFrame = window.requestAnimationFrame(draw);
};
scheduleDrawRef.current = scheduleDraw;
const observer = new ResizeObserver(scheduleDraw);
observer.observe(scroller);
scheduleDraw();
return () => {
observer.disconnect();
window.cancelAnimationFrame(drawFrame);
scheduleDrawRef.current = () => undefined;
chart.dispose();
};
}, [layout !== null]);
useLayoutEffect(() => {
scheduleDrawRef.current();
}, [layout]);
if (!layout) return null;
return (
<section className={styles.root} aria-label={t("过去一年的 Token 用量")}>
<div ref={scrollerRef} className={styles.scroller}>
<div
ref={canvasRef}
className={styles.canvas}
role="img"
aria-label={t("过去一年的 Token 用量日历")}
/>
<div className={styles.axis} aria-hidden="true">
{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>
);
}
@@ -0,0 +1,7 @@
@use "../../../styles/typography" as type;
.root {
--daily-token-tooltip-font-size: #{type.$font-size-2xs};
width: 100%;
height: 200px;
}
@@ -0,0 +1,204 @@
import type { EChartsCoreOption } from "echarts/core";
import { useMemo, useState } from "react";
import type { TokenUsageGranularity } from "../../../shared/api";
import { formatCompactInteger } from "../../../shared/utils/numberFormat";
import { EChart } from "./EChart";
import styles from "./DailyTokenUsageChart.module.scss";
export type DailyTokenUsage = {
bucketStartMs: number;
inputTokens: number;
cacheReadTokens: number;
cacheWriteTokens: number;
outputTokens: number;
};
type TooltipItem = {
dataIndex: number;
};
const seriesColors = {
input: "#0091ff",
cacheRead: "#40c463",
cacheWrite: "#3A62BA",
output: "#E7B40B",
} as const;
const levelLineColor = "#E7B40B";
const emptyBarColor = "rgba(139, 148, 158, 0.20)";
const EMPTY_BAR_RATIO = 1;
const DATA_HEIGHT_RATIO = 1;
const seriesFocus = {
emphasis: { focus: "series" },
blur: { itemStyle: { opacity: 0.2 } },
} as const;
function colorMark(color: string): string {
return `<span style="display:inline-block;width:8px;height:8px;margin-right:6px;border-radius:50%;background-color:${color};vertical-align:middle"></span>`;
}
function formatDay(value: Date) {
return `${value.getUTCMonth() + 1}/${value.getUTCDate()}`;
}
function pad(value: number) {
return String(value).padStart(2, "0");
}
function formatAxisLabel(bucketStartMs: number, granularity: TokenUsageGranularity) {
const value = new Date(bucketStartMs);
if (granularity === "minute") return `${pad(value.getHours())}:${pad(value.getMinutes())}`;
if (granularity === "hour") return `${pad(value.getHours())}:00`;
const day = value.getUTCDay();
if (day === 6) return t("周六");
if (day === 0) return t("周日");
return formatDay(value);
}
function formatTooltipTime(bucketStartMs: number, granularity: TokenUsageGranularity) {
const value = new Date(bucketStartMs);
if (granularity === "day") return formatDay(value);
const time = `${pad(value.getHours())}:${pad(value.getMinutes())}`;
return `${value.getMonth() + 1}/${value.getDate()} ${time}`;
}
function totalTokens(day: DailyTokenUsage) {
return day.inputTokens + day.cacheReadTokens + day.cacheWriteTokens + day.outputTokens;
}
export function DailyTokenUsageChart({
data,
granularity,
}: {
data: DailyTokenUsage[];
granularity: TokenUsageGranularity;
}) {
const [hovered, setHovered] = useState(false);
const maximumTotal = data.reduce((maximum, day) => Math.max(maximum, totalTokens(day)), 0);
const axisMaximum = Math.max(1, maximumTotal / DATA_HEIGHT_RATIO);
const emptyBarHeight = axisMaximum * EMPTY_BAR_RATIO;
const nonZeroTotals = data.map(totalTokens).filter((total) => total !== 0);
const averageLevel = nonZeroTotals.length === 0
? 0
: nonZeroTotals.reduce((sum, total) => sum + total, 0) / nonZeroTotals.length;
const option = useMemo<EChartsCoreOption>(() => ({
animationDuration: 450,
animationEasing: "cubicOut",
grid: { top: 8, right: 0, bottom: 0, left: 0 },
tooltip: {
trigger: "axis",
confine: true,
backgroundColor: "var(--vscode-editorHoverWidget-background)",
borderColor: "var(--vscode-editorHoverWidget-border)",
textStyle: { color: "var(--vscode-foreground)", fontFamily: "PingFang-Medium" },
extraCssText: "border-radius: 8px; box-shadow: 0 12px 32px rgb(0 0 0 / 30%); font-size: var(--daily-token-tooltip-font-size); line-height: 1.5;",
axisPointer: {
type: "shadow",
shadowStyle: { color: "rgba(139, 148, 158, 0.14)" },
},
formatter: (params: unknown) => {
const first = (params as TooltipItem[])[0];
const day = data[first.dataIndex];
return [
formatTooltipTime(day.bucketStartMs, granularity),
`${t("总请求")}:${formatCompactInteger(totalTokens(day))}`,
`${colorMark(seriesColors.input)}${t("输入(非缓存)")}:${formatCompactInteger(day.inputTokens)}`,
`${colorMark(seriesColors.cacheRead)}${t("缓存输入")}:${formatCompactInteger(day.cacheReadTokens)}`,
`${colorMark(seriesColors.cacheWrite)}${t("缓存写入")}:${formatCompactInteger(day.cacheWriteTokens)}`,
`${colorMark(seriesColors.output)}${t("模型输出")}:${formatCompactInteger(day.outputTokens)}`,
].join("<br/>");
},
},
xAxis: {
type: "category",
data: data.map(({ bucketStartMs }) => bucketStartMs),
axisTick: { show: false },
axisLine: { lineStyle: { color: "rgba(139, 148, 158, 0.32)" } },
axisLabel: {
interval: "auto",
hideOverlap: true,
formatter: (_value: string, index: number) => formatAxisLabel(data[index].bucketStartMs, granularity),
color: "#8c8c8c",
fontFamily: "HFKos",
margin: 14,
},
},
yAxis: {
type: "value",
show: false,
min: 0,
max: axisMaximum,
},
series: [
{
name: t("无用量"),
type: "bar",
stack: "empty-placeholder",
data: data.map((day) => totalTokens(day) === 0 ? emptyBarHeight : 0),
barMaxWidth: 18,
silent: true,
z: 0,
itemStyle: { color: emptyBarColor, borderRadius: [2, 2, 0, 0] },
emphasis: { disabled: true },
},
{
name: t("输入(非缓存)"),
type: "bar",
stack: "tokens",
data: data.map(({ inputTokens }) => inputTokens),
barMaxWidth: 18,
itemStyle: { color: seriesColors.input },
...seriesFocus,
},
{
name: t("缓存输入"),
type: "bar",
stack: "tokens",
data: data.map(({ cacheReadTokens }) => cacheReadTokens),
barMaxWidth: 18,
itemStyle: { color: seriesColors.cacheRead },
...seriesFocus,
},
{
name: t("缓存写入"),
type: "bar",
stack: "tokens",
data: data.map(({ cacheWriteTokens }) => cacheWriteTokens),
barMaxWidth: 18,
itemStyle: { color: seriesColors.cacheWrite },
...seriesFocus,
},
{
name: t("模型输出"),
type: "bar",
stack: "tokens",
data: data.map(({ outputTokens }) => outputTokens),
barMaxWidth: 18,
barGap: "-100%",
itemStyle: { color: seriesColors.output, borderRadius: [2, 2, 0, 0] },
markLine: {
silent: true,
symbol: "none",
lineStyle: { color: levelLineColor, opacity: hovered ? 1 : 0, type: "dashed", width: 2 },
label: {
show: hovered,
position: "insideStartTop",
formatter: t("平均"),
color: levelLineColor,
distance: 8,
},
data: [{ yAxis: averageLevel }],
},
...seriesFocus,
},
],
}), [averageLevel, axisMaximum, data, emptyBarHeight, granularity, hovered]);
return <EChart
option={option}
className={styles.root}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
/>;
}
@@ -0,0 +1,4 @@
.root {
width: 100%;
height: 260px;
}
@@ -0,0 +1,38 @@
import { BarChart, GaugeChart, LineChart } from "echarts/charts";
import { GridComponent, LegendComponent, MarkLineComponent, TooltipComponent } from "echarts/components";
import { getInstanceByDom, init, use, type EChartsCoreOption } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { useEffect, useRef, type MouseEventHandler } from "react";
import styles from "./EChart.module.scss";
use([BarChart, GaugeChart, LineChart, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, CanvasRenderer]);
type EChartProps = {
option: EChartsCoreOption;
className?: string;
onMouseEnter?: MouseEventHandler<HTMLDivElement>;
onMouseLeave?: MouseEventHandler<HTMLDivElement>;
};
export function EChart({ option, className = styles.root, onMouseEnter, onMouseLeave }: EChartProps) {
const element = useRef<HTMLDivElement>(null);
useEffect(() => {
const node = element.current;
if (!node) return;
const chart = init(node, undefined, { renderer: "canvas" });
const observer = new ResizeObserver(() => chart.resize());
observer.observe(node);
return () => {
observer.disconnect();
chart.dispose();
};
}, []);
useEffect(() => {
const node = element.current;
if (node) getInstanceByDom(node)?.setOption(option, { notMerge: true });
}, [option]);
return <div ref={element} className={className} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} />;
}
@@ -0,0 +1,22 @@
import type { EChartsCoreOption } from "echarts/core";
import type { LlmCall } from "../../../shared/api";
import { EChart } from "./EChart";
export function LatencyChart({ calls }: { calls: LlmCall[] }) {
const points = calls.slice(0, 20).reverse();
const option: EChartsCoreOption = {
animationDuration: 280,
color: ["#d79a62", "#ad84cf", "#72a8d8"],
grid: { top: 22, right: 18, bottom: 30, left: 48 },
legend: { top: 0, right: 8, textStyle: { color: "#999" } },
tooltip: { trigger: "axis" },
xAxis: { type: "category", data: points.map((call) => new Date(call.created_at_ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })), axisLabel: { color: "#888" }, axisLine: { lineStyle: { color: "#5555" } } },
yAxis: { type: "value", axisLabel: { color: "#888", formatter: "{value} ms" }, splitLine: { lineStyle: { color: "#8882" } } },
series: [
{ name: "TTFR", type: "line", smooth: true, symbol: "none", data: points.map((call) => call.ttfr_ms ?? 0) },
{ name: "TTFT", type: "line", smooth: true, symbol: "none", data: points.map((call) => call.ttft_ms ?? 0) },
{ name: t("总耗时"), type: "line", smooth: true, symbol: "none", data: points.map((call) => call.duration_ms ?? 0) },
],
};
return <EChart option={option} />;
}
@@ -0,0 +1,21 @@
import type { EChartsCoreOption } from "echarts/core";
import type { LlmCall } from "../../../shared/api";
import { EChart } from "./EChart";
export function TokenTrendChart({ calls }: { calls: LlmCall[] }) {
const points = calls.slice(0, 20).reverse();
const option: EChartsCoreOption = {
animationDuration: 280,
color: ["#6f91f4", "#62c6a3"],
grid: { top: 22, right: 18, bottom: 30, left: 48 },
legend: { top: 0, right: 8, textStyle: { color: "#999" } },
tooltip: { trigger: "axis" },
xAxis: { type: "category", data: points.map((call) => new Date(call.created_at_ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })), axisLabel: { color: "#888" }, axisLine: { lineStyle: { color: "#5555" } } },
yAxis: { type: "value", axisLabel: { color: "#888" }, splitLine: { lineStyle: { color: "#8882" } } },
series: [
{ name: t("输入 Token"), type: "bar", stack: "tokens", data: points.map((call) => call.input_tokens ?? 0), barMaxWidth: 22 },
{ name: t("输出 Token"), type: "bar", stack: "tokens", data: points.map((call) => call.output_tokens ?? 0), barMaxWidth: 22 },
],
};
return <EChart option={option} />;
}
@@ -0,0 +1,34 @@
@use "../../../styles/typography" as type;
.root {
position: relative;
width: 200px;
max-width: 100%;
height: 82px;
overflow: hidden;
align-self: center;
flex: 0 0 auto;
}
.chart {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 140px;
pointer-events: none;
}
.label {
position: absolute;
right: 0;
bottom: 10px;
left: 0;
display: flex;
justify-content: center;
color: var(--vscode-foreground);
font-family: var(--oa-number-font);
font-size: type.$font-size-xl;
line-height: 1;
pointer-events: none;
}
@@ -0,0 +1,62 @@
import type { EChartsCoreOption } from "echarts/core";
import { useEffect, useMemo, useState } from "react";
import { EChart } from "../charts/EChart";
import styles from "./CacheHitRateChart.module.scss";
const valueColor = "#40c463";
const trackColor = "rgba(139, 148, 158, 0.20)";
export function CacheHitRateChart({ rate, animationKey = 0 }: { rate: number; animationKey?: number }) {
const finiteRate = Number.isFinite(rate) ? rate : 0;
const percentage = Math.max(0, Math.min(100, finiteRate * 100));
const [displayedPercentage, setDisplayedPercentage] = useState(0);
const label = Number.isFinite(rate) ? `${percentage.toFixed(2)}%` : "--";
useEffect(() => {
setDisplayedPercentage(0);
let frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => setDisplayedPercentage(percentage));
});
return () => cancelAnimationFrame(frame);
}, [animationKey, percentage]);
const option = useMemo<EChartsCoreOption>(() => ({
animationDuration: 0,
animationDurationUpdate: displayedPercentage > 0 ? 1_000 : 0,
animationEasing: "cubicOut",
animationEasingUpdate: "cubicOut",
series: [{
type: "gauge",
min: 0,
max: 100,
startAngle: 180,
endAngle: 0,
center: ["50%", "50%"],
radius: "90%",
silent: true,
pointer: { show: false },
progress: {
show: true,
roundCap: true,
width: 11,
itemStyle: { color: displayedPercentage > 0 ? valueColor : "transparent" },
},
axisLine: {
roundCap: true,
lineStyle: { width: 11, color: [[1, trackColor]] },
},
axisTick: { show: false },
splitLine: { show: false },
axisLabel: { show: false },
anchor: { show: false },
title: { show: false },
detail: { show: false },
data: [{ value: displayedPercentage }],
}],
}), [displayedPercentage]);
return <div className={styles.root} role="img" aria-label={t("缓存命中率 {rate}", { rate: label })}>
<EChart className={styles.chart} option={option} />
<div className={styles.label}>{label}</div>
</div>;
}
@@ -0,0 +1,86 @@
@use "../../../styles/typography" as type;
.scroller {
width: 100%;
overflow-x: auto;
overflow-y: hidden;
}
.root {
width: 100%;
height: 130px;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
overflow: hidden;
border: 1px solid var(--vscode-sideBar-border);
border-radius: var(--oa-overlay-radius);
font-family: var(--oa-metrics-font);
}
.metric {
min-width: 0;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 16px;
& + & {
border-left: 1px solid var(--vscode-sideBar-border);
}
}
.label {
display: flex;
align-items: center;
gap: 5px;
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
line-height: 1;
}
.info {
width: 16px;
height: 16px;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
color: inherit;
background: transparent;
border: 0;
transition: color 150ms ease;
opacity: 0.5;
&:hover,
&:focus-visible {
color: var(--vscode-foreground);
}
}
.body {
min-width: 0;
}
.value {
overflow: hidden;
color: var(--vscode-foreground);
font-family: var(--oa-number-font);
font-size: type.$font-size-xxl;
line-height: 1;
text-overflow: ellipsis;
white-space: nowrap;
}
.secondary {
margin-top: 12px;
overflow: hidden;
color: var(--vscode-descriptionForeground);
font-size: 12px;
line-height: 1.4;
text-overflow: ellipsis;
white-space: nowrap;
}
.tooltipText {
white-space: pre-wrap;
}
@@ -0,0 +1,179 @@
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 { informationOutlineIcon } from "../../../shared/ui/icons";
import { CacheHitRateChart } from "./CacheHitRateChart";
import styles from "./HomeMetrics.module.scss";
export type HomeMetricsData = {
llmCalls: number;
successfulCalls: number;
failedCalls: number;
tokenUsage: number;
promptTokens: number;
cacheReadTokens: number;
cacheWriteTokens: number;
};
const TOKEN_PRICE_PER_MILLION = {
input: 5,
output: 25,
cacheRead: 0.5,
cacheWrite: 6.25,
} as const;
function formatMetricValue(value: number) {
const full = formatInteger(value);
const compact = formatCompactInteger(value);
return full === compact ? full : `${full} (${compact})`;
}
function formatRate(value: number | null) {
return value === null ? t("暂无数据") : `${(Math.max(0, Math.min(1, value)) * 100).toFixed(2)}%`;
}
function calculateRate(numerator: number, denominator: number) {
return denominator > 0 ? numerator / denominator : null;
}
function priceTokens(tokens: number, pricePerMillion: number) {
return (tokens / 1_000_000) * pricePerMillion;
}
function formatUSD(value: number) {
return `$${value.toFixed(2)}`;
}
function elementAnchor(element: HTMLElement): TooltipAnchor {
return {
contextElement: element,
getBoundingClientRect: () => element.getBoundingClientRect(),
};
}
function InfoTooltip({ content }: { content: string }) {
const [anchor, setAnchor] = useState<TooltipAnchor | null>(null);
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>
</>;
}
export function HomeMetrics({ data, refreshVersion = 0 }: { data: HomeMetricsData; refreshVersion?: number }) {
const inputTokens = Math.max(0, data.promptTokens - data.cacheReadTokens - data.cacheWriteTokens);
const outputTokens = Math.max(0, data.tokenUsage - data.promptTokens);
const defaultCacheHitRate = calculateRate(data.cacheReadTokens, data.cacheReadTokens + inputTokens);
const cacheReuseRate = calculateRate(
data.cacheReadTokens,
data.cacheReadTokens + data.cacheWriteTokens + inputTokens,
);
const successfulCallRate = calculateRate(data.successfulCalls, data.llmCalls);
const costs = {
input: priceTokens(inputTokens, TOKEN_PRICE_PER_MILLION.input),
output: priceTokens(outputTokens, TOKEN_PRICE_PER_MILLION.output),
cacheRead: priceTokens(data.cacheReadTokens, TOKEN_PRICE_PER_MILLION.cacheRead),
cacheWrite: priceTokens(data.cacheWriteTokens, TOKEN_PRICE_PER_MILLION.cacheWrite),
};
const totalCost = costs.input + costs.output + costs.cacheRead + costs.cacheWrite;
const cacheCost = costs.cacheRead + costs.cacheWrite;
const cacheTooltip = [
t("当前:{rate}", { rate: formatRate(defaultCacheHitRate) }),
t("公式:缓存读取 /(缓存读取 + 非缓存输入)"),
t("默认 {defaultRate} / 计入创建 {reuseRate}", {
defaultRate: formatRate(defaultCacheHitRate),
reuseRate: formatRate(cacheReuseRate),
}),
].join("\n");
const callsTooltip = [
t("按历史 LLM 调用记录汇总,进行中的调用不计入。"),
"",
t("总调用:{count}", { count: formatMetricValue(data.llmCalls) }),
t("成功调用:{count}", { count: formatMetricValue(data.successfulCalls) }),
t("异常调用:{count}", { count: formatMetricValue(data.failedCalls) }),
t("成功占比:{rate}", { rate: formatRate(successfulCallRate) }),
].join("\n");
const tokensTooltip = [
t("总请求 Token 包含提示词和模型输出。"),
"",
t("总请求:{tokens}", { tokens: formatMetricValue(data.tokenUsage) }),
t("提示词:{tokens}", { tokens: formatMetricValue(data.promptTokens) }),
t("输出推算:{tokens}", { tokens: formatMetricValue(outputTokens) }),
t("非缓存输入:{tokens}", { tokens: formatMetricValue(inputTokens) }),
t("缓存读取:{tokens}", { tokens: formatMetricValue(data.cacheReadTokens) }),
t("缓存写入:{tokens}", { tokens: formatMetricValue(data.cacheWriteTokens) }),
"",
t("缓存读写已计入提示词侧统计。"),
].join("\n");
const costTooltip = [
t("按 Claude Opus 4.7 价格估算。"),
t("缓存统计策略:默认口径({rate})", { rate: formatRate(defaultCacheHitRate) }),
"",
t("普通输入:{tokens} × ${price}/1M = {cost}", {
tokens: formatMetricValue(inputTokens),
price: TOKEN_PRICE_PER_MILLION.input,
cost: formatUSD(costs.input),
}),
t("模型输出:{tokens} × ${price}/1M = {cost}", {
tokens: formatMetricValue(outputTokens),
price: TOKEN_PRICE_PER_MILLION.output,
cost: formatUSD(costs.output),
}),
t("缓存读取:{tokens} × ${price}/1M = {cost}", {
tokens: formatMetricValue(data.cacheReadTokens),
price: TOKEN_PRICE_PER_MILLION.cacheRead,
cost: formatUSD(costs.cacheRead),
}),
t("缓存写入:{tokens} × ${price}/1M = {cost}", {
tokens: formatMetricValue(data.cacheWriteTokens),
price: TOKEN_PRICE_PER_MILLION.cacheWrite,
cost: formatUSD(costs.cacheWrite),
}),
"",
t("合计:{cost}", { cost: formatUSD(totalCost) }),
].join("\n");
return <div className={styles.scroller}>
<section className={styles.root} aria-label={t("调用统计")}>
<article className={styles.metric}>
<div className={styles.label}>{t("缓存命中率")}<InfoTooltip content={cacheTooltip} /></div>
<CacheHitRateChart rate={defaultCacheHitRate ?? 0} animationKey={refreshVersion} />
</article>
<article className={styles.metric}>
<div className={styles.label}>{t("LLM 调用")}<InfoTooltip content={callsTooltip} /></div>
<div className={styles.body}>
<div className={styles.value} title={formatInteger(data.llmCalls)}>{formatCompactInteger(data.llmCalls)}</div>
<div className={styles.secondary}>{t("成功 {successful} / 异常 {failed}", {
successful: formatCompactInteger(data.successfulCalls),
failed: formatCompactInteger(data.failedCalls),
})}</div>
</div>
</article>
<article className={styles.metric}>
<div className={styles.label}>{t("Token 消耗")}<InfoTooltip content={tokensTooltip} /></div>
<div className={styles.body}>
<div className={styles.value} title={formatInteger(data.tokenUsage)}>{formatCompactInteger(data.tokenUsage)}</div>
<div className={styles.secondary}>{t("提示词 {tokens}", { tokens: formatCompactInteger(data.promptTokens) })}</div>
</div>
</article>
<article className={styles.metric}>
<div className={styles.label}>{t("价值估算")}<InfoTooltip content={costTooltip} /></div>
<div className={styles.body}>
<div className={styles.value} title={formatUSD(totalCost)}>{formatUSD(totalCost)}</div>
<div className={styles.secondary}>{t("缓存读写 {cost}", { cost: formatUSD(cacheCost) })}</div>
</div>
</article>
</section>
</div>;
}
@@ -0,0 +1,78 @@
@use "../../../styles/typography" as type;
.root,
.presets {
display: flex;
align-items: center;
}
.filterRow { width: 100%; }
.root {
gap: 3px;
}
.presets {
overflow: hidden;
// border: 1px solid var(--vscode-sideBar-border);
border-radius: 5px;
button {
height: 25px;
padding: 0 8px;
color: var(--vscode-descriptionForeground);
background: transparent;
border: 0;
border-right: 1px solid var(--vscode-sideBar-border);
font-size: type.$font-size-xs;
white-space: nowrap;
&:last-child { border-right: 0; }
&:hover { color: var(--vscode-foreground); background: var(--vscode-list-hoverBackground); }
&[aria-pressed="true"] { color: var(--vscode-list-activeSelectionForeground); background: var(--vscode-list-activeSelectionBackground); }
}
}
.popover {
position: fixed;
z-index: 14000;
display: flex;
flex-direction: column;
gap: 12px;
padding: 12px;
color: var(--vscode-foreground);
background: var(--vscode-dropdown-background);
border: 1px solid var(--vscode-dropdown-border);
border-radius: var(--oa-overlay-radius);
box-shadow: var(--oa-dropdown-shadow);
overflow: visible;
label {
display: grid;
grid-template-columns: 64px minmax(0, 1fr);
align-items: center;
gap: 8px;
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
input {
min-width: 0;
height: 32px;
padding: 0 8px;
color: var(--vscode-input-foreground);
background: var(--vscode-input-background);
border: 1px solid var(--vscode-input-border);
border-radius: 5px;
outline: none;
font: inherit;
&:focus { border-color: var(--vscode-focusBorder); }
}
}
.popoverActions {
display: flex;
justify-content: flex-end;
gap: 6px;
}
@@ -0,0 +1,115 @@
import { autoUpdate, computePosition, flip, offset, shift, size } from "@floating-ui/dom";
import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { parseTimeInput } from "../../../shared/utils/parseTimeInput";
import controls from "../../../shared/ui/Controls.module.scss";
import { Icon } from "../../../shared/ui/Icon";
import { MultiSelect, type MultiSelectOption } from "../../../shared/ui/MultiSelect";
import { TooltipTrigger } from "../../../shared/ui/TooltipTrigger";
import { refreshIcon } from "../../../shared/ui/icons";
import styles from "./OverviewTimeRangeFilter.module.scss";
export type OverviewRangePreset = "ten-minutes" | "hour" | "today" | "week" | "month" | "custom";
export function OverviewTimeRangeFilter({ value, customOpen, customStart, customEnd, modelOptions, selectedModels, busy, onSelect, onCustomOpenChange, onCustomStartChange, onCustomEndChange, onSelectedModelsChange, onCustomApply, onRefresh }: {
value: OverviewRangePreset;
customOpen: boolean;
customStart: string;
customEnd: string;
modelOptions: MultiSelectOption[];
selectedModels: string[];
busy: boolean;
onSelect: (value: Exclude<OverviewRangePreset, "custom">) => void;
onCustomOpenChange: (open: boolean) => void;
onCustomStartChange: (value: string) => void;
onCustomEndChange: (value: string) => void;
onSelectedModelsChange: (value: string[]) => void;
onCustomApply: () => void;
onRefresh: () => void;
}) {
const presets: Array<{ value: Exclude<OverviewRangePreset, "custom">; label: string }> = [
{ value: "hour", label: t("近1小时") },
{ value: "today", label: t("近1自然日") },
{ value: "ten-minutes", label: t("近10分钟") },
{ value: "week", label: t("近一周") },
{ value: "month", label: t("近一个月") },
];
const customButton = useRef<HTMLButtonElement>(null);
const popover = useRef<HTMLDivElement>(null);
const popoverId = useId();
const [position, setPosition] = useState({ left: 0, top: 0, width: 300, maxHeight: 480 });
useLayoutEffect(() => {
if (!customOpen || !customButton.current || !popover.current) return;
return autoUpdate(customButton.current, popover.current, () => void computePosition(customButton.current!, popover.current!, {
placement: "bottom-end",
middleware: [offset(5), flip({ padding: 10 }), shift({ padding: 10 }), size({
padding: 10,
apply: ({ availableHeight }) => setPosition((current) => ({
...current,
maxHeight: Math.max(240, availableHeight),
})),
})],
}).then(({ x, y }) => setPosition((current) => ({ ...current, left: x, top: y }))));
}, [customOpen]);
useEffect(() => {
if (!customOpen) return;
const closeOutside = (event: PointerEvent) => {
const target = event.target as Node;
if (!customButton.current?.contains(target) && !popover.current?.contains(target)) onCustomOpenChange(false);
};
document.addEventListener("pointerdown", closeOutside);
return () => document.removeEventListener("pointerdown", closeOutside);
}, [customOpen, onCustomOpenChange]);
const parsedStart = parseTimeInput(customStart);
const parsedEnd = parseTimeInput(customEnd);
const customValid = parsedStart !== null && parsedEnd !== null && parsedStart < parsedEnd;
return <div className={styles.root} aria-label={t("概览时间范围")}>
<div className={styles.presets}>
{presets.map((preset) => <button
key={preset.value}
type="button"
aria-pressed={value === preset.value}
onClick={() => onSelect(preset.value)}
>{preset.label}</button>)}
<button
ref={customButton}
type="button"
aria-haspopup="dialog"
aria-controls={customOpen ? popoverId : undefined}
aria-expanded={customOpen}
aria-pressed={value === "custom"}
onClick={() => onCustomOpenChange(!customOpen)}
>{t("自定义")}</button>
</div>
<TooltipTrigger label={t("刷新")}><button className={controls.iconButton} aria-label={t("刷新")} disabled={busy} onClick={onRefresh}>
<Icon className={busy ? controls.spin : ""} icon={refreshIcon} size="1.1em" />
</button></TooltipTrigger>
{customOpen && createPortal(<div
id={popoverId}
ref={popover}
className={styles.popover}
role="dialog"
aria-label={t("自定义概览筛选")}
style={position}
onKeyDown={(event) => {
if (event.key === "Escape") {
event.preventDefault();
onCustomOpenChange(false);
customButton.current?.focus();
}
}}
>
<label><span>{t("开始时间")}</span><input type="text" placeholder={t("如:2026-08-23 09:00、1小时前")} value={customStart} onChange={(event) => onCustomStartChange(event.target.value)} /></label>
<label><span>{t("结束时间")}</span><input type="text" placeholder={t("如:现在、2026-08-23 18:00")} value={customEnd} onChange={(event) => onCustomEndChange(event.target.value)} /></label>
<div className={styles.filterRow}><MultiSelect label={t("模型")} value={selectedModels} options={modelOptions} onChange={onSelectedModelsChange} /></div>
<div className={styles.popoverActions}>
<button type="button" className={controls.secondary} onClick={() => onCustomOpenChange(false)}>{t("取消")}</button>
<button type="button" className={controls.primary} disabled={!customValid} onClick={onCustomApply}>{t("应用")}</button>
</div>
</div>, document.body)}
</div>;
}
@@ -0,0 +1,42 @@
import { createContext, useContext, type ReactNode } from "react";
import { useAppStore } from "../../shared/store/appStore";
import controls from "../../shared/ui/Controls.module.scss";
import styles from "./CursorSettings.module.scss";
const CaReady = createContext(false);
const ModelsReady = createContext(false);
export function CursorCaProvider({ children }: { children: ReactNode }) {
const { cursorHarness } = useAppStore();
return <CaReady.Provider value={cursorHarness?.ca === "ready"}>{children}</CaReady.Provider>;
}
export function CursorCaGate({ busy, waitingForRefresh, onInitialize, onRefresh, children }: { busy: boolean; waitingForRefresh: boolean; onInitialize: () => void; onRefresh: () => void; children: ReactNode }) {
const ready = useContext(CaReady);
const { cursorHarness } = useAppStore();
if (ready) return children;
const installedLocally = cursorHarness?.ca === "untrusted";
return <div className={styles.gate}>
<strong>{installedLocally ? t("需要在系统中信任本地 CA") : t("需要先初始化本地 CA")}</strong>
<span>{installedLocally ? t("请在终端中粘贴授权命令并输入密码,完成后点击下方按钮") : t("CA 仅保存在本机,用于安全解析 Cursor 的 HTTPS 请求。")}</span>
<button className={controls.primary} disabled={busy} onClick={waitingForRefresh ? onRefresh : onInitialize}>{busy ? t("刷新中…") : waitingForRefresh ? t("我已初始化,刷新") : installedLocally ? t("打开终端安装 CA") : t("初始化 CA")}</button>
</div>;
}
export function CursorModelProvider({ children }: { children: ReactNode }) {
const { models } = useAppStore();
return <ModelsReady.Provider value={models.length > 0}>{children}</ModelsReady.Provider>;
}
export function CursorModelGate({ busy, previewingImport, onAdd, onImport, children }: { busy: boolean; previewingImport: boolean; onAdd: () => void; onImport: () => void; children: ReactNode }) {
const ready = useContext(ModelsReady);
if (ready) return children;
return <div className={styles.gate}>
<strong>{t("还没有可供 Cursor 使用的模型")}</strong>
<span>{t("Cursor 接管已生效;添加模型配置后即可使用 BYOK 模型。")}</span>
<div className={styles.gateActions}>
<button className={controls.primary} disabled={busy} onClick={onAdd}>{t("添加模型")}</button>
<button className={controls.secondary} disabled={busy} onClick={onImport}>{previewingImport ? t("读取中…") : t("导入旧版配置")}</button>
</div>
</div>;
}
@@ -0,0 +1,186 @@
import type { IconifyIcon } from "@iconify/react/offline";
import { useEffect, useRef } from "react";
import Sortable from "sortablejs";
import type { Model } from "../../shared/api";
import { Button } from "../../shared/ui/Button";
import { Card } from "../../shared/ui/Card";
import { Icon } from "../../shared/ui/Icon";
import { claudeIcon, dragIcon, flatColorOrganizationIcon, openAiIcon } from "../../shared/ui/icons";
import { CursorModelTestResult, type CursorModelTestState } from "./CursorModelTestResult";
import styles from "./CursorSettings.module.scss";
export type CursorModelGrouping = "flat" | "provider" | "type";
export type CursorModelGroup = {
key: string;
label: string;
icon: IconifyIcon;
models: Model[];
};
type CursorModelCardsProps = {
models: Model[];
grouping: CursorModelGrouping;
disabled: boolean;
testingModelHashes: Set<string>;
testResults: Map<string, CursorModelTestState>;
onTest: (model: Model) => void;
onEdit: (model: Model) => void;
onDuplicate: (model: Model) => void;
onDelete: (model: Model) => void;
onReorder: (modelHashes: string[]) => void;
};
type ModelGridProps = Omit<CursorModelCardsProps, "grouping"> & {
sortable: boolean;
};
export function cursorModelGroups(models: Model[], grouping: Exclude<CursorModelGrouping, "flat">): CursorModelGroup[] {
const groups = new Map<string, CursorModelGroup>();
for (const model of models) {
const descriptor = grouping === "provider" ? providerGroup(model) : typeGroup(model);
const group = groups.get(descriptor.key);
if (group) {
group.models.push(model);
} else {
groups.set(descriptor.key, { ...descriptor, models: [model] });
}
}
return [...groups.values()];
}
export function CursorModelCards(props: CursorModelCardsProps) {
if (props.grouping === "flat") return <div style={{ paddingTop: "10px" }}>
<ModelGrid {...props} sortable />
</div>;
return <div className={styles.modelGroups}>
{cursorModelGroups(props.models, props.grouping).map((group) => <section className={styles.modelGroup} key={group.key}>
<div className={styles.modelGroupHeader}>
<Icon icon={group.icon} size="1.1em" />
<span>{group.label}</span>
</div>
<ModelGrid {...props} models={group.models} sortable={false} />
</section>)}
</div>;
}
function ModelGrid({
models,
sortable: sortableEnabled,
disabled,
testingModelHashes,
testResults,
onTest,
onEdit,
onDuplicate,
onDelete,
onReorder,
}: ModelGridProps) {
const grid = useRef<HTMLDivElement>(null);
const sortable = useRef<Sortable | null>(null);
const currentModels = useRef(models);
const reorder = useRef(onReorder);
currentModels.current = models;
reorder.current = onReorder;
useEffect(() => {
if (!sortableEnabled || !grid.current) return;
sortable.current = Sortable.create(grid.current, {
animation: 160,
dataIdAttr: "data-model-hash",
draggable: `.${styles.modelCard}`,
handle: `.${styles.sortHandle}`,
ghostClass: styles.sortGhost,
chosenClass: styles.sortChosen,
dragClass: styles.sortDragging,
forceFallback: true,
fallbackOnBody: true,
fallbackTolerance: 3,
onEnd: (event) => {
const oldIndex = event.oldDraggableIndex ?? event.oldIndex;
const newIndex = event.newDraggableIndex ?? event.newIndex;
if (typeof oldIndex !== "number"
|| typeof newIndex !== "number"
|| oldIndex === newIndex) {
sortable.current?.sort(currentModels.current.map((model) => model.model_hash), false);
return;
}
const reordered = currentModels.current.slice();
const [moved] = reordered.splice(oldIndex, 1);
if (!moved || newIndex < 0 || newIndex > reordered.length) {
sortable.current?.sort(currentModels.current.map((model) => model.model_hash), false);
return;
}
reordered.splice(newIndex, 0, moved);
reorder.current(reordered.map((model) => model.model_hash));
},
});
return () => {
sortable.current?.destroy();
sortable.current = null;
};
}, [sortableEnabled]);
useEffect(() => {
sortable.current?.option("disabled", disabled);
sortable.current?.sort(models.map((model) => model.model_hash), false);
}, [disabled, models]);
return <div ref={grid} className={styles.modelGrid}>
{models.map((model) => {
const result = testResults.get(model.model_hash);
const testing = testingModelHashes.has(model.model_hash);
return <Card className={styles.modelCard} data-model-hash={model.model_hash} key={model.model_hash}>
{sortableEnabled && <button type="button" className={styles.sortHandle} disabled={disabled} aria-label={t("拖动排序")} title={t("拖动排序")} onClick={(event) => event.stopPropagation()}>
<Icon icon={dragIcon} size="1.25em" />
</button>}
<div className={styles.modelCardContent}>
<div className={styles.modelCardTop}>
<div className={styles.modelCardName}>
<span className={styles.modelCardNameText}>{model.display_name}</span>
<span className={styles.modelCardModelId}>{model.model_id}</span>
</div>
<span className={styles.modelTypeBadge}>
<Icon icon={model.type === "anthropic" ? claudeIcon : openAiIcon} />
{model.type === "anthropic" ? "Anthropic" : "OpenAI"}
</span>
</div>
<div className={styles.modelCardTest}>
<CursorModelTestResult state={result} testing={testing} />
</div>
<div className={styles.modelCardActions}>
<Button size="small" disabled={disabled && !testing} onClick={() => onTest(model)}>{testing ? t("取消测试") : t("测试")}</Button>
<Button size="small" disabled={disabled} onClick={() => onEdit(model)}>{t("编辑")}</Button>
<Button size="small" disabled={disabled} onClick={() => onDuplicate(model)}>{t("复制")}</Button>
<Button size="small" className={styles.deleteButton} disabled={disabled} onClick={() => onDelete(model)}>{t("删除")}</Button>
</div>
</div>
</Card>;
})}
</div>;
}
function providerGroup(model: Model) {
const label = providerDomain(model.base_url);
return { key: label, label, icon: flatColorOrganizationIcon };
}
function providerDomain(baseUrl: string) {
const value = baseUrl.trim();
try {
return new URL(value).hostname.toLowerCase() || value;
} catch {
try {
return new URL(`https://${value}`).hostname.toLowerCase() || value;
} catch {
return value;
}
}
}
function typeGroup(model: Model) {
if (model.type === "anthropic") return { key: "anthropic", label: "Anthropic", icon: claudeIcon };
if (model.openai_endpoint === "/v1/chat/completions") return { key: "openai-chat", label: "OpenAI Chat", icon: openAiIcon };
return { key: "openai-responses", label: "OpenAI Responses", icon: openAiIcon };
}
@@ -0,0 +1,204 @@
import type { ModelInput, ModelType } from "../../shared/api";
import { defaultCustomHeadersText } from "../../shared/utils/modelDefaults";
import { modelPresets, presetEndpoint, trimTrailingSlash, type ModelPreset } from "../../shared/utils/modelPresets";
import { Button } from "../../shared/ui/Button";
import { Checkbox } from "../../shared/ui/Checkbox";
import { FormField, SecretTextInput, TextInput } from "../../shared/ui/FormControls";
import { JsonEditor } from "../../shared/ui/JsonEditor";
import { Combobox, Select } from "../../shared/ui/Select";
import { Switch } from "../../shared/ui/Switch";
import { claudeIcon, openAiIcon } from "../../shared/ui/icons";
import { CursorPresetChips } from "./CursorPresetChips";
import styles from "./CursorSettings.module.scss";
export type CursorModelDraft = {
model: ModelInput;
openAIExtraParamsText: string;
customHeadersText: string;
anthropicExtraParamsText: string;
};
export const emptyCursorModelDraft = (): CursorModelDraft => ({
model: {
sort_order: 0,
display_name: "",
type: "openai",
base_url: "",
use_full_url: false,
api_key: "",
tooltip_data: "",
model_id: "",
reasoning_effort: null,
openai_endpoint: "/v1/responses",
openai_extra_params_enabled: false,
openai_extra_params: {},
custom_headers_enabled: false,
custom_headers: {},
anthropic_extra_params_enabled: false,
anthropic_extra_params: {},
context_window_tokens: null,
max_completion_tokens: null,
anthropic_max_tokens: null,
anthropic_thinking_effort: "xhigh",
thinking_budget_tokens: null,
},
openAIExtraParamsText: "{}",
customHeadersText: defaultCustomHeadersText,
anthropicExtraParamsText: "{}",
});
export function CursorModelEditor({ draft, modelOptions, discovering, onChange, onDiscover }: {
draft: CursorModelDraft;
modelOptions: string[];
discovering: boolean;
onChange: (draft: CursorModelDraft) => void;
onDiscover: () => void;
}) {
const setModel = (patch: Partial<ModelInput>) => onChange({ ...draft, model: { ...draft.model, ...patch } });
const setType = (type: ModelType) => {
// 切换协议类型时,若当前地址命中某预设的另一协议端点,自动换到该预设对应协议的端点,
// 避免出现「类型是 Anthropic、URL 却是 OpenAI chat/completions」的错配
const other: ModelType = type === "anthropic" ? "openai" : "anthropic";
const preset = modelPresets.find((candidate) => trimTrailingSlash(presetEndpoint(candidate, other).baseUrl) === trimTrailingSlash(draft.model.base_url.trim()));
const endpoint = preset ? presetEndpoint(preset, type) : null;
onChange({
...draft,
model: {
...draft.model,
type,
...(endpoint ? {
base_url: endpoint.baseUrl,
use_full_url: endpoint.useFullUrl,
custom_headers_enabled: endpoint.customHeaders !== null,
custom_headers: endpoint.customHeaders ? { ...endpoint.customHeaders } : {},
} : {}),
openai_endpoint: type === "openai" ? (endpoint?.openaiEndpoint || draft.model.openai_endpoint || "/v1/responses") : "",
anthropic_thinking_effort: type === "anthropic" ? draft.model.anthropic_thinking_effort || "xhigh" : null,
},
customHeadersText: endpoint?.customHeaders ? JSON.stringify(endpoint.customHeaders, null, 2) : draft.customHeadersText,
});
};
const numberValue = (value: string) => value === "" ? null : Math.trunc(Number(value));
const canDiscover = Boolean(draft.model.base_url.trim() && draft.model.api_key.trim());
// 选中预设后,把该服务商已知的模型 id 并入下拉,方便直接选(仍可用「获取模型」发现)
const presetModelOptions = modelPresets
.filter((preset) => trimTrailingSlash(presetEndpoint(preset, draft.model.type).baseUrl) === trimTrailingSlash(draft.model.base_url.trim()))
.flatMap((preset) => preset.models.map((item) => item.model_id));
const combinedOptions = [...new Set([...modelOptions, ...presetModelOptions])];
const applyPreset = (preset: ModelPreset) => {
const endpoint = presetEndpoint(preset, draft.model.type);
const first = preset.models[0];
// 切到别家服务商时清空 API Key(不同家的 Key 不能串用);同一家内切换协议则保留
const currentBase = trimTrailingSlash(draft.model.base_url.trim());
const sameProvider = [preset.endpoints.anthropic, preset.endpoints.openai]
.some((candidate) => trimTrailingSlash(candidate.baseUrl) === currentBase);
onChange({
...draft,
model: {
...draft.model,
base_url: endpoint.baseUrl,
use_full_url: endpoint.useFullUrl,
openai_endpoint: draft.model.type === "openai" ? endpoint.openaiEndpoint : draft.model.openai_endpoint,
custom_headers_enabled: endpoint.customHeaders !== null,
custom_headers: endpoint.customHeaders ? { ...endpoint.customHeaders } : {},
api_key: sameProvider ? draft.model.api_key : "",
model_id: first?.model_id ?? draft.model.model_id,
display_name: first?.display_name ?? draft.model.display_name,
tooltip_data: !draft.model.tooltip_data.trim() || draft.model.tooltip_data === t("备注") ? preset.name : draft.model.tooltip_data,
context_window_tokens: first?.context_window_tokens ?? draft.model.context_window_tokens,
...(draft.model.type === "openai"
? { max_completion_tokens: first?.max_output_tokens ?? draft.model.max_completion_tokens }
: { anthropic_max_tokens: first?.max_output_tokens ?? draft.model.anthropic_max_tokens }),
},
customHeadersText: endpoint.customHeaders ? JSON.stringify(endpoint.customHeaders, null, 2) : draft.customHeadersText,
});
};
const requestUrlPlaceholder = draft.model.use_full_url
? draft.model.type === "anthropic"
? "https://api.anthropic.com/v1/messages"
: draft.model.openai_endpoint === "/v1/chat/completions"
? "https://api.openai.com/v1/chat/completions"
: "https://api.openai.com/v1/responses"
: draft.model.type === "anthropic"
? "https://api.anthropic.com"
: "https://api.openai.com";
return <div className={styles.editor}>
<CursorPresetChips type={draft.model.type} baseUrl={draft.model.base_url} onPick={applyPreset} />
<div className={styles.grid}>
<FormField label={t("模型类型")}><Select ariaLabel={t("模型类型")} value={draft.model.type} options={[
{ value: "openai", label: "OpenAI", icon: openAiIcon },
{ value: "anthropic", label: "Anthropic", icon: claudeIcon },
]} onChange={(value) => setType(value as ModelType)} /></FormField>
{draft.model.type === "openai" && <FormField label={t("请求协议")} hint={t("只决定请求与响应的格式,不会改变请求地址。")}> <Select ariaLabel={t("请求协议")} value={draft.model.openai_endpoint} options={[
{ value: "/v1/responses", label: "Responses API" },
{ value: "/v1/chat/completions", label: "Chat Completions API" },
]} onChange={(openai_endpoint) => setModel({ openai_endpoint })} /></FormField>}
<div className={styles.urlField}>
<FormField label={draft.model.use_full_url ? t("完整请求 URL") : t("服务器地址")} hint={draft.model.use_full_url ? t("系统会原样使用此地址,不追加或修改请求路径。") : t("系统会根据请求协议自动追加标准端点路径。")}> <TextInput placeholder={requestUrlPlaceholder} value={draft.model.base_url} onChange={(event) => setModel({ base_url: event.target.value })} /></FormField>
<Checkbox checked={draft.model.use_full_url} label={t("使用完整请求地址")} onChange={(use_full_url) => setModel({ use_full_url })} />
</div>
<FormField label="API Key" hint={t("访问模型服务所需的密钥。")}> <SecretTextInput placeholder="sk-xxxxxx" autoComplete="off" value={draft.model.api_key} onChange={(event) => setModel({ api_key: event.target.value })} /></FormField>
<FormField label={t("模型名称")} hint={t("可以直接输入模型标识,也可以读取接口返回的模型列表。")}> <Combobox value={draft.model.model_id} options={combinedOptions} placeholder="gpt-5" append={<Button className={styles.discoverButton} disabled={discovering || !canDiscover} onClick={onDiscover}>{discovering ? t("获取中…") : t("获取模型")}</Button>} onChange={(model_id) => setModel({ model_id, display_name: draft.model.display_name || model_id })} /></FormField>
<FormField label={t("显示名称")} hint={t("仅用于界面展示,不会改变发送给模型服务的模型名称。")}> <TextInput placeholder={t("例如:主力模型")} value={draft.model.display_name} onChange={(event) => setModel({ display_name: event.target.value })} /></FormField>
<FormField className={styles.fullWidth} label={t("备注")} hint={t("显示在 Cursor 模型说明中。")}> <TextInput placeholder={t("请输入模型备注")} value={draft.model.tooltip_data} onChange={(event) => setModel({ tooltip_data: event.target.value })} /></FormField>
<FormField label={t("上下文窗口 Token")} hint={t("留空时使用默认值。")}> <TextInput type="number" min={1} step={1} placeholder={t("留空使用默认值")} value={draft.model.context_window_tokens ?? ""} onChange={(event) => setModel({ context_window_tokens: numberValue(event.target.value) })} /></FormField>
{draft.model.type === "openai" ? <>
<FormField label={t("最大输出 Token")} hint={t("留空时使用默认值。")}> <TextInput type="number" min={1} step={1} placeholder={t("留空使用默认值")} value={draft.model.max_completion_tokens ?? ""} onChange={(event) => setModel({ max_completion_tokens: numberValue(event.target.value) })} /></FormField>
<FormField label={t("推理强度")}> <Select ariaLabel={t("推理强度")} value={draft.model.reasoning_effort ?? ""} options={effortOptions(true)} onChange={(value) => setModel({ reasoning_effort: value || null })} /></FormField>
</> : <>
<FormField label={t("最大输出 Token")} hint={t("留空时使用默认值。")}> <TextInput type="number" min={1} step={1} placeholder={t("留空使用默认值")} value={draft.model.anthropic_max_tokens ?? ""} onChange={(event) => setModel({ anthropic_max_tokens: numberValue(event.target.value) })} /></FormField>
<FormField label={t("思考强度")}> <Select ariaLabel={t("思考强度")} value={draft.model.anthropic_thinking_effort ?? "xhigh"} options={effortOptions(false)} onChange={(anthropic_thinking_effort) => setModel({ anthropic_thinking_effort })} /></FormField>
<FormField label={t("思考预算 Token")} hint={t("留空时使用 adaptive thinking。")}> <TextInput type="number" min={1} step={1} placeholder={t("留空使用 adaptive thinking")} value={draft.model.thinking_budget_tokens ?? ""} onChange={(event) => setModel({ thinking_budget_tokens: numberValue(event.target.value) })} /></FormField>
</>}
<ToggleJsonField
label={t("自定义 Headers")}
enabled={draft.model.custom_headers_enabled}
text={draft.customHeadersText}
onEnabledChange={(custom_headers_enabled) => setModel({ custom_headers_enabled })}
onTextChange={(customHeadersText) => onChange({ ...draft, customHeadersText })}
/>
{draft.model.type === "openai" ? <ToggleJsonField
label={t("OpenAI 额外参数")}
enabled={draft.model.openai_extra_params_enabled}
text={draft.openAIExtraParamsText}
onEnabledChange={(openai_extra_params_enabled) => setModel({ openai_extra_params_enabled })}
onTextChange={(openAIExtraParamsText) => onChange({ ...draft, openAIExtraParamsText })}
/> : <ToggleJsonField
label={t("Anthropic 额外参数")}
enabled={draft.model.anthropic_extra_params_enabled}
text={draft.anthropicExtraParamsText}
onEnabledChange={(anthropic_extra_params_enabled) => setModel({ anthropic_extra_params_enabled })}
onTextChange={(anthropicExtraParamsText) => onChange({ ...draft, anthropicExtraParamsText })}
/>}
</div>
</div>;
}
function ToggleJsonField({ label, enabled, text, onEnabledChange, onTextChange }: {
label: string;
enabled: boolean;
text: string;
onEnabledChange: (enabled: boolean) => void;
onTextChange: (text: string) => void;
}) {
return <div className={`${styles.fullWidth} ${styles.jsonOption}`}>
<label><span>{label}</span><Switch label={label} checked={enabled} onChange={onEnabledChange} /></label>
{enabled && <JsonEditor ariaLabel={label} value={text} onChange={onTextChange} />}
</div>;
}
function effortOptions(optional: boolean) {
return [
...(optional ? [{ value: "", label: t("不设置") }] : []),
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
];
}
@@ -0,0 +1,64 @@
@use "../../styles/typography" as type;
.root {
min-width: 0;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 7px 9px;
border: 1px solid transparent;
border-radius: 6px;
font-size: type.$font-size-xs;
}
.idle {
color: var(--vscode-descriptionForeground);
background: color-mix(in srgb, var(--vscode-foreground) 6%, transparent);
border-color: color-mix(in srgb, var(--vscode-foreground) 12%, transparent);
}
.testing {
color: var(--vscode-textLink-foreground);
background: color-mix(in srgb, var(--vscode-textLink-foreground) 10%, transparent);
border-color: color-mix(in srgb, var(--vscode-textLink-foreground) 24%, transparent);
}
.success {
color: var(--vscode-testing-iconPassed, #73c991);
background: color-mix(in srgb, var(--vscode-testing-iconPassed, #73c991) 11%, transparent);
border-color: color-mix(in srgb, var(--vscode-testing-iconPassed, #73c991) 28%, transparent);
}
.error {
color: var(--vscode-errorForeground, #f48771);
background: color-mix(in srgb, var(--vscode-errorForeground, #f48771) 10%, transparent);
border-color: color-mix(in srgb, var(--vscode-errorForeground, #f48771) 28%, transparent);
}
.summary {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.details {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: 4px;
padding: 0;
color: currentColor;
background: transparent;
border: 0;
font: inherit;
cursor: help;
white-space: nowrap;
&:focus-visible {
outline: 1px solid var(--vscode-focusBorder);
outline-offset: 2px;
}
}
@@ -0,0 +1,40 @@
import type { ModelConnectivityResult } from "../../shared/api";
import { Icon } from "../../shared/ui/Icon";
import { TooltipTrigger } from "../../shared/ui/TooltipTrigger";
import { informationOutlineIcon } from "../../shared/ui/icons";
import styles from "./CursorModelTestResult.module.scss";
export type CursorModelTestState =
| { status: "success"; result: ModelConnectivityResult }
| { status: "error"; error: string }
| { status: "cancelled" };
export function CursorModelTestResult({ state, testing = false }: { state?: CursorModelTestState; testing?: boolean }) {
if (testing) return <div className={`${styles.root} ${styles.testing}`}><span className={styles.summary}>{t("测试中…")}</span></div>;
if (!state) return <div className={`${styles.root} ${styles.idle}`}><span className={styles.summary}>{t("未测试")}</span></div>;
if (state.status === "cancelled") return <div className={`${styles.root} ${styles.idle}`}><span className={styles.summary}>{t("测试已取消")}</span></div>;
const success = state.status === "success";
const summary = success
? t("速度:{speed} tokens/s", { speed: formatSpeed(state.result.tokens_per_second) })
: t("错误:{error}", { error: state.error });
const detail = success
? t("速度 {speed} tokens/s · 首字 {firstText} ms · 总耗时 {duration} ms · 输出 {tokens} tokens{estimated} · 返回:{output}", {
speed: formatSpeed(state.result.tokens_per_second),
firstText: state.result.first_valid_response_ms ?? "--",
duration: state.result.duration_ms,
tokens: state.result.output_tokens,
estimated: state.result.tokens_estimated ? t("(估算)") : "",
output: state.result.output || "--",
})
: t("测试失败:{error}", { error: state.error });
return <div className={`${styles.root} ${success ? styles.success : styles.error}`}>
<span className={styles.summary}>{summary}</span>
<TooltipTrigger label={detail}><button type="button" className={styles.details}>{t("查看详情")}<Icon icon={informationOutlineIcon} size="1.1em" /></button></TooltipTrigger>
</div>;
}
function formatSpeed(value: number) {
return Number.isFinite(value) ? value.toFixed(1) : "0.0";
}
@@ -0,0 +1,47 @@
.wrap {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.label {
font-size: 12px;
color: var(--vscode-descriptionForeground, rgba(255, 255, 255, 0.7));
}
.chips {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.chip {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 3px 10px;
border: 1px solid var(--vscode-editorWidget-border, rgba(255, 255, 255, 0.16));
border-radius: 999px;
background: transparent;
color: inherit;
font-size: 12px;
cursor: pointer;
&:hover {
border-color: var(--vscode-focusBorder, #49b0ff);
}
&.active {
border-color: var(--vscode-focusBorder, #49b0ff);
color: var(--vscode-focusBorder, #49b0ff);
}
}
.icon {
width: 14px;
height: 14px;
border-radius: 3px;
object-fit: contain;
}
@@ -0,0 +1,25 @@
import type { ModelType } from "../../shared/api";
import { modelPresets, presetEndpoint, trimTrailingSlash, type ModelPreset } from "../../shared/utils/modelPresets";
import styles from "./CursorPresetChips.module.scss";
/** 常用服务商预设:点击按当前协议类型自动填充对应端点与默认模型 */
export function CursorPresetChips({ type, baseUrl, onPick }: { type: ModelType; baseUrl: string; onPick: (preset: ModelPreset) => void }) {
return <div className={styles.wrap}>
<span className={styles.label}>{t("常用预设")}</span>
<div className={styles.chips}>
{modelPresets.map((preset) => {
const active = trimTrailingSlash(baseUrl) === trimTrailingSlash(presetEndpoint(preset, type).baseUrl);
return <button
type="button"
key={preset.key}
className={active ? `${styles.chip} ${styles.active}` : styles.chip}
title={preset.keyHint}
onClick={() => onPick(preset)}
>
<img className={styles.icon} src={preset.icon} alt="" />
{preset.name}
</button>;
})}
</div>
</div>;
}
@@ -0,0 +1,266 @@
@use "../../styles/typography" as type;
.page {
display: grid;
gap: 16px;
}
.groupActions {
display: flex;
align-items: center;
overflow: hidden;
border-radius: 5px;
button {
height: 25px;
padding: 0 8px;
color: var(--vscode-descriptionForeground);
background: transparent;
border: 0;
border-right: 1px solid var(--vscode-sideBar-border);
font-size: type.$font-size-xs;
white-space: nowrap;
&:last-child { border-right: 0; }
&:hover:not(:disabled) { color: var(--vscode-foreground); background: var(--vscode-list-hoverBackground); }
&[aria-pressed="true"] { color: var(--vscode-list-activeSelectionForeground); background: var(--vscode-list-activeSelectionBackground); }
&:disabled { opacity: 0.5; cursor: not-allowed; }
}
}
.gateActions {
display: flex;
align-items: center;
gap: 8px;
}
.gate {
min-height: 250px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 9px;
color: var(--vscode-descriptionForeground);
text-align: center;
border: 1px dashed var(--vscode-sideBar-border);
border-radius: var(--oa-overlay-radius);
strong {
color: var(--vscode-foreground);
font-size: type.$font-size-base;
}
span {
max-width: 440px;
font-size: type.$font-size-xs;
}
button {
margin-top: 6px;
}
}
.modelGrid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 12px;
}
.modelGroups {
display: flex;
flex-direction: column;
gap: 20px;
padding-top: 10px;
}
.modelGroup {
display: flex;
flex-direction: column;
gap: 10px;
}
.modelGroupHeader {
display: flex;
align-items: center;
gap: 6px;
color: var(--vscode-foreground);
font-size: type.$font-size-base;
opacity: 0.6;
padding-left: 6px;
}
.modelCard {
position: relative;
padding: 16px;
}
.modelCardContent {
min-height: 120px;
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 12px;
}
.modelCardTop {
min-width: 0;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.modelCardName {
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
.modelCardNameText,
.modelCardModelId {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.modelCardNameText {
color: var(--vscode-foreground);
font-size: type.$font-size-base;
}
.modelCardModelId {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-2xs;
}
}
.modelTypeBadge {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 7px;
color: var(--vscode-foreground);
border: 1px solid var(--vscode-sideBar-border);
border-radius: 999px;
font-size: type.$font-size-2xs;
}
.modelCardTest {
min-height: 31px;
display: flex;
align-items: center;
}
.modelCardActions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
}
.deleteButton:hover {
color: var(--vscode-errorForeground, #f48771);
}
.sortHandle {
position: absolute;
top: 8px;
left: 8px;
z-index: 1;
width: 30px;
height: 30px;
display: grid;
place-items: center;
padding: 0;
color: transparent;
background: transparent;
border: 1px solid transparent;
border-radius: 6px;
opacity: 0;
cursor: grab;
touch-action: none;
transition: opacity 160ms ease, color 160ms ease, border-color 160ms ease, background-color 160ms ease;
&:focus-visible,
.modelCard:hover & {
color: var(--vscode-foreground);
background: var(--vscode-list-hoverBackground);
border-color: var(--vscode-sideBar-border);
opacity: 1;
}
&:active {
cursor: grabbing;
}
&:disabled {
cursor: not-allowed;
opacity: 0.3;
}
}
.sortGhost {
opacity: 0.4;
}
.sortChosen {
border-color: var(--vscode-focusBorder);
}
.sortDragging {
cursor: grabbing;
}
.editor {
display: flex;
flex-direction: column;
gap: 14px;
}
.command {
margin: 0;
padding: 10px;
overflow: auto;
color: var(--vscode-textLink-foreground);
background: var(--vscode-textCodeBlock-background);
border-radius: 4px;
white-space: pre-wrap;
user-select: text;
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.fullWidth {
width: 100%;
grid-column: 1 / -1;
}
.discoverButton {
min-height: 34px;
height: 34px;
flex: 0 0 auto;
}
.urlField {
min-width: 0;
display: flex;
flex-direction: column;
gap: 7px;
}
.switches {
display: flex;
flex-direction: column;
gap: 9px;
label {
min-width: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.jsonOption {
display: flex;
flex-direction: column;
gap: 8px;
> label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
@media (max-width: 720px) {
.grid {
grid-template-columns: 1fr;
}
.fullWidth {
grid-column: auto;
}
}
@@ -0,0 +1,308 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { api, type Model, type ModelInput } from "../../shared/api";
import { CursorCaGate, CursorCaProvider, CursorModelGate, CursorModelProvider } from "./CursorGates";
import { CursorModelCards, cursorModelGroups, type CursorModelGrouping } from "./CursorModelCards";
import { CursorModelEditor, emptyCursorModelDraft, type CursorModelDraft } from "./CursorModelEditor";
import { CursorModelTestResult, type CursorModelTestState } from "./CursorModelTestResult";
import styles from "./CursorSettings.module.scss";
import { PageContent } from "../../shell/layout/PageContent";
import { LegacyModelImport } from "./LegacyModelImport";
import { ConfirmDialog } from "../../shared/ui/ConfirmDialog";
import controls from "../../shared/ui/Controls.module.scss";
import { Icon } from "../../shared/ui/Icon";
import { Modal } from "../../shared/ui/Modal";
import { TooltipTrigger } from "../../shared/ui/TooltipTrigger";
import { addIcon } from "../../shared/ui/icons";
import { useMessage } from "../../shared/ui/message";
import { PageActions } from "../../shell/PageActions";
import { appStore, useAppStore } from "../../shared/store/appStore";
export function CursorSettingsPage() {
const { models, cursorHarness, cursorBusy } = useAppStore();
const message = useMessage();
const [draft, setDraft] = useState<CursorModelDraft | null>(null);
const [editing, setEditing] = useState<Model | null>(null);
const [modelOptions, setModelOptions] = useState<string[]>([]);
const [discovering, setDiscovering] = useState(false);
const [caCommand, setCaCommand] = useState<string | null>(null);
const [waitingForCaRefresh, setWaitingForCaRefresh] = useState(false);
const [deleting, setDeleting] = useState<Model | null>(null);
const [testingModelHashes, setTestingModelHashes] = useState<Set<string>>(() => new Set());
const [modelTestResults, setModelTestResults] = useState<Map<string, CursorModelTestState>>(() => new Map());
const [savingAndTesting, setSavingAndTesting] = useState(false);
const [batchTesting, setBatchTesting] = useState(false);
const [grouping, setGrouping] = useState<CursorModelGrouping>("flat");
const activeModelTests = useRef(new Map<string, { testId: string; controller: AbortController; cancelling: boolean }>());
const caReady = cursorHarness?.ca === "ready";
const providerGroups = cursorModelGroups(models, "provider");
const typeGroups = cursorModelGroups(models, "type");
const canGroupByProvider = providerGroups.length > 1;
const canGroupByType = typeGroups.length > 1;
useEffect(() => {
if ((grouping === "provider" && !canGroupByProvider) || (grouping === "type" && !canGroupByType)) {
setGrouping("flat");
}
}, [canGroupByProvider, canGroupByType, grouping]);
useEffect(() => {
if (caCommand) void api.copyCursorText(caCommand);
}, [caCommand]);
const initializeCa = async () => {
const status = await appStore.initializeCursorCa();
if (status?.ca === "untrusted" && status.ca_install_command) setCaCommand(status.ca_install_command);
};
const openNew = () => {
const next = emptyCursorModelDraft();
next.model.sort_order = models.length + 1;
setEditing(null);
setModelOptions([]);
setDraft(next);
};
const openEdit = (model: Model) => {
setEditing(model);
setModelOptions([model.model_id]);
setDraft({
model: modelInput(model),
openAIExtraParamsText: JSON.stringify(model.openai_extra_params, null, 2),
customHeadersText: JSON.stringify(model.custom_headers, null, 2),
anthropicExtraParamsText: JSON.stringify(model.anthropic_extra_params, null, 2),
});
};
const discover = async () => {
if (!draft) return;
setDiscovering(true);
try {
const custom_headers = parseHeaders(draft.customHeadersText);
const result = await api.discoverModels({
type: draft.model.type,
base_url: draft.model.base_url.trim(),
api_key: draft.model.api_key.trim(),
custom_headers_enabled: draft.model.custom_headers_enabled,
custom_headers,
});
setModelOptions([...new Set(result.models)]);
} catch (cause) {
message(errorText(cause));
} finally {
setDiscovering(false);
}
};
const persist = async (): Promise<Model | null> => {
if (!draft) return null;
const input = draftInput(draft);
if (editing) return appStore.updateCursorModel(editing.model_hash, input);
return (await appStore.createModels([input]))?.[0] ?? null;
};
const save = async () => {
try {
if (await persist()) {
setDraft(null);
setEditing(null);
}
} catch (cause) {
message(errorText(cause));
}
};
const cancelModelTest = async (modelHash: string) => {
const active = activeModelTests.current.get(modelHash);
if (!active || active.cancelling) return;
active.cancelling = true;
try {
await api.cancelModelTest(modelHash, active.testId);
active.controller.abort();
} catch (cause) {
active.cancelling = false;
message(t("取消测试失败:{error}", { error: errorText(cause) }), { duration: 5000 });
}
};
const cancelAllModelTests = async () => {
await Promise.all([...activeModelTests.current.keys()].map((modelHash) => cancelModelTest(modelHash)));
};
const testModel = async (model: Model, notify = true): Promise<"success" | "failure" | "cancelled"> => {
if (activeModelTests.current.has(model.model_hash)) {
await cancelModelTest(model.model_hash);
return "cancelled";
}
const active = { testId: crypto.randomUUID(), controller: new AbortController(), cancelling: false };
activeModelTests.current.set(model.model_hash, active);
setTestingModelHashes((current) => new Set(current).add(model.model_hash));
try {
const result = await api.testModel(model.model_hash, active.testId, active.controller.signal);
setModelTestResults((current) => new Map(current).set(model.model_hash, { status: "success", result }));
if (notify) message(t("模型 {model} 连通性测试成功({duration} ms)", { model: model.display_name, duration: result.duration_ms }));
return "success";
} catch (cause) {
if (active.cancelling || active.controller.signal.aborted) {
setModelTestResults((current) => new Map(current).set(model.model_hash, { status: "cancelled" }));
return "cancelled";
}
const error = errorText(cause);
setModelTestResults((current) => new Map(current).set(model.model_hash, { status: "error", error }));
if (notify) message(t("连通性测试失败:{error}", { error }), { duration: 5000 });
return "failure";
} finally {
if (activeModelTests.current.get(model.model_hash) === active) activeModelTests.current.delete(model.model_hash);
setTestingModelHashes((current) => {
const next = new Set(current);
next.delete(model.model_hash);
return next;
});
}
};
const saveAndTest = async () => {
setSavingAndTesting(true);
let saved: Model | null = null;
try {
saved = await persist();
} catch (cause) {
message(errorText(cause));
} finally {
setSavingAndTesting(false);
}
if (!saved) return;
setEditing(saved);
await testModel(saved);
await appStore.refresh();
};
const testAllModels = async () => {
if (!models.length || batchTesting) return;
setBatchTesting(true);
try {
const results = await Promise.all(models.map((model) => testModel(model, false)));
const successful = results.filter((result) => result === "success").length;
const failed = results.filter((result) => result === "failure").length;
const cancelled = results.filter((result) => result === "cancelled").length;
message(cancelled > 0
? t("连通性测试已取消:成功 {successful},失败 {failed}", { successful, failed })
: failed === 0
? t("全部 {count} 个模型连通性测试成功", { count: models.length })
: t("连通性测试完成:成功 {successful},失败 {failed}", { successful, failed }),
{ duration: failed === 0 && cancelled === 0 ? 2400 : 5000 });
} finally {
setBatchTesting(false);
}
};
const duplicateModel = async (model: Model) => {
const names = new Set(models.map((item) => item.display_name));
const baseName = t("{name} 副本", { name: model.display_name });
let displayName = baseName;
let suffix = 2;
while (names.has(displayName)) {
displayName = `${baseName} ${suffix}`;
suffix += 1;
}
const created = await appStore.createModels([{
...modelInput(model),
sort_order: models.length + 1,
display_name: displayName,
}]);
if (created) message(t("模型已复制"));
};
const reorderModels = useCallback(async (modelHashes: string[]) => {
if (!await appStore.reorderCursorModels(modelHashes)) {
message(appStore.getSnapshot().error || t("排序失败"));
}
}, [message]);
const list = <CursorModelCards
models={models}
grouping={grouping}
disabled={cursorBusy}
testingModelHashes={testingModelHashes}
testResults={modelTestResults}
onTest={(model) => void testModel(model)}
onEdit={openEdit}
onDuplicate={(model) => void duplicateModel(model)}
onDelete={setDeleting}
onReorder={reorderModels}
/>;
const refreshCa = async () => {
await appStore.refresh();
if (appStore.getSnapshot().cursorHarness?.ca !== "ready") setWaitingForCaRefresh(false);
};
const openCaTerminal = () => {
if (caCommand) void api.openCursorCaInstallTerminal(caCommand).catch((cause) => message(errorText(cause)));
setCaCommand(null);
setWaitingForCaRefresh(true);
};
const content = <CursorCaProvider><CursorCaGate busy={cursorBusy} waitingForRefresh={waitingForCaRefresh} onInitialize={() => void initializeCa()} onRefresh={() => void refreshCa()}>
<div className={styles.page}>
<LegacyModelImport>{({ busy: importingLegacyModels, previewing, open }) =>
<CursorModelProvider><CursorModelGate busy={cursorBusy || importingLegacyModels} previewingImport={previewing} onAdd={openNew} onImport={open}>{list}</CursorModelGate></CursorModelProvider>
}</LegacyModelImport>
</div>
</CursorCaGate></CursorCaProvider>;
const editorTestState = editing ? modelTestResults.get(editing.model_hash) : undefined;
const editorTesting = Boolean(editing && testingModelHashes.has(editing.model_hash));
const activeGroups = grouping === "provider" ? providerGroups : typeGroups;
const estimatedModelHeight = grouping === "flat"
? Math.max(380, Math.ceil(models.length / 3) * 196)
: Math.max(380, activeGroups.reduce((height, group) => height + Math.ceil(group.models.length / 3) * 196 + 34, 0) + Math.max(0, activeGroups.length - 1) * 20);
return <>
{models.length > 0 && <PageActions position="left">
<div className={styles.groupActions} role="group" aria-label={t("操作")}>
<button type="button" aria-pressed={grouping === "flat"} onClick={() => setGrouping("flat")}>{t("默认平铺")}</button>
{canGroupByProvider && <button type="button" aria-pressed={grouping === "provider"} onClick={() => setGrouping("provider")}>{t("按供应商")}</button>}
{canGroupByType && <button type="button" aria-pressed={grouping === "type"} onClick={() => setGrouping("type")}>{t("按类型")}</button>}
<button type="button" disabled={cursorBusy || (!batchTesting && testingModelHashes.size > 0)} onClick={() => void (batchTesting ? cancelAllModelTests() : testAllModels())}>{batchTesting ? t("取消全部测试") : t("一键测试")}</button>
</div>
</PageActions>}
<PageActions><TooltipTrigger label={caReady ? t("添加模型") : t("请先初始化 CA")}><button className={controls.iconButton} aria-label={t("添加模型")} disabled={!caReady || cursorBusy} onClick={openNew}><Icon icon={addIcon} size="1.1em" /></button></TooltipTrigger></PageActions>
<PageContent title={t("Cursor 配置")} sections={[{ key: "cursor-settings", estimatedHeight: estimatedModelHeight, content }]} />
<Modal fullHeight open={draft !== null} title={editing ? t("编辑模型") : t("添加模型")} banner={draft && (editorTesting || editorTestState) ? <CursorModelTestResult state={editorTestState} testing={editorTesting} /> : undefined} busy={cursorBusy || savingAndTesting} onClose={() => { if (editing && editorTesting) void cancelModelTest(editing.model_hash); setDraft(null); setEditing(null); }} onSubmit={() => void save()} secondaryAction={<button type="button" className={controls.secondary} disabled={cursorBusy || savingAndTesting} onClick={() => void (editorTesting && editing ? cancelModelTest(editing.model_hash) : saveAndTest())}>{savingAndTesting ? t("处理中…") : editorTesting ? t("取消测试") : t("保存并测试")}</button>}>
{draft && <>
<CursorModelEditor draft={draft} modelOptions={modelOptions} discovering={discovering} onChange={setDraft} onDiscover={() => void discover()} />
</>}
</Modal>
<ConfirmDialog open={caCommand !== null} title={t("安装本地 CA")} cancelLabel={t("关闭")} confirmLabel={t("打开终端")} onCancel={() => setCaCommand(null)} onConfirm={openCaTerminal}>
<div className={styles.editor}><strong>{t("需要授权安装证书")}</strong><span>{t("安装命令已自动复制。点击“打开终端”,将命令粘贴到终端中执行,并按提示输入密码。")}</span><pre className={styles.command}>{caCommand}</pre></div>
</ConfirmDialog>
<ConfirmDialog open={deleting !== null} title={t("删除模型")} cancelLabel={t("取消")} confirmLabel={t("删除")} onCancel={() => setDeleting(null)} onConfirm={() => { if (deleting) void appStore.deleteModel(deleting.model_hash); setDeleting(null); }}><p>{t("确定删除这个模型吗?")}</p></ConfirmDialog>
</>;
}
function modelInput(model: Model): ModelInput {
const { model_hash: _hash, created_at_ms: _created, updated_at_ms: _updated, ...input } = model;
return input;
}
function draftInput(draft: CursorModelDraft): ModelInput {
const model = {
...draft.model,
display_name: draft.model.display_name.trim(),
base_url: draft.model.base_url.trim(),
api_key: draft.model.api_key.trim(),
tooltip_data: draft.model.tooltip_data.trim(),
model_id: draft.model.model_id.trim(),
openai_extra_params: parseObject(draft.openAIExtraParamsText, t("OpenAI 额外参数")),
custom_headers: parseHeaders(draft.customHeadersText),
anthropic_extra_params: parseObject(draft.anthropicExtraParamsText, t("Anthropic 额外参数")),
};
if (!model.display_name || !model.base_url || !model.api_key || !model.tooltip_data || !model.model_id) throw new Error(t("服务器地址或完整请求 URL、API Key、模型名称、显示名称和备注不能为空"));
for (const [label, value] of [[t("上下文窗口 Token"), model.context_window_tokens], [t("最大输出 Token"), model.type === "openai" ? model.max_completion_tokens : model.anthropic_max_tokens], [t("思考预算 Token"), model.thinking_budget_tokens]] as const) {
if (value !== null && (!Number.isSafeInteger(value) || value <= 0)) throw new Error(t("{label} 必须是大于 0 的整数", { label }));
}
return model;
}
function parseHeaders(text: string): Record<string, string> {
const parsed = parseObject(text, t("自定义 Headers"));
if (Object.values(parsed).some((value) => typeof value !== "string")) throw new Error(t("自定义 Headers 的值必须都是字符串"));
return parsed as Record<string, string>;
}
function parseObject(text: string, label: string): Record<string, unknown> {
let parsed: unknown;
try { parsed = JSON.parse(text || "{}"); } catch { throw new Error(t("{label} 必须是有效 JSON", { label })); }
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") throw new Error(t("{label} 必须是 JSON 对象", { label }));
return parsed as Record<string, unknown>;
}
function errorText(cause: unknown) {
return cause instanceof Error ? cause.message : String(cause);
}
@@ -0,0 +1,92 @@
@use "../../styles/typography" as type;
.content {
display: grid;
gap: 14px;
}
.source {
display: grid;
gap: 6px;
code {
overflow-wrap: anywhere;
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.counts {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
> div {
display: grid;
gap: 3px;
padding: 10px;
background: var(--vscode-input-background);
border: 1px solid var(--vscode-input-border);
border-radius: 5px;
}
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.models {
display: grid;
gap: 6px;
}
.model {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
min-width: 0;
padding: 9px 10px;
background: var(--vscode-list-inactiveSelectionBackground);
border-radius: 5px;
> div {
display: grid;
min-width: 0;
gap: 3px;
}
small {
overflow: hidden;
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
text-overflow: ellipsis;
white-space: nowrap;
}
> span {
flex: 0 0 auto;
font-size: type.$font-size-xs;
}
}
.new {
color: var(--vscode-testing-iconPassed, #73c991);
}
.existing,
.hint {
color: var(--vscode-descriptionForeground);
}
.hint {
font-size: type.$font-size-xs;
}
@media (max-width: 680px) {
.model {
align-items: stretch;
flex-direction: column;
}
}
@@ -0,0 +1,92 @@
import { useState, type ReactNode } from "react";
import { api, type LegacyModelImportPreview } from "../../shared/api";
import { appStore } from "../../shared/store/appStore";
import { ConfirmDialog } from "../../shared/ui/ConfirmDialog";
import { useMessage } from "../../shared/ui/message";
import styles from "./LegacyModelImport.module.scss";
type LegacyModelImportControl = {
busy: boolean;
previewing: boolean;
open: () => void;
};
export function LegacyModelImport({ children }: { children: (control: LegacyModelImportControl) => ReactNode }) {
const message = useMessage();
const [preview, setPreview] = useState<LegacyModelImportPreview | null>(null);
const [previewing, setPreviewing] = useState(false);
const [importing, setImporting] = useState(false);
const open = async () => {
try {
setPreviewing(true);
setPreview(await api.previewV0049Models());
} catch (cause) {
message(errorText(cause));
} finally {
setPreviewing(false);
}
};
const confirm = async () => {
try {
setImporting(true);
const result = await appStore.importV0049Models();
if (!result) {
const error = appStore.getSnapshot().error;
if (error) message(error);
return;
}
setPreview(null);
message(result.imported > 0
? t("导入完成:新增 {imported} 个模型,跳过 {skipped} 个已存在模型", { imported: result.imported, skipped: result.skipped })
: t("配置中的 {count} 个模型均已存在,无需重复导入", { count: result.skipped }));
} catch (cause) {
message(errorText(cause));
} finally {
setImporting(false);
}
};
return <>
{children({ busy: previewing || importing, previewing, open: () => void open() })}
<ConfirmDialog
open={preview !== null}
title={t("确认导入旧版模型配置")}
busy={importing}
wide
cancelLabel={t("取消")}
confirmLabel={t("确认导入")}
onCancel={() => setPreview(null)}
onConfirm={() => void confirm()}
>
{preview && <div className={styles.content}>
<div className={styles.source}>
<strong>{t("配置文件")}</strong>
<code>{preview.source}</code>
</div>
<div className={styles.counts}>
<div><strong>{preview.total}</strong><small>{t("配置模型")}</small></div>
<div><strong>{preview.new_models}</strong><small>{t("将新增")}</small></div>
<div><strong>{preview.existing_models}</strong><small>{t("已存在")}</small></div>
</div>
<div className={styles.models}>
{preview.models.map((model) => <div className={styles.model} key={model.model_hash}>
<div>
<strong>{model.display_name}</strong>
<small>{model.model_id} · {model.type === "openai" ? "OpenAI" : "Anthropic"}</small>
</div>
<span className={model.existing ? styles.existing : styles.new}>
{model.existing ? t("已存在,跳过") : t("新增")}
</span>
</div>)}
</div>
<small className={styles.hint}>{t("重复导入相同配置不会创建重复模型;已经存在的模型会自动跳过。")}</small>
</div>}
</ConfirmDialog>
</>;
}
function errorText(cause: unknown) {
return cause instanceof Error ? cause.message : String(cause);
}
@@ -0,0 +1,31 @@
@use "../../styles/typography" as type;
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 16px;
& + & {
border-top: 1px solid var(--vscode-widget-border);
}
> div {
display: grid;
gap: 5px;
}
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.updateDot {
width: 7px;
height: 7px;
flex: 0 0 7px;
background: #ef4444;
border-radius: 50%;
}
@@ -0,0 +1,164 @@
import { useEffect, useState } from "react";
import {
currentAppVersion,
hasDockVisibilitySetting,
hasNativeAppLifecycle,
readAutostart,
readDesktopSettings,
writeAutostart,
writeDockIconVisibility,
writeSilentStart,
} from "../../shared/native/appLifecycle";
import { updateStore, useUpdateStore } from "../../shared/store/updateStore";
import { Button } from "../../shared/ui/Button";
import { Switch } from "../../shared/ui/Switch";
import { TitledCard } from "../../shared/ui/TitledCard";
import { useMessage } from "../../shared/ui/message";
import styles from "./AppLifecycleSettingsCard.module.scss";
export function AppLifecycleSettingsCard() {
const message = useMessage();
const native = hasNativeAppLifecycle();
const dockVisibilitySetting = hasDockVisibilitySetting();
const { availableVersion, checking, installing } = useUpdateStore();
const [version, setVersion] = useState("…");
const [autostart, setAutostart] = useState(false);
const [loadingAutostart, setLoadingAutostart] = useState(native);
const [silentStart, setSilentStart] = useState(false);
const [dockIconVisible, setDockIconVisible] = useState(true);
const [loadingDesktopSettings, setLoadingDesktopSettings] = useState(native);
useEffect(() => {
let disposed = false;
void currentAppVersion().then((next) => { if (!disposed) setVersion(next); });
if (native) {
void readAutostart()
.then((enabled) => { if (!disposed) setAutostart(enabled); })
.catch((cause) => message(cause instanceof Error ? cause.message : String(cause)))
.finally(() => { if (!disposed) setLoadingAutostart(false); });
void readDesktopSettings()
.then((settings) => {
if (disposed) return;
setSilentStart(settings.silent_start);
setDockIconVisible(settings.show_dock_icon);
})
.catch(() => {})
.finally(() => {
if (disposed) return;
setLoadingDesktopSettings(false);
});
}
return () => { disposed = true; };
}, [message, native]);
const toggleAutostart = async (enabled: boolean) => {
try {
setLoadingAutostart(true);
await writeAutostart(enabled);
setAutostart(await readAutostart());
message(enabled ? t("已开启开机启动") : t("已关闭开机启动"));
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
} finally {
setLoadingAutostart(false);
}
};
const toggleSilentStart = async (enabled: boolean) => {
try {
setLoadingDesktopSettings(true);
await writeSilentStart(enabled);
setSilentStart(enabled);
message(enabled ? t("已开启静默启动") : t("已关闭静默启动"));
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
} finally {
setLoadingDesktopSettings(false);
}
};
const toggleDockIcon = async (visible: boolean) => {
try {
setLoadingDesktopSettings(true);
await writeDockIconVisibility(visible);
setDockIconVisible(visible);
message(visible ? t("已显示 Dock 栏图标") : t("已隐藏 Dock 栏图标"));
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
} finally {
setLoadingDesktopSettings(false);
}
};
const checkUpdate = async () => {
try {
const nextVersion = await updateStore.check();
message(nextVersion ? t("发现新版本 {version}", { version: nextVersion }) : t("当前已是最新版本"));
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
}
};
const updateNow = async () => {
try {
await updateStore.install();
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
}
};
return <TitledCard title={t("应用设置")}>
<div className={styles.row}>
<div>
<strong>{t("开机启动")}</strong>
<small>{t("登录系统后自动启动 Cursor BYOK。")}</small>
</div>
<Switch
checked={autostart}
disabled={!native || loadingAutostart}
label={t("开机启动")}
onChange={(enabled) => void toggleAutostart(enabled)}
/>
</div>
{autostart && <div className={styles.row}>
<div>
<strong>{t("静默启动")}</strong>
<small>{t("开机启动时不显示主窗口,仅保留系统托盘图标。")}</small>
</div>
<Switch
checked={silentStart}
disabled={!native || loadingDesktopSettings}
label={t("静默启动")}
onChange={(enabled) => void toggleSilentStart(enabled)}
/>
</div>}
{dockVisibilitySetting && <div className={styles.row}>
<div>
<strong>{t("在 Dock 栏显示")}</strong>
<small>{t("关闭后隐藏 Dock 栏图标,仍可通过菜单栏图标打开应用。")}</small>
</div>
<Switch
checked={dockIconVisible}
disabled={loadingDesktopSettings}
label={t("在 Dock 栏显示")}
onChange={(visible) => void toggleDockIcon(visible)}
/>
</div>}
<div className={styles.row}>
<div>
<strong>{t("软件更新")}</strong>
<small>{availableVersion
? t("版本 {version} 可以安装", { version: availableVersion })
: t("当前版本 {version}", { version })}</small>
</div>
{availableVersion
? <Button size="small" variant="primary" disabled={installing} onClick={() => void updateNow()}>
{installing ? t("安装中…") : t("下载并安装")}
<span className={styles.updateDot} aria-hidden="true" />
</Button>
: <Button size="small" disabled={!native || checking} onClick={() => void checkUpdate()}>
{checking ? t("检查中…") : t("检查更新")}
</Button>}
</div>
</TitledCard>;
}
@@ -0,0 +1,53 @@
@use "../../styles/typography" as type;
.content,
.customFields {
display: grid;
gap: 14px;
}
.content {
padding: 16px;
}
.row {
min-width: 0;
min-height: 34px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
}
.control {
width: min(420px, 62%);
}
.value {
min-width: 0;
max-width: 70%;
color: var(--vscode-descriptionForeground);
overflow-wrap: anywhere;
text-align: right;
}
.headerAction {
padding: 4px;
color: var(--vscode-textLink-foreground);
background: transparent;
border: 0;
font-size: type.$font-size-xs;
&:hover { color: var(--vscode-textLink-activeForeground); }
&:disabled { opacity: .5; }
}
.actionGroup {
display: flex;
align-items: center;
gap: 6px;
}
@media (max-width: 680px) {
.control { width: 68%; }
}
@@ -0,0 +1,81 @@
import type { ProxySettings, ProxySettingsInput } from "../../shared/api";
import { Button } from "../../shared/ui/Button";
import { Checkbox } from "../../shared/ui/Checkbox";
import { TextInput } from "../../shared/ui/FormControls";
import { Select } from "../../shared/ui/Select";
import { TitledCard } from "../../shared/ui/TitledCard";
import styles from "./ProxySettingsCard.module.scss";
export function ProxySettingsCard({
settings,
draft,
editing,
saving,
onDraftChange,
onEdit,
onCancel,
onSave,
}: {
settings: ProxySettings | null;
draft: ProxySettingsInput;
editing: boolean;
saving: boolean;
onDraftChange: (draft: ProxySettingsInput) => void;
onEdit: () => void;
onCancel: () => void;
onSave: () => void;
}) {
const custom = draft.mode === "custom";
const modeLabel = (mode: ProxySettingsInput["mode"]) => mode === "system" ? t("使用系统代理") : t("自定义");
const action = editing ? (
<div className={styles.actionGroup}>
<Button size="small" disabled={saving} onClick={onCancel}>{t("取消")}</Button>
<Button variant="primary" size="small" disabled={saving} onClick={onSave}>{saving ? t("保存中…") : t("保存")}</Button>
</div>
) : (
<button type="button" className={styles.headerAction} disabled={!settings} onClick={onEdit}>
{t("编辑")}
</button>
);
return <TitledCard title={t("代理设置")} action={action}>
<div className={styles.content}>
{editing ? <>
<div className={styles.row}>
<strong>{t("代理方式")}</strong>
<div className={styles.control}><Select ariaLabel={t("代理方式")} value={draft.mode} options={[{ value: "system", label: t("使用系统代理") }, { value: "custom", label: t("自定义") }]} onChange={(mode) => onDraftChange({ ...draft, mode: mode as ProxySettingsInput["mode"] })} /></div>
</div>
{custom && <div className={styles.customFields}>
<div className={styles.row}>
<strong>{t("代理地址")}</strong>
<div className={styles.control}><TextInput value={draft.address} placeholder="http://127.0.0.1:7890" onChange={(event) => onDraftChange({ ...draft, address: event.target.value })} /></div>
</div>
<div className={styles.row}>
<strong>{t("认证")}</strong>
<Checkbox checked={draft.auth_enabled} label={t("代理需要认证")} onChange={(auth_enabled) => onDraftChange({ ...draft, auth_enabled })} />
</div>
{draft.auth_enabled && <div className={styles.customFields}>
<div className={styles.row}>
<strong>{t("用户名")}</strong>
<div className={styles.control}><TextInput value={draft.username} autoComplete="off" onChange={(event) => onDraftChange({ ...draft, username: event.target.value })} /></div>
</div>
<div className={styles.row}>
<strong>{t("密码")}</strong>
<div className={styles.control}><TextInput type="password" value={draft.password ?? ""} autoComplete="new-password" placeholder={settings?.has_password ? t("留空表示保留当前密码") : ""} onChange={(event) => onDraftChange({ ...draft, password: event.target.value })} /></div>
</div>
</div>}
</div>}
</> : <>
<div className={styles.row}><strong>{t("代理方式")}</strong><span className={styles.value}>{settings ? modeLabel(settings.mode) : t("加载中…")}</span></div>
{settings?.mode === "custom" && <div className={styles.customFields}>
<div className={styles.row}><strong>{t("代理地址")}</strong><span className={styles.value}>{settings.address}</span></div>
<div className={styles.row}><strong>{t("认证")}</strong><span className={styles.value}>{settings.auth_enabled ? t("已启用") : t("未启用")}</span></div>
{settings.auth_enabled && <>
<div className={styles.row}><strong>{t("用户名")}</strong><span className={styles.value}>{settings.username || "—"}</span></div>
<div className={styles.row}><strong>{t("密码")}</strong><span className={styles.value}>{settings.has_password ? t("已设置") : t("未设置")}</span></div>
</>}
</div>}
</>}
</div>
</TitledCard>;
}
@@ -0,0 +1,163 @@
@use "../../styles/typography" as type;
.page {
display: grid;
gap: 16px;
}
.settingRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 16px;
div {
display: grid;
gap: 5px;
}
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.storageRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 16px;
> div {
display: grid;
gap: 5px;
}
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.textButton {
padding: 4px;
color: var(--vscode-textLink-foreground);
background: transparent;
border: 0;
&:hover { color: var(--vscode-textLink-activeForeground); }
}
.importRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 16px;
> div {
display: grid;
gap: 5px;
}
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.confirmContent {
display: grid;
gap: 8px;
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.themeActions {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 14px;
button {
min-height: 30px;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 0 11px;
color: var(--vscode-foreground);
background: var(--vscode-input-background);
border: 1px solid var(--vscode-input-border);
border-radius: 5px;
}
}
.languageControl {
width: 180px;
flex: 0 0 auto;
}
.portSettings {
display: grid;
gap: 14px;
padding: 16px;
}
.portFields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.portFooter {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.portValue {
min-width: 0;
min-height: 34px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
span {
color: var(--vscode-descriptionForeground);
}
}
.cardActions {
display: flex;
align-items: center;
gap: 6px;
}
@media (max-width: 680px) {
.portFields {
grid-template-columns: 1fr;
}
.importRow {
align-items: stretch;
flex-direction: column;
}
}
.themeActions .selected {
border-color: var(--vscode-focusBorder);
}
@@ -0,0 +1,317 @@
import { useEffect, useState } from "react";
import { api, type ProxySettings, type ProxySettingsInput, type StatisticsStorage, type StatisticsStorageScope, type TabSettings } from "../../shared/api";
import { PageContent } from "../../shell/layout/PageContent";
import { LegacyModelImport } from "../models/LegacyModelImport";
import { AppLifecycleSettingsCard } from "./AppLifecycleSettingsCard";
import { ProxySettingsCard } from "./ProxySettingsCard";
import { TabSettingsCard } from "./TabSettingsCard";
import { Button } from "../../shared/ui/Button";
import { Checkbox } from "../../shared/ui/Checkbox";
import { ConfirmDialog } from "../../shared/ui/ConfirmDialog";
import { FormField, TextInput } from "../../shared/ui/FormControls";
import { Select } from "../../shared/ui/Select";
import { TitledCard } from "../../shared/ui/TitledCard";
import { setLocalePreference, useI18n, type LocalePreference } from "../../i18n/store";
import { useMessage } from "../../shared/ui/message";
import { appStore, useAppStore } from "../../shared/store/appStore";
import { themeOptions } from "../../shared/theme/theme";
import styles from "./SettingsPage.module.scss";
export function SettingsPage() {
const { detailed, ports, theme } = useAppStore();
const { preference, locale } = useI18n();
const message = useMessage();
const [proxyPort, setProxyPort] = useState(String(ports.proxy_port));
const [servicePort, setServicePort] = useState(String(ports.service_port));
const [editingPorts, setEditingPorts] = useState(false);
const [savingPorts, setSavingPorts] = useState(false);
const [storage, setStorage] = useState<StatisticsStorage | null>(null);
const [confirmClear, setConfirmClear] = useState(false);
const [clearScope, setClearScope] = useState<StatisticsStorageScope>("details");
const [clearing, setClearing] = useState(false);
const [outboundProxy, setOutboundProxy] = useState<ProxySettings | null>(null);
const [proxyDraft, setProxyDraft] = useState<ProxySettingsInput>({ mode: "system", address: "", auth_enabled: false, username: "", password: "" });
const [editingProxy, setEditingProxy] = useState(false);
const [savingProxy, setSavingProxy] = useState(false);
const [tabSettings, setTabSettings] = useState<TabSettings | null>(null);
const [tabDraft, setTabDraft] = useState<TabSettings>({ mode: "public", address: "" });
const [editingTab, setEditingTab] = useState(false);
const [savingTab, setSavingTab] = useState(false);
useEffect(() => {
void Promise.all([api.statisticsStorage(), api.proxySettings(), api.tabSettings()]).then(([nextStorage, nextProxy, nextTab]) => {
setStorage(nextStorage);
setOutboundProxy(nextProxy);
setProxyDraft({ mode: nextProxy.mode, address: nextProxy.address, auth_enabled: nextProxy.auth_enabled, username: nextProxy.username, password: "" });
setTabSettings(nextTab);
setTabDraft(nextTab);
}).catch((cause) => message(cause instanceof Error ? cause.message : String(cause)));
}, [message]);
useEffect(() => {
setProxyPort(String(ports.proxy_port));
setServicePort(String(ports.service_port));
}, [ports.proxy_port, ports.service_port]);
const parsePort = (value: string, label: string) => {
const port = Number(value);
if (!Number.isInteger(port) || port < 0 || port > 65_535) {
throw new Error(`${label}${t("必须是 0–65535 之间的整数")}`);
}
return port;
};
const savePorts = async () => {
try {
const next = {
proxy_port: parsePort(proxyPort, t("代理端口")),
service_port: parsePort(servicePort, t("服务端口")),
};
setSavingPorts(true);
if (await appStore.updatePorts(next)) {
setEditingPorts(false);
message(t("端口设置已保存,重启软件后生效"), { duration: 4_000 });
}
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
} finally {
setSavingPorts(false);
}
};
const editPorts = () => {
setProxyPort(String(ports.proxy_port));
setServicePort(String(ports.service_port));
setEditingPorts(true);
};
const cancelPortEdit = () => {
setProxyPort(String(ports.proxy_port));
setServicePort(String(ports.service_port));
setEditingPorts(false);
};
const clearStorage = async () => {
try {
setClearing(true);
setStorage(await api.clearStatisticsStorage(clearScope));
setConfirmClear(false);
await appStore.refresh();
message(clearScope === "all" ? t("全部统计数据已清理") : t("详细记录已清理"));
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
} finally {
setClearing(false);
}
};
const editProxy = () => {
if (!outboundProxy) return;
setProxyDraft({ mode: outboundProxy.mode, address: outboundProxy.address, auth_enabled: outboundProxy.auth_enabled, username: outboundProxy.username, password: "" });
setEditingProxy(true);
};
const cancelProxyEdit = () => {
if (outboundProxy) {
setProxyDraft({ mode: outboundProxy.mode, address: outboundProxy.address, auth_enabled: outboundProxy.auth_enabled, username: outboundProxy.username, password: "" });
}
setEditingProxy(false);
};
const saveProxy = async () => {
try {
setSavingProxy(true);
const saved = await api.setProxySettings({ ...proxyDraft, password: proxyDraft.password || undefined });
setOutboundProxy(saved);
setProxyDraft({ mode: saved.mode, address: saved.address, auth_enabled: saved.auth_enabled, username: saved.username, password: "" });
setEditingProxy(false);
message(t("代理设置已保存"));
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
} finally {
setSavingProxy(false);
}
};
const editTab = () => {
if (!tabSettings) return;
setTabDraft(tabSettings);
setEditingTab(true);
};
const cancelTabEdit = () => {
if (tabSettings) setTabDraft(tabSettings);
setEditingTab(false);
};
const saveTab = async () => {
try {
if (tabDraft.mode === "custom" && !tabDraft.address.trim()) throw new Error(t("TAB 服务地址不能为空"));
setSavingTab(true);
const saved = await api.setTabSettings({ ...tabDraft, address: tabDraft.address.trim() });
setTabSettings(saved);
setTabDraft(saved);
setEditingTab(false);
message(t("TAB 设置已保存"));
} catch (cause) {
message(cause instanceof Error ? cause.message : String(cause));
} finally {
setSavingTab(false);
}
};
const formatBytes = (bytes: number) => {
if (bytes < 1024) return `${bytes} B`;
const units = ["KB", "MB", "GB", "TB"];
let value = bytes / 1024;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; }
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
};
const clearTitle = clearScope === "all" ? t("确定要清理全部统计数据吗?") : t("确定要清理详细记录吗?");
const clearDescription = clearScope === "all"
? t("所有调用汇总、详细内容和追踪记录都会被删除。模型配置、CA 和应用设置不会受到影响,此操作无法撤销。")
: t("仅删除请求、响应和追踪附件等详细内容,保留调用汇总、统计指标和配置。");
const content = (
<div className={styles.page}>
<TitledCard title={t("调用观测")}>
<div className={styles.settingRow}>
<div>
<strong>{t("详细模式")}</strong>
<small>
{t("额外保存完整请求和流响应;默认只保存时间、状态与用量。")}
</small>
</div>
<Checkbox
label={t("详细模式")}
checked={detailed}
onChange={(checked) => void appStore.updateDetailed(checked)}
/>
</div>
</TitledCard>
<TitledCard title={t("端口设置")} action={editingPorts ? (
<div className={styles.cardActions}>
<Button size="small" disabled={savingPorts} onClick={cancelPortEdit}>{t("取消")}</Button>
<Button variant="primary" size="small" disabled={savingPorts} onClick={() => void savePorts()}>{savingPorts ? t("保存中…") : t("保存")}</Button>
</div>
) : (
<button type="button" className={styles.textButton} onClick={editPorts}>{t("编辑")}</button>
)}>
<div className={styles.portSettings}>
<div className={styles.portFields}>
{editingPorts ? <><FormField
label={t("代理端口")}
hint={t("Cursor 使用的本地代理端口;填写 0 时启动时随机选择。")}
>
<TextInput
type="number"
min={0}
max={65535}
step={1}
value={proxyPort}
onChange={(event) => setProxyPort(event.target.value)}
/>
</FormField>
<FormField
label={t("服务端口")}
hint={t(
"桌面前端连接的本地管理服务端口;填写 0 时启动时随机选择。",
)}
>
<TextInput
type="number"
min={0}
max={65535}
step={1}
value={servicePort}
onChange={(event) => setServicePort(event.target.value)}
/>
</FormField></> : <>
<div className={styles.portValue}><strong>{t("代理端口")}</strong><span>{ports.proxy_port}</span></div>
<div className={styles.portValue}><strong>{t("服务端口")}</strong><span>{ports.service_port}</span></div>
</>}
</div>
<div className={styles.portFooter}>
<small>
{t(
"端口被占用时会自动选择新的随机端口并保存。修改后需要重启软件才会生效。",
)}
</small>
</div>
</div>
</TitledCard>
<ProxySettingsCard settings={outboundProxy} draft={proxyDraft} editing={editingProxy} saving={savingProxy} onDraftChange={setProxyDraft} onEdit={editProxy} onCancel={cancelProxyEdit} onSave={() => void saveProxy()} />
<TabSettingsCard settings={tabSettings} draft={tabDraft} editing={editingTab} saving={savingTab} onDraftChange={setTabDraft} onEdit={editTab} onCancel={cancelTabEdit} onSave={() => void saveTab()} />
<AppLifecycleSettingsCard />
<LegacyModelImport>{({ busy, previewing, open }) => <TitledCard title={t("导入")}>
<div className={styles.importRow}>
<div>
<strong>{t("旧版配置")}</strong>
<small>{t("从本机旧版配置读取模型;确认前会显示新增和已存在的模型。")}</small>
</div>
<Button size="small" disabled={busy} onClick={open}>
{previewing ? t("读取中…") : t("查看并导入")}
</Button>
</div>
</TitledCard>}</LegacyModelImport>
<TitledCard title={t("语言")}>
<div className={styles.settingRow}>
<div>
<strong>{t("界面语言")}</strong>
<small>{t("默认跟随操作系统;不支持的系统语言使用英文。当前:{language}", { language: locale === "zh-CN" ? "简体中文" : "English" })}</small>
</div>
<div className={styles.languageControl}>
<Select
value={preference}
ariaLabel={t("界面语言")}
options={[
{ value: "system", label: t("跟随系统") },
{ value: "zh-CN", label: "简体中文" },
{ value: "en-US", label: "English" },
]}
onChange={(value) => setLocalePreference(value as LocalePreference)}
/>
</div>
</div>
</TitledCard>
<TitledCard title={t("主题")}>
<div className={styles.themeActions}>
{themeOptions.map(({ id }) => (
<button
className={theme === id ? styles.selected : ""}
key={id}
onClick={() => appStore.selectTheme(id)}
>
{id === "default-dark" ? t("默认暗色") : t("默认亮色")}
</button>
))}
</div>
</TitledCard>
<TitledCard title={t("存储管理")}>
<div className={styles.storageRow}>
<div>
<strong>{t("统计数据")}</strong>
<small>{storage ? formatBytes(storage.bytes) : t("计算中…")}</small>
</div>
<button
type="button"
className={styles.textButton}
onClick={() => { setClearScope("details"); setConfirmClear(true); }}
>
{t("清理存储空间")}
</button>
</div>
</TitledCard>
<ConfirmDialog
open={confirmClear}
title={clearTitle}
busy={clearing}
cancelLabel={t("取消")}
confirmLabel={t("确认清理")}
onCancel={() => setConfirmClear(false)}
onConfirm={() => void clearStorage()}
>
<div className={styles.confirmContent}>
<Select
value={clearScope}
ariaLabel={t("清理范围")}
options={[
{ value: "details", label: t("仅清理详细记录") },
{ value: "all", label: t("清理全部统计数据") },
]}
onChange={(value) => setClearScope(value as StatisticsStorageScope)}
/>
<small>{clearDescription}</small>
</div>
</ConfirmDialog>
</div>
);
return <PageContent title={t("设置")} sections={[{ key: "settings", estimatedHeight: 1200, content }]} />;
}
@@ -0,0 +1,78 @@
@use "../../styles/typography" as type;
.title {
min-width: 0;
display: flex;
align-items: center;
gap: 5px;
}
.content {
display: grid;
gap: 14px;
padding: 16px;
}
.row {
min-width: 0;
min-height: 34px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
}
.description {
min-width: 0;
display: grid;
gap: 5px;
small {
color: var(--vscode-descriptionForeground);
font-size: type.$font-size-xs;
}
}
.control {
width: min(420px, 62%);
}
.value {
min-width: 0;
max-width: 70%;
color: var(--vscode-descriptionForeground);
overflow-wrap: anywhere;
text-align: right;
}
.headerAction {
padding: 4px;
color: var(--vscode-textLink-foreground);
background: transparent;
border: 0;
font-size: type.$font-size-xs;
&:hover { color: var(--vscode-textLink-activeForeground); }
&:disabled { opacity: .5; }
}
.actionGroup {
display: flex;
align-items: center;
gap: 6px;
}
@media (max-width: 680px) {
.row {
align-items: stretch;
flex-direction: column;
gap: 10px;
}
.control,
.value {
width: 100%;
max-width: none;
text-align: left;
}
}
@@ -0,0 +1,90 @@
import cursorIconUrl from "../../shared/assets/icons/cursor.svg";
import type { TabMode, TabSettings } from "../../shared/api";
import { Button } from "../../shared/ui/Button";
import { TextInput } from "../../shared/ui/FormControls";
import { Icon } from "../../shared/ui/Icon";
import { Select } from "../../shared/ui/Select";
import { TitledCard } from "../../shared/ui/TitledCard";
import styles from "./TabSettingsCard.module.scss";
export function TabSettingsCard({
settings,
draft,
editing,
saving,
onDraftChange,
onEdit,
onCancel,
onSave,
}: {
settings: TabSettings | null;
draft: TabSettings;
editing: boolean;
saving: boolean;
onDraftChange: (settings: TabSettings) => void;
onEdit: () => void;
onCancel: () => void;
onSave: () => void;
}) {
const modeLabel = (mode: TabMode) => {
if (mode === "public") return t("使用公益服务");
if (mode === "direct") return t("直连");
return t("自定义");
};
const action = editing ? (
<div className={styles.actionGroup}>
<Button size="small" disabled={saving} onClick={onCancel}>{t("取消")}</Button>
<Button variant="primary" size="small" disabled={saving} onClick={onSave}>{saving ? t("保存中…") : t("保存")}</Button>
</div>
) : (
<button type="button" className={styles.headerAction} disabled={!settings} onClick={onEdit}>{t("编辑")}</button>
);
return <TitledCard
title={<div className={styles.title}><Icon src={cursorIconUrl} size="1.1em" /><span>{t("TAB 设置")}</span></div>}
action={action}
>
<div className={styles.content}>
{editing ? <>
<div className={styles.row}>
<div className={styles.description}>
<strong>{t("TAB 选择")}</strong>
<small>{t("控制 Cursor TAB 相关接口的连接方式。")}</small>
</div>
<div className={styles.control}><Select
value={draft.mode}
ariaLabel={t("TAB 选择")}
options={[
{ value: "public", label: t("使用公益服务") },
{ value: "direct", label: t("直连") },
{ value: "custom", label: t("自定义") },
]}
onChange={(mode) => onDraftChange({ ...draft, mode: mode as TabMode })}
/></div>
</div>
{draft.mode === "custom" && <div className={styles.row}>
<div className={styles.description}>
<strong>{t("TAB 服务地址")}</strong>
<small>{t("原接口路径会追加到此服务地址。")}</small>
</div>
<div className={styles.control}><TextInput
value={draft.address}
placeholder="https://tab.leokun.cn"
aria-label={t("TAB 服务地址")}
onChange={(event) => onDraftChange({ ...draft, address: event.target.value })}
onKeyDown={(event) => { if (event.key === "Enter") onSave(); }}
/></div>
</div>}
</> : <>
<div className={styles.row}>
<strong>{t("TAB 选择")}</strong>
<span className={styles.value}>{settings ? modeLabel(settings.mode) : t("加载中…")}</span>
</div>
{settings?.mode === "custom" && <div className={styles.row}>
<strong>{t("TAB 服务地址")}</strong>
<span className={styles.value}>{settings.address}</span>
</div>}
</>}
</div>
</TitledCard>;
}