Skip to content

WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。

fix: skip credit queries for expired accounts

[email protected]20153330a1f0
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 64c3e40..48c85f4 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -546,8 +546,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.70:视频壁纸层夹在 body 底色与 #root 之间,毛玻璃主题下正常显示画面。
// #507: explicit cleanup of old Windows client temp files, only before a verified cold launch.
// 1.2.81:在共享目标分支加入视频壁纸及失败重试、主题路径边界修复。
-const DAEMON_VERSION = '1.2.81';
-const DAEMON_BUILD_ID = 'release-1.2.81-video-wallpaper';
+const DAEMON_VERSION = '1.2.82';
+const DAEMON_BUILD_ID = 'release-1.2.82-expired-credit-filter';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -1320,6 +1320,12 @@ function normTs(v) {
return Math.round(ts);
}
+function isAccountIdentityExpired(account, now = Date.now()) {
+ const raw = account && account.tokenExpiresAt;
+ const expiresAt = typeof raw === 'string' && Number.isNaN(Number(raw)) ? Date.parse(raw) : normTs(raw);
+ return expiresAt !== null && expiresAt <= now;
+}
+
// 带超时的 JSON 请求(返回解析后的 JSON;解析失败回退 {code,message})
function httpJson(url, method, body, headers) {
return new Promise((resolve, reject) => {
@@ -11443,7 +11449,8 @@ function handleApi(req, res) {
const checked = c && c.ok && (c.verified === true || classifyCheckinResult({ httpOk: true, code: c.code, message: c.message }).ok)
? c
: null;
- return Object.assign({}, a, { creditSegments: [] }, accountCreditCache.get(a.uid), {
+ const cachedCredit = isAccountIdentityExpired(a) ? null : accountCreditCache.get(a.uid);
+ return Object.assign({}, a, { creditSegments: [] }, cachedCredit || {}, {
checkin: checkinDisplayValue(checked, today),
activityStreak: growthStreakCache.peek(a.uid),
});
@@ -11479,6 +11486,8 @@ function handleApi(req, res) {
const file = accountBackupFile(uid);
if (!fs.existsSync(file)) return json(res, 404, { ok: false, error: '账号备份不存在' });
const j = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(file, 'utf8'))); // [wd-compat]
+ const accountMeta = listAccounts(DATA_DIR).find(account => account.uid === uid);
+ if (isAccountIdentityExpired(accountMeta)) return json(res, 401, { ok: false, expired: true, error: '登录身份过期' });
const tk = wdCompatAuthToken(j.auth);
if (!tk) return json(res, 400, { ok: false, error: '备份中无 accessToken' });
const current = currentAccount();
@@ -11598,12 +11607,14 @@ function handleApi(req, res) {
try {
const range = historyRange(url.searchParams.get('days') || 7);
const accounts = listAccounts(DATA_DIR);
+ const activeAccounts = accounts.filter(account => !isAccountIdentityExpired(account));
const uid = url.searchParams.get('account') || '';
- const selected = uid ? accounts.filter(a => a.uid === uid) : accounts;
+ const selected = uid ? activeAccounts.filter(a => a.uid === uid) : activeAccounts;
if (uid && !selected.length) return json(res, 400, { ok: false, error: '账号选择无效' });
+ if (!selected.length) return json(res, 400, { ok: false, error: '没有可查询积分的有效账号' });
creditHistorySync.start({ accounts: selected, days: range.days });
return creditHistorySync.wait().then(result => json(res, 200, { ok: true, ...result,
- accounts: accounts.map(a => ({ uid: a.uid, nickname: a.nickname || '' })) }));
+ accounts: activeAccounts.map(a => ({ uid: a.uid, nickname: a.nickname || '' })) }));
} catch (error) { return json(res, error.status || 400, { ok: false, error: error.message }); }
}
if (req.method === 'GET' && p === '/api/credit-stats/sync') {
@@ -11618,10 +11629,11 @@ function handleApi(req, res) {
typeof uid !== 'string' || !accounts.some(account => account.uid === uid)))) {
return json(res, 400, { ok: false, error: '账号选择无效' });
}
- const selected = requested === undefined ? accounts : accounts.filter(account => requested.includes(account.uid));
+ const activeAccounts = accounts.filter(account => !isAccountIdentityExpired(account));
+ const selected = requested === undefined ? activeAccounts : activeAccounts.filter(account => requested.includes(account.uid));
if (!selected.length) return json(res, 400, { ok: false, error: '请先选择账号' });
return json(res, 202, { ok: true, job: creditHistorySync.start({ accounts: selected, days: range.days }),
- accounts: accounts.map(a => ({ uid: a.uid, nickname: a.nickname || '' })) });
+ accounts: activeAccounts.map(a => ({ uid: a.uid, nickname: a.nickname || '' })) });
}).catch(error => json(res, error.status || 400, { ok: false,
error: error.status === 409 ? '另一个积分查询正在进行,请稍后重试' : '查询参数无效,请选择近 7、30 或 90 天' }));
}
diff --git a/scripts/inject.js b/scripts/inject.js
index 1adb297..bb8e831 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -16456,14 +16456,36 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function mergeAccountSnapshot(previous, incoming) {
var byUid = new Map();
- (incoming || []).forEach(function (account) { byUid.set(account.uid, Object.assign({}, account)); });
+ (incoming || []).forEach(function (account) {
+ account = Object.assign({}, account);
+ if (isIdentityExpired(account) || account.creditExpired === true) {
+ account.credits = null;
+ account.creditSegments = [];
+ account.creditUnlimited = false;
+ account.creditExpired = true;
+ }
+ byUid.set(account.uid, account);
+ });
var merged = [];
previous.forEach(function (cached) {
var account = byUid.get(cached.uid);
if (!account) return; // 删除的账号不能被缓存复活。
- ['credits', 'creditSegments', 'creditUnlimited', 'creditExpired', 'dailyProgress', 'growthTodayActive'].forEach(function (key) {
+ var identityExpired = isIdentityExpired(account);
+ var creditExpired = account.creditExpired === true;
+ ['credits', 'creditSegments', 'creditUnlimited', 'dailyProgress', 'growthTodayActive'].forEach(function (key) {
if (account[key] === undefined && cached[key] !== undefined) account[key] = cached[key];
});
+ // An expired identity must never inherit a previous balance. The
+ // creditExpired marker is only carried by an explicit fresh response;
+ // otherwise a later metadata refresh may retry a recovered account.
+ if (identityExpired || creditExpired) {
+ account.credits = null;
+ account.creditSegments = [];
+ account.creditUnlimited = false;
+ account.creditExpired = true;
+ } else if (account.creditExpired === undefined) {
+ account.creditExpired = false;
+ }
if (!isKnownActivityStreak(account.activityStreak) && isKnownActivityStreak(cached.activityStreak)) {
account.activityStreak = cached.activityStreak;
}
@@ -17869,7 +17891,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function updateCreditSummaryFromAccounts() {
var sum = 0;
state.accounts.forEach(function (account) {
- if (typeof account.credits === 'number' && isFinite(account.credits)) sum += account.credits;
+ if (!isIdentityExpired(account) && !account.creditExpired && typeof account.credits === 'number' && isFinite(account.credits)) sum += account.credits;
});
state.creditSummaryValue = sum;
updateAccountSummary();
@@ -17877,9 +17899,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function refreshCreditForAccount(uid) {
uid = String(uid || '').trim();
- if (!uid || !alive || !state.accounts.some(function (account) { return account.uid === uid; })) return Promise.resolve();
+ var account = state.accounts.find(function (item) { return item.uid === uid; });
+ if (!uid || !alive || !account) return Promise.resolve();
var generation = (state.creditRefreshGeneration[uid] || 0) + 1;
state.creditRefreshGeneration[uid] = generation;
+ if (isIdentityExpired(account) || account.creditExpired) {
+ account.credits = null;
+ account.creditSegments = [];
+ account.creditUnlimited = false;
+ account.creditExpired = true;
+ updateCreditCell(uid, null, []);
+ updateCreditSummaryFromAccounts();
+ return Promise.resolve();
+ }
return requestCredit(uid).then(function (result) {
if (!alive || generation !== state.creditRefreshGeneration[uid]) return;
var account = state.accounts.find(function (item) { return item.uid === uid; });
@@ -17925,6 +17957,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function queryAccount(a) {
if (runId !== state.creditRunId || !state.open) return;
var generation = state.creditRefreshGeneration[a.uid] || 0;
+ if (isIdentityExpired(a) || a.creditExpired) {
+ for (var i = 0; i < state.accounts.length; i++) {
+ if (state.accounts[i].uid === a.uid) {
+ state.accounts[i].credits = null;
+ state.accounts[i].creditSegments = [];
+ state.accounts[i].creditUnlimited = false;
+ state.accounts[i].creditExpired = true;
+ break;
+ }
+ }
+ updateCreditCell(a.uid, null, []);
+ state.creditRemaining = Math.max(0, state.creditRemaining - 1);
+ settleBatch();
+ return;
+ }
// 无论成功、HTTP 错误、身份过期还是超时,都必须进入 finally。
Promise.resolve().then(function () { return requestCredit(a.uid); })
.then(function (r) {
diff --git a/test/account-list-stability.test.js b/test/account-list-stability.test.js
index 72ce07c..f5150fd 100644
--- a/test/account-list-stability.test.js
+++ b/test/account-list-stability.test.js
@@ -137,6 +137,22 @@ test('temporary credit failures retain the cached value but expired identity cle
assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').creditExpired, true);
});
+test('expired identities are cleared from cached totals and skipped by credit refresh', async () => {
+ const h = harness();
+ h.ctx.render({ accounts: [
+ { ...account('expired', 100), identityExpired: true },
+ account('live', 200),
+ ] });
+ assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').credits, null);
+ h.ctx.fetchCreditsForAccounts(); await tick();
+ assert.deepEqual(h.requests.map(request => JSON.parse(request.options.body).uid), ['live']);
+ h.requests[0].resolve({ credits: 7, segments: [{ remaining: 7, expiresAt: 200 }] }); await tick();
+ assert.equal(h.ctx.state.creditSummaryValue, 7);
+ assert.equal(h.ctx.state.accounts.find(a => a.uid === 'expired').credits, null);
+ await h.ctx.refreshCreditForAccount('expired');
+ assert.deepEqual(h.requests.map(request => JSON.parse(request.options.body).uid), ['live']);
+});
+
test('account refresh errors retain the cached list', async () => {
const h = harness(); h.ctx.render({ accounts: [account('a', 100)] });
const before = h.cards()[0];
@@ -175,9 +191,9 @@ test('fresh current-account and identity changes update card controls', () => {
const h = harness(); h.ctx.render({ accounts: [account('a', 100), account('b', 200)] });
const before = h.cards();
h.ctx.render({ current: { uid: 'b' }, accounts: [{ ...account('a', 100), identityExpired: true }, account('b', 200)] });
- assert.deepEqual(h.order(), ['a', 'b']);
+ assert.deepEqual(h.order(), ['b', 'a']);
assert.notEqual(h.cards()[0], before[0]);
- assert.equal(h.cards()[1].className, 'wbs-card cur');
+ assert.equal(h.cards().find(card => card.getAttribute('data-uid') === 'b').className, 'wbs-card cur');
});
test('expired identities retain a manual switch while malformed backups remain blocked', () => {
@@ -186,9 +202,11 @@ test('expired identities retain a manual switch while malformed backups remain b
{ ...account('expired', 100), identityExpired: true },
{ ...account('invalid', 200), authValid: false },
] });
- assert.match(h.cards()[0].innerHTML, /wbs-acc-switch/);
- assert.match(h.cards()[0].innerHTML, /可能需要重新登录/);
- assert.doesNotMatch(h.cards()[1].innerHTML, /wbs-acc-switch/);
+ const expiredCard = h.cards().find(card => card.getAttribute('data-uid') === 'expired');
+ const invalidCard = h.cards().find(card => card.getAttribute('data-uid') === 'invalid');
+ assert.match(expiredCard.innerHTML, /wbs-acc-switch/);
+ assert.match(expiredCard.innerHTML, /可能需要重新登录/);
+ assert.doesNotMatch(invalidCard.innerHTML, /wbs-acc-switch/);
});
test('a background credit expiry response does not hide the manual switch', () => {
diff --git a/test/credit-history-sync.test.js b/test/credit-history-sync.test.js
index a969b86..412a235 100644
--- a/test/credit-history-sync.test.js
+++ b/test/credit-history-sync.test.js
@@ -128,6 +128,14 @@ test('both credit statistics entry points are remote queries, not local database
assert.match(routes,/creditHistorySync\.wait/);
});
+test('credit statistics routes exclude accounts whose identity token has expired', () => {
+ const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/daemon.js'), 'utf8');
+ const routes = source.slice(source.indexOf("if (req.method === 'GET' && p === '/api/credit-stats')"), source.indexOf('// Read-only per-account continuous activity'));
+ assert.match(routes, /isAccountIdentityExpired/);
+ assert.match(routes, /accounts\.filter\(account => !isAccountIdentityExpired\(account\)\)/);
+ assert.match(routes, /requested === undefined \? activeAccounts : activeAccounts\.filter/);
+});
+
test('durable daily cache fills only gaps, including zero-use days, and survives restart', async t => {
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'wbs-credit-cache-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));