Files
vscode-getdeepin-quota/src/statusBar.ts
T

503 lines
17 KiB
TypeScript
Raw Normal View History

2026-04-22 15:28:45 +08:00
import * as vscode from 'vscode';
2026-04-27 10:03:22 +08:00
import { QuotaResponse, QuotaDisplay } from './types';
2026-04-22 15:28:45 +08:00
export class StatusBarManager {
private statusBarItem: vscode.StatusBarItem;
2026-04-22 16:51:03 +08:00
private currentPanel: vscode.WebviewPanel | undefined;
private onRefresh: () => Promise<{
data: QuotaDisplay | null;
lastRefreshAt: Date | null;
error: string | null;
}>;
2026-04-22 15:28:45 +08:00
constructor(onRefresh: () => Promise<{
data: QuotaDisplay | null;
lastRefreshAt: Date | null;
error: string | null;
}>) {
2026-04-22 16:51:03 +08:00
this.onRefresh = onRefresh;
2026-04-22 15:28:45 +08:00
this.statusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
100
);
this.statusBarItem.command = 'getdeepin-quota.showPopup';
this.statusBarItem.text = '$(cloud) AI用量';
this.statusBarItem.show();
}
updateNotLoggedIn(): void {
2026-04-27 17:52:00 +08:00
this.statusBarItem.text = '$(cloud) 未设置Token';
this.statusBarItem.tooltip = new vscode.MarkdownString('**点击设置 GetDeepin AI Token**');
2026-04-22 15:28:45 +08:00
}
updateWithError(): void {
this.statusBarItem.text = '$(cloud) 获取失败';
2026-04-27 17:52:00 +08:00
this.statusBarItem.tooltip = new vscode.MarkdownString('**获取数据失败**\n\n点击重试或重新设置 Token');
2026-04-22 15:28:45 +08:00
}
updateWithQuota(data: QuotaDisplay): void {
2026-04-27 17:52:00 +08:00
const domesticUsed = (100 - data.domestic.remainingDailyPercent).toFixed(0);
const globalUsed = (100 - data.global.remainingMonthlyPercent).toFixed(0);
2026-04-22 15:28:45 +08:00
2026-04-27 17:52:00 +08:00
this.statusBarItem.text = `$(cloud) 国内 ${domesticUsed}% | 国外 ${globalUsed}%`;
2026-04-22 15:28:45 +08:00
this.statusBarItem.tooltip = this.generateTooltipMarkdown(data);
}
private generateTooltipMarkdown(data: QuotaDisplay): vscode.MarkdownString {
const md = new vscode.MarkdownString();
md.supportHtml = true;
const formatPercent = (n: number) => n.toFixed(1);
2026-04-27 17:52:00 +08:00
const formatTokens = (n: number) => n.toLocaleString('zh-CN');
const getProgressBar = (usedPercent: number) => {
const filled = Math.round(usedPercent / 5);
2026-04-22 15:28:45 +08:00
const empty = 20 - filled;
return '█'.repeat(filled) + '░'.repeat(empty);
};
md.appendMarkdown(`### AI 模型用量统计\n\n`);
md.appendMarkdown(`**${data.user.display_name}** (${data.user.job_id}) \n`);
md.appendMarkdown(`${data.user.email}\n\n`);
md.appendMarkdown('---\n\n');
2026-04-27 17:52:00 +08:00
const domesticDailyUsed = 100 - data.domestic.remainingDailyPercent;
const domesticDailyWarning = domesticDailyUsed > 80 ? '⚠️ ' : '';
md.appendMarkdown(`#### ${domesticDailyWarning}${data.domestic.label}\n\n`);
md.appendMarkdown(`日额度: \`${getProgressBar(domesticDailyUsed)}\` 已用 \`${formatPercent(domesticDailyUsed)}%\`\n\n`);
const domesticMonthlyUsed = 100 - data.domestic.remainingMonthlyPercent;
md.appendMarkdown(`月额度: \`${getProgressBar(domesticMonthlyUsed)}\` 已用 \`${formatPercent(domesticMonthlyUsed)}%\`\n\n`);
md.appendMarkdown(`累计消耗: ${formatTokens(data.domestic.totalTokens)} tokens\n\n`);
2026-04-22 15:28:45 +08:00
md.appendMarkdown(`支持模型: ${data.domestic.models.map(m => `\`${m}\``).join(' ')}\n\n`);
2026-04-27 17:52:00 +08:00
const globalMonthlyUsed = 100 - data.global.remainingMonthlyPercent;
const globalWarning = globalMonthlyUsed > 80 ? '⚠️ ' : '';
2026-04-27 10:03:22 +08:00
md.appendMarkdown(`#### ${globalWarning}${data.global.label}\n\n`);
2026-04-27 17:52:00 +08:00
if (data.global.hasDailyLimit && data.global.remainingDailyPercent !== null) {
const globalDailyUsed = 100 - data.global.remainingDailyPercent;
md.appendMarkdown(`日额度: \`${getProgressBar(globalDailyUsed)}\` 已用 \`${formatPercent(globalDailyUsed)}%\`\n\n`);
}
md.appendMarkdown(`月额度: \`${getProgressBar(globalMonthlyUsed)}\` 已用 \`${formatPercent(globalMonthlyUsed)}%\`\n\n`);
md.appendMarkdown(`累计消耗: ${formatTokens(data.global.totalTokens)} tokens\n\n`);
2026-04-22 15:28:45 +08:00
md.appendMarkdown(`支持模型: ${data.global.models.map(m => `\`${m}\``).join(' ')}\n\n`);
md.appendMarkdown('---\n\n');
2026-04-27 17:52:00 +08:00
md.appendMarkdown('*点击查看详情*');
2026-04-22 15:28:45 +08:00
return md;
}
showPopup(
data: QuotaDisplay | null,
isLoggedIn: boolean,
lastRefreshAt: Date | null,
lastRefreshError: string | null
): void {
2026-04-22 15:28:45 +08:00
if (!isLoggedIn) {
this.showLoginPrompt();
return;
}
if (!data) {
this.showErrorPrompt(lastRefreshAt, lastRefreshError);
2026-04-22 15:28:45 +08:00
return;
}
this.showQuotaPanel(data, lastRefreshAt, lastRefreshError);
2026-04-22 15:28:45 +08:00
}
private showLoginPrompt(): void {
vscode.window.showQuickPick(
2026-04-27 17:52:00 +08:00
[{ label: '$(key) 设置 Token', id: 'login' }],
{ placeHolder: '请先设置 GetDeepin AI Token' }
2026-04-22 15:28:45 +08:00
).then(selection => {
2026-04-22 16:51:03 +08:00
if ((selection as any)?.id === 'login') {
2026-04-22 15:28:45 +08:00
vscode.commands.executeCommand('getdeepin-quota.login');
}
});
}
private showErrorPrompt(lastRefreshAt: Date | null, lastRefreshError: string | null): void {
2026-04-22 15:28:45 +08:00
vscode.window.showQuickPick(
[
{ label: '$(refresh) 重试', id: 'refresh' },
{ label: '$(preview) 查看详情', id: 'details' },
2026-04-27 17:52:00 +08:00
{ label: '$(key) 重新设置 Token', id: 'login' }
2026-04-22 15:28:45 +08:00
],
{
placeHolder: lastRefreshError
? `获取用量数据失败: ${lastRefreshError}`
: '获取用量数据失败'
}
2026-04-22 15:28:45 +08:00
).then(selection => {
2026-04-22 16:51:03 +08:00
const item = selection as any;
if (item?.id === 'refresh') {
2026-04-22 15:28:45 +08:00
vscode.commands.executeCommand('getdeepin-quota.refresh');
} else if (item?.id === 'details') {
this.showQuotaPanel(null, lastRefreshAt, lastRefreshError);
2026-04-22 16:51:03 +08:00
} else if (item?.id === 'login') {
2026-04-22 15:28:45 +08:00
vscode.commands.executeCommand('getdeepin-quota.login');
}
});
}
private showQuotaPanel(
data: QuotaDisplay | null,
lastRefreshAt: Date | null,
lastRefreshError: string | null
): void {
2026-04-22 16:51:03 +08:00
if (this.currentPanel) {
this.currentPanel.reveal(vscode.ViewColumn.Active);
this.currentPanel.webview.html = this.generatePanelHtml(data, lastRefreshAt, lastRefreshError);
2026-04-22 16:51:03 +08:00
return;
}
const panel = vscode.window.createWebviewPanel(
'getdeepin-quota',
'AI 模型用量详情',
vscode.ViewColumn.Active,
{ enableScripts: true }
);
this.currentPanel = panel;
panel.webview.html = this.generatePanelHtml(data, lastRefreshAt, lastRefreshError);
2026-04-22 16:51:03 +08:00
panel.webview.onDidReceiveMessage(async (message) => {
if (message.command === 'refresh') {
try {
const result = await this.onRefresh();
if (this.currentPanel === panel) {
this.currentPanel.webview.html = this.generatePanelHtml(
result.data,
result.lastRefreshAt,
result.error
);
return;
}
} finally {
if (this.currentPanel === panel) {
void this.currentPanel.webview.postMessage({ command: 'refreshFinished' });
}
2026-04-22 16:51:03 +08:00
}
}
});
panel.onDidDispose(() => {
this.currentPanel = undefined;
});
}
private generatePanelHtml(
data: QuotaDisplay | null,
lastRefreshAt: Date | null,
lastRefreshError: string | null
): string {
2026-04-27 17:52:00 +08:00
const formatTokens = (n: number) => n.toLocaleString('zh-CN');
2026-04-22 15:28:45 +08:00
const formatPercent = (n: number) => n.toFixed(1);
const formatTime = (time: Date | null) => time
? time.toLocaleString('zh-CN', { hour12: false })
: '暂无';
2026-04-22 15:28:45 +08:00
2026-04-27 17:52:00 +08:00
const renderQuotaSection = (
label: string,
remainingDailyPercent: number | null,
remainingMonthlyPercent: number,
hasDailyLimit: boolean,
totalTokens: number,
models: string[]
) => {
const dailyUsed = remainingDailyPercent !== null ? 100 - remainingDailyPercent : null;
const monthlyUsed = 100 - remainingMonthlyPercent;
let html = `
<div class="quota-section">
<h2>${label}</h2>`;
if (hasDailyLimit && dailyUsed !== null) {
html += `
<div class="quota-row">
<span class="quota-label">日额度</span>
<span class="quota-percent ${dailyUsed > 80 ? 'warning' : ''}">${formatPercent(dailyUsed)}%</span>
<span class="quota-details">已使用</span>
</div>
<div class="progress-container">
<div class="progress-bar ${dailyUsed > 80 ? 'progress-warning' : 'progress-ok'}" style="width: ${Math.min(dailyUsed, 100)}%;"></div>
</div>`;
}
html += `
<div class="quota-row">
<span class="quota-label">月额度</span>
<span class="quota-percent ${monthlyUsed > 80 ? 'warning' : ''}">${formatPercent(monthlyUsed)}%</span>
<span class="quota-details">已使用</span>
</div>
<div class="progress-container">
<div class="progress-bar ${monthlyUsed > 80 ? 'progress-warning' : 'progress-ok'}" style="width: ${Math.min(monthlyUsed, 100)}%;"></div>
</div>
<div class="quota-row">
<span class="quota-label">累计消耗</span>
<span class="quota-details">${formatTokens(totalTokens)} tokens</span>
</div>
<div class="models-list">
${models.map(m => `<span class="model-tag">${m}</span>`).join('')}
</div>
</div>`;
return html;
};
const refreshMetaHtml = `
<div class="meta-row">
<span class="meta-label">最后刷新</span>
<span class="meta-value">${formatTime(lastRefreshAt)}</span>
</div>
${lastRefreshError ? `
<div class="error-banner">
<strong>刷新失败</strong>
<div>${lastRefreshError}</div>
</div>` : ''}`;
const quotaContentHtml = data ? `
${renderQuotaSection(
data.domestic.label,
data.domestic.remainingDailyPercent,
data.domestic.remainingMonthlyPercent,
data.domestic.hasDailyLimit,
data.domestic.totalTokens,
data.domestic.models
)}
${renderQuotaSection(
data.global.label,
data.global.remainingDailyPercent,
data.global.remainingMonthlyPercent,
data.global.hasDailyLimit,
data.global.totalTokens,
data.global.models
)}` : `
<div class="empty-state">
当前没有可展示的额度数据,请检查 Token 或稍后重试。
</div>`;
2026-04-22 16:51:03 +08:00
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
font-family: var(--vscode-font-family);
padding: 20px;
color: var(--vscode-foreground);
background-color: var(--vscode-editor-background);
}
.header {
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px solid var(--vscode-panel-border);
}
.header h1 {
margin: 0 0 8px 0;
font-size: 24px;
}
.user-info {
color: var(--vscode-descriptionForeground);
}
.meta-row {
display: flex;
gap: 8px;
margin-bottom: 16px;
color: var(--vscode-descriptionForeground);
}
.meta-label {
min-width: 60px;
}
.meta-value {
color: var(--vscode-foreground);
}
.error-banner {
margin-bottom: 20px;
padding: 12px 14px;
border-radius: 6px;
border: 1px solid var(--vscode-inputValidation-errorBorder);
background-color: var(--vscode-inputValidation-errorBackground);
color: var(--vscode-inputValidation-errorForeground);
}
.error-banner strong {
display: block;
margin-bottom: 4px;
}
.empty-state {
margin: 20px 0 24px;
padding: 16px;
border: 1px dashed var(--vscode-panel-border);
border-radius: 6px;
color: var(--vscode-descriptionForeground);
}
2026-04-22 16:51:03 +08:00
.quota-section {
margin-bottom: 24px;
}
.quota-section h2 {
margin: 0 0 12px 0;
font-size: 16px;
}
2026-04-27 10:03:22 +08:00
.quota-row {
2026-04-22 16:51:03 +08:00
display: flex;
align-items: center;
gap: 12px;
2026-04-27 10:03:22 +08:00
margin-bottom: 8px;
}
.quota-label {
min-width: 60px;
color: var(--vscode-descriptionForeground);
2026-04-22 16:51:03 +08:00
}
.quota-percent {
2026-04-27 10:03:22 +08:00
font-size: 20px;
2026-04-22 16:51:03 +08:00
font-weight: bold;
2026-04-27 10:03:22 +08:00
min-width: 70px;
2026-04-22 16:51:03 +08:00
}
.quota-details {
color: var(--vscode-descriptionForeground);
}
.progress-container {
width: 100%;
height: 8px;
background-color: var(--vscode-progressBar-background);
border-radius: 4px;
overflow: hidden;
margin-bottom: 12px;
}
.progress-bar {
height: 100%;
border-radius: 4px;
transition: width 0.3s ease;
}
.models-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
2026-04-27 10:03:22 +08:00
margin-top: 12px;
2026-04-22 16:51:03 +08:00
}
.model-tag {
padding: 4px 8px;
background-color: var(--vscode-badge-background);
color: var(--vscode-badge-foreground);
border-radius: 4px;
font-size: 12px;
}
.warning { color: #f59e0b; }
.progress-ok { background-color: #10b981; }
.progress-warning { background-color: #f59e0b; }
.actions {
margin-top: 24px;
padding-top: 16px;
border-top: 1px solid var(--vscode-panel-border);
}
.refresh-btn {
padding: 8px 16px;
background-color: var(--vscode-button-background);
color: var(--vscode-button-foreground);
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
display: inline-flex;
align-items: center;
gap: 6px;
2026-04-22 16:51:03 +08:00
}
.refresh-btn:hover {
background-color: var(--vscode-button-hoverBackground);
}
.refresh-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid var(--vscode-button-foreground);
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
2026-04-22 16:51:03 +08:00
</style>
</head>
<body>
<div class="header">
<h1>AI 模型用量统计</h1>
${data ? `
2026-04-22 16:51:03 +08:00
<div class="user-info">
<strong>${data.user.display_name}</strong> (${data.user.job_id}) · ${data.user.email}
</div>` : ''}
2026-04-22 16:51:03 +08:00
</div>
2026-04-22 15:28:45 +08:00
${refreshMetaHtml}
2026-04-22 16:51:03 +08:00
${quotaContentHtml}
2026-04-22 16:51:03 +08:00
<div class="actions">
<button id="refresh-btn" class="refresh-btn" onclick="refresh()">刷新数据</button>
2026-04-22 16:51:03 +08:00
</div>
<script>
const vscode = acquireVsCodeApi();
function setRefreshing(refreshing) {
const btn = document.getElementById('refresh-btn');
if (!btn) {
return;
}
btn.disabled = refreshing;
btn.innerHTML = refreshing
? '<span class="spinner"></span>刷新中...'
: '刷新数据';
}
window.addEventListener('message', (event) => {
if (event.data?.command === 'refreshFinished') {
setRefreshing(false);
}
});
2026-04-22 16:51:03 +08:00
function refresh() {
setRefreshing(true);
2026-04-22 16:51:03 +08:00
vscode.postMessage({ command: 'refresh' });
}
</script>
</body>
</html>
`;
2026-04-22 15:28:45 +08:00
}
dispose(): void {
this.statusBarItem.dispose();
}
}
export function parseQuotaResponse(response: QuotaResponse): QuotaDisplay {
const domestic = response.groups.find(g => g.key === 'domestic')!;
const global = response.groups.find(g => g.key === 'global')!;
return {
user: response.user,
domestic: {
2026-04-27 10:03:22 +08:00
label: domestic.label,
models: domestic.models,
2026-04-27 17:52:00 +08:00
hasDailyLimit: domestic.remaining_daily_percent !== null,
remainingDailyPercent: domestic.remaining_daily_percent ?? 100,
remainingMonthlyPercent: domestic.remaining_monthly_percent,
totalTokens: domestic.usage.total_tokens
2026-04-22 15:28:45 +08:00
},
global: {
2026-04-27 10:03:22 +08:00
label: global.label,
models: global.models,
2026-04-27 17:52:00 +08:00
hasDailyLimit: global.remaining_daily_percent !== null,
remainingDailyPercent: global.remaining_daily_percent,
remainingMonthlyPercent: global.remaining_monthly_percent,
totalTokens: global.usage.total_tokens
2026-04-22 15:28:45 +08:00
}
};
}