Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,12 @@ impl AccountStore {
self.snapshot(&state, Visibility::All)
}

/// 单条账号的公开形态:沿用全量快照的字段口径,不做展示过滤。
pub(crate) fn public_account_by_id(&self, id: &str) -> Option<Value> {
let record = self.read_record(id)?;
Some(self.public_account(&record))
}

/// 界面用的账号快照:**只含此刻真的能用的那些家**(判据见 [`account_visible`])。
///
/// 所有面向用户的账号入口都应走这一条(`/api/session`、`/api/accounts`、
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,10 +306,10 @@ pub async fn refresh_single(
use crate::server::errors::GatewayError;
let recorder = storage::Recorder::start(CREDENTIAL, "manual", None)
.map_err(|error| GatewayError::with_status(503, error))?;
let before = types::accounts(store);
let before = types::account(store, id);
let started = std::time::Instant::now();
let result = credential_maintenance::refresh_checked(store, adapter, id).await;
let after = types::accounts(store);
let after = types::account(store, id);
let raw = json!({
"id": id, "provider": store.account_provider_of(id).unwrap_or_default(),
"status": if result.is_ok() { "refreshed" } else { "failed" },
Expand Down
50 changes: 30 additions & 20 deletions desktop-tauri/src-tauri/server/src/server/core/maintenance/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,31 +72,41 @@ pub struct AccountSnapshot {
pub expires_at: Option<i64>,
}

fn account_snapshot(account: &Value) -> Option<(String, AccountSnapshot)> {
let id = account.get("id")?.as_str()?;
let name = if account.get("nameCustom").and_then(Value::as_bool) == Some(true) {
text(account, "name")
} else {
["nickname", "name", "email"]
.into_iter()
.find_map(|key| text(account, key))
}
.unwrap_or_else(|| id.to_string());
let expires_at = [
"accessTokenExpiresAt",
"tokenExpiresAt",
"expiresAt",
"tokenExpireAt",
]
.into_iter()
.find_map(|key| millis(account.get(key)));
Some((id.to_string(), AccountSnapshot { name, expires_at }))
}

pub fn accounts(store: &AccountStore) -> HashMap<String, AccountSnapshot> {
store.list_accounts()["accounts"]
.as_array()
.into_iter()
.flatten()
.filter_map(|account| {
let id = account.get("id")?.as_str()?;
let name = if account.get("nameCustom").and_then(Value::as_bool) == Some(true) {
text(account, "name")
} else {
["nickname", "name", "email"]
.into_iter()
.find_map(|key| text(account, key))
}
.unwrap_or_else(|| id.to_string());
let expires_at = [
"accessTokenExpiresAt",
"tokenExpiresAt",
"expiresAt",
"tokenExpireAt",
]
.into_iter()
.find_map(|key| millis(account.get(key)));
Some((id.to_string(), AccountSnapshot { name, expires_at }))
})
.filter_map(account_snapshot)
.collect()
}

pub fn account(store: &AccountStore, id: &str) -> HashMap<String, AccountSnapshot> {
store.public_account_by_id(id)
.as_ref()
.and_then(account_snapshot)
.into_iter()
.collect()
}

Expand Down
16 changes: 7 additions & 9 deletions desktop-tauri/src-tauri/server/src/web_shim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
//! · 凭证:桌面壳自动带第一把 Key(进程内读);网页端由**用户输入**
//! (401 时弹出输入层,存 localStorage 后重试一次)。
//! · 事件:Tauri 的 push 事件不存在,改为**模拟** ——
//! `accounts:state-changed` 在写类请求成功后拉一次 /api/session 重放
//! `accounts:state-changed` 在写类请求成功后通知状态失效,由界面统一读取
//! (300ms 防抖,合并连续写);`login:state` 由本文件的登录状态机
//! 本地驱动;`backend:error` / `accounts:auto-maintained` 没有对应物,
//! 订阅返回空操作(桌面端它们也只是「去查一次」的提醒)。
Expand Down Expand Up @@ -851,12 +851,9 @@ pub fn shim_js() -> &'static str {
var stateEmitTimer = null;
function emitStateSoon() {
if (stateEmitTimer) return;
stateEmitTimer = setTimeout(async function () {
stateEmitTimer = setTimeout(function () {
stateEmitTimer = null;
try {
var next = await call('GET', '/api/session');
stateListeners.forEach(function (cb) { try { cb(next); } catch (e) { console.warn(e); } });
} catch (e) { /* 面板关闭中的正常失败 */ }
stateListeners.forEach(function (cb) { try { cb(); } catch (e) { console.warn(e); } });
}, 300);
}

Expand Down Expand Up @@ -1677,7 +1674,8 @@ pub fn shim_js() -> &'static str {
getAccountSorting: function () { return call('GET', '/api/accounts/sorting'); },
saveAccountSorting: function (payload) { return call('PUT', '/api/accounts/sorting', payload || {}); },
switchAccount: function (id) { return call('POST', '/api/accounts/current', { id: id }); },
refreshAccountToken: function (id) { return call('POST', '/api/accounts/refresh', id ? { id: id } : {}); },
// [喵喵喵]: 单号和批量调用方负责操作后的补读,避免桥层再触发一轮整表刷新。
refreshAccountToken: function (id) { return rawCall('POST', '/api/accounts/refresh', id ? { id: id } : {}); },
removeAccount: function (id) { return call('DELETE', '/api/accounts/' + encodeURIComponent(id)); },
updateAccount: function (id, patch) { return call('PATCH', '/api/accounts/' + encodeURIComponent(id), patch); },
// 整队重排(账号页分组模式拖拽的落库通道;与桌面 bridge.rs 的同名方法成对)。
Expand Down Expand Up @@ -2346,8 +2344,8 @@ pub fn shim_js() -> &'static str {
return result ? '?' + result : '';
}

// 写类请求成功后重放一次状态(模拟桌面的 accounts:state-changed 推送):
// 拦一层 call,只对管理 API 的非 GET 生效,/v1/* 与登录轮询不受影响。
// 写类请求成功后通知状态失效(模拟桌面的 accounts:state-changed 推送):
// 状态读取由界面统一调度;只对管理 API 的非 GET 生效,/v1/* 与登录轮询不受影响。
var rawCall = call;
call = function (method, path, body) {
var promise = rawCall(method, path, body);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,19 @@ export function BatchDialog({ ids, action, onClose }: { ids: string[]; action: s
const [result, setResult] = React.useState<React.ReactNode>('')
const [refreshProgress, setRefreshProgress] = React.useState<BatchTokenRefreshProgress | null>(null)
const running = React.useRef(false)
const accounts = ids.map(id => findAccount(id)).filter((account): account is AccountRecord => account !== null)
const accountList = allAccounts()
const accounts = React.useMemo(
() => ids.map(id => findAccount(id)).filter((account): account is AccountRecord => account !== null),
[ids, accountList],
)
const usageAccounts = accounts.filter(supportsUsage)
const editingRules = current === 'limiters' && (limiterMode === 'append' || limiterMode === 'replace')
const needsBalance = editingRules && limiterDraft.some(group => group.conditions.some(condition => condition.metric !== 'tokens' && condition.metric !== 'requests'))
const targets = current === 'refresh'
? accounts.filter(account => !tokenRefreshSkipReason(account))
: current === 'usageQuery' || needsBalance ? usageAccounts : accounts
const skippedAccounts = accounts.filter(account => !targets.includes(account))
const targetIds = new Set(targets.map(account => account.id))
const skippedAccounts = accounts.filter(account => !targetIds.has(account.id))
const copyOptions = current === 'usageQuery' ? usageAccounts : accounts
const source = copyOptions.find(account => account.id === sourceId)
const concHardCap = accounts.reduce(
Expand Down
Loading