refactor: rebuild desktop app with Tauri

This commit is contained in:
leookun committed 2026-08-24 02:49:00 +08:00
1 parent a3ec2a0dfc
commit 4053a7fb20
808 files changed
+87359 -181491

No files matched your search

@@ -0,0 +1,30 @@
@use "../../styles/typography" as type;
.root {
--cache-hit-track-color: color-mix(in srgb, var(--vscode-foreground) 12%, transparent);
--cache-hit-value-color: var(--vscode-gitDecoration-addedResourceForeground, #4ade80);
position: relative;
width: 132px;
height: 82px;
align-self: center;
flex: 0 0 auto;
}
.canvas {
width: 100% !important;
height: 100% !important;
}
.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,75 @@
import { ArcElement, Chart as ChartJS, Tooltip, type ChartOptions, type ScriptableContext } from "chart.js";
import { useMemo } from "react";
import { Doughnut } from "react-chartjs-2";
import styles from "./CacheHitRateChart.module.scss";
ChartJS.register(ArcElement, Tooltip);
type SegmentRadius = number | {
outerStart: number;
outerEnd: number;
innerStart: number;
innerEnd: number;
};
function chartColor(context: ScriptableContext<"doughnut">) {
const styles = getComputedStyle(context.chart.canvas);
const variable = context.dataIndex === 0 ? "--cache-hit-value-color" : "--cache-hit-track-color";
return styles.getPropertyValue(variable).trim();
}
function segmentBorderRadius(percentage: number, dataIndex: number): SegmentRadius {
const radius = 5;
if (percentage <= 0) {
return dataIndex === 1
? { outerStart: radius, outerEnd: radius, innerStart: radius, innerEnd: radius }
: 0;
}
if (percentage >= 100) {
return dataIndex === 0
? { outerStart: radius, outerEnd: radius, innerStart: radius, innerEnd: radius }
: 0;
}
return dataIndex === 0
? { outerStart: radius, outerEnd: 0, innerStart: radius, innerEnd: 0 }
: { outerStart: 0, outerEnd: radius, innerStart: 0, innerEnd: radius };
}
const options: ChartOptions<"doughnut"> = {
responsive: true,
maintainAspectRatio: false,
cutout: "82%",
rotation: -90,
circumference: 180,
animation: { duration: 450 },
events: [],
plugins: {
legend: { display: false },
tooltip: { enabled: false },
},
};
export function CacheHitRateChart({ rate }: { rate: number }) {
const finiteRate = Number.isFinite(rate) ? rate : 0;
const percentage = Math.max(0, Math.min(100, finiteRate * 100));
const label = Number.isFinite(rate) ? `${percentage.toFixed(2)}%` : "--";
const data = useMemo(() => ({
labels: [t("命中"), t("未命中")],
datasets: [{
data: [percentage, Math.max(0, 100 - percentage)],
backgroundColor: chartColor,
borderWidth: 0,
hoverBorderWidth: 0,
selfJoin: false,
borderRadius: (context: ScriptableContext<"doughnut">) => segmentBorderRadius(percentage, context.dataIndex),
}],
}), [percentage]);
return <div className={styles.root} role="img" aria-label={t("缓存命中率 {rate}", { rate: label })}>
<Doughnut className={styles.canvas} data={data} options={options} />
<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 "../../utils/numberFormat";
import { Icon } from "../ui/Icon";
import { Tooltip, type TooltipAnchor } from "../ui/Tooltip";
import { informationOutlineIcon } from "../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 }: { data: HomeMetricsData }) {
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} />
</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>;
}