mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-29 16:00:51 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4254104c9 | ||
|
|
36136728c6 | ||
|
|
0d731c5059 | ||
|
|
3fe4248fd6 | ||
|
|
3cc9c71ab5 | ||
|
|
2dc3ba8d56 | ||
|
|
7c16190936 | ||
|
|
c89152ce08 | ||
|
|
4b8825a28f | ||
|
|
95a89e9010 |
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: cpr-dev-guide
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护入口
|
||||
description: Codex Proxy RS 的需求评估、排障、开发、代码审查与文档维护,包括对代码和文档改动的验收
|
||||
---
|
||||
|
||||
# 开发指南
|
||||
@@ -22,9 +22,9 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
## 先确定领域与必读规范
|
||||
|
||||
按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节
|
||||
确定方案前按受影响行为和实际文件执行下表所有命中项。流程引用首次完整读取,长文档按标题定位指定章节。单独验收和开发收尾采用同一组领域规范
|
||||
|
||||
| 领域或操作,行为影响与文件路径满足其一即可 | 确定方案前读取与执行 |
|
||||
| 领域或操作,行为影响与文件路径满足其一即可 | 必读规范与检查 |
|
||||
| --- | --- |
|
||||
| 调整页面、弹窗、表单、按钮、文案、样式或交互;目标在 `frontend/`、`modules/ui/`、插件前端,或是 `.vue` 文件 | [前端流程](references/frontend.md),局部修改同样按影响范围检查组件复用、文案、Token、样式、视觉状态和运行证据 |
|
||||
| 插件接入、SDK、Runtime、扩展接口或独立网关插件,含账号、调度或 API 中为插件新增的处理;目标在 `backend/crates/gateway-plugin/`、`modules/plugins/` | [插件职责边界](references/plugin-boundaries.md)及所用 [SDK](../../../backend/crates/gateway-plugin/sdk/README.md) 类型与能力合同;独立插件开发、排查或审查同时执行 [cpr-plugin-dev](../cpr-plugin-dev/SKILL.md) |
|
||||
@@ -41,11 +41,13 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
|
||||
|
||||
## 执行与收尾
|
||||
|
||||
长任务按 [任务延续与收尾](../../../AGENTS.md#任务延续与收尾)恢复已匹配的领域、具体约束与验证进度。单独收到验收请求时,先确认待验收版本和范围,发现偏差按当前授权处理
|
||||
|
||||
1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改
|
||||
2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
2. 按最终差异与受影响行为重新匹配上表,逐项对照适用条款检查实际实现。处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复
|
||||
3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用
|
||||
4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。交代实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期,不把构建通过当作行为验收
|
||||
5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。验收结论同时依据规范核对结果与行为验证证据;有规范偏差或缺少必要证据时,指出具体位置或未验证场景。前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期
|
||||
6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名
|
||||
|
||||
## 测试维护
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
interface:
|
||||
display_name: "cpr-dev-guide"
|
||||
short_description: "开发、排障与审查入口,按行为影响匹配领域边界并验证实现"
|
||||
default_prompt: "使用 $cpr-dev-guide 按请求、行为影响和实际文件匹配领域必读规范,读完职责边界再确定方案,完成已授权的开发或审查、自审与验证。"
|
||||
short_description: "开发、排障、审查与验收入口,按受影响行为匹配并执行领域规范"
|
||||
default_prompt: "使用 $cpr-dev-guide 按受影响行为和实际文件匹配领域规范,开发时据此确定方案,验收时对照最终实现和验证证据。"
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
| 任务意图与常见说法 | 必用技能 |
|
||||
| --- | --- |
|
||||
| 需求评估、排障、开发、修复、代码审查、改文档,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
|
||||
| 需求评估、排障、开发、修复、代码审查、改文档、验收实现,包括“看下这个 Issue”“改弹窗/样式/文案”“修接口/调度/数据库”“验收一下这次改动” | [cpr-dev-guide](.agents/skills/cpr-dev-guide/SKILL.md),按实际操作和文件匹配规范,跨前后端同时执行 |
|
||||
| 提交/提个 PR、准备或更新 PR、看下 PR、回复 PR 讨论、处理 PR 审查意见 | [cpr-github-pr](.agents/skills/cpr-github-pr/SKILL.md);实现自审、审查或修改同时执行 cpr-dev-guide |
|
||||
| 提 Issue、反馈到仓库、把问题或建议整理成 Issue、补充或回复 Issue | [cpr-github-issue](.agents/skills/cpr-github-issue/SKILL.md) |
|
||||
| 写、修或审查独立网关插件,排查插件接入、打包插件 | [cpr-plugin-dev](.agents/skills/cpr-plugin-dev/SKILL.md),同时执行 cpr-dev-guide;仅改宿主能力时由 cpr-dev-guide 加载插件边界 |
|
||||
| 发版、准备版本、发布 beta/实验版、整理发布说明、打发行 tag | [cpr-release](.agents/skills/cpr-release/SKILL.md) |
|
||||
|
||||
结合上下文识别“提交吧”“看看这个问题”等省略说法:普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
|
||||
结合当前任务判断“继续”“验收一下”等省略说法。验收代码或文档改动时执行开发指南;核对发布产物时走发版技能。普通 Git 提交不自动变成 PR,代码排查不自动变成 Issue;审查与发版准备不代表获准远程写入
|
||||
|
||||
首次命中技能时完整读取其 `SKILL.md`,再读取领域必读规范,之后按当前步骤补充实现、命令和示例。技能名称、描述或入口摘要不能代替首次读取的正文与必读引用;引用中明确要求“先读”“必须读取”或“执行”的规范也要落实,其他资料按需读取
|
||||
|
||||
@@ -26,7 +26,7 @@ Issue 和 PR 回复统一按 [GitHub 回复口吻](CONTRIBUTING.md#github-回复
|
||||
### 任务延续与收尾
|
||||
|
||||
- 在任务上下文和压缩摘要中保留目标、授权、当前阶段、已读规范的路径与关键约束、验证命令与结果及对应代码状态、剩余事项
|
||||
- 同一任务可复用实际完成的读取与验证记录;仅在规范变更、进入未覆盖领域或具体决策缺少条款时补读对应内容。输出截断只补缺失部分,上下文压缩与阶段切换本身不触发重读或重验
|
||||
- 续接任务时,从记录中恢复当前步骤适用的规范与待查项,核对已有证据对应的实现。规范变更、进入新领域或缺少具体约束时补读对应条款,输出截断只补缺失部分。已有证据仍适用的检查直接复用
|
||||
- 远端更新或合并冲突后,按实际变更及其依赖影响补充自审和验证,复用未受影响的证据
|
||||
- 实现、自审与必要验证完成后,按[验证停止条件](CONTRIBUTING.md#验证)停止扩围;完成已获授权的剩余交付步骤并确认结果后结束
|
||||
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ AI 开发和审查入口是根目录的 [AGENTS.md](AGENTS.md)。在仓库上下
|
||||
### 项目技能
|
||||
|
||||
仓库技能位于 `.agents/skills/`,随代码共享。技能提供执行流程,协作与审查标准仍以本文和 `AGENTS.md` 为准。
|
||||
AI 开发、排查、代码审查和文档修改必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
|
||||
AI 开发、排查、代码审查、文档修改及对这些改动的验收必须执行 `cpr-dev-guide`;准备、创建、更新及审查 PR 必须执行 `cpr-github-pr`,不以用户是否显式点名技能为条件。PR 内修复仍须经过开发流程,不能用填写 PR 正文代替实现自审与验证
|
||||
|
||||
| 技能 | 用途 | 调用示例 |
|
||||
| --- | --- | --- |
|
||||
|
||||
@@ -42,6 +42,7 @@ pub struct ProviderAccountCapabilities {
|
||||
/// 导入时应用的账号设置;名称只覆盖单账号导入,其余设置统一应用
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountImportSettings {
|
||||
pub platform_icon: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub enabled: bool,
|
||||
@@ -222,6 +223,7 @@ pub struct AccountPage {
|
||||
/// 同一状态快照下的账号事实与唯一状态投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPageItem {
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub projection: AccountStatusProjection,
|
||||
@@ -240,6 +242,7 @@ pub struct AccountCapacity {
|
||||
/// 账号可编辑事实的一次性替换命令
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UpdateAccount {
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_id: String,
|
||||
/// 缺省保留名称,空字符串清除名称并使用邮箱展示
|
||||
pub name: Option<String>,
|
||||
|
||||
@@ -350,7 +350,9 @@ impl ClientKeyBudgetWindowPeriod {
|
||||
|
||||
/// 手动对齐只需要账号身份,列表不读取凭据、额度或用量
|
||||
#[derive(serde::Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BudgetReferenceAccount {
|
||||
pub platform_icon: Option<String>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
|
||||
@@ -783,6 +783,7 @@ pub struct AccountRequestBucket {
|
||||
/// Dashboard 中一个账号的完整用量事实
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DashboardAccountUsage {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
pub account_id: String,
|
||||
pub provider_kind: String,
|
||||
@@ -890,6 +891,7 @@ impl UsageErrorOrigin {
|
||||
/// 使用记录表格的窄读模型
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UsageListRecord {
|
||||
pub platform_icon: Option<String>,
|
||||
pub outcome: RequestOutcome,
|
||||
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
||||
pub has_upstream_error: bool,
|
||||
@@ -1167,7 +1169,8 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
@@ -1640,6 +1643,8 @@ pub struct UsageInsight {
|
||||
/// 已完成分母计算的诊断项
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DiagnosticsItem {
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
|
||||
@@ -1319,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
pub capacity: super::accounts::AccountCapacity,
|
||||
|
||||
@@ -27,6 +27,7 @@ pub struct ProxyListQuery {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProxyAccountRef {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<super::upstream_info::ProviderUpstreamInfo>,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
|
||||
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: super::peer_link::upstream::account_capacity(
|
||||
&stored.account,
|
||||
@@ -647,6 +648,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
used_slots: in_flight
|
||||
|
||||
@@ -382,9 +382,11 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.account_provider_kind.as_deref(),
|
||||
item.providers.first().map(String::as_str),
|
||||
item.account_plan_type.as_deref(),
|
||||
),
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
account_plan_type: item.account_plan_type,
|
||||
request_count: item.request_count,
|
||||
success_count: item.success_count,
|
||||
|
||||
@@ -740,6 +740,7 @@ impl FakeAccountStore {
|
||||
last_error_message: account.last_error_message.clone(),
|
||||
};
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
@@ -1895,6 +1896,7 @@ async fn accounts_update_should_commit_then_release_disabled_account_and_publish
|
||||
.update(
|
||||
&context("update-request"),
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -1935,6 +1937,7 @@ async fn accounts_update_should_not_notify_provider_when_store_commit_fails() {
|
||||
.update(
|
||||
&context("update-failure"),
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -4017,6 +4020,7 @@ fn unsupported() -> ProviderAdminError {
|
||||
|
||||
pub(super) fn import_settings() -> gateway_admin::model::accounts::AccountImportSettings {
|
||||
gateway_admin::model::accounts::AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: Some("团队备用".to_owned()),
|
||||
model_access: Default::default(),
|
||||
|
||||
@@ -516,6 +516,7 @@ async fn dashboard_should_preserve_provider_plan_names() {
|
||||
*store.account_usage.lock().unwrap() = plans
|
||||
.iter()
|
||||
.map(|(plan, _)| DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: format!("account-{plan}"),
|
||||
provider_kind: "openai".to_owned(),
|
||||
|
||||
@@ -451,6 +451,7 @@ fn total_record(
|
||||
now: DateTime<Utc>,
|
||||
) -> UsageListRecord {
|
||||
UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
@@ -542,7 +543,8 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
caller_error_count: 0,
|
||||
retry_count: 0,
|
||||
retried_request_count: 0,
|
||||
account_provider_kind: None,
|
||||
providers: vec![],
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
|
||||
@@ -355,6 +355,7 @@ async fn linked_accounts_share_plan_resolution_and_only_read_cached_quota() {
|
||||
.provider(provider.clone())
|
||||
.proxies(Arc::new(TestProxies {
|
||||
accounts: Some(vec![ProxyAccountRef {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
id: "acct_plan".to_owned(),
|
||||
name: "套餐测试".to_owned(),
|
||||
|
||||
@@ -2,6 +2,25 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn validate_platform_icons(
|
||||
state: &impl crate::SessionState,
|
||||
names: &[&str],
|
||||
) -> Result<(), AdminError> {
|
||||
if names.iter().any(|name| !name.is_empty()) {
|
||||
let catalog = state
|
||||
.platform_icon_names()
|
||||
.await
|
||||
.map_err(|_| AdminError::service_unavailable())?;
|
||||
if names
|
||||
.iter()
|
||||
.any(|&name| !name.is_empty() && !catalog.contains(name))
|
||||
{
|
||||
return Err(map_wire_error(WireValidationError::new("platformIcon")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_account_notes(notes: Option<&str>) -> Result<(), WireValidationError> {
|
||||
if notes.is_some_and(|notes| {
|
||||
notes.chars().count() > 500
|
||||
@@ -22,6 +41,8 @@ fn parse_provider(value: &str) -> Result<ProviderKind, WireValidationError> {
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountImportSettingsRequest {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub platform_icon: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub notes: Option<String>,
|
||||
pub enabled: bool,
|
||||
@@ -52,6 +73,7 @@ impl AccountImportSettingsRequest {
|
||||
.name
|
||||
.map(|name| name.trim().to_owned())
|
||||
.filter(|name| !name.is_empty()),
|
||||
platform_icon: self.platform_icon,
|
||||
notes: self.notes,
|
||||
enabled: self.enabled,
|
||||
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
|
||||
@@ -213,6 +235,7 @@ fn validate_authorization_flow(
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateAccountRequest {
|
||||
pub platform_icon: Option<String>,
|
||||
pub connection: Option<AccountConnectionUpdateRequest>,
|
||||
pub outbound_proxy_id: Option<String>,
|
||||
pub account_id: String,
|
||||
@@ -253,6 +276,7 @@ impl UpdateAccountRequest {
|
||||
outbound_proxy: super::wire::proxy_selection(self.outbound_proxy_id)?,
|
||||
account_id: self.account_id,
|
||||
name: self.name.map(|name| name.trim().to_owned()),
|
||||
platform_icon: self.platform_icon,
|
||||
notes: self.notes,
|
||||
enabled: self.enabled,
|
||||
concurrency_limit: parse_concurrency_limit(self.concurrency_limit)?,
|
||||
|
||||
@@ -182,6 +182,15 @@ async fn import_accounts<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.platform_icon.as_deref())
|
||||
.as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (provider, command) = request
|
||||
.into_command(auth.context().mutation_context())
|
||||
.map_err(map_wire_error)?;
|
||||
@@ -232,6 +241,15 @@ async fn complete_account_authorization<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.platform_icon.as_deref())
|
||||
.as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (provider, command) = request
|
||||
.into_command(auth.context().mutation_context())
|
||||
.map_err(map_wire_error)?;
|
||||
@@ -255,6 +273,11 @@ async fn update_account<S>(
|
||||
where
|
||||
S: SessionState + Send + Sync,
|
||||
{
|
||||
super::credentials::validate_platform_icons(
|
||||
&state,
|
||||
request.platform_icon.as_deref().as_slice(),
|
||||
)
|
||||
.await?;
|
||||
let (command, connection) = request.into_command().map_err(map_wire_error)?;
|
||||
let context = auth.context().mutation_context();
|
||||
let result = if let Some(provider_material) = connection {
|
||||
|
||||
@@ -149,6 +149,12 @@ where
|
||||
if request.items.is_empty() || request.items.len() > MAX_IMPORT_TASK_ITEMS {
|
||||
return Err(map_wire_error(WireValidationError::new("items")));
|
||||
}
|
||||
let icons: Vec<_> = request
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| item.settings.as_ref()?.platform_icon.as_deref())
|
||||
.collect();
|
||||
super::credentials::validate_platform_icons(&state, &icons).await?;
|
||||
let encoded = serde_json::to_vec(&request.items)
|
||||
.map_err(|_| map_wire_error(WireValidationError::new("items")))?;
|
||||
let fingerprint = Sha256::digest(&encoded).into();
|
||||
|
||||
@@ -67,6 +67,7 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
platform_icon,
|
||||
account,
|
||||
capacity,
|
||||
capabilities,
|
||||
@@ -111,6 +112,7 @@ pub(super) fn account_view(
|
||||
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
quota.protection_rules = protection_rules;
|
||||
AccountView {
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
auto_use_quota_credits: account.auto_use_quota_credits,
|
||||
upstream,
|
||||
|
||||
@@ -247,6 +247,7 @@ pub struct AccountSummaryView {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub quota_settings: gateway_core::account::AccountQuotaSettings,
|
||||
pub auto_use_quota_credits: bool,
|
||||
pub upstream: Option<super::AccountUpstreamInfoView>,
|
||||
|
||||
@@ -276,6 +276,7 @@ pub(crate) fn usage_list_record_view(
|
||||
account_id: record.provider_account_ref,
|
||||
account_email: record.provider_account_email,
|
||||
account_name: record.provider_account_name,
|
||||
platform_icon: record.platform_icon,
|
||||
account_notes: record.provider_account_notes,
|
||||
account_plan_type: record.provider_account_plan_type,
|
||||
account_plan_type_display: record.provider_account_plan_type_display,
|
||||
@@ -940,6 +941,7 @@ pub(crate) fn dashboard_view(
|
||||
.email
|
||||
.clone()
|
||||
.unwrap_or_else(|| credential.name.clone()),
|
||||
platform_icon: credential.platform_icon,
|
||||
notes: credential.notes,
|
||||
plan_type: credential.plan_type.clone(),
|
||||
plan_type_display: credential
|
||||
@@ -1350,6 +1352,8 @@ pub(crate) fn diagnostics_view(
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| DiagnosticItemView {
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
key: item.key,
|
||||
authentication_kind: item.account_authentication_kind,
|
||||
name: if item.name == "__none__" {
|
||||
|
||||
@@ -86,6 +86,7 @@ pub struct ImageBillingView {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UsageListRecordView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub error_origin: &'static str,
|
||||
pub client_status_code: Option<u16>,
|
||||
pub upstream_status_code: Option<u16>,
|
||||
@@ -432,6 +433,7 @@ pub enum DashboardAccountMetric {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DashboardAccountUsageView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub upstream: Option<crate::admin::accounts::AccountUpstreamInfoView>,
|
||||
pub id: String,
|
||||
pub provider: String,
|
||||
@@ -872,6 +874,8 @@ pub struct UsageCacheView {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiagnosticItemView {
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub authentication_kind: Option<String>,
|
||||
|
||||
@@ -152,6 +152,7 @@ impl From<ProxyTestResult> for ProxyTestView {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProxyAccountView {
|
||||
platform_icon: Option<String>,
|
||||
upstream: Option<super::accounts::AccountUpstreamInfoView>,
|
||||
id: String,
|
||||
name: String,
|
||||
@@ -345,6 +346,7 @@ where
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|account| ProxyAccountView {
|
||||
platform_icon: account.platform_icon,
|
||||
upstream: account.upstream.map(|info| {
|
||||
super::accounts::upstream_info_view(
|
||||
info,
|
||||
|
||||
@@ -41,7 +41,7 @@ pub(crate) async fn models(
|
||||
Query(query): Query<ModelsQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key");
|
||||
let anthropic = headers.contains_key("anthropic-version");
|
||||
let service = state.data_plane();
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await {
|
||||
Ok(client) => client,
|
||||
@@ -104,7 +104,7 @@ pub(crate) async fn model_detail(
|
||||
headers: HeaderMap,
|
||||
Path(model_id): Path<String>,
|
||||
) -> Response {
|
||||
let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key");
|
||||
let anthropic = headers.contains_key("anthropic-version");
|
||||
let service = state.data_plane();
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await {
|
||||
Ok(client) => client,
|
||||
|
||||
@@ -216,6 +216,7 @@ pub fn initialize(
|
||||
})
|
||||
};
|
||||
let state = ApiState {
|
||||
platform_icon_catalog: Arc::new(config.asset_directory.join("platform-icons.json")),
|
||||
admin,
|
||||
data_plane: DataPlaneService::new(execution, lifecycle),
|
||||
health: HealthStatus::new(probes, worker_health, diagnostics.clone()),
|
||||
@@ -337,6 +338,7 @@ pub enum ApiError {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ApiState {
|
||||
platform_icon_catalog: Arc<PathBuf>,
|
||||
admin: AdminServices,
|
||||
data_plane: DataPlaneService,
|
||||
health: HealthStatus,
|
||||
@@ -355,6 +357,11 @@ impl ApiState {
|
||||
}
|
||||
|
||||
impl SessionState for ApiState {
|
||||
async fn platform_icon_names(&self) -> std::io::Result<std::collections::HashSet<String>> {
|
||||
let bytes = tokio::fs::read(self.platform_icon_catalog.as_ref()).await?;
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
}
|
||||
|
||||
fn admin_services(&self) -> &AdminServices {
|
||||
&self.admin
|
||||
}
|
||||
|
||||
@@ -4,5 +4,8 @@ use gateway_admin::AdminServices;
|
||||
|
||||
/// 控制面 HTTP adapter 消费同一组用例;权限由各入口服务端校验
|
||||
pub trait SessionState {
|
||||
fn platform_icon_names(
|
||||
&self,
|
||||
) -> impl Future<Output = std::io::Result<std::collections::HashSet<String>>> + Send;
|
||||
fn admin_services(&self) -> &AdminServices;
|
||||
}
|
||||
|
||||
@@ -411,6 +411,7 @@ fn account_page_item(
|
||||
use gateway_core::account::resolve_account_status;
|
||||
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
account: AccountRecord {
|
||||
quota_paused: false,
|
||||
@@ -670,6 +671,67 @@ async fn connection_update_requires_admin_and_validates_before_calling_the_servi
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_icon_requires_a_known_preset_before_mutation() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
for (name, expected) in [
|
||||
("DeepSeek", StatusCode::SERVICE_UNAVAILABLE),
|
||||
("", StatusCode::SERVICE_UNAVAILABLE),
|
||||
("Unlisted", StatusCode::BAD_REQUEST),
|
||||
("https://example.invalid/logo.svg", StatusCode::BAD_REQUEST),
|
||||
] {
|
||||
let settings = serde_json::json!({
|
||||
"platformIcon": name, "enabled": true,
|
||||
"concurrencyLimit": null, "weight": 1, "groupIds": []
|
||||
});
|
||||
for (route, payload) in [
|
||||
(
|
||||
"update",
|
||||
serde_json::json!({
|
||||
"accountId": "acct_api", "platformIcon": name, "enabled": true,
|
||||
"concurrencyLimit": null, "weight": 1, "groupIds": []
|
||||
}),
|
||||
),
|
||||
(
|
||||
"import",
|
||||
serde_json::json!({"provider": "openai", "data": {}, "settings": settings}),
|
||||
),
|
||||
(
|
||||
"oauth/complete",
|
||||
serde_json::json!({
|
||||
"provider": "xai", "flowId": "flow-test", "callbackUrl": "code", "settings": settings
|
||||
}),
|
||||
),
|
||||
] {
|
||||
let request = Request::post(format!("/api/admin/accounts/{route}"))
|
||||
.header("x-request-id", "req_account_icon")
|
||||
.header(header::COOKIE, "cpr_session=valid-session")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(payload.to_string()))
|
||||
.unwrap();
|
||||
let response = admin::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
.oneshot(request)
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
if expected == StatusCode::BAD_REQUEST {
|
||||
assert_eq!(status, expected, "{route}: {name}");
|
||||
assert_eq!(body["message"], "platformIcon 字段不合法");
|
||||
} else if route == "update" {
|
||||
assert_eq!(status, expected, "{route}: {name}");
|
||||
} else {
|
||||
// 夹具 Provider 未实现导入和授权,合法图标应通过校验并到达 Provider
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{route}: {name}: {body}");
|
||||
assert_eq!(body["message"], "该服务商不支持此操作");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn personal_info_requires_admin_and_a_valid_account_query() {
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
|
||||
@@ -564,6 +564,7 @@ mod provider {
|
||||
last_error_message: None,
|
||||
};
|
||||
AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
used_slots: None,
|
||||
|
||||
@@ -311,6 +311,10 @@ impl ClientDistributionResolver for StaticClientDistribution {
|
||||
pub(super) struct AdminTestState(AdminServices);
|
||||
|
||||
impl SessionState for AdminTestState {
|
||||
async fn platform_icon_names(&self) -> std::io::Result<std::collections::HashSet<String>> {
|
||||
Ok(["DeepSeek".to_owned()].into())
|
||||
}
|
||||
|
||||
fn admin_services(&self) -> &AdminServices {
|
||||
&self.0
|
||||
}
|
||||
|
||||
@@ -748,7 +748,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
total_request_count: 4,
|
||||
items: vec![DiagnosticObservation {
|
||||
key: "acct_diag".to_owned(),
|
||||
account_provider_kind: Some("openai".to_owned()),
|
||||
providers: vec!["openai".to_owned()],
|
||||
platform_icon: Some("Adobe".to_owned()),
|
||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||
account_plan_type: plan_type.map(str::to_owned),
|
||||
account_plan_type_display: None,
|
||||
@@ -791,6 +792,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
value["data"]["items"][0]["accountUpstreamPeer"],
|
||||
json!(peer.map(|(d, o)| d && o))
|
||||
);
|
||||
assert_eq!(value["data"]["items"][0]["providers"], json!(["openai"]));
|
||||
assert_eq!(value["data"]["items"][0]["platformIcon"], "Adobe");
|
||||
assert_eq!(value["data"]["items"][0]["requestShare"], 0.5);
|
||||
assert_eq!(value["data"]["items"][0]["retryCount"], 3);
|
||||
assert_eq!(value["data"]["items"][0]["retryRate"], 0.5);
|
||||
@@ -981,6 +984,7 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
.lock()
|
||||
.expect("usage records")
|
||||
.push(UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
@@ -1962,6 +1966,7 @@ async fn dashboard_summary_identifies_trend_metrics_and_account_usage_values() {
|
||||
.map(|(index, (requests, tokens, last_used_at))| {
|
||||
let account_id = format!("acct_metric_{index}");
|
||||
DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: account_id.clone(),
|
||||
provider_kind: "openai".to_owned(),
|
||||
@@ -2153,6 +2158,7 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme
|
||||
provider_accounts: Default::default(),
|
||||
trend: Vec::new(),
|
||||
account_usage: vec![DashboardAccountUsage {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
account_id: "acct_relative_time".to_owned(),
|
||||
provider_kind: "openai".to_owned(),
|
||||
|
||||
@@ -287,6 +287,7 @@ impl ProxyStore for MemoryProxies {
|
||||
}
|
||||
Ok(ProxyAccountPage {
|
||||
items: vec![ProxyAccountRef {
|
||||
platform_icon: None,
|
||||
upstream: None,
|
||||
id: "acct_linked".to_owned(),
|
||||
name: "工作账号".to_owned(),
|
||||
@@ -569,7 +570,7 @@ async fn proxy_routes_save_reload_test_rename_and_delete_without_exposing_creden
|
||||
assert_eq!(
|
||||
linked["data"]["items"],
|
||||
json!([{
|
||||
"id":"acct_linked", "name":"工作账号", "email":"work@example.invalid",
|
||||
"id":"acct_linked", "name":"工作账号", "email":"work@example.invalid", "platformIcon":null,
|
||||
"provider":"openai", "enabled":true, "authenticationKind":"oauth",
|
||||
"planType":"plus", "planTypeDisplay":"Plus", "groups":[], "upstream":null
|
||||
}])
|
||||
|
||||
@@ -34,7 +34,9 @@ async fn anthropic_models_use_explicit_headers_and_cursor_pagination() {
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::get(path)
|
||||
.header(AUTHORIZATION, "Bearer sk_models_test")
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
@@ -90,6 +92,7 @@ async fn anthropic_model_detail_keeps_public_model_access() {
|
||||
.oneshot(
|
||||
Request::get(path)
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
@@ -296,6 +299,22 @@ impl ExecutionService for ModelsExecution {
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticated_model_requests(path: &str) -> [Request<Body>; 3] {
|
||||
let api_key_request = Request::get(path)
|
||||
.header("x-api-key", "sk_models_test")
|
||||
.body(Body::empty())
|
||||
.expect("API key request");
|
||||
let mut dual_header_request = authorized_request(path);
|
||||
dual_header_request
|
||||
.headers_mut()
|
||||
.insert("x-api-key", "sk_models_test".parse().expect("API key"));
|
||||
[
|
||||
authorized_request(path),
|
||||
api_key_request,
|
||||
dual_header_request,
|
||||
]
|
||||
}
|
||||
|
||||
fn authorized_request(path: &str) -> Request<Body> {
|
||||
Request::get(path)
|
||||
.header(AUTHORIZATION, "Bearer sk_models_test")
|
||||
@@ -490,18 +509,20 @@ async fn native_catalog_failure_does_not_publish_a_synthetic_or_empty_success()
|
||||
requested_versions: Mutex::default(),
|
||||
middleware: None,
|
||||
});
|
||||
let response = api_router(execution)
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models?client_version=0.154.0"))
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
|
||||
assert_eq!(value["error"]["code"], "model_catalog_unavailable");
|
||||
assert!(value.get("models").is_none());
|
||||
for request in authenticated_model_requests("/v1/models?client_version=0.154.0") {
|
||||
let response = api_router(execution.clone())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("response");
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
|
||||
assert_eq!(value["error"]["code"], "model_catalog_unavailable");
|
||||
assert!(value.get("models").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -781,52 +802,64 @@ async fn models_should_preserve_unknown_context_windows() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_should_keep_the_codex_contract_when_profiles_are_empty() {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models?client_version=0.145.0"))
|
||||
.await
|
||||
.expect("list empty Codex models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read empty Codex models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("Codex models JSON");
|
||||
for request in authenticated_model_requests("/v1/models?client_version=0.145.0") {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("list empty Codex models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read empty Codex models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("Codex models JSON");
|
||||
|
||||
assert_eq!(value, serde_json::json!({ "models": [] }));
|
||||
assert_eq!(value, serde_json::json!({ "models": [] }));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_with_provider_profiles_should_keep_the_openai_list_contract() {
|
||||
let response = api_router(ModelsExecution::with_profiles())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models"))
|
||||
.await
|
||||
.expect("list compatible models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read compatible models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON");
|
||||
for request in authenticated_model_requests("/v1/models") {
|
||||
let response = api_router(ModelsExecution::with_profiles())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("list compatible models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read compatible models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON");
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
serde_json::json!({
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"},
|
||||
{"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"}
|
||||
]
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
value,
|
||||
serde_json::json!({
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"},
|
||||
{"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"}
|
||||
]
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_detail_should_keep_the_official_path_id_contract() {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(authorized_request("/v1/models/model-a"))
|
||||
.await
|
||||
.expect("model detail response");
|
||||
for request in authenticated_model_requests("/v1/models/responses-only") {
|
||||
let response = api_router(ModelsExecution::new())
|
||||
.await
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("model detail response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("model body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("model JSON");
|
||||
assert_eq!(value["id"], "responses-only");
|
||||
assert_eq!(value["object"], "model");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
|
||||
last_error_message: None,
|
||||
};
|
||||
*fixture.account.lock().unwrap() = Some(AccountPageItem {
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: AccountCapacity {
|
||||
used_slots: None,
|
||||
|
||||
@@ -101,6 +101,7 @@ pub(super) async fn fixture() -> AdminTestFixture {
|
||||
|
||||
fn usage_record() -> UsageListRecord {
|
||||
UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
error_code: None,
|
||||
|
||||
@@ -772,8 +772,8 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
.ok_or_else(|| admin_store_error(ENTITY, StoreError::NotFound {
|
||||
source: None, entity: ENTITY, id: id.as_str().to_owned()
|
||||
}))?;
|
||||
let rows: Vec<(String, String, Option<String>, String)> = sqlx::query_as(
|
||||
"select a.id, a.name, a.email, a.provider_kind from provider_accounts a
|
||||
let rows: Vec<(String, String, Option<String>, String, Option<String>)> = sqlx::query_as(
|
||||
"select a.id, a.name, a.email, a.provider_kind, a.platform_icon from provider_accounts a
|
||||
where a.id > $1
|
||||
and ($2 = '' or strpos(lower(a.name), lower($2)) > 0
|
||||
or strpos(lower(coalesce(a.email, '')), lower($2)) > 0)
|
||||
@@ -793,12 +793,15 @@ impl ClientKeyStore for PgAdminClientKeyStore {
|
||||
let items: Vec<_> = rows
|
||||
.into_iter()
|
||||
.take(usize::from(PAGE_SIZE))
|
||||
.map(|(id, name, email, provider)| BudgetReferenceAccount {
|
||||
id,
|
||||
name,
|
||||
email,
|
||||
provider,
|
||||
})
|
||||
.map(
|
||||
|(id, name, email, provider, platform_icon)| BudgetReferenceAccount {
|
||||
platform_icon,
|
||||
id,
|
||||
name,
|
||||
email,
|
||||
provider,
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
let next_cursor = items.last().filter(|_| has_more).map(|row| row.id.clone());
|
||||
Ok(BudgetReferenceAccountPage { items, next_cursor })
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
const PROVIDER_SET: &str = "coalesce(array_agg(distinct provider_kind) filter(where provider_kind <> ''), '{}'::text[]) as providers,";
|
||||
|
||||
/// 输入 matching 提供分组键、指标输入列及 is_completed_usage
|
||||
/// 精确分位数在整个结果组内计算,不把局部分位数合并成新的分位数
|
||||
pub(super) fn push_fact_aggregation(
|
||||
@@ -16,6 +18,7 @@ pub(super) fn push_fact_aggregation(
|
||||
DistributionRead::Full,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,6 +29,7 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
distributions: DistributionRead,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
if read_costs && matches!(distributions, DistributionRead::Statistics) {
|
||||
push_fact_statistics_by_currency(query, counter_names, distribution_names);
|
||||
@@ -35,6 +39,9 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
let statistics_only = matches!(distributions, DistributionRead::Statistics);
|
||||
let counters = selected_counter_expressions(counter_names);
|
||||
query.push(", counted as (select output_bucket,name,max(started_at) filter(where is_completed_usage) as last_used_at,");
|
||||
if model_providers {
|
||||
query.push(PROVIDER_SET);
|
||||
}
|
||||
push_counter_object(query, &counters);
|
||||
query.push(" as counts");
|
||||
if read_distributions && (exact_percentiles || statistics_only) {
|
||||
@@ -51,21 +58,16 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
// 空币种仍参与场景费用,金额为空的实际费用继续在展开后排除
|
||||
query.push(", cost_groups as (select output_bucket,name,cost_currency,sum(cost_amount) as cost_amount,sum(standard_cost_amount) as standard_cost_amount,sum(no_cache_cost_amount) as no_cache_cost_amount from matching where is_completed_usage group by output_bucket,name,cost_currency), cost_values as (select output_bucket,name,currency,sum(amount)::text as amount from cost_groups cross join lateral (values (cost_currency,cost_amount),('standard_usd',standard_cost_amount),('no_cache_usd',no_cache_cost_amount)) cost(currency,amount) where currency is not null and amount is not null group by output_bucket,name,currency), merged_costs as (select output_bucket,name,jsonb_object_agg(currency,amount) as costs from cost_values group by output_bucket,name)");
|
||||
}
|
||||
if !read_distributions {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,'{}'::jsonb as distributions,'{}'::jsonb as exact_percentiles,");
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
"'{}'::jsonb"
|
||||
});
|
||||
query.push(" as costs from counted c");
|
||||
if read_costs {
|
||||
query.push(" left join merged_costs k using(output_bucket,name)");
|
||||
if !read_distributions || exact_percentiles || statistics_only {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,");
|
||||
if model_providers {
|
||||
query.push("c.providers,");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if exact_percentiles || statistics_only {
|
||||
query.push(" select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,c.distributions,c.exact_percentiles,");
|
||||
query.push(if read_distributions {
|
||||
"c.distributions,c.exact_percentiles,"
|
||||
} else {
|
||||
"'{}'::jsonb as distributions,'{}'::jsonb as exact_percentiles,"
|
||||
});
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -99,6 +101,9 @@ pub(super) fn push_fact_aggregation_selected(
|
||||
query.push(" from sample_stats s");
|
||||
query.push(" left join merged_bins b using(output_bucket,name,metric)");
|
||||
query.push(" group by s.output_bucket,s.name) select c.output_bucket as bucket_start,c.name,c.counts,c.last_used_at,");
|
||||
if model_providers {
|
||||
query.push("c.providers,");
|
||||
}
|
||||
query.push(if read_costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -133,6 +138,7 @@ fn push_fact_statistics_by_currency(
|
||||
true,
|
||||
counter_names,
|
||||
distribution_names,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -322,6 +328,7 @@ pub(super) fn push_summary_aggregation(
|
||||
costs: bool,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
push_summary_aggregation_from(
|
||||
query,
|
||||
@@ -330,6 +337,7 @@ pub(super) fn push_summary_aggregation(
|
||||
costs,
|
||||
counter_names,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -341,6 +349,7 @@ fn push_summary_aggregation_from(
|
||||
costs: bool,
|
||||
counter_names: Option<&[&str]>,
|
||||
distribution_names: Option<&[&str]>,
|
||||
model_providers: bool,
|
||||
) {
|
||||
let distributions = !matches!(distribution_read, DistributionRead::None);
|
||||
// 每个源汇总只展开一次固定指标,避免按指标键放大行数再排序
|
||||
@@ -359,6 +368,9 @@ fn push_summary_aggregation_from(
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
query.push(", grouped as (select output_bucket,name,max(last_used_at) as last_used_at,");
|
||||
if model_providers {
|
||||
query.push(PROVIDER_SET);
|
||||
}
|
||||
push_counter_object(query, &counters);
|
||||
query
|
||||
.push(" as counts from ")
|
||||
@@ -404,6 +416,9 @@ fn push_summary_aggregation_from(
|
||||
}
|
||||
}
|
||||
query.push(" select g.output_bucket as bucket_start,g.name,g.last_used_at,g.counts,");
|
||||
if model_providers {
|
||||
query.push("g.providers,");
|
||||
}
|
||||
query.push(if costs {
|
||||
"coalesce(k.costs,'{}'::jsonb)"
|
||||
} else {
|
||||
@@ -475,6 +490,14 @@ pub(super) fn fact_dimension_sql(dimension: Option<DiagnosticDimension>) -> &'st
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summary_provider_column(collection: &str) -> &'static str {
|
||||
if matches!(collection, "account_model" | "key_model") {
|
||||
"dimensions[2]"
|
||||
} else {
|
||||
"dimensions[1]"
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summary_dimension_sql(
|
||||
collection: &str,
|
||||
dimension: Option<DiagnosticDimension>,
|
||||
@@ -483,7 +506,10 @@ pub(super) fn summary_dimension_sql(
|
||||
match dimension {
|
||||
None => "''::text".to_owned(),
|
||||
Some(DiagnosticDimension::Provider) => {
|
||||
format!("coalesce(nullif(dimensions[{}],''),'unrouted')", 1 + offset)
|
||||
format!(
|
||||
"coalesce(nullif({},''),'unrouted')",
|
||||
summary_provider_column(collection)
|
||||
)
|
||||
}
|
||||
Some(DiagnosticDimension::Model) => format!(
|
||||
"coalesce(nullif(dimensions[{}],''),dimensions[{}],'')",
|
||||
|
||||
@@ -81,7 +81,14 @@ impl AnalyticsSnapshot<'_> {
|
||||
granularity,
|
||||
boundaries.as_deref(),
|
||||
);
|
||||
q.push(format!(" as output_bucket,{name} as name,counts,costs from request_analytics_1h where collection=")).push_bind(AGGREGATE_COLLECTION).push(" and bucket_start >= ").push_bind(range.start).push(" and bucket_start < ").push_bind(range.end);
|
||||
let model_providers =
|
||||
dimension == Some(DiagnosticDimension::Model) && account_models.is_none();
|
||||
let provider = if model_providers {
|
||||
"dimensions[1] as provider_kind,"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
q.push(format!(" as output_bucket,{name} as name,{provider}counts,costs from request_analytics_1h where collection=")).push_bind(AGGREGATE_COLLECTION).push(" and bucket_start >= ").push_bind(range.start).push(" and bucket_start < ").push_bind(range.end);
|
||||
for (index, value) in [
|
||||
(1, &filter.provider_kind),
|
||||
(2, &filter.model),
|
||||
@@ -124,7 +131,14 @@ impl AnalyticsSnapshot<'_> {
|
||||
if selection.costs {
|
||||
q.push(" union all select output_bucket,name,'cost',c.key,c.value::numeric from matching cross join lateral jsonb_each_text(costs) c");
|
||||
}
|
||||
q.push("), totals as (select output_bucket,name,kind,key,sum(value)::text as value from entries group by output_bucket,name,kind,key) select output_bucket,name,jsonb_object_agg(key,value) filter(where kind='count') as counts,jsonb_object_agg(key,value) filter(where kind='cost') as costs from totals group by output_bucket,name");
|
||||
if model_providers {
|
||||
q.push(" union all select distinct output_bucket,name,'provider',provider_kind,0::numeric from matching where provider_kind <> ''");
|
||||
}
|
||||
q.push("), totals as (select output_bucket,name,kind,key,sum(value)::text as value from entries group by output_bucket,name,kind,key) select output_bucket,name,jsonb_object_agg(key,value) filter(where kind='count') as counts,jsonb_object_agg(key,value) filter(where kind='cost') as costs");
|
||||
if model_providers {
|
||||
q.push(",array_agg(key) filter(where kind='provider') as providers");
|
||||
}
|
||||
q.push(" from totals group by output_bucket,name");
|
||||
let mut rows = q.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
.try_next()
|
||||
@@ -140,6 +154,11 @@ impl AnalyticsSnapshot<'_> {
|
||||
}
|
||||
let key = (get(&row, "output_bucket")?, name);
|
||||
let state = states.entry(key).or_default();
|
||||
if model_providers {
|
||||
state
|
||||
.providers
|
||||
.extend(get::<Option<Vec<String>>>(&row, "providers")?.unwrap_or_default());
|
||||
}
|
||||
let counts =
|
||||
get::<Option<sqlx::types::Json<BTreeMap<String, String>>>>(&row, "counts")?
|
||||
.map(|v| v.0)
|
||||
|
||||
@@ -104,6 +104,7 @@ impl AnalyticsSnapshot<'_> {
|
||||
"unavailable_count",
|
||||
]),
|
||||
None,
|
||||
false,
|
||||
);
|
||||
sql.push(") fact_parts");
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ pub(crate) struct MetricState {
|
||||
pub(super) distributions: BTreeMap<String, Histogram>,
|
||||
pub(super) costs: BTreeMap<String, String>,
|
||||
pub(super) last_used_at: Option<DateTime<Utc>>,
|
||||
// 模型诊断查询时从分组维度提取,不写入持久化指标
|
||||
#[serde(skip)]
|
||||
pub(super) providers: BTreeSet<String>,
|
||||
#[serde(skip)]
|
||||
exact_percentiles: Option<BTreeMap<String, Vec<Option<f64>>>>,
|
||||
}
|
||||
@@ -38,6 +41,7 @@ impl MetricState {
|
||||
)?
|
||||
.0,
|
||||
last_used_at: get(row, "last_used_at")?,
|
||||
providers: BTreeSet::new(),
|
||||
exact_percentiles: None,
|
||||
})
|
||||
}
|
||||
@@ -125,6 +129,7 @@ impl MetricState {
|
||||
if self.count("request_count") == 0 {
|
||||
self.exact_percentiles.clone_from(&other.exact_percentiles);
|
||||
}
|
||||
self.providers.extend(other.providers.iter().cloned());
|
||||
self.last_used_at = self.last_used_at.max(other.last_used_at);
|
||||
for (name, count) in &other.counts {
|
||||
self.increment(name, *count)?;
|
||||
|
||||
@@ -634,7 +634,8 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
observations.push(DiagnosticObservation {
|
||||
key: key.clone(),
|
||||
name: key,
|
||||
account_provider_kind: None,
|
||||
providers: state.providers.iter().cloned().collect(),
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
@@ -671,9 +672,9 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map(|item| item.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let statement = if dimension == DiagnosticDimension::Account {
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, coalesce(historical.provider_kind,a.provider_kind) as provider_kind, a.platform_icon, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join provider_accounts a on a.id=requested.id left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
} else {
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, null::text as provider_kind, null::text as platform_icon, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
};
|
||||
let labels = sqlx::query(statement)
|
||||
.bind(ids)
|
||||
@@ -684,7 +685,10 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
let id: String = get(&row, "id")?;
|
||||
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
|
||||
item.name = get(&row, "name")?;
|
||||
item.account_provider_kind = get(&row, "provider_kind")?;
|
||||
item.providers = get::<Option<String>>(&row, "provider_kind")?
|
||||
.into_iter()
|
||||
.collect();
|
||||
item.platform_icon = get(&row, "platform_icon")?;
|
||||
item.account_authentication_kind = get(&row, "authentication_kind")?;
|
||||
item.account_plan_type = get(&row, "plan_type")?;
|
||||
item.account_plan_type_display = get(&row, "plan_type_display")?;
|
||||
@@ -951,6 +955,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
let read_distributions = !matches!(distributions, DistributionRead::None);
|
||||
filter.validate()?;
|
||||
self.require_visible(Some(range))?;
|
||||
let model_providers = dimension == Some(DiagnosticDimension::Model);
|
||||
let selected = collection_for(filter, dimension);
|
||||
let boundaries = if granularity == Some(ObservationGranularity::Day) {
|
||||
Some(calendar_buckets(range, timezone)?)
|
||||
@@ -1004,7 +1009,15 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
} else {
|
||||
"'{}'::jsonb as distributions"
|
||||
};
|
||||
query.push(format!(" as output_bucket,{name} as name,outcome,counts,{costs},{distribution_sql},last_used_at from {table} a where collection="))
|
||||
let provider = if model_providers {
|
||||
format!(
|
||||
"{} as provider_kind,",
|
||||
aggregate::summary_provider_column(collection)
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
query.push(format!(" as output_bucket,{name} as name,{provider}outcome,counts,{costs},{distribution_sql},last_used_at from {table} a where collection="))
|
||||
.push_bind(collection).push(" and schema_version=").push_bind(SCHEMA_VERSION)
|
||||
.push(" and histogram_version=").push_bind(HISTOGRAM_VERSION);
|
||||
push_summary_buckets(&mut query, &buckets, seconds);
|
||||
@@ -1032,6 +1045,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
read_costs,
|
||||
counters,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
let mut rows = query.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
@@ -1041,7 +1055,11 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
{
|
||||
let bucket = get(&row, "bucket_start")?;
|
||||
let name = get(&row, "name")?;
|
||||
let state = MetricState::decode(&row)?;
|
||||
let mut state = MetricState::decode(&row)?;
|
||||
if model_providers {
|
||||
state.providers =
|
||||
get::<Vec<String>>(&row, "providers")?.into_iter().collect();
|
||||
}
|
||||
result.entry((bucket, name)).or_default().merge(&state)?;
|
||||
}
|
||||
}
|
||||
@@ -1124,6 +1142,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
distributions,
|
||||
counters,
|
||||
distribution_names,
|
||||
model_providers,
|
||||
);
|
||||
let mut rows = query.build().fetch(&mut *self.tx);
|
||||
while let Some(row) = rows
|
||||
@@ -1132,10 +1151,13 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map_err(|error| postgres_unavailable("aggregate analytics facts", error))?
|
||||
{
|
||||
let key = (get(&row, "bucket_start")?, get(&row, "name")?);
|
||||
let state = MetricState::decode_aggregate(
|
||||
let mut state = MetricState::decode_aggregate(
|
||||
&row,
|
||||
exact && matches!(distributions, DistributionRead::Full),
|
||||
)?;
|
||||
if model_providers {
|
||||
state.providers = get::<Vec<String>>(&row, "providers")?.into_iter().collect();
|
||||
}
|
||||
if exact {
|
||||
result.insert(key, state);
|
||||
} else {
|
||||
|
||||
@@ -111,6 +111,7 @@ pub(crate) async fn declare_usage_statistics(
|
||||
DistributionRead::None,
|
||||
Some(&names),
|
||||
None,
|
||||
false,
|
||||
);
|
||||
query.push(") facts");
|
||||
}
|
||||
|
||||
@@ -139,6 +139,7 @@ pub(crate) fn admin_dashboard_account_usage(
|
||||
authentication_kind: usage.authentication_kind,
|
||||
name: usage.name,
|
||||
email: usage.email,
|
||||
platform_icon: usage.platform_icon,
|
||||
notes: usage.notes,
|
||||
plan_type: usage.plan_type,
|
||||
plan_type_display: None,
|
||||
@@ -279,7 +280,8 @@ fn admin_diagnostic_observation(
|
||||
admin_observability::DiagnosticObservation {
|
||||
key: observation.key,
|
||||
name: observation.name,
|
||||
account_provider_kind: observation.account_provider_kind,
|
||||
providers: observation.providers,
|
||||
platform_icon: observation.platform_icon,
|
||||
account_authentication_kind: observation.account_authentication_kind,
|
||||
account_plan_type: observation.account_plan_type,
|
||||
account_plan_type_display: observation.account_plan_type_display,
|
||||
@@ -389,6 +391,7 @@ pub(crate) fn usage_list_record_from_row(
|
||||
provider_account_ref: get(row, "provider_account_ref")?,
|
||||
provider_account_name: get(row, "provider_account_name")?,
|
||||
provider_account_email: get(row, "provider_account_email")?,
|
||||
platform_icon: get(row, "platform_icon")?,
|
||||
provider_account_notes: get(row, "provider_account_notes")?,
|
||||
provider_account_upstream_peer: None,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
|
||||
@@ -228,6 +228,7 @@ pub use gateway_admin::model::observability::AccountRequestBucket as ProviderAcc
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderAccountUsageObservation {
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_id: String,
|
||||
pub provider_kind: String,
|
||||
pub authentication_kind: String,
|
||||
@@ -383,7 +384,8 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
|
||||
@@ -14,7 +14,9 @@ pub(crate) async fn provider_account_usage(
|
||||
}
|
||||
|
||||
// 账号卡片先确定有限候选,避免为少量账号聚合整个历史范围
|
||||
let mut statement = QueryBuilder::<Postgres>::new("select pa.* from provider_accounts pa");
|
||||
let mut statement = QueryBuilder::<Postgres>::new(
|
||||
"select pa.*, pa.platform_icon as platform_icon from provider_accounts pa",
|
||||
);
|
||||
if let Some(account_ids) = &query.account_ids {
|
||||
statement
|
||||
.push(" where pa.id=any(")
|
||||
@@ -85,6 +87,7 @@ pub(crate) async fn provider_account_usage(
|
||||
authentication_kind: get(&row, "authentication_kind")?,
|
||||
name: get(&row, "name")?,
|
||||
email: get(&row, "email")?,
|
||||
platform_icon: get(&row, "platform_icon")?,
|
||||
notes: get(&row, "notes")?,
|
||||
plan_type: get(&row, "plan_type")?,
|
||||
request_count: state.count("completed_request_count"),
|
||||
|
||||
@@ -136,6 +136,7 @@ pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||
mr.provider_kind, mr.provider_account_ref,
|
||||
mr.provider_account_name_snapshot as provider_account_name,
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
(select a.platform_icon from provider_accounts a where a.id = mr.provider_account_ref) as platform_icon,
|
||||
mr.provider_account_notes_snapshot as provider_account_notes,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
|
||||
@@ -343,13 +343,13 @@ impl AccountStore for PgAdminAccountStore {
|
||||
let item_ids = page
|
||||
.accounts
|
||||
.iter()
|
||||
.map(|account| account.id.clone())
|
||||
.map(|(account, _)| account.id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut groups_by_account = self.account_groups_by_account(&item_ids).await?;
|
||||
let items = page
|
||||
.accounts
|
||||
.into_iter()
|
||||
.map(|summary| {
|
||||
.map(|(summary, platform_icon)| {
|
||||
let account_id = summary.id.clone();
|
||||
let projection = account_status_projection(
|
||||
&summary,
|
||||
@@ -359,6 +359,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
let mut account = admin_account_record(summary)?;
|
||||
account.groups = groups_by_account.remove(&account_id).unwrap_or_default();
|
||||
Ok(AccountPageItem {
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
.get(&account.id)
|
||||
@@ -404,9 +405,9 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.await?;
|
||||
let mut account = admin_account_record(record.summary)?;
|
||||
account.groups = groups.remove(&account_id).unwrap_or_default();
|
||||
let default_concurrency: i64 = sqlx::query_scalar(
|
||||
"select max_concurrent_per_account from runtime_settings where id = 1",
|
||||
)
|
||||
let (default_concurrency, platform_icon): (i64, Option<String>) = sqlx::query_as(
|
||||
"select s.max_concurrent_per_account, (select a.platform_icon from provider_accounts a where a.id = $1) from runtime_settings s where s.id = 1",
|
||||
).bind(&account_id)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
@@ -423,6 +424,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
)
|
||||
})?;
|
||||
Ok(Some(AccountPageItem {
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
.get(&account_id)
|
||||
@@ -675,6 +677,9 @@ impl AccountStore for PgAdminAccountStore {
|
||||
if command.outbound_proxy.is_some() {
|
||||
changed_fields.push("outbound_proxy".to_owned());
|
||||
}
|
||||
if command.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if command.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
@@ -689,6 +694,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
quota_settings: None,
|
||||
auto_use_quota_credits: None,
|
||||
name: command.name,
|
||||
platform_icon: command.platform_icon,
|
||||
notes: command.notes,
|
||||
enabled: Some(command.enabled),
|
||||
concurrency_limit: Some(command.concurrency_limit),
|
||||
@@ -800,6 +806,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
quota_settings: command.quota_settings,
|
||||
auto_use_quota_credits: command.auto_use_quota_credits,
|
||||
name: None,
|
||||
platform_icon: None,
|
||||
notes: None,
|
||||
enabled: command.enabled,
|
||||
concurrency_limit: command.concurrency_limit,
|
||||
@@ -944,6 +951,9 @@ pub(super) fn prepare_import(
|
||||
if let Some(settings) = &settings {
|
||||
changed_fields
|
||||
.extend(["enabled", "concurrency_limit", "weight", "group_ids"].map(str::to_owned));
|
||||
if settings.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if settings.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
@@ -1038,6 +1048,9 @@ pub(super) fn prepare_rotation(
|
||||
if settings.outbound_proxy.is_some() {
|
||||
changed_fields.push("outbound_proxy".to_owned());
|
||||
}
|
||||
if settings.platform_icon.is_some() {
|
||||
changed_fields.push("platform_icon".to_owned());
|
||||
}
|
||||
if settings.notes.is_some() {
|
||||
changed_fields.push("notes".to_owned());
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::*;
|
||||
pub(crate) struct AdminAccountPageRows {
|
||||
pub(crate) config_revision: AdminRevision,
|
||||
pub(crate) default_concurrency: u64,
|
||||
pub(crate) accounts: Vec<ProviderAccountSummary>,
|
||||
pub(crate) accounts: Vec<(ProviderAccountSummary, Option<String>)>,
|
||||
pub(crate) total: u64,
|
||||
pub(crate) summary: AccountSummary,
|
||||
}
|
||||
@@ -105,7 +105,7 @@ pub(crate) async fn load_admin_account_page(
|
||||
from runtime_settings
|
||||
where id = 1
|
||||
)
|
||||
select coalesce(p.enabled, true) as outbound_proxy_enabled, coalesce(p.max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_id, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.email, a.upstream_user_id,
|
||||
select coalesce(p.enabled, true) as outbound_proxy_enabled, coalesce(p.max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_id, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.platform_icon as platform_icon, a.email, a.upstream_user_id,
|
||||
a.upstream_account_id, a.plan_type, a.authentication_kind,
|
||||
a.credential_revision, a.has_refresh_token, a.access_token_expires_at,
|
||||
a.next_refresh_at, a.enabled, a.quota_settings, a.quota_paused, a.auto_use_quota_credits, a.concurrency_limit, a.weight, a.model_access_json,
|
||||
@@ -201,7 +201,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
.flatten()
|
||||
.map(|_| row)
|
||||
})
|
||||
.map(account_summary_from_row)
|
||||
.map(|row| {
|
||||
let icon = get(&row, "platform_icon")?;
|
||||
Ok((account_summary_from_row(row)?, icon))
|
||||
})
|
||||
.collect::<StoreResult<Vec<_>>>()
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
Ok(AdminAccountPageRows {
|
||||
|
||||
@@ -570,6 +570,7 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
set_platform_icon(&mut transaction, &command.account_ids, command.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = command.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(
|
||||
&mut transaction,
|
||||
@@ -685,6 +686,21 @@ async fn update_provider_account_name_in_transaction(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_platform_icon(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
ids: &[String],
|
||||
icon: Option<&str>,
|
||||
) -> StoreResult<()> {
|
||||
let Some(icon) = icon else { return Ok(()) };
|
||||
sqlx::query("update provider_accounts set platform_icon = nullif($2, '') where id = any($1)")
|
||||
.bind(ids)
|
||||
.bind(icon)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("set account platform icon", source))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_provider_account_notes_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
account_ids: &[String],
|
||||
@@ -1165,6 +1181,7 @@ pub(super) async fn import_provider_accounts_in_transaction(
|
||||
&settings.group_ids,
|
||||
)
|
||||
.await?;
|
||||
set_platform_icon(transaction, &unique_ids, settings.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = settings.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(transaction, &unique_ids, notes).await?;
|
||||
}
|
||||
@@ -1236,6 +1253,7 @@ pub(super) async fn rotate_provider_account_admin_in_transaction(
|
||||
.await?;
|
||||
replace_account_group_assignments_in_transaction(transaction, ids, &settings.group_ids)
|
||||
.await?;
|
||||
set_platform_icon(transaction, ids, settings.platform_icon.as_deref()).await?;
|
||||
if let Some(notes) = settings.notes.as_deref() {
|
||||
update_provider_account_notes_in_transaction(transaction, ids, notes).await?;
|
||||
}
|
||||
|
||||
@@ -252,6 +252,7 @@ impl fmt::Debug for RotateProviderAccount {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BatchUpdateProviderAccountsAdmin {
|
||||
pub platform_icon: Option<String>,
|
||||
pub pauses: gateway_admin::model::accounts::PreparedQuotaPauses,
|
||||
pub quota_settings: Option<gateway_core::account::AccountQuotaSettings>,
|
||||
pub auto_use_quota_credits: Option<bool>,
|
||||
|
||||
@@ -542,7 +542,7 @@ impl ProxyStore for PgProxyRepository {
|
||||
})
|
||||
})?;
|
||||
let mut items = sqlx::query(
|
||||
"select id, name, email, provider_kind, authentication_kind, plan_type, enabled from provider_accounts
|
||||
"select id, name, email, provider_kind, authentication_kind, plan_type, enabled, a.platform_icon as platform_icon from provider_accounts a
|
||||
where outbound_proxy_id = $1 and (strpos(lower(name), lower($2)) > 0
|
||||
or strpos(lower(coalesce(email, '')), lower($2)) > 0)
|
||||
order by name, id limit $3 offset $4",
|
||||
@@ -557,6 +557,7 @@ impl ProxyStore for PgProxyRepository {
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
Ok(ProxyAccountRef {
|
||||
platform_icon: row.try_get("platform_icon").map_err(|source| invalid().with_source(source))?,
|
||||
upstream: None,
|
||||
id: row.try_get("id").map_err(|source| invalid().with_source(source))?,
|
||||
name: row.try_get("name").map_err(|source| invalid().with_source(source))?,
|
||||
|
||||
@@ -395,7 +395,7 @@ async fn health_counters_match_for_rollups_and_facts_without_counting_recovery_o
|
||||
("health_recovered", "failed", 502),
|
||||
] {
|
||||
seed(&database.pool, id, start + TimeDelta::minutes(5), &[]).await;
|
||||
sqlx::query("update model_requests set outcome=$2,client_status_code=$3 where id=$1")
|
||||
sqlx::query("update model_requests set outcome=$2,client_status_code=$3,provider_kind=case when $1='health_success' then 'xai' else 'openai' end where id=$1")
|
||||
.bind(id)
|
||||
.bind(outcome)
|
||||
.bind(status)
|
||||
@@ -459,6 +459,7 @@ async fn health_counters_match_for_rollups_and_facts_without_counting_recovery_o
|
||||
assert_eq!(diagnostic.total_request_count, 5);
|
||||
assert_eq!(diagnostic.items.len(), 1);
|
||||
let counts = &diagnostic.items[0];
|
||||
assert_eq!(counts.providers, ["openai", "xai"]);
|
||||
assert_eq!(
|
||||
(
|
||||
counts.request_count,
|
||||
|
||||
@@ -31,6 +31,7 @@ async fn import_name_only_overrides_a_single_account_and_keeps_batch_names() {
|
||||
.import_provider_accounts(ImportProviderAccounts {
|
||||
outbound_proxy: None,
|
||||
settings: Some(AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: name.map(str::to_owned),
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -769,3 +770,166 @@ async fn reset_credit_automation_persists_pending_checks_cas_and_follows_account
|
||||
);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn platform_icon_is_owned_by_account_and_survives_credential_changes() {
|
||||
use gateway_admin::model::accounts::AccountImportSettings;
|
||||
|
||||
let Some(database) = TestDatabase::create("account_icon").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let api_account = |id: &str, identity: &str| {
|
||||
let mut record = account(id, identity);
|
||||
record.authentication_kind = "api_key".to_owned();
|
||||
record.provider_credentials_json = JsonObject::try_from_value(
|
||||
"provider_credentials_json",
|
||||
serde_json::json!({
|
||||
"base_url": "https://example.invalid/v1",
|
||||
"api_key": "test-key"
|
||||
}),
|
||||
256 * 1024,
|
||||
)
|
||||
.unwrap();
|
||||
record
|
||||
};
|
||||
for id in ["acct_first", "acct_second"] {
|
||||
repository
|
||||
.insert_provider_account(api_account(id, id))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let store = admin_account_store(&database.pool);
|
||||
let context = MutationContext {
|
||||
actor: MutationActor::System,
|
||||
request_id: "account-icon".to_owned(),
|
||||
};
|
||||
let mut edit = UpdateAccount {
|
||||
account_id: "acct_first".to_owned(),
|
||||
platform_icon: Some("DeepSeek".to_owned()),
|
||||
name: None,
|
||||
notes: None,
|
||||
enabled: true,
|
||||
concurrency_limit: None,
|
||||
weight: gateway_core::account::AccountWeight::DEFAULT,
|
||||
model_access: None,
|
||||
group_ids: vec![],
|
||||
outbound_proxy: None,
|
||||
};
|
||||
let icon_for = async |id: &str| {
|
||||
store
|
||||
.load_account(id, AccountRuntimeSnapshot::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.platform_icon
|
||||
};
|
||||
store.update_account(edit.clone(), &context).await.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
assert!(icon_for("acct_second").await.is_none());
|
||||
edit.account_id = "acct_second".to_owned();
|
||||
edit.platform_icon = Some("Claude".to_owned());
|
||||
store.update_account(edit.clone(), &context).await.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
// 省略整份设置或仅省略图标,都保留已有账号的选择;新账号不继承同地址图标
|
||||
for (index, settings) in [
|
||||
None,
|
||||
Some(AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
enabled: true,
|
||||
concurrency_limit: None,
|
||||
weight: gateway_core::account::AccountWeight::DEFAULT,
|
||||
model_access: None,
|
||||
group_ids: vec![],
|
||||
}),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
repository
|
||||
.import_provider_accounts(ImportProviderAccounts {
|
||||
outbound_proxy: None,
|
||||
settings,
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned(),
|
||||
},
|
||||
accounts: vec![
|
||||
api_account("acct_candidate", "acct_first"),
|
||||
api_account("acct_new", "acct_new"),
|
||||
],
|
||||
audit: audit(
|
||||
&format!("audit_icon_import_{index}"),
|
||||
"import",
|
||||
"provider_accounts",
|
||||
),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
assert!(icon_for("acct_new").await.is_none());
|
||||
}
|
||||
let mut credential = credential_update("acct_first", 3, "rotated");
|
||||
credential.provider_credentials_json = JsonObject::try_from_value(
|
||||
"provider_credentials_json",
|
||||
serde_json::json!({
|
||||
"base_url": "https://other.example.invalid/v2",
|
||||
"api_key": "rotated-key"
|
||||
}),
|
||||
256 * 1024,
|
||||
)
|
||||
.unwrap();
|
||||
repository
|
||||
.rotate_provider_account(RotateProviderAccount {
|
||||
settings: None,
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned(),
|
||||
},
|
||||
profile: profile("acct_first", "first"),
|
||||
replacement_identity: None,
|
||||
credential,
|
||||
audit: audit("audit_icon_rotate", "rotate", "acct_first"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
edit.account_id = "acct_first".to_owned();
|
||||
edit.platform_icon = Some("Gemini".to_owned());
|
||||
let before = repository
|
||||
.load_provider_account("acct_first")
|
||||
.await
|
||||
.unwrap();
|
||||
// 审计失败发生在图标写入之后,凭据和图标必须一起回滚
|
||||
assert!(
|
||||
repository
|
||||
.rotate_provider_account(RotateProviderAccount {
|
||||
settings: Some(edit.clone()),
|
||||
scope: ProviderAccountAdminScope {
|
||||
provider_kind: "openai".to_owned()
|
||||
},
|
||||
profile: profile("acct_first", "failed"),
|
||||
replacement_identity: None,
|
||||
credential: credential_update("acct_first", 4, "failed"),
|
||||
audit: audit("audit_icon_rotate", "rotate", "acct_first"),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
repository
|
||||
.load_provider_account("acct_first")
|
||||
.await
|
||||
.unwrap(),
|
||||
before
|
||||
);
|
||||
assert_eq!(icon_for("acct_first").await.as_deref(), Some("DeepSeek"));
|
||||
|
||||
edit.platform_icon = Some(String::new());
|
||||
store.update_account(edit, &context).await.unwrap();
|
||||
assert!(icon_for("acct_first").await.is_none());
|
||||
assert_eq!(icon_for("acct_second").await.as_deref(), Some("Claude"));
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
@@ -426,6 +426,7 @@ async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_e
|
||||
)),
|
||||
);
|
||||
let rename = UpdateAccount {
|
||||
platform_icon: None,
|
||||
account_id: id.to_string(),
|
||||
name: Some("renamed team".to_owned()),
|
||||
notes: None,
|
||||
|
||||
@@ -472,6 +472,7 @@ async fn profile_changes_survive_inflight_background_and_manual_token_refresh()
|
||||
admin_account_store(&database.pool)
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
account_id: id.to_string(),
|
||||
name: Some("renamed team".to_owned()),
|
||||
notes: None,
|
||||
@@ -1284,6 +1285,7 @@ async fn terminal_admin_mutations_keep_revision_account_and_audit_atomic() {
|
||||
let result = store
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -1373,6 +1375,7 @@ async fn account_proxy_edits_preserve_credentials_and_clear_egress_without_audit
|
||||
request_id: "proxy-edit".to_owned(),
|
||||
};
|
||||
let command = UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -1450,6 +1453,7 @@ async fn account_rename_preserves_facts_and_is_searchable() {
|
||||
request_id: "rename-account".to_owned(),
|
||||
};
|
||||
let command = UpdateAccount {
|
||||
platform_icon: None,
|
||||
account_id: "acct_rename".to_owned(),
|
||||
name: Some(" 研发团队 ".to_owned()),
|
||||
notes: None,
|
||||
@@ -1557,6 +1561,7 @@ async fn account_notes_round_trip_and_survive_import_and_scheduling_updates() {
|
||||
request_id: "notes-edit".to_owned(),
|
||||
};
|
||||
let command = UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
account_id: "acct_notes".to_owned(),
|
||||
notes: Some(" 团队备用\n下月续费 ".to_owned()),
|
||||
@@ -1640,6 +1645,7 @@ async fn account_notes_round_trip_and_survive_import_and_scheduling_updates() {
|
||||
},
|
||||
accounts: vec![account("acct_notes", "notes-user")],
|
||||
settings: Some(gateway_admin::model::accounts::AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
enabled: true,
|
||||
@@ -1711,6 +1717,7 @@ async fn invalid_account_notes_roll_back_scheduling_revision_and_audit() {
|
||||
let result = admin_account_store(&database.pool)
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
account_id: "acct_notes".to_owned(),
|
||||
notes: Some("备".repeat(501)),
|
||||
@@ -2214,6 +2221,7 @@ async fn authorization_create_returns_existing_account_id_when_identity_is_upser
|
||||
)
|
||||
.unwrap(),
|
||||
settings: Some(gateway_admin::model::accounts::AccountImportSettings {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: Some(" OAuth 新建备注 ".to_owned()),
|
||||
model_access: Default::default(),
|
||||
@@ -2750,6 +2758,7 @@ async fn provider_account_admin_mutations_are_scoped_audited_and_atomic() {
|
||||
|
||||
let revision = repository
|
||||
.batch_update_provider_accounts_admin(BatchUpdateProviderAccountsAdmin {
|
||||
platform_icon: None,
|
||||
pauses: Default::default(),
|
||||
quota_settings: None,
|
||||
auto_use_quota_credits: None,
|
||||
@@ -2822,6 +2831,7 @@ async fn credential_rotation_and_settings_share_one_transaction() {
|
||||
.await
|
||||
.expect("seed group");
|
||||
let settings = UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: Some(" 团队新名称 ".to_owned()),
|
||||
account_id: ACCOUNT_ID.to_owned(),
|
||||
notes: Some("统一保存".to_owned()),
|
||||
@@ -3608,6 +3618,7 @@ async fn proxy_edit_preserves_an_inflight_token_refresh() {
|
||||
admin_account_store(&database.pool)
|
||||
.update_account(
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
@@ -3667,6 +3678,7 @@ async fn account_import_settings_apply_atomically_to_new_and_existing_identities
|
||||
.await
|
||||
.expect("seed group");
|
||||
let settings = AccountImportSettings {
|
||||
platform_icon: Some("DeepSeek".to_owned()),
|
||||
name: None,
|
||||
notes: Some(" 批量新建\n团队备用 ".to_owned()),
|
||||
model_access: Default::default(),
|
||||
@@ -3693,14 +3705,14 @@ async fn account_import_settings_apply_atomically_to_new_and_existing_identities
|
||||
.expect("import with settings");
|
||||
assert_eq!(result.config_revision.get(), 2);
|
||||
for id in ["acct_new_settings", "acct_existing_settings"] {
|
||||
let row: (bool, Option<i64>, i16) = sqlx::query_as(
|
||||
"select enabled, concurrency_limit, weight from provider_accounts where id = $1",
|
||||
let row: (bool, Option<i64>, i16, Option<String>) = sqlx::query_as(
|
||||
"select enabled, concurrency_limit, weight, platform_icon from provider_accounts where id = $1",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(&database.pool)
|
||||
.await
|
||||
.expect("saved settings");
|
||||
assert_eq!(row, (false, Some(3), 7));
|
||||
assert_eq!(row, (false, Some(3), 7, Some("DeepSeek".to_owned())));
|
||||
assert_eq!(account_group_ids(&database.pool, id).await, [GROUP_ID]);
|
||||
assert_eq!(
|
||||
repository
|
||||
@@ -3727,6 +3739,7 @@ async fn account_import_settings_apply_atomically_to_new_and_existing_identities
|
||||
},
|
||||
AccountImportSettings {
|
||||
notes: Some("备".repeat(501)),
|
||||
platform_icon: Some("Gemini".to_owned()),
|
||||
..settings
|
||||
},
|
||||
] {
|
||||
@@ -3765,6 +3778,16 @@ async fn account_import_settings_apply_atomically_to_new_and_existing_identities
|
||||
account_group_ids(&database.pool, "acct_existing_settings").await,
|
||||
[GROUP_ID]
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, Option<String>>(
|
||||
"select platform_icon from provider_accounts where id = 'acct_existing_settings'"
|
||||
)
|
||||
.fetch_one(&database.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("DeepSeek")
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from admin_audit_events where id = 'audit_import_settings_failed'"
|
||||
|
||||
@@ -429,6 +429,7 @@ fn success() -> ProxyTestResult {
|
||||
|
||||
fn update(account_id: &str, selection: AccountProxySelection) -> UpdateAccount {
|
||||
UpdateAccount {
|
||||
platform_icon: None,
|
||||
name: None,
|
||||
notes: None,
|
||||
model_access: Default::default(),
|
||||
|
||||
@@ -635,6 +635,10 @@ async fn diagnostics_should_fallback_to_name_then_ref_for_missing_snapshots() {
|
||||
.expect("insert legacy request without live account");
|
||||
finalize_request(&database.pool, "req_snap_legacy", started_at).await;
|
||||
|
||||
sqlx::query("update provider_accounts set platform_icon='Adobe' where id='acct_snap_c'")
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let repository = observability_repository(&database.pool);
|
||||
super::drain_analytics(&database.pool).await;
|
||||
let diagnostics = repository
|
||||
@@ -647,6 +651,13 @@ async fn diagnostics_should_fallback_to_name_then_ref_for_missing_snapshots() {
|
||||
.await
|
||||
.expect("account diagnostics")
|
||||
.items;
|
||||
for row in &diagnostics {
|
||||
assert_eq!(row.providers, ["openai"]);
|
||||
assert_eq!(
|
||||
row.platform_icon.as_deref(),
|
||||
(row.key == "acct_snap_c").then_some("Adobe")
|
||||
);
|
||||
}
|
||||
let by_key = diagnostics
|
||||
.iter()
|
||||
.map(|item| (item.key.as_str(), item.name.as_str()))
|
||||
|
||||
@@ -403,6 +403,16 @@ async fn empty_native_history_still_shows_aggregates_and_bad_values_return_error
|
||||
.request_count,
|
||||
7
|
||||
);
|
||||
let models = repo
|
||||
.usage_diagnostics(
|
||||
range,
|
||||
NativeFilter::default(),
|
||||
gateway_store::postgres::DiagnosticDimension::Model,
|
||||
10,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(models.items[0].providers, ["openai"]);
|
||||
store
|
||||
.write_aggregates(aggregates(vec![contribution("only", i64::MIN, 90, "1")]))
|
||||
.await
|
||||
|
||||
@@ -48,3 +48,4 @@ e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_a
|
||||
709df48f4dd067332177fb8bee15c5e75d4666a0dc9c7a8e48f8480a01a99908 0048_openai_runtime_settings.sql
|
||||
44a24ba1bab7630881b4eeac66806231d3a7040dd72a99b0475e1a0f20cfc540 0049_client_key_validity_and_proxy_test_targets.sql
|
||||
c62495a0aff26b149381370fe1eea656091ab8d9d7d55aee27be4f56d5885fd3 0050_prompt_rewrite_rules.sql
|
||||
c4cc50c137deabae7895b97a8a8681c618f2b856276455d591475a02956ee373 0051_account_platform_icons.sql
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- 账号独立选择展示图标,未设置时使用 Provider 默认图标
|
||||
alter table provider_accounts add column platform_icon text;
|
||||
+9
-4
@@ -732,14 +732,14 @@ WebSocket 在交付业务事件前合成的错误保留已确认的失败状态
|
||||
|
||||
### 模型目录
|
||||
|
||||
携带 `anthropic-version` 或 `x-api-key` 请求头时,`GET /v1/models` 返回 Messages 模型目录:
|
||||
携带 `anthropic-version` 请求头时,`GET /v1/models` 返回 Messages 模型目录:
|
||||
`{ data, first_id, last_id, has_more }`,单条模型使用 `type: "model"`、`id`、`display_name` 和 `created_at`
|
||||
列表与详情只展示当前 Key 的账号能通过 Messages 调用的模型及其别名。未知发布日期使用 Unix epoch,未知能力和 Token 上限为 null
|
||||
|
||||
该格式支持 `after_id`、`before_id` 游标和 `limit`,默认每页 20 条,范围 1–1000;未知游标或无效限制返回 400
|
||||
`GET /v1/models/{model_id}` 使用同一显式协议头选择格式和错误合同,不根据 User-Agent 猜测协议
|
||||
|
||||
使用 Bearer Key 并省略上述协议头时,`GET /v1/models` 返回 OpenAI 兼容列表 `{"object": "list", "data": [...]}`。混合分组得到当前 Key 可见的各平台模型并集,同名 ID 只出现一次。
|
||||
未携带 `anthropic-version` 时,`GET /v1/models` 返回 OpenAI 兼容列表 `{"object": "list", "data": [...]}`。`Authorization` 和 `x-api-key` 仅用于鉴权,不选择目录协议。混合分组得到当前 Key 可见的各平台模型并集,同名 ID 只出现一次。
|
||||
携带非空 `client_version` 查询参数时,返回 Codex 专用目录 `{"models": [...]}`
|
||||
|
||||
OpenAI Provider 使用后台按账号发现的目录,客户端版本只选择输出格式。目录完整保留每个原生模型 JSON 对象,包括
|
||||
@@ -1746,7 +1746,7 @@ Token 与模型用量共用该范围,上游额度快照缺失时仍可展示
|
||||
|
||||
RT-only 使用同一形状,只提交 `refreshToken`。不得把真实 token 写入日志、issue、fixture 或文档
|
||||
|
||||
账号导入与首次 OAuth complete 可附带 `settings: { enabled, concurrencyLimit, weight, groupIds, name?, notes?, modelAccess? }`。
|
||||
账号导入与首次 OAuth complete 可附带 `settings: { enabled, concurrencyLimit, weight, groupIds, name?, notes?, modelAccess?, platformIcon? }`。
|
||||
提供 `settings` 时前四项均必填,`concurrencyLimit: null` 继承运行参数,否则为 1–4294967295 的整数;
|
||||
`weight` 为 1–100,`groupIds` 为完整分组集合。设置应用于本次导入的全部账号,包括匹配到的已有账号,
|
||||
与凭据在同一事务内提交;分组不存在时整次回滚。省略 `settings` 时新账号使用默认设置并保持未分组,
|
||||
@@ -1757,6 +1757,10 @@ RT-only 使用同一形状,只提交 `refreshToken`。不得把真实 token
|
||||
省略、`null`、留空或多账号导入均保留导入数据或服务商提供的名称;管理端批量导入不提交 `name`。
|
||||
API Key 账号未指定名称时默认使用「密钥账号」
|
||||
|
||||
账号可在导入、首次 OAuth complete 的 `settings.platformIcon` 或编辑的 `platformIcon` 选择管理端内置的单色品牌图标(例如 `DeepSeek`)。
|
||||
选择仅作用于本次操作的账号,与上游地址无关。省略字段或 `null` 保留已有选择,新账号使用默认图标;空字符串恢复 Provider 默认图标。
|
||||
连接变更、凭据刷新和重新授权保留账号图标。账号列表和详情的 `platformIcon` 返回当前选择,默认时为 `null`
|
||||
|
||||
账号列表的每个 item 返回轻量 `groups: [{ id, name, enabled }]`
|
||||
|
||||
内置 Provider 的账号导出统一使用 `label` 表示本地名称,名称为空时省略;本地创建与更新时间使用
|
||||
@@ -3167,7 +3171,8 @@ Antigravity 的展示名取自请求时已观测到的 Google 套餐描述,快
|
||||
### 卡片洞察查询
|
||||
|
||||
请求健康、响应性能、成本效率与热点诊断分别查询自己的路由;性能和成本按选中的 `metric` 查询,诊断按 `dimension` 查询。
|
||||
各分项接口均支持时间范围和平台筛选。
|
||||
各分项接口均支持时间范围和平台筛选。诊断的 `provider` 维度按实际路由平台分组;
|
||||
模型项的 `providers` 列出当前筛选范围内出现的平台,同名模型合并为一行。账号项返回所属平台和当前自定义图标 `platformIcon`,未设置时使用平台默认图标。
|
||||
`overview` 返回完整洞察,管理端卡片使用分项接口
|
||||
|
||||
健康、性能与成本接口返回 `analytics`、`granularity`、`metric` 和 `data`。
|
||||
|
||||
@@ -398,6 +398,8 @@ views/<页面>/
|
||||
|
||||
账号页管理分组、模型限制、并发、代理与导入任务。行操作与批量导出读取服务端返回的账号能力。OpenAI 的 API Key、OAuth 传输与逐条 token 导入归 `providers/openai/accounts`,Provider 表单持有凭据草稿与校验规则。新增时向页面提交导入文档,编辑时仅提供变更的连接配置
|
||||
|
||||
账号图标字段 `components/PlatformIconField.vue` 组合品牌目录与 Provider 默认图标;搜索、网格选择、键盘交互和表单状态由 UI 库的 `ZIconPicker` 管理
|
||||
|
||||
运行设置由同一份草稿和配置版本原子保存。通用和平台设置分区组合 `views/settings/components/` 中的控件,备份、定价、客户端版本及隐私规则等多文件组件各自封装私有实现。平台分区按 Provider 展示专属配置,通用分区承载提示词改写、调度、并发与排队、重试、错误保护、凭据刷新、历史保留、全局模型映射及安全与访问设置
|
||||
|
||||
全局配置和 Key 覆盖共用 `components/request-profile/index.vue` 的身份编辑流程,各 Provider 在 `providers/<id>/request-profile/` 解释自己的配置字段。定价页按查询接口返回的档位编辑
|
||||
@@ -642,6 +644,8 @@ OpenAI 的 OAuth 与 API Key 共用现有账号和事务。API Key 的 Base URL
|
||||
标准 `data` 模型列表通过通用画像输出,完整 Codex `models` 目录保留原生对象。通用账号层按 Provider 提交的
|
||||
credential state 调度,不以是否存在上游用户 ID 推断可用性;OAuth 未完成身份投影时由 Provider 保持 `unknown`。
|
||||
状态恢复和未补齐身份的凭据轮换保留 `unknown`。
|
||||
账号图标是通用展示设置,保存在 `provider_accounts.platform_icon`,由账号导入和编辑事务写入。
|
||||
未设置时显示 Provider 默认图标;连接地址、凭据刷新与重新授权不改变选择,Provider 和插件凭据合同不承载图标设置。
|
||||
API Key 默认使用 Responses 协议和 HTTP/SSE,Responses 可选 WS 优先,Messages 只支持 HTTP。
|
||||
协议和传输资格在选号阶段验证,WS pool 与 continuation 按凭据版本隔离。
|
||||
Responses API Key 与 OAuth 共用原生请求与响应链路;Messages API Key 使用独立 HTTP transport,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Plugin } from 'vite'
|
||||
import { mkdirSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { toc } from '@lobehub/icons-vue/es/toc'
|
||||
|
||||
export function platformIcons(): Plugin {
|
||||
const id = 'virtual:platform-icons'
|
||||
const fileName = 'platform-icons.json'
|
||||
const source = JSON.stringify(toc.map(item => item.id))
|
||||
return {
|
||||
name: 'platform-icons',
|
||||
configureServer(server) {
|
||||
// 独立启动的开发网关也从部署约定的静态目录校验选择
|
||||
const directory = join(server.config.root, 'dist')
|
||||
mkdirSync(directory, { recursive: true })
|
||||
writeFileSync(join(directory, fileName), source)
|
||||
},
|
||||
resolveId(source) {
|
||||
if (source === id)
|
||||
return `\0${id}`
|
||||
},
|
||||
load(source) {
|
||||
if (source !== `\0${id}`)
|
||||
return
|
||||
const entries = toc.map(({ id: name, fullTitle }) =>
|
||||
`${JSON.stringify(name)}: { label: ${JSON.stringify(fullTitle)}, load: () => import(${JSON.stringify(`@lobehub/icons-vue/es/${name}/components/Mono`)}) }`,
|
||||
)
|
||||
return `export default { ${entries.join(',')} }`
|
||||
},
|
||||
generateBundle() {
|
||||
// 同一批实际打包的单色图标供管理 API 校验
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName,
|
||||
source,
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
Vendored
+5
@@ -7,3 +7,8 @@ declare module 'virtual:plugin-bridge-source' {
|
||||
const source: string
|
||||
export default source
|
||||
}
|
||||
|
||||
declare module 'virtual:platform-icons' {
|
||||
const icons: Record<string, { label: string, load: () => Promise<{ default: import('vue').Component }> }>
|
||||
export default icons
|
||||
}
|
||||
|
||||
@@ -16,10 +16,10 @@
|
||||
"build:source": "vue-tsc -p tsconfig.source.json --noEmit && vite build --mode source"
|
||||
},
|
||||
"dependencies": {
|
||||
"@boxicons/vue": "1.0.1",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.6",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.14.0",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lobehub/icons-vue": "1.2.0",
|
||||
"@lucide/vue": "^1.77.0",
|
||||
"@vueuse/core": "^15.0.0",
|
||||
"@vueuse/integrations": "^15.0.0",
|
||||
|
||||
Generated
+19
-18
@@ -191,18 +191,18 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@boxicons/vue':
|
||||
specifier: 1.0.1
|
||||
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
|
||||
'@codex-proxy/ui':
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.6
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/0a24a90657b6c7957e736c24f37911e87576aa7c(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.14.0
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/5754b9b13efd6d7e6d97b7c21e7d67c00c7c32a6(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
'@fontsource-variable/inter':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@fontsource-variable/jetbrains-mono':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@lobehub/icons-vue':
|
||||
specifier: 1.2.0
|
||||
version: 1.2.0(vue@3.5.46(typescript@6.0.3))
|
||||
'@lucide/vue':
|
||||
specifier: ^1.77.0
|
||||
version: 1.77.0(vue@3.5.46(typescript@6.0.3))
|
||||
@@ -437,11 +437,6 @@ packages:
|
||||
resolution: {integrity: sha512-c+xgSWboV2pdwXP67BUWDVRHi2BO5Q3KwxyFVs7taVTY+fsK47/L51ZXQoV9rozHJDNHvJ4v4WEsI/IlxV2l2A==}
|
||||
engines: {node: ^22.18.0 || >=24.11.0}
|
||||
|
||||
'@boxicons/vue@1.0.1':
|
||||
resolution: {integrity: sha512-eZKXfR0oQTq06MJAEgvGqx1Oi9aLNfqVFdEDY4YWEN3AVf167WY9OH5wMjRDVL1mn3GgplpdmPEIe+Sj7/A3PQ==}
|
||||
peerDependencies:
|
||||
vue: '>=3.0.0'
|
||||
|
||||
'@cacheable/memory@2.2.0':
|
||||
resolution: {integrity: sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==}
|
||||
|
||||
@@ -456,9 +451,9 @@ packages:
|
||||
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
|
||||
engines: {node: '>= 20.12.0'}
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/0a24a90657b6c7957e736c24f37911e87576aa7c':
|
||||
resolution: {gitHosted: true, integrity: sha512-Xv/1yz01IBSJK098vSrWPqg/gJoxd3H7Y8lS9wHTIGKyQ3FpOHyXxgbXGGc9GMw9fmAwELr50I5Yfg9zLA/PqA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/0a24a90657b6c7957e736c24f37911e87576aa7c}
|
||||
version: 0.13.6
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/5754b9b13efd6d7e6d97b7c21e7d67c00c7c32a6':
|
||||
resolution: {gitHosted: true, integrity: sha512-eiuhv7/uduqj701lyZEmiSOuZISyRFPsjKAFmsK0cYVASbK3weCSQAuaVAK6fthvVeECtI57jCNG5KTTL+PNpg==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/5754b9b13efd6d7e6d97b7c21e7d67c00c7c32a6}
|
||||
version: 0.14.0
|
||||
engines: {node: '>=24'}
|
||||
peerDependencies:
|
||||
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
@@ -880,6 +875,11 @@ packages:
|
||||
'@keyv/serialize@1.1.1':
|
||||
resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==}
|
||||
|
||||
'@lobehub/icons-vue@1.2.0':
|
||||
resolution: {integrity: sha512-ke6VQK3awjrPlQlf6Ko5SHRjCWYBv70pycwrbV/iNAUg3kfK6NyvmooulDY0PkItbg6W7iqiRjGCwwb0vMfdXQ==}
|
||||
peerDependencies:
|
||||
vue: ^3.5.0
|
||||
|
||||
'@lucide/vue@1.77.0':
|
||||
resolution: {integrity: sha512-B+okr/d8qC2imLzNPJ5tW8Nf7uKC19DgiOafxU0bOMfLnkd5Tkss4GW640+s5FierTJjgl99LpuO40u+yni0qQ==}
|
||||
peerDependencies:
|
||||
@@ -3562,10 +3562,6 @@ snapshots:
|
||||
'@babel/helper-string-parser': 8.0.6
|
||||
'@babel/helper-validator-identifier': 8.0.6
|
||||
|
||||
'@boxicons/vue@1.0.1(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
'@cacheable/memory@2.2.0':
|
||||
dependencies:
|
||||
'@cacheable/utils': 2.5.0
|
||||
@@ -3590,7 +3586,7 @@ snapshots:
|
||||
fast-wrap-ansi: 0.2.2
|
||||
sisteransi: 1.0.5
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/0a24a90657b6c7957e736c24f37911e87576aa7c(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/5754b9b13efd6d7e6d97b7c21e7d67c00c7c32a6(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
dependencies:
|
||||
'@ant-design/colors': 8.0.1
|
||||
'@ant-design/fast-color': 3.0.1
|
||||
@@ -4014,6 +4010,11 @@ snapshots:
|
||||
|
||||
'@keyv/serialize@1.1.1': {}
|
||||
|
||||
'@lobehub/icons-vue@1.2.0(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
es-toolkit: 1.53.2
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
'@lucide/vue@1.77.0(vue@3.5.46(typescript@6.0.3))':
|
||||
dependencies:
|
||||
vue: 3.5.46(typescript@6.0.3)
|
||||
|
||||
@@ -43,6 +43,7 @@ export interface AccountOAuthStartResponse {
|
||||
}
|
||||
|
||||
export interface AccountImportSettings {
|
||||
platformIcon?: string
|
||||
name?: string
|
||||
notes?: string
|
||||
enabled: boolean
|
||||
|
||||
@@ -60,6 +60,7 @@ export interface AccountConnectionUpdate {
|
||||
}
|
||||
|
||||
interface AccountUpdateParam {
|
||||
platformIcon?: string
|
||||
connection?: AccountConnectionUpdate
|
||||
outboundProxyId?: string
|
||||
accountId: string
|
||||
|
||||
@@ -145,6 +145,7 @@ export interface AccountQuotaBucketSettings {
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
platformIcon?: string | null
|
||||
quotaSettings: Record<string, AccountQuotaBucketSettings>
|
||||
autoUseQuotaCredits: boolean
|
||||
upstream: AccountUpstream | null
|
||||
|
||||
@@ -141,6 +141,7 @@ export interface DashboardAccountRequestBucket {
|
||||
}
|
||||
|
||||
export interface DashboardAccountUsage {
|
||||
platformIcon?: string | null
|
||||
upstream: AccountUpstream | null
|
||||
id: string
|
||||
provider: string
|
||||
|
||||
@@ -235,6 +235,7 @@ export function getKeyModelTotals(id: string, period: KeyStatisticsPeriod, asOf:
|
||||
}
|
||||
|
||||
export interface BudgetReferenceAccount {
|
||||
platformIcon?: string | null
|
||||
id: string
|
||||
name: string
|
||||
email: string | null
|
||||
|
||||
@@ -48,6 +48,7 @@ interface ProxyPage {
|
||||
}
|
||||
|
||||
export interface OutboundProxyAccount {
|
||||
platformIcon?: string | null
|
||||
upstream: AccountUpstream | null
|
||||
id: string
|
||||
name: string
|
||||
|
||||
@@ -93,6 +93,7 @@ export interface UsageErrorFacts {
|
||||
}
|
||||
|
||||
export interface UsageListRecord extends UsageErrorFacts {
|
||||
platformIcon?: string | null
|
||||
logicalOutcome: string
|
||||
clientStatusCode: number | null
|
||||
upstreamStatusCode: number | null
|
||||
@@ -382,6 +383,8 @@ export type UsageMetricResponse<M extends keyof UsageMetricData> = {
|
||||
}[M]
|
||||
|
||||
export interface UsageDiagnosticItem {
|
||||
providers: string[]
|
||||
platformIcon: string | null
|
||||
key: string
|
||||
name: string
|
||||
authenticationKind: string | null
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { Github } from '@boxicons/vue'
|
||||
import { ZDialog, ZMenuItem } from '@codex-proxy/ui'
|
||||
import { AppWindow } from '@lucide/vue'
|
||||
import { shallowRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
import { platformIcon } from '@/providers/platformIcons'
|
||||
|
||||
const props = defineProps<{ provider?: BuiltinProvider }>()
|
||||
const emit = defineEmits<{
|
||||
@@ -53,7 +53,7 @@ function select() {
|
||||
:aria-label="t('keys.configuration.viewOnGitHub', { name: 'CC Switch' })"
|
||||
class="inline-grid size-9 shrink-0 place-items-center rounded-z-sm text-z-text-tertiary outline-none transition-colors hover:text-z-text focus-visible:ring-2 focus-visible:ring-z-control-outline focus-visible:ring-inset motion-reduce:transition-none"
|
||||
>
|
||||
<Github class="size-6" aria-hidden="true" />
|
||||
<component :is="platformIcon('Github')" class="size-6" aria-hidden="true" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<script setup lang="ts">
|
||||
import { ZFormItem, ZIconPicker } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, providerIcon, providerIconName } from '@/providers/catalog'
|
||||
import { platformIcon, platformIconOptions } from '@/providers/platformIcons'
|
||||
|
||||
const props = defineProps<{ disabled: boolean, provider?: string }>()
|
||||
const model = defineModel<string>()
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const catalog = platformIconOptions.map(option => ({
|
||||
...option,
|
||||
icon: platformIcon(option.value)!,
|
||||
}))
|
||||
const defaultIcon = computed(() => props.provider
|
||||
? providerIconName(props.provider)
|
||||
: undefined)
|
||||
const options = computed(() => props.provider && !defaultIcon.value
|
||||
? [
|
||||
{
|
||||
value: '',
|
||||
label: formatProviderLabel(props.provider),
|
||||
icon: providerIcon(props.provider),
|
||||
},
|
||||
...catalog,
|
||||
]
|
||||
: catalog)
|
||||
// 默认图标是有效展示值,只有用户选择才写入账号覆盖;未知 Provider 的空标识表示跟随默认
|
||||
const selection = computed({
|
||||
get: () => model.value ?? defaultIcon.value ?? (props.provider ? '' : undefined),
|
||||
set: (value: string | undefined) => { model.value = value || undefined },
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZFormItem :label="t('accounts.platformIcon.label')">
|
||||
<ZIconPicker
|
||||
v-model="selection" :options="options" :disabled="disabled" :clearable="model !== undefined"
|
||||
:aria-label="t('accounts.platformIcon.label')"
|
||||
:placeholder="t('accounts.platformIcon.default')"
|
||||
:clear-label="t('accounts.platformIcon.clear')"
|
||||
/>
|
||||
</ZFormItem>
|
||||
</template>
|
||||
@@ -1,12 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { authenticationIcon, formatAuthenticationLabel, formatProviderLabel, providerIcon } from '@/providers/catalog'
|
||||
import { accountPlatform, authenticationIcon, formatAuthenticationLabel } from '@/providers/catalog'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
provider?: string | null
|
||||
platformIcon?: string | null
|
||||
showPlatformLabel?: boolean
|
||||
authenticationKind?: string | null
|
||||
size?: 'xs' | 'sm' | 'md'
|
||||
}>(),
|
||||
@@ -15,37 +16,32 @@ const props = withDefaults(
|
||||
},
|
||||
)
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const normalizedProvider = computed(() => (props.provider ?? '').trim().toLowerCase())
|
||||
const providerIconComponent = computed(() => normalizedProvider.value
|
||||
? providerIcon(normalizedProvider.value)
|
||||
: undefined)
|
||||
const platform = computed(() => accountPlatform(props))
|
||||
const authenticationIconComponent = computed(() => authenticationIcon(props.authenticationKind))
|
||||
const showAuthenticationKind = computed(() => props.authenticationKind !== undefined)
|
||||
const sizeClasses = {
|
||||
xs: { gap: 'gap-0.75', container: 'size-4.5 rounded-md', icon: 'size-2.5' },
|
||||
sm: { gap: 'gap-1', container: 'size-5 rounded-md', icon: 'size-3' },
|
||||
md: { gap: 'gap-2', container: 'size-7 rounded-lg', icon: 'size-4' },
|
||||
md: { gap: 'gap-2', container: 'size-7 rounded-lg', icon: 'size-3.5' },
|
||||
}
|
||||
const classes = computed(() => sizeClasses[props.size])
|
||||
|
||||
const providerLabel = computed(() => formatProviderLabel(props.provider, t('common.providers.unknown')))
|
||||
|
||||
const authenticationLabel = computed(() => formatAuthenticationLabel(props.authenticationKind))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="inline-flex items-center whitespace-nowrap" :class="classes.gap">
|
||||
<span class="inline-flex max-w-full items-center whitespace-nowrap" :class="classes.gap">
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center justify-center bg-z-fill-secondary/80 text-z-text"
|
||||
:class="classes.container"
|
||||
:title="providerLabel"
|
||||
:title="platform.label"
|
||||
>
|
||||
<component :is="providerIconComponent" v-if="providerIconComponent" :class="classes.icon" />
|
||||
<component :is="platform.icon" v-if="platform.icon" :class="classes.icon" />
|
||||
<span v-else class="text-[10px] font-heavy text-z-text-quaternary">?</span>
|
||||
</span>
|
||||
|
||||
<span :class="showPlatformLabel ? 'truncate text-z-sm font-bold text-z-text' : 'sr-only'">{{ platform.label }}</span>
|
||||
|
||||
<span
|
||||
v-if="showAuthenticationKind"
|
||||
class="inline-flex shrink-0 items-center justify-center bg-z-fill-secondary/80 text-z-text"
|
||||
@@ -56,8 +52,6 @@ const authenticationLabel = computed(() => formatAuthenticationLabel(props.authe
|
||||
<span v-else class="text-[10px] font-heavy text-z-text-quaternary">?</span>
|
||||
</span>
|
||||
|
||||
<span class="sr-only">
|
||||
{{ providerLabel }}<template v-if="showAuthenticationKind">,{{ authenticationLabel }}</template>
|
||||
</span>
|
||||
<span v-if="showAuthenticationKind" class="sr-only">,{{ authenticationLabel }}</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
@@ -177,7 +177,7 @@ function addModels(ids: readonly string[]) {
|
||||
}
|
||||
|
||||
function handleSearchEnter(event: KeyboardEvent) {
|
||||
if (event.isComposing)
|
||||
if (event.isComposing || event.keyCode === 229)
|
||||
return
|
||||
event.preventDefault()
|
||||
if (canAdd.value)
|
||||
|
||||
@@ -11,7 +11,6 @@ interface SetupInput {
|
||||
provider: BuiltinProvider
|
||||
apiKey: string
|
||||
root: string
|
||||
windows: boolean
|
||||
websocketEnabled: boolean
|
||||
}
|
||||
|
||||
@@ -50,20 +49,17 @@ image_generation = true
|
||||
goals = true`
|
||||
}
|
||||
|
||||
export function buildClientConfig({ provider, root, apiKey, windows, websocketEnabled }: SetupInput) {
|
||||
const path = (relative: string) => windows
|
||||
? `%USERPROFILE%\\${relative.replaceAll('/', '\\')}`
|
||||
: `~/${relative}`
|
||||
export function buildClientConfig({ provider, root, apiKey, websocketEnabled }: SetupInput) {
|
||||
const baseUrl = `${root}/v1`
|
||||
if (provider === 'openai') {
|
||||
return {
|
||||
title: path('.codex/config.toml'),
|
||||
title: '~/.codex/config.toml',
|
||||
text: buildCodexConfig(apiKey, baseUrl, websocketEnabled),
|
||||
}
|
||||
}
|
||||
if (provider === 'xai') {
|
||||
return {
|
||||
title: path('.grok/config.toml'),
|
||||
title: '~/.grok/config.toml',
|
||||
text: `[models]
|
||||
default = "cpr"
|
||||
|
||||
@@ -76,7 +72,7 @@ api_backend = "responses"`,
|
||||
}
|
||||
|
||||
return {
|
||||
title: path('.gemini/config/config.json'),
|
||||
title: '~/.gemini/config/config.json',
|
||||
text: JSON.stringify({
|
||||
gateway: {
|
||||
enabled: true,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { Apple, MicrosoftWindows, Tux } from '@boxicons/vue'
|
||||
import { ZButton, ZDialog, ZIconButton, ZScrollbar, ZSegmented, ZSwitch } from '@codex-proxy/ui'
|
||||
import { ZButton, ZDialog, ZIconButton, ZScrollbar, ZSwitch } from '@codex-proxy/ui'
|
||||
import { Copy, Upload } from '@lucide/vue'
|
||||
import { computed, shallowRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -16,19 +15,12 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
const showImport = shallowRef(false)
|
||||
const key = computed(() => props.apiKey?.key ?? '')
|
||||
const provider = shallowRef<BuiltinProvider>('openai')
|
||||
const platform = shallowRef('macos')
|
||||
const ws = shallowRef(false)
|
||||
const root = resolveServiceRootUrl()
|
||||
const platformOptions = [
|
||||
{ label: 'macOS', value: 'macos', icon: Apple },
|
||||
{ label: 'Linux', value: 'linux', icon: Tux },
|
||||
{ label: 'Windows', value: 'windows', icon: MicrosoftWindows },
|
||||
]
|
||||
const config = computed(() => buildClientConfig({
|
||||
provider: provider.value,
|
||||
root,
|
||||
apiKey: key.value,
|
||||
windows: platform.value === 'windows',
|
||||
websocketEnabled: ws.value,
|
||||
}))
|
||||
|
||||
@@ -44,24 +36,21 @@ function importToClient() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZDialog v-model="open" destroy-on-close :title="title ?? t('keys.configuration.title')" width="46rem" @close="showImport = false" @closed="emit('closed')">
|
||||
<div class="grid min-w-0 gap-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<ZDialog v-model="open" destroy-on-close :body-scrollable="false" :title="title ?? t('keys.configuration.title')" width="46rem" @close="showImport = false" @closed="emit('closed')">
|
||||
<div class="flex min-h-0 min-w-0 flex-col gap-3">
|
||||
<div class="flex shrink-0 flex-wrap items-center justify-between gap-2">
|
||||
<ProviderSelect v-model="provider" :aria-label="t('keys.configuration.platform')" />
|
||||
<ZSegmented v-model="platform" :aria-label="t('keys.configuration.os')" :options="platformOptions" display="icon" class="w-30 [&_svg]:size-4.5" size="small" />
|
||||
<ZSwitch v-if="provider === 'openai'" v-model="ws" :aria-label="t('keys.configuration.toggleWebSocket')" active-text="WS" inactive-text="WS" inline-prompt :width="56" />
|
||||
</div>
|
||||
<section class="min-w-0 overflow-hidden rounded-z-card bg-z-fill-quaternary">
|
||||
<ZScrollbar max-height="min(58dvh, 34rem)">
|
||||
<div class="mx-3 mb-3 min-w-0">
|
||||
<div class="flex flex-wrap items-center gap-3 py-2">
|
||||
<code class="min-w-0 flex-1 break-all text-z-sm text-z-text-secondary">{{ config.title }}</code>
|
||||
<ZSwitch v-if="provider === 'openai'" v-model="ws" :aria-label="t('keys.configuration.toggleWebSocket')" active-text="WS" inactive-text="WS" inline-prompt :width="56" />
|
||||
<ZIconButton variant="solid" size="small" :disabled="!key" :aria-label="t('common.actions.copy')" @click="emit('copy', config.text)">
|
||||
<Copy class="size-3.5" />
|
||||
</ZIconButton>
|
||||
</div>
|
||||
<pre class="m-0 rounded-z bg-z-bg-container px-3.5 py-3 font-mono text-z-sm leading-relaxed wrap-anywhere whitespace-pre-wrap text-z-text" v-text="config.text" />
|
||||
</div>
|
||||
<section class="flex min-h-0 min-w-0 flex-col overflow-hidden rounded-z-card bg-z-fill-quaternary">
|
||||
<div class="mx-3 flex shrink-0 flex-wrap items-center gap-3 py-2">
|
||||
<code class="min-w-0 flex-1 break-all text-z-sm text-z-text-secondary">{{ config.title }}</code>
|
||||
<ZIconButton variant="solid" size="small" :disabled="!key" :aria-label="t('common.actions.copy')" @click="emit('copy', config.text)">
|
||||
<Copy class="size-3.5" />
|
||||
</ZIconButton>
|
||||
</div>
|
||||
<ZScrollbar max-height="min(58dvh, 34rem)" class="mx-3 mb-3 flex min-h-0 flex-col rounded-z bg-z-bg-container">
|
||||
<pre class="m-0 px-3.5 py-3 font-mono text-z-sm leading-relaxed wrap-anywhere whitespace-pre-wrap text-z-text" v-text="config.text" />
|
||||
</ZScrollbar>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -3,21 +3,24 @@ import type { UsageReasoningRecord } from './presenter'
|
||||
|
||||
import { Bot, SquareDashedBottomCode } from '@lucide/vue'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { usageReasoningEffort } from './presenter'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
record: UsageReasoningRecord
|
||||
}>()
|
||||
|
||||
const effort = computed(() => usageReasoningEffort(props.record))
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
v-if="effort || record.subagentKind"
|
||||
class="inline-flex items-center gap-1 whitespace-nowrap text-z-sm font-bold text-z-text"
|
||||
>
|
||||
<span>{{ usageReasoningEffort(record) }}</span>
|
||||
<span v-if="effort">{{ effort }}</span>
|
||||
<span
|
||||
v-if="record.subagentKind"
|
||||
class="inline-flex shrink-0 text-z-purple-text"
|
||||
|
||||
@@ -58,7 +58,7 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
<template #provider="{ row }">
|
||||
<ProviderIconGroup
|
||||
:provider="String(row.provider || '')"
|
||||
:platform-icon="row.platformIcon" :provider="String(row.provider || '')"
|
||||
:authentication-kind="row.authenticationKind"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -77,10 +77,9 @@ export function usageUserAgent(record: { userAgent?: string | null }) {
|
||||
}
|
||||
|
||||
export function usageReasoningEffort(record: UsageReasoningRecord) {
|
||||
const reasoningEffort = record.reasoningEffort || '—'
|
||||
if (record.subagentKind)
|
||||
return reasoningEffort
|
||||
return record.reasoningPreset || reasoningEffort
|
||||
return record.reasoningEffort
|
||||
return record.reasoningPreset || record.reasoningEffort
|
||||
}
|
||||
|
||||
export function usageModelDisplay(record: UsageModelRecord) {
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
{
|
||||
"accounts": {
|
||||
"platformIcon": {
|
||||
"label": "Account icon",
|
||||
"default": "Default icon",
|
||||
"clear": "Reset to default"
|
||||
},
|
||||
"quotaSettings": {
|
||||
"badge": "Quota paused",
|
||||
"title": "Quota bucket settings",
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
"toggleWebSocket": "Switch WebSocket configuration",
|
||||
"fullApiKeyNotAvailable": "Full API key not available",
|
||||
"title": "Use API key",
|
||||
"os": "Operating system",
|
||||
"importTo": "Import",
|
||||
"selectImportTool": "Choose a tool to import into",
|
||||
"ccSwitchDescription": "Manage AI client configurations",
|
||||
|
||||
@@ -113,7 +113,6 @@
|
||||
"model": "Model",
|
||||
"reasoningEffort": "Effort",
|
||||
"endpoint": "Endpoint",
|
||||
"upstream": "Upstream",
|
||||
"cost": "Cost",
|
||||
"latency": "Latency",
|
||||
"time": "Time",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
{
|
||||
"accounts": {
|
||||
"platformIcon": {
|
||||
"label": "账号图标",
|
||||
"default": "默认图标",
|
||||
"clear": "恢复默认"
|
||||
},
|
||||
"quotaSettings": {
|
||||
"badge": "额度暂停",
|
||||
"title": "额度桶设置",
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
"toggleWebSocket": "切换 WebSocket 配置",
|
||||
"fullApiKeyNotAvailable": "完整 API密钥不可用",
|
||||
"title": "使用密钥",
|
||||
"os": "操作系统",
|
||||
"importTo": "导入到",
|
||||
"selectImportTool": "选择要导入的工具",
|
||||
"ccSwitchDescription": "管理和切换 AI 客户端配置",
|
||||
|
||||
@@ -113,7 +113,6 @@
|
||||
"model": "模型",
|
||||
"reasoningEffort": "推理强度",
|
||||
"endpoint": "端点",
|
||||
"upstream": "上游",
|
||||
"cost": "费用",
|
||||
"latency": "延迟",
|
||||
"time": "时间",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
{
|
||||
"accounts": {
|
||||
"platformIcon": {
|
||||
"label": "帳號圖示",
|
||||
"default": "預設圖示",
|
||||
"clear": "恢復預設"
|
||||
},
|
||||
"quotaSettings": {
|
||||
"badge": "額度暫停",
|
||||
"title": "額度桶設定",
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
"toggleWebSocket": "切換 WebSocket 配置",
|
||||
"fullApiKeyNotAvailable": "完整 API密鑰不可用",
|
||||
"title": "使用密鑰",
|
||||
"os": "作業系統",
|
||||
"importTo": "導入到",
|
||||
"selectImportTool": "選擇要導入的工具",
|
||||
"ccSwitchDescription": "管理和切換 AI 客戶端配置",
|
||||
|
||||
@@ -113,7 +113,6 @@
|
||||
"model": "模型",
|
||||
"reasoningEffort": "推理強度",
|
||||
"endpoint": "端點",
|
||||
"upstream": "上游",
|
||||
"cost": "費用",
|
||||
"latency": "延遲",
|
||||
"time": "時間",
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import type { Component } from 'vue'
|
||||
import { GoogleAntigravity, Key, LinkAlt, Openai, Xai } from '@boxicons/vue'
|
||||
import { Fingerprint, Plug } from '@lucide/vue'
|
||||
import { Fingerprint, Key, Link as LinkIcon, Plug } from '@lucide/vue'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import { platformIcon } from './platformIcons'
|
||||
|
||||
const providers = {
|
||||
openai: { label: 'OpenAI', icon: Openai },
|
||||
antigravity: { label: 'Antigravity', icon: GoogleAntigravity },
|
||||
xai: { label: 'xAI', icon: Xai },
|
||||
openai: { label: 'OpenAI', icon: 'OpenAI' },
|
||||
antigravity: { label: 'Antigravity', icon: 'Antigravity' },
|
||||
xai: { label: 'xAI', icon: 'XAI' },
|
||||
} as const
|
||||
|
||||
export const PROVIDER_IDS = Object.keys(providers) as BuiltinProvider[]
|
||||
@@ -25,11 +26,29 @@ export function formatProviderLabel(value?: string | null, fallback = '—') {
|
||||
: (normalized || fallback)
|
||||
}
|
||||
|
||||
export function providerIcon(value: string): Component {
|
||||
export function providerIconName(value: string) {
|
||||
const id = value.trim().toLowerCase()
|
||||
return isBuiltinProvider(id)
|
||||
? providers[id].icon
|
||||
: Plug
|
||||
: undefined
|
||||
}
|
||||
|
||||
export function providerIcon(value: string): Component {
|
||||
const name = providerIconName(value)
|
||||
return (name && platformIcon(name)) || Plug
|
||||
}
|
||||
|
||||
export function accountPlatform(identity: { provider?: string | null, platformIcon?: string | null }) {
|
||||
const { provider, platformIcon: name } = identity
|
||||
const icon = name && platformIcon(name)
|
||||
if (icon)
|
||||
return { icon, label: name }
|
||||
return {
|
||||
icon: provider?.trim()
|
||||
? providerIcon(provider)
|
||||
: undefined,
|
||||
label: formatProviderLabel(provider, t('common.providers.unknown')),
|
||||
}
|
||||
}
|
||||
|
||||
export function formatAuthenticationLabel(value?: string | null) {
|
||||
@@ -45,7 +64,7 @@ export function formatAuthenticationLabel(value?: string | null) {
|
||||
|
||||
export function authenticationIcon(value?: string | null): Component | undefined {
|
||||
switch (value?.trim().toLowerCase()) {
|
||||
case 'oauth': return LinkAlt
|
||||
case 'oauth': return LinkIcon
|
||||
case 'api_key': return Key
|
||||
case undefined:
|
||||
case '': return undefined
|
||||
|
||||
@@ -37,21 +37,21 @@ function updateProtocol(protocol: string) {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZFormItem prop="connection.base_url" :rules="rules.base_url" :show-message="Boolean(form.base_url.trim())" :label="t('common.fields.baseUrl')" required>
|
||||
<ZFormItem class="col-span-full" prop="connection.base_url" :rules="rules.base_url" :show-message="Boolean(form.base_url.trim())" :label="t('common.fields.baseUrl')" required>
|
||||
<template #extra>
|
||||
<span class="text-z-xs text-z-text-quaternary" :title="t('accounts.credentials.baseUrlHelp')">{{ t('accounts.credentials.apiPrefix') }}</span>
|
||||
</template>
|
||||
<ZInput v-model="form.base_url" type="url" placeholder="https://api.example.com/v1" :disabled="disabled" autocomplete="off" />
|
||||
</ZFormItem>
|
||||
<ZFormItem prop="connection.apiKey" :rules="rules.apiKey" :show-message="Boolean(form.apiKey)" :label="t('common.fields.apiKey')" :required="!editing">
|
||||
<ZFormItem class="col-span-full" prop="connection.apiKey" :rules="rules.apiKey" :show-message="Boolean(form.apiKey)" :label="t('common.fields.apiKey')" :required="!editing">
|
||||
<ZInput v-model="form.apiKey" type="password" :placeholder="editing ? t('accounts.credentials.apiKeyPlaceholder') : t('accounts.credentials.enterUpstreamKey')" :disabled="disabled" autocomplete="new-password" />
|
||||
</ZFormItem>
|
||||
<div class="grid grid-cols-[minmax(0,1fr)_auto] gap-4 sm:grid-cols-2">
|
||||
<div class="col-span-full grid grid-cols-2 gap-4.5 md:col-span-1">
|
||||
<ZFormItem prop="connection.protocol" :rules="rules.protocol" :show-message="false" :label="t('accounts.credentials.protocolLabel')">
|
||||
<ZSegmented :model-value="form.protocol" :aria-label="t('accounts.credentials.protocolLabel')" :options="protocolOptions" :disabled="disabled" @update:model-value="updateProtocol" />
|
||||
<ZSegmented class="w-full" :model-value="form.protocol" :aria-label="t('accounts.credentials.protocolLabel')" :options="protocolOptions" :disabled="disabled" @update:model-value="updateProtocol" />
|
||||
</ZFormItem>
|
||||
<ZFormItem prop="connection.transport" :rules="rules.transport" :show-message="false" :label="t('accounts.credentials.transportLabel')">
|
||||
<ZSegmented v-model="form.transport" :aria-label="t('accounts.credentials.transportLabel')" :options="transportOptions" :disabled="disabled" :title="form.protocol === 'messages' ? t('accounts.credentials.messagesTransportHelp') : t('accounts.credentials.webSocketHelp')" />
|
||||
<ZSegmented v-model="form.transport" class="w-full" :aria-label="t('accounts.credentials.transportLabel')" :options="transportOptions" :disabled="disabled" :title="form.protocol === 'messages' ? t('accounts.credentials.messagesTransportHelp') : t('accounts.credentials.webSocketHelp')" />
|
||||
</ZFormItem>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -17,7 +17,7 @@ const transportOptions = [
|
||||
|
||||
<template>
|
||||
<ApiKeyFields v-if="kind === 'api_key'" v-model="apiKey" editing :disabled="disabled || !configurationReady" />
|
||||
<ZFormItem v-else-if="kind === 'oauth'" :label="t('accounts.editor.transportLabel')">
|
||||
<ZFormItem v-else-if="kind === 'oauth'" class="col-span-full md:col-span-1" :label="t('accounts.editor.transportLabel')">
|
||||
<ZSegmented v-model="oauthTransport" class="w-40" :aria-label="t('accounts.editor.transportLabel')" :options="transportOptions" :disabled="disabled || !configurationReady" />
|
||||
</ZFormItem>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { Component } from 'vue'
|
||||
import loaders from 'virtual:platform-icons'
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
|
||||
export const platformIconOptions = Object.entries(loaders).map(([value, { label }]) => ({ value, label }))
|
||||
const components = new Map<string, Component>()
|
||||
|
||||
export function platformIcon(name: string) {
|
||||
if (!Object.hasOwn(loaders, name))
|
||||
return undefined
|
||||
let component = components.get(name)
|
||||
if (!component) {
|
||||
component = defineAsyncComponent(loaders[name].load)
|
||||
components.set(name, component)
|
||||
}
|
||||
return component
|
||||
}
|
||||
@@ -114,7 +114,7 @@ function connectionLogClass(tone: string) {
|
||||
<component
|
||||
:is="statusView.icon"
|
||||
class="size-5"
|
||||
:class="[statusView.iconClass, status === 'running' ? 'animate-pulse' : '']"
|
||||
:class="[statusView.iconClass, status === 'running' && 'motion-safe:animate-pulse']"
|
||||
/>
|
||||
</span>
|
||||
<div class="min-w-0">
|
||||
|
||||
@@ -31,6 +31,7 @@ const connectionComponent = computed(() => providerAccounts(props.account?.provi
|
||||
const connection = useTemplateRef<AccountConnectionForm>('connectionEditor')
|
||||
const notes = defineModel<string>('notes', { required: true })
|
||||
const name = defineModel<string>('name', { required: true })
|
||||
const platformIcon = defineModel<string | undefined>('platformIcon', { required: true })
|
||||
const enabled = defineModel<boolean>('enabled', { required: true })
|
||||
const concurrencyLimit = defineModel<string>('concurrencyLimit', { required: true })
|
||||
const modelAccess = defineModel<AccountModelAccess | undefined>('modelAccess', { required: true })
|
||||
@@ -82,7 +83,7 @@ async function requestSave() {
|
||||
<div class="flex shrink-0 items-center gap-3">
|
||||
<AccountPlanBadge :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="sm" />
|
||||
<ProviderIconGroup
|
||||
:provider="account.provider"
|
||||
:platform-icon="account.platformIcon" :provider="account.provider"
|
||||
:authentication-kind="account.authenticationKind"
|
||||
/>
|
||||
</div>
|
||||
@@ -91,6 +92,7 @@ async function requestSave() {
|
||||
<AccountSettingsFields
|
||||
v-model:name="name"
|
||||
v-model:notes="notes"
|
||||
v-model:platform-icon="platformIcon"
|
||||
v-model:enabled="enabled"
|
||||
v-model:concurrency-limit="concurrencyLimit"
|
||||
v-model:weight="weight"
|
||||
@@ -102,15 +104,15 @@ async function requestSave() {
|
||||
:groups-loading="groupsLoading"
|
||||
:disabled="saving"
|
||||
:show-scheduling="false"
|
||||
show-platform-icon
|
||||
:current-proxy-id="account.outboundProxyId"
|
||||
:endpoint="account.outboundProxyEndpoint"
|
||||
:account-id="account.id"
|
||||
:provider="account.provider"
|
||||
>
|
||||
<template #connection>
|
||||
<template v-if="connectionComponent" #connection>
|
||||
<component
|
||||
:is="connectionComponent"
|
||||
v-if="connectionComponent"
|
||||
:key="account.id"
|
||||
ref="connectionEditor"
|
||||
:account="account"
|
||||
|
||||
@@ -18,15 +18,11 @@ const props = withDefaults(
|
||||
size?: 'md' | 'lg'
|
||||
showPlan?: boolean
|
||||
showNotes?: boolean
|
||||
metaPosition?: 'title' | 'secondary'
|
||||
metaSize?: 'xs' | 'sm'
|
||||
}>(),
|
||||
{
|
||||
size: 'md',
|
||||
showPlan: false,
|
||||
showNotes: false,
|
||||
metaPosition: 'title',
|
||||
metaSize: 'sm',
|
||||
},
|
||||
)
|
||||
|
||||
@@ -68,10 +64,6 @@ const avatarSizeClass = computed(() =>
|
||||
: 'size-9 text-z',
|
||||
)
|
||||
|
||||
const metaGapClass = computed(() => props.metaSize === 'xs'
|
||||
? 'gap-1'
|
||||
: 'gap-1.5')
|
||||
|
||||
const avatarToneClass = computed(() => {
|
||||
const identity = props.account.id || props.account.email || displayTitle.value
|
||||
return stablePresetVisualToneClass(identity)
|
||||
@@ -91,25 +83,10 @@ const avatarToneClass = computed(() => {
|
||||
<span class="min-w-0 truncate text-z font-heavy text-z-text" :title="identityTitle">
|
||||
{{ displayTitle }}
|
||||
</span>
|
||||
<span
|
||||
v-if="metaPosition === 'title' && (showPlan || $slots.meta)"
|
||||
class="inline-flex shrink-0 items-center justify-end"
|
||||
:class="metaGapClass"
|
||||
>
|
||||
<slot name="meta" />
|
||||
<AccountPlanBadge v-if="showPlan" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" :size="metaSize" />
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="metaPosition === 'secondary' && (showPlan || $slots.meta)"
|
||||
class="mt-0.5 inline-flex min-w-0 items-center"
|
||||
:class="metaGapClass"
|
||||
>
|
||||
<slot name="meta" />
|
||||
<AccountPlanBadge v-if="showPlan" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" :size="metaSize" />
|
||||
<AccountPlanBadge v-if="showPlan" class="shrink-0" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="sm" />
|
||||
</div>
|
||||
<AccountSecondaryText
|
||||
v-else-if="secondaryText"
|
||||
v-if="secondaryText"
|
||||
:text="secondaryText"
|
||||
:label="visibleNotes ? t('accounts.identity.notes') : t('accounts.identity.email')"
|
||||
:class="secondaryClass"
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountGroupRef, AccountModelAccess } from '@/api'
|
||||
|
||||
import { ZFormItem, ZInput, ZSwitch, ZTextarea } from '@codex-proxy/ui'
|
||||
import { ZFormItem, ZInput, ZSegmented, ZTextarea } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import AccountModelAccessField from '@/components/account-model-access-field/index.vue'
|
||||
import AccountGroupCheckboxGrid from '@/components/AccountGroupCheckboxGrid.vue'
|
||||
import PlatformIconField from '@/components/PlatformIconField.vue'
|
||||
import { providerAccounts } from '@/providers/accounts'
|
||||
import AccountProxyField from './account-proxy-field/index.vue'
|
||||
|
||||
@@ -20,6 +22,7 @@ withDefaults(defineProps<{
|
||||
preserveProxy?: boolean
|
||||
preserveModelAccess?: boolean
|
||||
showScheduling?: boolean
|
||||
showPlatformIcon?: boolean
|
||||
namePlaceholder?: string
|
||||
notesPlaceholder?: string
|
||||
}>(), { preserveProxy: true, showScheduling: true })
|
||||
@@ -28,6 +31,7 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const name = defineModel<string>('name')
|
||||
const notes = defineModel<string>('notes')
|
||||
const platformIcon = defineModel<string>('platformIcon')
|
||||
const modelAccess = defineModel<AccountModelAccess | undefined>('modelAccess', { required: true })
|
||||
const enabled = defineModel<boolean>('enabled')
|
||||
const concurrencyLimit = defineModel<string>('concurrencyLimit', { required: true })
|
||||
@@ -35,32 +39,44 @@ const weight = defineModel<string>('weight', { required: true })
|
||||
const proxyMode = defineModel<string>('proxyMode', { required: true })
|
||||
const proxyId = defineModel<string>('proxyId', { required: true })
|
||||
const selectedGroupIds = defineModel<string[]>('selectedGroupIds', { required: true })
|
||||
const schedulingOptions = computed(() => [
|
||||
{
|
||||
value: 'enabled',
|
||||
label: t('accounts.actions.enableScheduling'),
|
||||
},
|
||||
{
|
||||
value: 'disabled',
|
||||
label: t('accounts.actions.disableScheduling'),
|
||||
},
|
||||
])
|
||||
const schedulingMode = computed({
|
||||
get: () => enabled.value ? 'enabled' : 'disabled',
|
||||
set: (value: string) => { enabled.value = value === 'enabled' },
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid gap-4.5">
|
||||
<ZFormItem v-if="name !== undefined" prop="name" :label="t('accounts.credentials.accountName')">
|
||||
<ZInput
|
||||
v-model="name"
|
||||
:aria-label="t('accounts.credentials.accountName')"
|
||||
:placeholder="namePlaceholder ?? t('accounts.editor.namePlaceholder')"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<slot name="connection" />
|
||||
<AccountModelAccessField v-model="modelAccess" form-prop="modelAccess" :account-id="modelAccountId ?? accountId" :image-model-presets="providerAccounts(provider)?.imageModelPresets" :disabled="disabled" :allow-preserve="preserveModelAccess" />
|
||||
<slot name="scheduling">
|
||||
<div v-if="showScheduling" class="flex min-h-6 items-center justify-between gap-3">
|
||||
<span class="text-z leading-none font-medium text-z-text-secondary">{{ t('accounts.scheduling.scheduling') }}</span>
|
||||
<ZSwitch
|
||||
v-model="enabled"
|
||||
:aria-label="t('accounts.scheduling.switchAccountSchedule')"
|
||||
<div class="grid gap-4.5 sm:grid-cols-2">
|
||||
<div v-if="name !== undefined || showPlatformIcon" class="grid gap-x-4 sm:col-span-2 sm:grid-cols-2">
|
||||
<ZFormItem v-if="name !== undefined" prop="name" :label="t('accounts.credentials.accountName')">
|
||||
<ZInput
|
||||
v-model="name"
|
||||
:aria-label="t('accounts.credentials.accountName')"
|
||||
:placeholder="namePlaceholder ?? t('accounts.editor.namePlaceholder')"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
</div>
|
||||
</slot>
|
||||
</ZFormItem>
|
||||
<PlatformIconField v-if="showPlatformIcon" v-model="platformIcon" :provider="provider" :disabled="disabled" />
|
||||
</div>
|
||||
<!-- 凭据字段占整行,末组连接选项与并发、权重共用一行 -->
|
||||
<slot name="connection" />
|
||||
|
||||
<div class="grid gap-4.5 sm:grid-cols-2">
|
||||
<div class="grid gap-4.5" :class="[$slots.connection ? 'sm:col-span-2 md:col-span-1' : 'sm:col-span-2', (showScheduling || $slots.scheduling) ? 'sm:grid-cols-3' : 'sm:grid-cols-2']">
|
||||
<slot name="scheduling">
|
||||
<ZFormItem v-if="showScheduling" :label="t('accounts.scheduling.scheduling')">
|
||||
<ZSegmented v-model="schedulingMode" class="w-full" :aria-label="t('accounts.scheduling.switchAccountSchedule')" :options="schedulingOptions" :disabled="disabled" />
|
||||
</ZFormItem>
|
||||
</slot>
|
||||
<ZFormItem prop="concurrencyLimit" :label="t('accounts.scheduling.concurrencyLimit')">
|
||||
<ZInput
|
||||
v-model="concurrencyLimit"
|
||||
@@ -85,7 +101,9 @@ const selectedGroupIds = defineModel<string[]>('selectedGroupIds', { required: t
|
||||
</ZFormItem>
|
||||
</div>
|
||||
|
||||
<ZFormItem :label="t('accounts.scheduling.groupLabel')">
|
||||
<AccountModelAccessField v-model="modelAccess" class="sm:col-span-2" form-prop="modelAccess" :account-id="modelAccountId ?? accountId" :image-model-presets="providerAccounts(provider)?.imageModelPresets" :disabled="disabled" :allow-preserve="preserveModelAccess" />
|
||||
|
||||
<ZFormItem class="sm:col-span-2" :label="t('accounts.scheduling.groupLabel')">
|
||||
<AccountGroupCheckboxGrid
|
||||
v-model="selectedGroupIds"
|
||||
:groups="groups"
|
||||
@@ -93,8 +111,8 @@ const selectedGroupIds = defineModel<string[]>('selectedGroupIds', { required: t
|
||||
:disabled="disabled"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<AccountProxyField v-model:mode="proxyMode" v-model:proxy-id="proxyId" form-prop="proxyId" :preserve="preserveProxy" :current-proxy-id="currentProxyId" :endpoint="endpoint" :account-id="accountId" :disabled="disabled" />
|
||||
<ZFormItem v-if="notes !== undefined" :label="t('common.fields.notes')">
|
||||
<AccountProxyField v-model:mode="proxyMode" v-model:proxy-id="proxyId" class="sm:col-span-2" form-prop="proxyId" :preserve="preserveProxy" :current-proxy-id="currentProxyId" :endpoint="endpoint" :account-id="accountId" :disabled="disabled" />
|
||||
<ZFormItem v-if="notes !== undefined" class="sm:col-span-2" :label="t('common.fields.notes')">
|
||||
<ZTextarea v-model="notes" :rows="3" :maxlength="500" :placeholder="notesPlaceholder ?? t('accounts.editor.notesHelp')" :disabled="disabled" />
|
||||
</ZFormItem>
|
||||
</div>
|
||||
|
||||
@@ -39,6 +39,7 @@ const name = computed({
|
||||
<AccountSettingsFields
|
||||
v-model:name="name"
|
||||
v-model:notes="form.notes"
|
||||
v-model:platform-icon="form.platformIcon"
|
||||
v-model:enabled="form.enabled"
|
||||
v-model:concurrency-limit="form.concurrencyLimit"
|
||||
v-model:weight="form.weight"
|
||||
@@ -47,6 +48,7 @@ const name = computed({
|
||||
v-model:proxy-mode="form.proxyMode"
|
||||
v-model:proxy-id="form.proxyId"
|
||||
preserve-model-access
|
||||
show-platform-icon
|
||||
|
||||
:groups="groups"
|
||||
:provider="accountCreateProvider(form)"
|
||||
|
||||
@@ -135,7 +135,7 @@ async function continueToImport() {
|
||||
size="sm"
|
||||
/>
|
||||
<ProviderIconGroup
|
||||
:provider="account.provider"
|
||||
:platform-icon="account.platformIcon" :provider="account.provider"
|
||||
:authentication-kind="account.authenticationKind"
|
||||
/>
|
||||
<ZIconButton
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user