feat: add provider usage query with JavaScript scripting support (#101)

* feat: add provider usage query functionality

- Updated `Cargo.toml` to include `regex` and `rquickjs` dependencies for usage script execution.
- Implemented `query_provider_usage` command in `commands.rs` to handle usage queries.
- Created `UsageScript` and `UsageData` structs in `provider.rs` for managing usage script configurations and results.
- Added `execute_usage_script` function in `usage_script.rs` to run user-defined scripts for querying usage.
- Enhanced `ProviderList` component to include a button for configuring usage scripts and a modal for editing scripts.
- Introduced `UsageFooter` component to display usage information and status.
- Added `UsageScriptModal` for editing and testing usage scripts with preset templates.
- Updated Tauri API to support querying provider usage.
- Modified types in `types.ts` to include structures for usage scripts and results.

* feat(usage): support multi-plan usage display for providers

- 【Feature】
  - Update `UsageResult` to support an array of `UsageData` for displaying multiple usage plans per provider.
  - Refactor `query_provider_usage` command to parse both single `UsageData` objects (for backward compatibility) and arrays of `UsageData`.
  - Enhance `usage_script` validation to accept either a single usage object or an array of usage objects.
- 【Frontend】
  - Redesign `UsageFooter` to iterate and display details for all available usage plans, introducing `UsagePlanItem` for individual plan rendering.
  - Improve usage display with color-coded remaining balance and clear plan information.
  - Update `UsageScriptModal` test notification to summarize all returned plans.
  - Remove redundant `isCurrent` prop from `UsageFooter` in `ProviderList`.
- 【Build】
  - Change frontend development server port from `3000` to `3005` in `tauri.conf.json` and `vite.config.mts`.

* feat(usage): enhance query flexibility and display
- 【`src/types.ts`, `src-tauri/src/provider.rs`】Make `UsageData` fields optional and introduce `extra` and `invalidMessage` for more flexible reporting.
  - `expiresAt` replaced by generic `extra` field.
  - `isValid`, `remaining`, `unit` are now optional.
  - Added `invalidMessage` to provide specific reasons for invalid status.
- 【`src-tauri/src/usage_script.rs`】Relax usage script result validation to accommodate optional fields in `UsageData`.
- 【`src/components/UsageFooter.tsx`】Update UI to display `extra` field and `invalidMessage`, and conditionally render `remaining` and `unit` based on availability.
- 【`src/components/UsageScriptModal.tsx`】
  - Add a new `NewAPI` preset template demonstrating advanced extractor logic for complex API responses.
  - Update script instructions to reflect optional fields and new variable syntax (`{{apiKey}}`).
  - Remove old "DeepSeek" and "OpenAI" templates.
  - Remove basic syntax check for `return` statement.
- 【`.vscode/settings.json`】Add `dish-ai-commit.base.language` setting.
- 【`src-tauri/src/commands.rs`】Adjust usage logging to handle optional `remaining` and `unit` fields.

* chore(config): remove VS Code settings from version control

- delete .vscode/settings.json to remove editor-specific configurations
- add /.vscode to .gitignore to prevent tracking of local VS Code settings
- ensure personalized editor preferences are not committed to the repository

* fix(provider): preserve usage script during provider update

- When updating a provider, the `usage_script` configuration within `ProviderMeta` was not explicitly merged.
- This could lead to the accidental loss of `usage_script` settings if the incoming `provider` object in the update request did not contain this field.
- Ensure `usage_script` is cloned from the existing provider's meta when merging `ProviderMeta` during an update.

* refactor(provider): enforce base_url for usage scripts and update dev ports
- 【Backend】
    - `src-tauri/src/commands.rs`: Made `ANTHROPIC_BASE_URL` a required field for Claude providers and `base_url` a required field in `config.toml` for Codex providers when extracting credentials for usage script execution. This improves error handling by explicitly failing if these critical URLs are missing or malformed.
- 【Frontend】
    - `src/App.tsx`, `src/components/ProviderList.tsx`: Passed `appType` prop to `ProviderList` component to ensure `updateProvider` calls within `handleSaveUsageScript` correctly identify the application type.
- 【Config】
    - `src-tauri/tauri.conf.json`, `vite.config.mts`: Updated development server ports from `3005` to `3000` to standardize local development environment.

* refactor(usage): improve usage data fetching logic

- Prevent redundant API calls by tracking last fetched parameters in `useEffect`.
- Avoid concurrent API requests by adding a guard in `fetchUsage`.
- Clear usage data and last fetch parameters when usage query is disabled.
- Add `queryProviderUsage` API declaration to `window.api` interface.

* fix(usage-script): ensure usage script updates and improve reactivity

- correctly update `usage_script` from new provider meta during updates
- replace full page reload with targeted provider data refresh after saving usage script settings
- trigger usage data fetch or clear when `usageEnabled` status changes in `UsageFooter`
- reduce logging verbosity for usage script execution in backend commands and script execution

* style(usage-footer): adjust usage plan item layout

- Decrease width of extra field column from 35% to 30%
- Increase width of usage information column from 40% to 45%
- Improve visual balance and readability of usage plan items
This commit is contained in:
Sirhexs
2025-10-15 09:15:25 +08:00
committed by GitHub
parent 59644b29e6
commit 3e4df2c96a
18 changed files with 1179 additions and 10 deletions

View File

@@ -0,0 +1,210 @@
import React, { useEffect, useState, useRef } from "react";
import { UsageResult, UsageData } from "../types";
import { AppType } from "../lib/tauri-api";
import { RefreshCw, AlertCircle } from "lucide-react";
interface UsageFooterProps {
providerId: string;
appType: AppType;
usageEnabled: boolean; // 是否启用了用量查询
}
const UsageFooter: React.FC<UsageFooterProps> = ({
providerId,
appType,
usageEnabled,
}) => {
const [usage, setUsage] = useState<UsageResult | null>(null);
const [loading, setLoading] = useState(false);
// 记录上次请求的关键参数,防止重复请求
const lastFetchParamsRef = useRef<string>('');
const fetchUsage = async () => {
// 防止并发请求
if (loading) return;
setLoading(true);
try {
const result = await window.api.queryProviderUsage(
providerId,
appType
);
setUsage(result);
} catch (error: any) {
console.error("查询用量失败:", error);
setUsage({
success: false,
error: error?.message || "查询失败",
});
} finally {
setLoading(false);
}
};
useEffect(() => {
if (usageEnabled) {
// 生成当前参数的唯一标识(包含 usageEnabled 状态)
const currentParams = `${providerId}-${appType}-${usageEnabled}`;
// 只有参数真正变化时才发起请求
if (currentParams !== lastFetchParamsRef.current) {
lastFetchParamsRef.current = currentParams;
fetchUsage();
}
} else {
// 如果禁用了,清空记录和数据
lastFetchParamsRef.current = '';
setUsage(null);
}
}, [providerId, usageEnabled, appType]);
// 只在启用用量查询且有数据时显示
if (!usageEnabled || !usage) return null;
// 错误状态
if (!usage.success) {
return (
<div className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between gap-2 text-xs">
<div className="flex items-center gap-2 text-red-500 dark:text-red-400">
<AlertCircle size={14} />
<span>{usage.error || "查询失败"}</span>
</div>
{/* 刷新按钮 */}
<button
onClick={() => fetchUsage()}
disabled={loading}
className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors disabled:opacity-50 flex-shrink-0"
title="刷新用量"
>
<RefreshCw size={12} className={loading ? "animate-spin" : ""} />
</button>
</div>
</div>
);
}
const usageDataList = usage.data || [];
// 无数据时不显示
if (usageDataList.length === 0) return null;
return (
<div className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700">
{/* 标题行:包含刷新按钮 */}
<div className="flex items-center justify-between mb-2">
<span className="text-xs text-gray-500 dark:text-gray-400 font-medium">
</span>
<button
onClick={() => fetchUsage()}
disabled={loading}
className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors disabled:opacity-50"
title="刷新用量"
>
<RefreshCw size={12} className={loading ? "animate-spin" : ""} />
</button>
</div>
{/* 套餐列表 */}
<div className="flex flex-col gap-3">
{usageDataList.map((usageData, index) => (
<UsagePlanItem key={index} data={usageData} />
))}
</div>
</div>
);
};
// 单个套餐数据展示组件
const UsagePlanItem: React.FC<{ data: UsageData }> = ({ data }) => {
const { planName, extra, isValid, invalidMessage, total, used, remaining, unit } = data;
// 判断套餐是否失效isValid 为 false 或未定义时视为有效)
const isExpired = isValid === false;
return (
<div className="flex items-center gap-3">
{/* 标题部分25% */}
<div className="text-xs text-gray-500 dark:text-gray-400 min-w-0" style={{ width: "25%" }}>
{planName ? (
<span
className={`font-medium truncate block ${isExpired ? "text-red-500 dark:text-red-400" : ""}`}
title={planName}
>
💰 {planName}
</span>
) : (
<span className="opacity-50"></span>
)}
</div>
{/* 扩展字段30% */}
<div className="text-xs text-gray-500 dark:text-gray-400 min-w-0 flex items-center gap-2" style={{ width: "30%" }}>
{extra && (
<span
className={`truncate ${isExpired ? "text-red-500 dark:text-red-400" : ""}`}
title={extra}
>
{extra}
</span>
)}
{isExpired && (
<span className="text-red-500 dark:text-red-400 font-medium text-[10px] px-1.5 py-0.5 bg-red-50 dark:bg-red-900/20 rounded flex-shrink-0">
{invalidMessage || "已失效"}
</span>
)}
</div>
{/* 用量信息45% */}
<div className="flex items-center justify-end gap-2 text-xs flex-shrink-0" style={{ width: "45%" }}>
{/* 总额度 */}
{total !== undefined && (
<>
<span className="text-gray-500 dark:text-gray-400"></span>
<span className="tabular-nums text-gray-600 dark:text-gray-400">
{total === -1 ? "∞" : total.toFixed(2)}
</span>
<span className="text-gray-400 dark:text-gray-600">|</span>
</>
)}
{/* 已用额度 */}
{used !== undefined && (
<>
<span className="text-gray-500 dark:text-gray-400">使</span>
<span className="tabular-nums text-gray-600 dark:text-gray-400">
{used.toFixed(2)}
</span>
<span className="text-gray-400 dark:text-gray-600">|</span>
</>
)}
{/* 剩余额度 - 突出显示 */}
{remaining !== undefined && (
<>
<span className="text-gray-500 dark:text-gray-400"></span>
<span
className={`font-semibold tabular-nums ${
isExpired
? "text-red-500 dark:text-red-400"
: remaining < (total || remaining) * 0.1
? "text-orange-500 dark:text-orange-400"
: "text-green-600 dark:text-green-400"
}`}
>
{remaining.toFixed(2)}
</span>
</>
)}
{unit && <span className="text-gray-500 dark:text-gray-400">{unit}</span>}
</div>
</div>
);
};
export default UsageFooter;