From 6afd4647aef63bd2e2b8b1cc8db88169b739c9af Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Sat, 9 May 2026 14:20:45 +0800 Subject: [PATCH] more interactive refresh and ux improvements --- package-lock.json | 16 ++-- package.json | 2 +- src/authService.ts | 17 ++-- src/extension.ts | 65 +++++++++++---- src/statusBar.ts | 195 +++++++++++++++++++++++++++++++++++++-------- 5 files changed, 234 insertions(+), 61 deletions(-) diff --git a/package-lock.json b/package-lock.json index f8e9884..2c877ae 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "getdeepin-quota", - "version": "0.0.1", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "getdeepin-quota", - "version": "0.0.1", + "version": "0.1.0", "devDependencies": { "@types/node": "^20.10.0", "@types/vscode": "^1.85.0", @@ -17,9 +17,9 @@ } }, "node_modules/@types/node": { - "version": "20.19.39", - "resolved": "https://registry.npmmirror.com/@types/node/-/node-20.19.39.tgz", - "integrity": "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==", + "version": "20.19.40", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-20.19.40.tgz", + "integrity": "sha512-xxx6M2IpSTnnKcR0cMvIiohkiCx20/oRPtWGbenFygKCGl3zqUzdNjQ/1V4solq1LU+dgv0nQzeGOuqkqZGg0Q==", "dev": true, "license": "MIT", "dependencies": { @@ -27,9 +27,9 @@ } }, "node_modules/@types/vscode": { - "version": "1.116.0", - "resolved": "https://registry.npmmirror.com/@types/vscode/-/vscode-1.116.0.tgz", - "integrity": "sha512-sYHp4MO6BqJ2PD7Hjt0hlIS3tMaYsVPJrd0RUjDJ8HtOYnyJIEej0bLSccM8rE77WrC+Xox/kdBwEFDO8MsxNA==", + "version": "1.118.0", + "resolved": "https://registry.npmmirror.com/@types/vscode/-/vscode-1.118.0.tgz", + "integrity": "sha512-Ah6eTlqDcwIMELEVwQMO++rJAFBRz/oLluLD/vWdYrH1KuI9kfpaM+7pg0OvvascgcJy+ghLCERAYouM4QbzGw==", "dev": true, "license": "MIT" }, diff --git a/package.json b/package.json index 709e368..57aef64 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "getdeepin-quota", "displayName": "GetDeepin AI Quota", "description": "显示大模型资源用量情况", - "version": "0.0.3", + "version": "0.1.0", "publisher": "getdeepin", "repository": "https://gitlabwh.uniontech.com/wangzichong/vscode-getdeepin-quota", "engines": { diff --git a/src/authService.ts b/src/authService.ts index 6b8bef0..25146da 100644 --- a/src/authService.ts +++ b/src/authService.ts @@ -48,6 +48,10 @@ export class AuthService { } } +export type FetchQuotaResult = + | { ok: true; response: Response } + | { ok: false; error: string }; + export class QuotaService { private authService: AuthService; @@ -55,9 +59,9 @@ export class QuotaService { this.authService = authService; } - async fetchQuota(): Promise { + async fetchQuota(): Promise { if (!this.authService.isLoggedIn()) { - return null; + return { ok: false, error: '未设置 Token' }; } try { @@ -69,17 +73,18 @@ export class QuotaService { if (response.status === 401 || response.status === 403) { await this.authService.logout(); - return null; + return { ok: false, error: 'Token 无效或已过期' }; } if (!response.ok) { - return null; + return { ok: false, error: `请求失败(HTTP ${response.status})` }; } - return response; + return { ok: true, response }; } catch (error) { console.error('Fetch quota failed:', error); - return null; + const message = error instanceof Error ? error.message : String(error); + return { ok: false, error: `网络请求失败:${message}` }; } } } diff --git a/src/extension.ts b/src/extension.ts index c6f797c..782fa1e 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -9,6 +9,20 @@ let authService: AuthService; let quotaService: QuotaService; let statusBar: StatusBarManager; let currentQuota: QuotaDisplay | null = null; +let lastRefreshAt: Date | null = null; +let lastRefreshError: string | null = null; + +function getConfiguredBaseUrl(): string { + const config = vscode.workspace.getConfiguration('getdeepin-quota'); + const url = config.get('baseUrl', 'https://ai.getdeepin.org/'); + return url.endsWith('/') ? url : `${url}/`; +} + +type RefreshResult = { + data: QuotaDisplay | null; + lastRefreshAt: Date | null; + error: string | null; +}; export async function activate(context: vscode.ExtensionContext) { storageService = new StorageService(context); @@ -24,8 +38,7 @@ export async function activate(context: vscode.ExtensionContext) { statusBar = new StatusBarManager( async () => { - await refreshQuota(); - return currentQuota; + return await refreshQuota(); } ); context.subscriptions.push(statusBar); @@ -39,9 +52,10 @@ export async function activate(context: vscode.ExtensionContext) { } async function loginCommand(): Promise { + const baseUrl = getConfiguredBaseUrl(); const token = await vscode.window.showInputBox({ prompt: '请输入 Bearer Token', - placeHolder: '在 https://ai.getdeepin.org/me 生成 Token', + placeHolder: `在 ${baseUrl}me 生成 Token`, password: true }); @@ -50,21 +64,26 @@ async function loginCommand(): Promise { } await authService.setToken(token); - const response = await quotaService.fetchQuota(); + const result = await quotaService.fetchQuota(); - if (!response) { - vscode.window.showErrorMessage('Token 无效或已过期,请检查后重试'); + if (!result.ok) { + vscode.window.showErrorMessage(result.error); await authService.logout(); statusBar.updateNotLoggedIn(); return; } try { - const data = await response.json() as QuotaResponse; + const data = await result.response.json() as QuotaResponse; currentQuota = parseQuotaResponse(data); + lastRefreshAt = new Date(); + lastRefreshError = null; statusBar.updateWithQuota(currentQuota); vscode.window.showInformationMessage('Token 验证成功'); - } catch { + } catch (error) { + console.error('Parse quota response failed:', error); + currentQuota = null; + lastRefreshError = '解析用量数据失败'; vscode.window.showErrorMessage('解析用量数据失败'); statusBar.updateWithError(); } @@ -73,30 +92,48 @@ async function loginCommand(): Promise { async function logoutCommand(): Promise { await authService.logout(); currentQuota = null; + lastRefreshAt = null; + lastRefreshError = null; statusBar.updateNotLoggedIn(); vscode.window.showInformationMessage('已移除 Token'); } -async function refreshQuota(): Promise { - const response = await quotaService.fetchQuota(); +async function refreshQuota(): Promise { + const result = await quotaService.fetchQuota(); - if (!response) { + if (!result.ok) { + currentQuota = null; + lastRefreshError = result.error; statusBar.updateWithError(); - return; + return { + data: null, + lastRefreshAt, + error: lastRefreshError + }; } try { - const data = await response.json() as QuotaResponse; + const data = await result.response.json() as QuotaResponse; currentQuota = parseQuotaResponse(data); + lastRefreshAt = new Date(); + lastRefreshError = null; statusBar.updateWithQuota(currentQuota); } catch (error) { console.error('Parse quota response failed:', error); + currentQuota = null; + lastRefreshError = '解析用量数据失败'; statusBar.updateWithError(); } + + return { + data: currentQuota, + lastRefreshAt, + error: lastRefreshError + }; } function showPopup(): void { - statusBar.showPopup(currentQuota, authService.isLoggedIn()); + statusBar.showPopup(currentQuota, authService.isLoggedIn(), lastRefreshAt, lastRefreshError); } export function deactivate() {} diff --git a/src/statusBar.ts b/src/statusBar.ts index 4bfbd5f..f17cf08 100644 --- a/src/statusBar.ts +++ b/src/statusBar.ts @@ -4,9 +4,17 @@ import { QuotaResponse, QuotaDisplay } from './types'; export class StatusBarManager { private statusBarItem: vscode.StatusBarItem; private currentPanel: vscode.WebviewPanel | undefined; - private onRefresh: () => Promise; + private onRefresh: () => Promise<{ + data: QuotaDisplay | null; + lastRefreshAt: Date | null; + error: string | null; + }>; - constructor(onRefresh: () => Promise) { + constructor(onRefresh: () => Promise<{ + data: QuotaDisplay | null; + lastRefreshAt: Date | null; + error: string | null; + }>) { this.onRefresh = onRefresh; this.statusBarItem = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Right, @@ -78,18 +86,23 @@ export class StatusBarManager { return md; } - showPopup(data: QuotaDisplay | null, isLoggedIn: boolean): void { + showPopup( + data: QuotaDisplay | null, + isLoggedIn: boolean, + lastRefreshAt: Date | null, + lastRefreshError: string | null + ): void { if (!isLoggedIn) { this.showLoginPrompt(); return; } if (!data) { - this.showErrorPrompt(); + this.showErrorPrompt(lastRefreshAt, lastRefreshError); return; } - this.showQuotaPanel(data); + this.showQuotaPanel(data, lastRefreshAt, lastRefreshError); } private showLoginPrompt(): void { @@ -103,27 +116,38 @@ export class StatusBarManager { }); } - private showErrorPrompt(): void { + private showErrorPrompt(lastRefreshAt: Date | null, lastRefreshError: string | null): void { vscode.window.showQuickPick( [ { label: '$(refresh) 重试', id: 'refresh' }, + { label: '$(preview) 查看详情', id: 'details' }, { label: '$(key) 重新设置 Token', id: 'login' } ], - { placeHolder: '获取用量数据失败' } + { + placeHolder: lastRefreshError + ? `获取用量数据失败: ${lastRefreshError}` + : '获取用量数据失败' + } ).then(selection => { const item = selection as any; if (item?.id === 'refresh') { vscode.commands.executeCommand('getdeepin-quota.refresh'); + } else if (item?.id === 'details') { + this.showQuotaPanel(null, lastRefreshAt, lastRefreshError); } else if (item?.id === 'login') { vscode.commands.executeCommand('getdeepin-quota.login'); } }); } - private showQuotaPanel(data: QuotaDisplay): void { + private showQuotaPanel( + data: QuotaDisplay | null, + lastRefreshAt: Date | null, + lastRefreshError: string | null + ): void { if (this.currentPanel) { this.currentPanel.reveal(vscode.ViewColumn.Active); - this.currentPanel.webview.html = this.generatePanelHtml(data); + this.currentPanel.webview.html = this.generatePanelHtml(data, lastRefreshAt, lastRefreshError); return; } @@ -135,13 +159,24 @@ export class StatusBarManager { ); this.currentPanel = panel; - panel.webview.html = this.generatePanelHtml(data); + panel.webview.html = this.generatePanelHtml(data, lastRefreshAt, lastRefreshError); panel.webview.onDidReceiveMessage(async (message) => { if (message.command === 'refresh') { - const newData = await this.onRefresh(); - if (newData && this.currentPanel) { - this.currentPanel.webview.html = this.generatePanelHtml(newData); + 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' }); + } } } }); @@ -151,9 +186,16 @@ export class StatusBarManager { }); } - private generatePanelHtml(data: QuotaDisplay): string { + private generatePanelHtml( + data: QuotaDisplay | null, + lastRefreshAt: Date | null, + lastRefreshError: string | null + ): string { const formatTokens = (n: number) => n.toLocaleString('zh-CN'); const formatPercent = (n: number) => n.toFixed(1); + const formatTime = (time: Date | null) => time + ? time.toLocaleString('zh-CN', { hour12: false }) + : '暂无'; const renderQuotaSection = ( label: string, @@ -203,6 +245,39 @@ export class StatusBarManager { return html; }; + const refreshMetaHtml = ` +
+ 最后刷新 + ${formatTime(lastRefreshAt)} +
+ ${lastRefreshError ? ` +
+ 刷新失败 +
${lastRefreshError}
+
` : ''}`; + + 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 + )}` : ` +
+ 当前没有可展示的额度数据,请检查 Token 或稍后重试。 +
`; + return ` @@ -227,6 +302,37 @@ export class StatusBarManager { .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); + } .quota-section { margin-bottom: 24px; } @@ -294,45 +400,70 @@ export class StatusBarManager { border-radius: 4px; cursor: pointer; font-size: 14px; + display: inline-flex; + align-items: center; + gap: 6px; } .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; + }

AI 模型用量统计

+ ${data ? ` +
` : ''} - ${renderQuotaSection( - data.domestic.label, - data.domestic.remainingDailyPercent, - data.domestic.remainingMonthlyPercent, - data.domestic.hasDailyLimit, - data.domestic.totalTokens, - data.domestic.models - )} + ${refreshMetaHtml} - ${renderQuotaSection( - data.global.label, - data.global.remainingDailyPercent, - data.global.remainingMonthlyPercent, - data.global.hasDailyLimit, - data.global.totalTokens, - data.global.models - )} + ${quotaContentHtml}
- +