Skip to content

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

fix: complete 1.2.19 account isolation and phrase interactions

[email protected]97b2897f429a
diff --git a/scripts/account-identity.js b/scripts/account-identity.js
new file mode 100644
index 0000000..faff1fc
--- /dev/null
+++ b/scripts/account-identity.js
@@ -0,0 +1,41 @@
+'use strict';
+const crypto = require('crypto');
+
+// WorkDaddy ids identify a login context; official auth/session uids stay intact.
+function accountIdentity(account = {}) {
+ const rawUid = String(account.rawUid || account.uid || '').trim();
+ const type = String(account.type || '').trim();
+ const enterpriseId = String(account.enterpriseId || '').trim();
+ if (!enterpriseId && !['ultimate', 'exclusive'].includes(type)) return rawUid;
+ // Edition upgrades within the same enterprise must not create another account.
+ const scope = enterpriseId ? ['enterprise', enterpriseId] : ['edition', type];
+ return 'wdent_' + crypto.createHash('sha256').update(JSON.stringify([rawUid, scope])).digest('hex');
+}
+
+const AMBIGUOUS_SESSION_ACCOUNT = '个人版与企业版共用官方会话 UID,无法可靠区分会话归属,已停止同步;账号备份和切换仍可使用';
+function createSessionAccountResolver(accounts) {
+ const byId = new Map(), byUid = new Map();
+ for (const account of accounts) {
+ const id = String(account.uid || '');
+ const rawUid = String(account.rawUid || id);
+ byId.set(id, rawUid);
+ if (!byUid.has(rawUid)) byUid.set(rawUid, new Set());
+ byUid.get(rawUid).add(id);
+ }
+ function raw(uid) { return byId.get(String(uid)) || String(uid); }
+ function assertUnambiguous(uid) {
+ if ((byUid.get(raw(uid)) || new Set()).size > 1) {
+ const error = new Error(AMBIGUOUS_SESSION_ACCOUNT);
+ error.code = 'WBS_AMBIGUOUS_SESSION_ACCOUNT';
+ throw error;
+ }
+ return raw(uid);
+ }
+ function identity(uid) {
+ const ids = byUid.get(String(uid));
+ if (ids && ids.size > 1) return String(uid); // Ownership is unknown; never guess an enterprise.
+ return ids && ids.size === 1 ? ids.values().next().value : String(uid);
+ }
+ return { raw, identity, assertUnambiguous };
+}
+module.exports = { accountIdentity, createSessionAccountResolver, AMBIGUOUS_SESSION_ACCOUNT };
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 8423859..fd65d63 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -65,7 +65,7 @@ chmod 644 "$APP/Contents/Resources/AppIcon.icns"
echo "==> 应用图标已同步(背景 #e1e1e1)"
# 2) 覆盖运行时代码和主题配置,保留 launcher/Info.plist/壁纸/node_modules/theme-audit.js。
-for f in daemon.js persona.js markdown-preview.js renderer-api-bridge.js codebuddy-native.js codebuddy-native-recovery.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-account-sync.js official-automation-sync.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js session-deletion-sync.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js wallpaper-rotation.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js client-launch-settings.js workbuddy-launch-env.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+for f in daemon.js account-identity.js session-copy-error.js persona.js markdown-preview.js renderer-api-bridge.js codebuddy-native.js codebuddy-native-recovery.js codebuddy-session-store.js codebuddy-files.js toast-runtime.js toast-options.js primary-account.js account-credit-cache.js completion-report.js automation-runtime.js automation-model.js automation-packages.js automation-compatibility.js automation-transfer.js automation-discovery.js automation-likes.js automation-zip.js automation.js automation-account-sync.js official-automation-sync.js automation-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.js session-deletion-sync.js third-party-models.js secure-transfer.js session-transfer.js windows-process-boundary.js windows-installer-launch.js workbuddy-compat.js inject.js theme-patches.js theme-text-shadow.js wallpaper-rotation.js theme-vars.js credit-segments.js credit-resource-queries.js credit-request-usage.js credit-history-sync.js credit-usage-store.js credit-rotation.js token-stats.js growth-active.js growth-daily.js atomic-file-write.js client-launch-settings.js workbuddy-launch-env.js ui-port.js checkin-result.js lib.js platform.js profiles.js workbuddy-target.js cdp-targets.js sentry-report.js usage-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
done
# Theme tokens are source code too; the reusable shell may contain older colors.
diff --git a/scripts/codebuddy-files.js b/scripts/codebuddy-files.js
index 2879840..5bbd564 100644
--- a/scripts/codebuddy-files.js
+++ b/scripts/codebuddy-files.js
@@ -9,12 +9,13 @@ const validId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,200}$/.t
// CodeBuddy's extension owns per-account history trees. Expose their files in
// the existing archive/snapshot vocabulary so panel and sync transactions stay
// shared; never synthesize an empty WorkBuddy transcript for a native session.
-function createCodeBuddyFiles({root, sync}) {
+function createCodeBuddyFiles({root, sync, resolveAccountUid = uid => uid}) {
const rows = new Map();
function parseIndex(text) {
try { return JSON.parse(text); } catch (_) { throw Error('CodeBuddy 会话索引格式不兼容'); }
}
function register(row) {
+ if (row) row = {...row, user_id: resolveAccountUid(row.user_id)};
if (!row || !validId(row.id) || !validId(row.user_id) || typeof row.cwd !== 'string' || !path.isAbsolute(row.cwd)) throw Error('CodeBuddy 会话归属或工作区无效');
rows.set(row.id, row);
}
diff --git a/scripts/credit-usage-store.js b/scripts/credit-usage-store.js
index adf64c0..0ff09cb 100644
--- a/scripts/credit-usage-store.js
+++ b/scripts/credit-usage-store.js
@@ -354,6 +354,7 @@ function createCreditUsageStore(options = {}) {
if (reset !== null && (!Number.isSafeInteger(reset) || reset < 0)) throw new Error('限流解封时间无效');
const reason = reasonCode === null || reasonCode === undefined ? null : Number(reasonCode);
if (reason !== null && !Number.isSafeInteger(reason)) throw new Error('限流 code 无效');
+ if (reason !== 6000 && reason !== 6004) throw new Error('不支持的模型限制 code');
await db.run(
`INSERT INTO model_rate_limit_records
(profile_id, uid, model_id, model_name, reset_at, observed_at, source, reason_code)
@@ -369,20 +370,22 @@ function createCreditUsageStore(options = {}) {
try { fs.chmodSync(dbPath, 0o600); } catch (_) {}
}
- async function hasModelRateLimitElsewhere({ uid, modelId, resetAt, now }) {
+ async function hasModelRateLimitElsewhere({ uid, modelId, resetAt, reasonCode, now }) {
await initialize();
const accountUid = validIdentity(uid, 'uid');
const id = validIdentity(modelId, 'model id');
const reset = Number(resetAt);
if (!Number.isSafeInteger(reset) || reset < 0) throw new Error('限流解封时间无效');
+ const reason = reasonCode === null || reasonCode === undefined ? 6004 : Number(reasonCode);
+ if (reason !== 6000 && reason !== 6004) throw new Error('限流 code 无效');
const timestamp = Number(now === undefined ? Date.now() : now);
if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error('限流查询时间无效');
const rows = await db.all(
`SELECT 1
FROM model_rate_limit_records
- WHERE profile_id = ? AND uid <> ? AND model_id = ? AND reset_at = ? AND reset_at > ?
+ WHERE profile_id = ? AND uid <> ? AND model_id = ? AND reset_at = ? AND reason_code = ? AND reset_at > ?
LIMIT 1`,
- [profileId, accountUid, id, reset, timestamp]
+ [profileId, accountUid, id, reset, reason, timestamp]
);
return rows.length > 0;
}
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 2daf2e0..51cd957 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -27,6 +27,8 @@ const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
+const { accountIdentity, createSessionAccountResolver } = require('./account-identity');
+const { sanitizeSessionCopyError } = require('./session-copy-error');
const net = require('net');
const { inspectPersona, copyPersona, readPersonaSettings, listPersonaSources, configurePersona, dismissPersonaNotice, syncSharedPersonaForSwitch } = require('./persona.js');
let sessionSync = require('./session-sync.js');
@@ -86,6 +88,8 @@ const {
parseAuthJson,
backupCurrent,
listAccounts,
+ migrateAccountIdentities,
+ knownAccountIdentities,
switchTo,
deleteAccount,
wdCompatText, // [wd-compat]
@@ -238,7 +242,7 @@ const { runCompletionReport, probeAccountCompletion } = require('./completion-re
const { createPrimaryAccountStore } = require('./primary-account.js');
const PROFILE = getProfile();
const DATA_DIR = defaultDataDir();
-const codeBuddyFiles = PROFILE.kind === 'codebuddy' ? createCodeBuddyFiles({root: PROFILE.historyRoot, sync:sessionSync}) : null;
+const codeBuddyFiles = PROFILE.kind === 'codebuddy' ? createCodeBuddyFiles({root: PROFILE.historyRoot, sync:sessionSync, resolveAccountUid: uid => assertSessionAccountIdentity(uid)}) : null;
if (codeBuddyFiles) sessionSync = codeBuddyFiles.sync;
// CN and international CodeBuddy share the history tree, but their WorkDaddy
@@ -531,8 +535,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.65:兼容空会话同步、自定义模型和重定向备份目录,工作目录恢复退避重试。
// 1.2.66:刷新凭据按原信封加密保存,同账号刷新去重,过期账号保留手动切换。
// 1.2.67:Windows 重启 GUI 客户端时不再请求隐藏主窗口,与冷启动保持一致。
-const DAEMON_VERSION = '1.2.69';
-const DAEMON_BUILD_ID = 'release-1.2.69-issue-fixes-1.2.19';
+const DAEMON_VERSION = '1.2.74';
+const DAEMON_BUILD_ID = 'release-1.2.74-account-identity-sync-errors';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -1420,9 +1424,10 @@ function scheduleOAuthStateCleanup(loginId) {
// 把无感登录采集到的账号写入 accounts/<uid>.info 备份(不触碰当前登录文件)
function saveSeamlessAccount(tokenData, accData) {
- const uid = String(accData.uid || '');
- if (!uid) throw new Error('官方接口未返回 uid,无法保存账号');
+ if (!String(accData.uid || '')) throw new Error('官方接口未返回 uid,无法保存账号');
+ const uid = accountIdentity(accData);
ensureDirs(DATA_DIR);
+ migrateAccountIdentities(DATA_DIR);
const session = buildSeamlessAuthFile(tokenData, accData);
const dest = backupPath(DATA_DIR, uid);
const tmp = dest + '.tmp';
@@ -1430,7 +1435,9 @@ function saveSeamlessAccount(tokenData, accData) {
fs.renameSync(tmp, dest);
fs.chmodSync(dest, 0o600);
updateMeta(DATA_DIR, {
- uid,
+ uid: String(accData.uid),
+ type: accData.type,
+ enterpriseId: accData.enterpriseId,
nickname: accData.nickname || '',
uin: accData.uin || '',
phone: accData.phoneNumber || '',
@@ -1879,7 +1886,7 @@ function readCodeBuddyBackupSession(uid) {
let session;
try { session = wdCompatDecryptAuthJson(JSON.parse(fs.readFileSync(file, 'utf8'))); }
catch (_) { throw new Error('账号备份无效'); }
- if (!parseAuthJson(session, { strict: true }) || String(session.account?.uid || '') !== String(uid)) {
+ if (!parseAuthJson(session, { strict: true }) || accountIdentity(session.account) !== String(uid)) {
throw new Error('账号备份无效或不属于当前地区');
}
if (!wdCompatAuthToken(session.auth)) throw new Error('账号备份中无可用 accessToken');
@@ -1923,7 +1930,7 @@ function syncCodeBuddyAuth() {
fs.renameSync(temp, AUTH_FILE);
fs.chmodSync(AUTH_FILE, 0o600);
}
- writeCodeBuddyNativeState(String(session.account.uid), false);
+ writeCodeBuddyNativeState(accountIdentity(session.account), false);
return session;
});
nativeAuthSyncTail = work;
@@ -1941,15 +1948,15 @@ async function switchAccountForProfile(uid) {
const file = accountBackupFile(uid);
const session = JSON.parse(fs.readFileSync(file, 'utf8'));
if (!parseAuthJson(session, {strict:true})) throw new Error('账号备份无效或不属于当前地区');
- if (String(session.account && session.account.uid) !== String(uid)) throw new Error('账号备份标识不匹配');
+ if (accountIdentity(session.account) !== String(uid)) throw new Error('账号备份标识不匹配');
if (!wdCompatAuthToken(session.auth)) {
if (wdCompatContainsEncryptedFields(session)) throw new Error('账号备份中的加密凭据无法解密,请在 WorkBuddy 侧重新登录后再导出');
throw new Error('账号备份中无 accessToken');
}
const result = await codeBuddyNative.replace(session);
- if (!result || result.uid !== String(uid)) throw new Error('CodeBuddy 未确认账号切换');
+ if (!result || String(result.uid) !== String(session.account.uid)) throw new Error('CodeBuddy 未确认账号切换');
const current = await syncCodeBuddyAuth();
- if (!current || String(current.account.uid) !== String(uid)) throw new Error('CodeBuddy 账号复核失败');
+ if (!current || accountIdentity(current.account) !== String(uid)) throw new Error('CodeBuddy 账号复核失败');
backupCurrent(DATA_DIR, log);
return {uid:String(uid),nickname:wdCompatText(current.account.nickname),nativeSwitched:true};
}
@@ -2961,11 +2968,11 @@ async function readRendererAccountSnapshot(expectedUid) {
awaitPromise: true, returnByValue: true,
});
const profile = result && result.result && result.result.value;
- if (!profile || profile.error || String(profile.uid || '') !== uid) throw new Error('切换后的 WorkBuddy 账号未就绪');
+ if (!profile || profile.error || accountIdentity(profile) !== uid) throw new Error('切换后的 WorkBuddy 账号未就绪');
if (typeof profile.nickname !== 'string' || typeof profile.type !== 'string' || typeof profile.href !== 'string') {
throw new Error('切换后的 WorkBuddy 账号资料不完整');
}
- const snapshot = { version: 1, uid, nickname: profile.nickname, type: profile.type, savedAt: Date.now() };
+ const snapshot = { version: 1, uid: String(profile.uid), nickname: profile.nickname, type: profile.type, savedAt: Date.now() };
for (const key of ['editionType', 'enterpriseId', 'enterpriseName', 'enterpriseUserName', 'avatarUrl', 'isPro', 'isAdmin', 'oneidAccountId', 'enableArdotDesign', 'showDefaultPermission']) {
if (profile[key] !== undefined && profile[key] !== null) snapshot[key] = profile[key];
}
@@ -4851,7 +4858,7 @@ const officialAutomationSyncEngine = PROFILE.kind === 'workbuddy'
? createOfficialAutomationSync({
dataDir: DATA_DIR,
db: SESSION_DB,
- getAccountUids: () => listAccounts(DATA_DIR).map(account => account.uid),
+ getAccountUids: () => listAccounts(DATA_DIR).map(account => assertSessionAccountIdentity(account.uid)),
})
: null;
const CODEBUDDY_SESSIONS = PROFILE.kind === 'codebuddy' ? createCodeBuddySessionStore({
@@ -4866,8 +4873,45 @@ const CODEBUDDY_SESSIONS = PROFILE.kind === 'codebuddy' ? createCodeBuddySession
},
}) : null;
+let sessionAccountResolverCache = null;
+function sessionAccountResolver() {
+ let fingerprint = '';
+ for (const file of [path.join(DATA_DIR, 'accounts'), path.join(DATA_DIR, 'meta.json')]) {
+ try { const stat = fs.statSync(file); fingerprint += stat.mtimeMs + ':' + stat.ctimeMs + ':' + stat.size + ';'; } catch (_) { fingerprint += '-;'; }
+ }
+ if (!sessionAccountResolverCache || sessionAccountResolverCache.fingerprint !== fingerprint) {
+ const accounts = listAccounts(DATA_DIR);
+ // Deleting a backup cannot make an already ambiguous official UID safe.
+ for (const [rawUid, ids] of Object.entries(knownAccountIdentities(DATA_DIR))) {
+ if (Array.isArray(ids)) ids.forEach(uid => accounts.push({ uid, rawUid }));
+ }
+ sessionAccountResolverCache = { fingerprint, resolver: createSessionAccountResolver(accounts) };
+ }
+ return sessionAccountResolverCache.resolver;
+}
+function assertSessionAccountIdentity(uid) {
+ return sessionAccountResolver().assertUnambiguous(uid);
+}
+function sessionAccountAmbiguous(uid) {
+ try { assertSessionAccountIdentity(uid); return false; } catch (_) { return true; }
+}
+function sessionDatabaseParams(sql, params) {
+ const mapped = params.slice();
+ // Match owner parameters only. Titles, cwd, session ids, etc. are never aliases.
+ for (const match of sql.matchAll(/\buser_id\s*=\s*\?/gi)) {
+ const at = parameterCount(sql.slice(0, match.index));
+ mapped[at] = assertSessionAccountIdentity(params[at]);
+ }
+ const insert = sql.match(/INSERT\s+INTO\s+sessions\s*\(([^)]+)\)\s*VALUES\s*\(/i);
+ if (insert) {
+ const at = insert[1].split(',').map(column => column.trim()).indexOf('user_id');
+ if (at >= 0) mapped[at] = assertSessionAccountIdentity(params[at]);
+ }
+ return mapped;
+}
+
function sqliteRun(sql, params = []) {
- return (CODEBUDDY_SESSIONS || SESSION_DB).run(sql, params);
+ return (CODEBUDDY_SESSIONS || SESSION_DB).run(sql, sessionDatabaseParams(sql, params));
}
function sqlParamAt(textSql, params, questionIndex) {
return params[parameterCount(textSql.slice(0, questionIndex + 1)) - 1];
@@ -4875,8 +4919,9 @@ function sqlParamAt(textSql, params, questionIndex) {
async function sqliteQuery(sql, params = []) {
const expectedParams = parameterCount(sql);
if (expectedParams !== params.length) throw new Error(`sqlite 参数数量不匹配: SQL 需要 ${expectedParams} 个,实际收到 ${params.length} 个`);
- const rows = await (CODEBUDDY_SESSIONS || SESSION_DB).all(sql, params);
- return rows.map(row => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, value == null ? '' : String(value).trim()])));
+ const rows = await (CODEBUDDY_SESSIONS || SESSION_DB).all(sql, sessionDatabaseParams(sql, params));
+ rows.forEach(row => { if (row.user_id) assertSessionAccountIdentity(row.user_id); });
+ return rows.map(row => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, key === 'user_id' ? sessionAccountResolver().identity(value == null ? '' : String(value).trim()) : value == null ? '' : String(value).trim()])));
}
// WorkBuddy 将会话正文保存在 ~/.workbuddy*/projects 等系统目录,同时在 sessions.cwd
@@ -5777,6 +5822,8 @@ async function copySessionRecord(src, targetUid, options = {}) {
const sourceUid = String(options.sourceUid || src.user_id || '').trim();
targetUid = String(targetUid || '').trim();
if (!sourceUid || !targetUid || sourceUid === targetUid) return { status: 'skipped', sourceId: src.id, targetId: src.id };
+ assertSessionAccountIdentity(sourceUid);
+ assertSessionAccountIdentity(targetUid);
// Provenance, not matching titles/timestamps, identifies an existing copy.
const lineageId = options.lineageId || getAutoCopySession(DATA_DIR, sourceUid, src.id).lineageId ||
ensureAutoCopySession(DATA_DIR, sourceUid, src.id, { enabled: false });
@@ -6050,6 +6097,8 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
const source = String(sourceUid || '').trim();
const target = String(targetUid || '').trim();
if (!source || !target || source === target) return [];
+ assertSessionAccountIdentity(source);
+ assertSessionAccountIdentity(target);
const deletions = typeof getSessionDeletionSync === 'function' ? getSessionDeletionSync() : null;
if (deletions && await deletions.reconcileAll() && typeof refreshWorkBuddySessionList === 'function') {
await refreshWorkBuddySessionList(target, 'sessions-deleted');
@@ -6356,9 +6405,10 @@ function runAutoCopyQueue() {
.catch((e) => {
const job = item.job;
job.status = 'error';
- job.error = e.message;
+ job.error = sanitizeSessionCopyError(e);
+ job.taskFailed = true;
job.finishedAt = Date.now();
- log(`[sessions-auto-copy] 任务失败: ${e.message}`);
+ log(`[sessions-auto-copy] 任务失败: ${job.error}`);
const cleanup = setTimeout(() => autoCopyJobs.delete(job.id), 30 * 60 * 1000);
if (cleanup.unref) cleanup.unref();
pruneAutoCopyJobs();
@@ -6635,6 +6685,7 @@ function publicAutoCopyJob(job) {
warning: job.warning || '',
conflicts: job.conflicts,
details: Array.isArray(job.details) ? job.details.slice(0, 500) : [],
+ taskFailed: job.status === 'error',
error: job.error,
sourceUid: job.sourceUid,
targetUid: job.targetUid,
@@ -7355,6 +7406,30 @@ function deleteQuickPhrases(ids) {
writeSessionState(st);
return readSessionState();
}
+function reorderQuickPhrases(ids) {
+ if (!Array.isArray(ids)) throw new Error('快捷短语顺序无效');
+ const state = readSessionState();
+ if (ids.length !== state.phrases.length) throw new Error('快捷短语列表已变化,请刷新后重试');
+ const byId = new Map(state.phrases.map((item) => [String(item.id), item]));
+ const seen = new Set();
+ const ordered = ids.map((value) => {
+ const id = String(value || '').trim();
+ if (!id || seen.has(id) || !byId.has(id)) throw new Error('快捷短语顺序无效');
+ seen.add(id);
+ return byId.get(id);
+ });
+ state.phrases = ordered;
+ writeSessionState(state);
+ return readSessionState();
+}
+async function insertQuickPhraseIntoComposer(text) {
+ const value = String(text || '');
+ if (!value.trim()) throw new Error('短语不能为空');
+ if (value.length > 10000) throw new Error('快捷短语过长');
+ if (!cdp.connected) throw new Error('CDP 未连接');
+ await cdpSend('Input.insertText', { text: value });
+ return { inserted: true };
+}
function normalizeQuickPhraseIds(ids) {
if (!Array.isArray(ids)) throw new Error('快捷短语选择必须是数组');
if (ids.length > 1000) throw new Error('单次最多处理 1000 条快捷短语');
@@ -7781,7 +7856,10 @@ function currentAccount() {
const c = readAuthFile(resolution.file);
const a = (c.raw && c.raw.auth) || {};
return {
- uid: c.uid,
+ uid: c.accountId || c.uid,
+ rawUid: c.uid,
+ type: c.type,
+ enterpriseId: c.enterpriseId,
nickname: c.nickname,
phone: c.phone,
uin: c.uin,
@@ -7809,7 +7887,7 @@ function syncAccountAutomations(sourceUid, targetUid) {
async function syncOfficialAccountAutomations(sourceUid, targetUid) {
if (!officialAutomationSyncEngine) return { copied: 0, skipped: 0, total: 0 };
- return officialAutomationSyncEngine(sourceUid, targetUid);
+ return officialAutomationSyncEngine(assertSessionAccountIdentity(sourceUid), assertSessionAccountIdentity(targetUid));
}
function accountBackupFile(uid) {
@@ -8480,7 +8558,7 @@ async function releaseThemeByCdp() {
async function restoreNativeAppearanceByCdp() {
if (!cdp.connected) return;
let _accUid = null;
- try { const _a = currentAccount(); _accUid = _a ? _a.uid : null; } catch (_) {}
+ try { const _a = currentAccount(); _accUid = _a ? (_a.rawUid || _a.uid) : null; } catch (_) {}
const uid = (typeof _accUid === 'string' && _accUid) ? _accUid : null;
if (!uid) return;
try {
@@ -8807,7 +8885,7 @@ async function applyThemeByCdp(id, options = {}) {
if (!settled || settled.exceptionDetails || !settled.result || !settled.result.value || !settled.result.value.ready) throw new Error('官方深色主题尚未就绪,请重试毛玻璃主题');
}
let _accUid = null;
- try { const _a = currentAccount(); _accUid = _a ? _a.uid : null; } catch (_) {}
+ try { const _a = currentAccount(); _accUid = _a ? (_a.rawUid || _a.uid) : null; } catch (_) {}
const uid = (typeof _accUid === 'string' && _accUid) ? _accUid : null;
const theme = getTheme(id);
const colors = (theme && theme.colors) || {};
@@ -10506,6 +10584,22 @@ function handleApi(req, res) {
}
});
}
+ // 会话模块:POST /api/quick-phrase-reorder { ids: [...] }
+ if (req.method === 'POST' && p === '/api/quick-phrase-reorder') {
+ return readBody(req).then((body) => {
+ try {
+ return json(res, 200, { ok: true, ...reorderQuickPhrases(body && body.ids) });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ // 会话模块:POST /api/quick-phrase-insert { text }(在当前输入光标处插入,不发送)
+ if (req.method === 'POST' && p === '/api/quick-phrase-insert') {
+ return readBody(req).then((body) => insertQuickPhraseIntoComposer(body && body.text))
+ .then((result) => json(res, 200, { ok: true, ...result }))
+ .catch((e) => json(res, 400, { ok: false, error: e.message }));
+ }
// 快捷短语加密导出:POST /api/quick-phrases/export { ids, password }
if (req.method === 'POST' && p === '/api/quick-phrases/export') {
return readBody(req).then((body) => {
@@ -10876,18 +10970,31 @@ function handleApi(req, res) {
try {
const uid = String(body && body.uid || '').trim();
const modelId = String(body && body.modelId || '').trim();
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) return json(res, 400, { ok: false, error: 'uid 格式无效' });
- if (!/^[^\x00-\x1F\x7F]{1,160}$/.test(modelId)) return json(res, 400, { ok: false, error: '模型 ID 无效' });
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(uid)) {
+ log('[model-rate-limit] WARN 拒绝上报: invalid-uid');
+ return json(res, 400, { ok: false, error: 'uid 格式无效' });
+ }
+ if (!/^[^\x00-\x1F\x7F]{1,160}$/.test(modelId)) {
+ log('[model-rate-limit] WARN 拒绝上报: invalid-model-id');
+ return json(res, 400, { ok: false, error: '模型 ID 无效' });
+ }
const account = listAccounts(DATA_DIR).find((item) => String(item.uid) === uid);
- if (!account) return json(res, 404, { ok: false, error: '账号不存在' });
+ if (!account) {
+ log('[model-rate-limit] WARN 拒绝上报: account-not-found');
+ return json(res, 404, { ok: false, error: '账号不存在' });
+ }
const reasonCode = body && body.reasonCode === null ? null : Number(body && body.reasonCode);
- if (reasonCode !== 6004) return json(res, 400, { ok: false, error: '仅记录模型限流 code 6004' });
+ if (![6000, 6004].includes(reasonCode)) {
+ log('[model-rate-limit] WARN 拒绝上报: unsupported-reason-code');
+ return json(res, 400, { ok: false, error: '仅记录模型用量限制 code 6000 和频率限制 code 6004' });
+ }
const now = Date.now();
const resetAt = body && body.resetAt === null ? null : Number(body && body.resetAt);
if (resetAt !== null && (!Number.isSafeInteger(resetAt) || resetAt < now - 86400000 || resetAt > now + 90 * 86400000)) {
+ log('[model-rate-limit] WARN 拒绝上报: invalid-reset-time');
return json(res, 400, { ok: false, error: '解封时间无效' });
}
- if (resetAt !== null && await CREDIT_USAGE_STORE.hasModelRateLimitElsewhere({ uid, modelId, resetAt, now })) {
+ if (resetAt !== null && await CREDIT_USAGE_STORE.hasModelRateLimitElsewhere({ uid, modelId, resetAt, reasonCode, now })) {
return json(res, 200, { ok: true, skipped: 'duplicate-across-accounts' });
}
await CREDIT_USAGE_STORE.saveModelRateLimit({
@@ -10900,6 +11007,7 @@ function handleApi(req, res) {
});
return json(res, 200, { ok: true });
} catch (error) {
+ log('[model-rate-limit] WARN 写入失败: storage-error');
return json(res, 400, { ok: false, error: error.message });
}
});
@@ -11344,15 +11452,16 @@ function handleApi(req, res) {
for (const candidate of candidates) {
const normalizedImport = normalizeAccountImportJson(candidate);
if (!normalizedImport) continue;
- const { uid, normalized } = normalizedImport;
- const acct = normalized.account;
+ const { normalized, authRecord } = normalizedImport;
+ const uid = authRecord.accountId;
+ migrateAccountIdentities(DATA_DIR);
const dest = backupPath(DATA_DIR, uid);
const tmp = dest + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(normalized), { mode: 0o600 });
fs.renameSync(tmp, dest);
try { fs.chmodSync(dest, 0o600); } catch (_) {}
updateMeta(DATA_DIR, {
- uid,
+ ...authRecord,
nickname: wdCompatText(normalized.account.nickname),
uin: typeof normalized.account.uin === 'string' || typeof normalized.account.uin === 'number' ? normalized.account.uin : '',
phone: wdCompatText(normalized.account.phoneNumber),
@@ -11378,24 +11487,26 @@ function handleApi(req, res) {
ensureDirs(DATA_DIR);
const imported = [];
for (const item of list) {
- const uid = String(item && item.uid || '').trim();
+ const suppliedUid = String(item && item.uid || '').trim();
const info = item && item.info;
// 导出文件属于用户输入;UID 只能是账号文件名的一段,禁止路径分隔符和
// 特殊目录名,避免导入请求把认证内容写到 accounts 目录之外。
- if (!uid || uid.length > 200 || uid === '.' || uid === '..' || /[\\/\0]/.test(uid) || typeof info !== 'string') continue;
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(suppliedUid) || typeof info !== 'string') continue;
let j;
try { j = JSON.parse(info); } catch (_) { continue; }
const acct = j.account || (Array.isArray(j.accounts) && j.accounts[0]);
- if (!acct || !acct.uid || String(acct.uid) !== uid) continue; // 安全校验:uid 必须匹配
+ if (!acct || !acct.uid) continue;
const authRecord = parseAuthJson(j);
- if (!authRecord || authRecord.uid !== uid) continue;
+ if (!authRecord || (suppliedUid !== authRecord.uid && suppliedUid !== authRecord.accountId)) continue;
+ const uid = authRecord.accountId;
+ migrateAccountIdentities(DATA_DIR);
const dest = backupPath(DATA_DIR, uid);
const tmp = dest + '.tmp';
fs.writeFileSync(tmp, info, { mode: 0o600 });
fs.renameSync(tmp, dest);
try { fs.chmodSync(dest, 0o600); } catch (_) {}
updateMeta(DATA_DIR, {
- uid,
+ ...authRecord,
nickname: wdCompatText(acct.nickname),
uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '',
phone: wdCompatText(acct.phoneNumber),
@@ -11910,6 +12021,7 @@ function handleApi(req, res) {
);
if (!rows.length || String(rows[0].user_id || '') !== uid) return json(res, 404, { ok: false, error: '会话不存在或不属于该账号' });
}
+ assertSessionAccountIdentity(uid);
const rules = setAutoCopyRule(DATA_DIR, { uid, kind, key, enabled: body.enabled !== false });
return json(res, 200, { ok: true, uid, kind, key: kind === 'workspace' ? canonicalWorkspace(key) : key, rules });
} catch (e) {
@@ -11947,6 +12059,7 @@ function handleApi(req, res) {
(/^[A-Za-z0-9_-]{1,128}$/.test(claimedUid) && fs.existsSync(accountBackupFile(claimedUid)) ? claimedUid : '');
if (!uid) return json(res, 409, { ok: false, error: '当前账号不可用' });
if (!body || typeof body !== 'object' || Array.isArray(body)) return json(res, 400, { ok: false, error: '脏会话通知格式无效' });
+ assertSessionAccountIdentity(uid);
if (body.ready === true) markSessionDirtyBaseline(uid);
const events = Array.isArray(body.events) ? body.events : [];
if (events.length > 500) return json(res, 400, { ok: false, error: '脏会话通知过多' });
@@ -12157,6 +12270,7 @@ function handleApi(req, res) {
'SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ') AND deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0;',
ids
);
+ before.forEach(row => assertSessionAccountIdentity(row.user_id));
await sqliteRun(
"UPDATE sessions SET user_id = ?, updated_at = ? WHERE id IN (" + placeholders + ");",
[targetUid, Date.now(), ...ids]
@@ -12214,6 +12328,7 @@ function handleApi(req, res) {
if (!memberIds.length) return json(res, 404, { ok: false, error: '会话不存在或已删除' });
const placeholders = sqlPlaceholders(memberIds);
const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ') AND COALESCE(is_background_automation, 0) = 0;', memberIds);
+ before.forEach(row => assertSessionAccountIdentity(row.user_id));
const matchedSet = new Set(before.map((row) => String(row.id || '')));
const matchedIds = memberIds.filter((id) => matchedSet.has(String(id)));
const matchedRows = before.filter((row) => matchedSet.has(String(row.id || '')));
@@ -12767,7 +12882,7 @@ function handleApi(req, res) {
const info = backupCurrent(DATA_DIR, log);
return json(res, 200, {
ok: true,
- uid: info.uid,
+ uid: info.accountId || info.uid,
nickname: info.nickname,
});
} catch (e) {
@@ -12793,7 +12908,7 @@ function handleApi(req, res) {
// Renderer projection state can briefly retain the destination id from
// the previous rotation. Never carry an id into the next account unless
// the session index proves it belongs to the account being replaced.
- if (currentConversationId && sourceUid) {
+ if (currentConversationId && sourceUid && !sessionAccountAmbiguous(sourceUid)) {
const ownerRows = await sqliteQuery(
'SELECT user_id, cwd FROM sessions WHERE id = ? AND deleted_at IS NULL LIMIT 1;',
[currentConversationId]
@@ -12805,6 +12920,7 @@ function handleApi(req, res) {
currentConversationRow = { ...ownerRows[0], id: currentConversationId };
}
}
+ if (sessionAccountAmbiguous(sourceUid)) currentConversationId = '';
if (sourceUid !== uid) await preserveAccountSwitchTheme(uid);
const acct = await switchAccountForProfile(uid);
const hint = acct.nativeSwitched ? '原生登录态已切换,无需重启客户端' : '登录文件已切换,请刷新窗口使新账号生效';
diff --git a/scripts/inject.js b/scripts/inject.js
index 82fa798..0d18838 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -377,8 +377,8 @@ function classifyAutoContinueReply(snapshot) {
if (s.serviceErrorFallback) {
return { trigger: false, reason: 'service-error-fallback' };
}
- if (s.nonRetryableError || s.quotaExhausted || s.rateLimited || s.authFailure) {
- return { trigger: false, reason: s.rateLimited ? 'model-rate-limited' : (s.quotaExhausted ? 'quota-exhausted' : 'non-retryable-error') };
+ if (s.nonRetryableError || s.quotaExhausted || s.usageLimited || s.rateLimited || s.authFailure) {
+ return { trigger: false, reason: s.rateLimited ? 'model-rate-limited' : (s.usageLimited ? 'model-usage-limited' : (s.quotaExhausted ? 'quota-exhausted' : 'non-retryable-error')) };
}
if (s.error || s.networkFailure) {
return { trigger: true, reason: s.networkFailure ? 'network-failure' : 'error-ui' };
@@ -387,7 +387,7 @@ function classifyAutoContinueReply(snapshot) {
return { trigger: false, reason: 'no-incomplete-evidence' };
}
-var AUTO_CONTINUE_QUOTA_CODES = { 14012: true, 14014: true, 14018: true, 14019: true, 6004: true };
+var AUTO_CONTINUE_QUOTA_CODES = { 14012: true, 14014: true, 14018: true, 14019: true, 6000: true, 6004: true };
function normalizeAutoContinueError(error) {
if (!error || typeof error !== 'object') return null;
@@ -401,9 +401,10 @@ function normalizeAutoContinueError(error) {
}
return null;
}
- // The official cap banner gives terminal.bizCode=6004 precedence over the
- // outer transport code (including 0/500), so statistics must do the same.
- var code = Number(terminal.bizCode) === 6004 ? 6004 : numberValue(error.code, error.bizCode, terminal.bizCode, details.code);
+ // Official model limits use terminal.bizCode even when the outer request
+ // reports a transport error.
+ var code = Number(terminal.bizCode) === 6000 || Number(terminal.bizCode) === 6004
+ ? Number(terminal.bizCode) : numberValue(error.code, error.bizCode, terminal.bizCode, details.code);
var statusCode = numberValue(error.statusCode, error.status, error.httpStatus);
var requestModelId = String(error.requestModelId || error.modelId || details.requestModelId || '').slice(0, 160);
var category = String(error.category || error.type || details.category || '').slice(0, 80).toLowerCase();
@@ -414,6 +415,7 @@ function normalizeAutoContinueError(error) {
return typeof value === 'string';
}).map(function (value) { return value.slice(0, 4096); }).join(' ');
var rateLimited = code === 6004 || statusCode === 429 || /rate.?limit|频率|限流/i.test(category + ' ' + message);
+ var usageLimited = code === 6000;
var quotaExhausted = code === 14018 || code === 14012 || code === 14014 || code === 14019 || /quota|credit|额度|积分|余额/i.test(category + ' ' + message);
var authFailure = statusCode === 401 || statusCode === 403 || /auth|credential|登录|认证/i.test(category + ' ' + message);
var resetAt = null;
@@ -441,9 +443,10 @@ function normalizeAutoContinueError(error) {
requestModelId: requestModelId,
resetAt: resetAt,
rateLimited: rateLimited,
+ usageLimited: usageLimited,
quotaExhausted: quotaExhausted,
authFailure: authFailure,
- nonRetryable: rateLimited || quotaExhausted || authFailure || AUTO_CONTINUE_QUOTA_CODES[code] === true,
+ nonRetryable: rateLimited || usageLimited || quotaExhausted || authFailure || AUTO_CONTINUE_QUOTA_CODES[code] === true,
terminal: terminal === error.terminal || terminal.isTerminal === true,
};
}
@@ -459,14 +462,15 @@ function createModelRateLimitObserver(options) {
var state = controller.sessionStore.getState() || {};
[state.error, state.warning].forEach(function (error) {
var normalized = normalizeAutoContinueError(error);
- if (!normalized || normalized.code !== 6004) return;
+ if (!normalized || (normalized.code !== 6004 && normalized.code !== 6000)) return;
var modelId = normalized.requestModelId || String(state.model || state.modelId || '');
if (!modelId) return;
binding.latest = {
conversationId: String(controller.conversationId || ''),
assistantId: String(error.requestId || ''),
- rateLimited: true,
- errorCode: 6004,
+ rateLimited: normalized.code === 6004,
+ limitType: normalized.code === 6000 ? 'usage' : 'frequency',
+ errorCode: normalized.code,
errorRequestModelId: modelId,
errorModelName: modelId,
errorResetAt: normalized.resetAt,
@@ -514,6 +518,7 @@ function classifyAutoContinueError(error) {
var normalized = normalizeAutoContinueError(error) || {};
return {
quotaExhausted: !!normalized.quotaExhausted,
+ usageLimited: !!normalized.usageLimited,
rateLimited: !!normalized.rateLimited,
authFailure: !!normalized.authFailure,
nonRetryable: !!normalized.nonRetryable,
@@ -538,6 +543,7 @@ function classifyAutoContinueControllerSnapshot(snapshot) {
terminal: !!s.terminal,
serviceErrorFallback: !!s.serviceErrorFallback,
quotaExhausted: !!s.quotaExhausted,
+ usageLimited: !!s.usageLimited,
rateLimited: !!s.rateLimited,
authFailure: !!s.authFailure,
nonRetryableError: !!s.nonRetryableError,
@@ -572,6 +578,7 @@ function controllerAutoContinueDecision(snapshot) {
completionMarker: s.completionMarker,
serviceErrorFallback: s.serviceErrorFallback,
quotaExhausted: s.quotaExhausted,
+ usageLimited: s.usageLimited,
rateLimited: s.rateLimited,
authFailure: s.authFailure,
nonRetryableError: s.nonRetryableError,
@@ -820,10 +827,10 @@ function isSessionMonitorInProgress(snapshot) {
function isSessionMonitorInterrupted(snapshot) {
var s = snapshot || {};
if (!s || s.busy || s.blocked || s.hydrating) return false; // 运行/等决策/恢复中:交给 in-progress 分支
- // 额度/限频错误通常同时带有 terminal=true 和 serviceErrorFallback=true。
+ // 限额错误通常同时带有 terminal=true 和 serviceErrorFallback=true。
// 它们必须进入一次监控判定,先落盘模型限频记录并刷新账号标签;
// controllerAutoContinueDecision 仍会因终局证据返回 trigger=false,因此不会自动重试。
- if (s.rateLimited || s.quotaExhausted) return true;
+ if (s.rateLimited || s.usageLimited || s.quotaExhausted) return true;
return controllerAutoContinueDecision(s).trigger === true;
}
@@ -1165,7 +1172,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var n;
if ((n = document.querySelector('.wbs-root'))) n.remove();
if ((n = document.getElementById('wbs-window-logo'))) n.remove();
- var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline, .wbs-explore-pop, .wbs-fork-button');
+ var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline, .wbs-explore-pop, #wbs-qp-insert-tooltip, .wbs-fork-button');
for (var i = 0; i < st.length; i++) st[i].remove();
var nav = document.querySelectorAll('.wbs-message-nav-root');
for (var ni = 0; ni < nav.length; ni++) nav[ni].remove();
@@ -1506,6 +1513,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var WBS_ACCOUNT_NOTE_HOVER_KEY = 'workdaddy.account.noteHover.' + PROFILE_ID;
var WBS_GROWTH_PLAN_HOVER_KEY = 'workdaddy.account.growthPlanHover.' + PROFILE_ID;
var WBS_I18N_EN = {
+ '个人版与企业版共用官方会话 UID,无法可靠区分会话归属,已停止同步;账号备份和切换仍可使用': 'Personal and enterprise accounts share an official session UID. Sync stopped because ownership is ambiguous; account backup and switching remain available',
+ '会话数据库正被占用,请稍后重新同步': 'Session database is busy. Please retry later',
+ '没有读取或写入会话文件的权限,请检查文件权限后重新同步': 'Cannot access session files. Check permissions and retry',
+ '会话数据库或文件不存在,请确认 WorkBuddy 已正常启动后重新同步': 'Session database or file is missing. Start WorkBuddy and retry',
+ '磁盘空间不足,请释放空间后重新同步': 'Disk is full. Free space and retry',
+ '会话数据库无法读取,请先检查 WorkBuddy 是否能正常打开会话': 'Session database is unreadable. Check whether WorkBuddy can open sessions',
+ '会话数据库结构不兼容,请更新 WorkDaddy 后重新同步': 'Session database schema is incompatible. Update WorkDaddy and retry',
+ '同步任务异常中断,请稍后重新同步;若仍失败,请反馈客户端版本及同步阶段': 'Sync task interrupted. Retry later; if it persists, report the client version and sync stage',
+
+ '任务失败': 'Task failed',
+ '同步任务': 'Sync task',
+ '请查看明细': 'Please view details',
+ '同步任务异常中断,请稍后重新同步': 'Sync task interrupted. Please retry later',
+ '企业身份的个性化目录尚未确认,暂不支持共享个性化': 'Enterprise personalization directory is unverified; sharing is unavailable',
"同步个性化": "Sync personalization",
"不再提醒": "Don't remind me again",
"了解同步个性化": "About personalization sync",
@@ -1729,7 +1750,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'停止运行': 'Stop running',
'账号': 'Accounts', '主题': 'Theme', '会话': 'Sessions', '模型': 'Models', '增强': 'Enhance', '自动化': 'Automation', '电脑': 'Computer', '关于': 'About', '设置': 'Settings',
'导出': 'Export', '导入': 'Import', '删除': 'Delete', '编辑': 'Edit', '保存': 'Save', '内置': 'Built-in', '取消': 'Cancel', '确定': 'Confirm', '确认': 'Confirm', '复制': 'Copy', '切换': 'Switch', '启用': 'Enable', '停用': 'Disable', '停止': 'Stop', '立即运行': 'Run now', '新建任务': 'New task', '刷新': 'Refresh', '步骤 JSON': 'Steps JSON', '任务说明': 'Task description', '任务名称': 'Task name', '调度': 'Schedule', '手动运行': 'Manual', '手动': 'Manual', '每小时': 'Hourly', '每天': 'Daily', '选择任务': 'Select tasks', '查看接口': 'View capabilities', '拾取元素': 'Pick element', '复制 XPath': 'Copy XPath', '运行中': 'Running', '已成功': 'Succeeded', '失败': 'Failed', '未运行': 'Not run', '页面加载完成': 'Page loaded', '账号切换完成': 'Account switched', '新自动化任务': 'New automation task', '任务已保存': 'Task saved', '任务已开始运行': 'Task started', '步骤 JSON 格式无效': 'Invalid steps JSON', '步骤 JSON 必须是数组': 'Steps JSON must be an array', '查看接口说明': 'View interface docs', '自动化接口协议': 'Automation interface protocol', '复制全部': 'Copy all', '接口协议已复制': 'Interface protocol copied', '暂无自动化任务': 'No automations yet', '编辑任务': 'Edit task', '触发方式': 'Trigger', '插入点击步骤': 'Insert click step', 'XPath 已复制': 'XPath copied', '点击步骤已插入': 'Click step inserted', '请先拾取元素': 'Pick an element first', '加载自动化失败': 'Failed to load automations', '读取接口失败': 'Failed to read interfaces', '批量操作失败': 'Batch operation failed', '删除失败': 'Delete failed', '确认删除该任务?': 'Delete this task?', '执行': 'Apply', '已拾取': 'Picked', '运行失败': 'Run failed', '(副本)': ' (copy)', '查看提示词': 'View prompt', '交给 WorkBuddy 创建': 'Ask WorkBuddy to create', '正在打开新任务…': 'Opening a new task…', '已创建新会话,WorkBuddy 完成后任务会自动出现': 'New session created. The task will appear after WorkBuddy finishes.', 'WorkBuddy 创建失败': 'WorkBuddy creation failed', '加载示例失败': 'Failed to load examples', '暂无示例': 'No examples available', '运行日志': 'Run logs', '暂无运行日志': 'No run logs yet', '开始时间': 'Started', '结束时间': 'Finished', '捕获错误': 'Caught error', '暂无执行日志': 'No execution log entries', '执行日志': 'Execution log', '尚未结束': 'Still running',
- '暂存提示词': 'Stash prompt', '暂存': 'Stashed', '引用文本': 'Quote text', '快捷短语': 'Quick phrases', '点击后发送': 'Send on click', '编辑 →': 'Edit →', '新增': 'Add', '批量操作': 'Batch actions', '批量管理': 'Batch manage', '全选': 'Select all', '取消全选': 'Deselect all', '已选 0': 'Selected 0',
+ '暂存提示词': 'Stash prompt', '暂存': 'Stashed', '引用文本': 'Quote text', '快捷短语': 'Quick phrases', '点击后发送': 'Send on click', '仅插入到对话框': 'Insert into dialog only', '拖动排序': 'Drag to reorder', '排序失败:': 'Reorder failed:', '插入失败:': 'Insert failed:', '编辑 →': 'Edit →', '新增': 'Add', '批量操作': 'Batch actions', '批量管理': 'Batch manage', '全选': 'Select all', '取消全选': 'Deselect all', '已选 0': 'Selected 0',
'分支到新会话': 'Start a new conversation here', '从这里开始新会话': 'Start a new conversation here', '复制到这条回复为止的聊天内容,在当前工作区继续聊;原会话不变。': 'Copy the conversation up to this reply into a new conversation in the current workspace. The original stays unchanged.', '正在创建分支会话…': 'Creating branch session…', '分支会话已创建,正在打开…': 'Branch created. Opening…', '分支会话已创建,但无法自动打开,请在会话列表中查找。': 'Branch created but could not open automatically. Check the sessions list.', '新会话未出现在列表中,请在会话列表中查找。': 'The new session is not listed yet. Check the sessions list.', '无法确认所选消息的分支位置,请稍后重试': 'Cannot confirm this reply position. Try again shortly.', '分支失败: ': 'Branch failed: ',
'账号汇总': 'Account summary', '账号数': 'Accounts', '总积分': 'Total credits', '手机': 'Phone', '有效期至': 'Expires', '当前使用中': 'Currently active', '隐藏敏感信息': 'Mask sensitive info', '显示明文': 'Show plaintext', '登录新账号': 'Log in a new account', '没有可导出的账号备份': 'No account backups to export', '还没有备份账号。打开/登录一次 WorkBuddy 后会自动备份,稍后再来查看。': 'No account backups yet. Open or log in to WorkBuddy once and check again later.',
'软件渲染(闪屏兼容)': 'Software rendering (flicker workaround)',
@@ -1942,8 +1963,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'开启后 WorkBuddy 需要你决策时会用弹窗提问(写入全局自定义指令,所有会话生效)': 'When enabled, WorkBuddy asks with a dialog when your decision is needed (written to the global custom prompt; affects all sessions)',
'当前没有进行中的会话,无法开启「所有会话结束允许休眠」': 'No active sessions; cannot enable “Allow sleep when all sessions end”',
'进行中的会话': 'active session(s)', '预计剩余': 'Estimated remaining', ' 秒': ' seconds', ' 分': ' minutes',
- '预计解封:': 'Reset estimate: ', '预计解封:时间未知': 'Reset estimate: unknown', '预计解封': 'Reset estimate', '时间未知': 'Time unknown', '模型限流': 'Model rate limited', '模型限流·': 'Model rate limited ·', '模型频率限制': 'Model rate limit', '账号状态': 'Account status', '当前没有有效的模型限流记录': 'No active model rate-limit records',
- '当前模型已触发频率限制,已停止自动发送': 'This model is rate limited; automatic sending stopped', '当前账号积分已耗尽': 'This account has no credits left', '模型:': 'Model: ',
+ '预计解封:': 'Reset estimate: ', '预计解封:时间未知': 'Reset estimate: unknown', '预计解封': 'Reset estimate', '预计恢复:': 'Recovery estimate: ', '预计恢复:时间未知': 'Recovery estimate: unknown', '预计恢复': 'Recovery estimate', '时间未知': 'Time unknown', '模型限流': 'Model rate limited', '模型限流·': 'Model rate limited ·', '模型限制': 'Model limit', '模型限制·': 'Model limit ·', '模型频率限制': 'Model rate limit', '频率限制': 'Frequency limit', '用量限制': 'Usage limit', '账号状态': 'Account status', '当前没有有效的模型限制记录': 'No active model limit records',
+ '当前模型已触发频率限制,已停止自动发送': 'This model is rate limited; automatic sending stopped', '当前模型用量已达限制,已停止自动发送': 'This model has reached its usage limit; automatic sending stopped', '当前账号积分已耗尽': 'This account has no credits left', '模型:': 'Model: ',
'无法打开安装程序': 'Could not open the installer',
'安装程序已打开,请按提示退出 WorkBuddy 并完成安装。': 'The installer is open. Please quit WorkBuddy as prompted and finish installing.',
'安装程序已打开,请到任务栏选择安装窗口;按提示退出 WorkBuddy 后完成安装。': 'The installer is open. Select its window from the taskbar, then quit WorkBuddy as prompted to finish installing.',
@@ -3700,7 +3721,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function applyInjectedI18n() {
applyI18n(root);
- var nodes = document.querySelectorAll('.wbs-stash-inline,.wbs-queue-tag,.wbs-message-nav-root,.wbs-fork-button,#wbs-fork-tooltip,#wbs-auto-inspector,#wbs-auto-inspect-tip');
+ var nodes = document.querySelectorAll('.wbs-stash-inline,.wbs-queue-tag,.wbs-message-nav-root,.wbs-fork-button,#wbs-fork-tooltip,#wbs-qp-insert-tooltip,#wbs-auto-inspector,#wbs-auto-inspect-tip');
for (var i = 0; i < nodes.length; i++) applyI18n(nodes[i]);
}
window.__wbsSetLanguage = setLanguage;
@@ -3867,7 +3888,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>';
applyI18n(exploreBtn);
var explorePopover = exploreBtn.querySelector('.wbs-explore-pop');
- var exploreMenu = mountExplorePopover(exploreBtn, explorePopover);
+ var qpInsertTooltip = mountQuickPhraseInsertTooltip(explorePopover);
+ registerDisposer(qpInsertTooltip.destroy);
+ var exploreMenu = mountExplorePopover(exploreBtn, explorePopover, qpInsertTooltip.hide);
registerDisposer(exploreMenu.destroy);
var exploreSendTxt = explorePopover.querySelector('.wbs-explore-send-txt');
if (exploreSendTxt) {
@@ -3918,7 +3941,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
// Only the popup leaves the official toolbar. Its body-level stacking context
// keeps it above the usage summary even when the composer creates its own layer.
- function mountExplorePopover(button, popup) {
+ function mountExplorePopover(button, popup, onClose) {
if (CAPS.enhance === false) return { close: function () {}, open: function () {}, destroy: function () {} };
mountPersistentOverlay(popup);
var timer = null;
@@ -3928,7 +3951,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
listeners.push(function () { target.removeEventListener(name, handler, options); });
}
function cancelClose() { if (timer) { clearTimeout(timer); timer = null; } }
- function close() { cancelClose(); popup.classList.remove('is-open'); button.setAttribute('aria-expanded', 'false'); }
+ function close() { cancelClose(); popup.classList.remove('is-open'); button.setAttribute('aria-expanded', 'false'); if (onClose) onClose(); }
function open() {
cancelClose();
var rect = button.getBoundingClientRect();
@@ -3962,6 +3985,37 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
listen(document, 'pointerdown', function (event) { if (!button.contains(event.target) && !popup.contains(event.target)) close(); }, true);
return { close: close, open: open, destroy: function () { close(); listeners.forEach(function (remove) { remove(); }); popup.remove(); } };
}
+ function mountQuickPhraseInsertTooltip(popup) {
+ var tooltip = el('span', 'wbs-telemetry-tooltip wbs-qp-insert-tooltip', '仅插入到对话框');
+ tooltip.id = 'wbs-qp-insert-tooltip';
+ tooltip.setAttribute('role', 'tooltip');
+ mountPersistentOverlay(tooltip);
+ applyI18n(tooltip);
+ var listeners = [];
+ function listen(target, name, handler, options) {
+ target.addEventListener(name, handler, options);
+ listeners.push(function () { target.removeEventListener(name, handler, options); });
+ }
+ function hide() { tooltip.classList.remove('is-visible'); popup.classList.remove('wbs-explore-action-tip'); }
+ function buttonAt(target) { return target && target.closest && target.closest('[data-qp-insert]'); }
+ function show(event) {
+ var button = buttonAt(event.target);
+ if (!button || !popup.contains(button) || !popup.classList.contains('is-open')) return;
+ var rect = button.getBoundingClientRect();
+ tooltip.classList.add('is-visible'); popup.classList.add('wbs-explore-action-tip');
+ var width = tooltip.offsetWidth, height = tooltip.offsetHeight;
+ tooltip.style.left = Math.round(Math.max(8, Math.min(window.innerWidth - width - 8, rect.left + rect.width / 2 - width / 2))) + 'px';
+ tooltip.style.top = Math.round(Math.max(8, Math.min(window.innerHeight - height - 8, rect.bottom + height + 10 < window.innerHeight ? rect.bottom + 7 : rect.top - height - 7))) + 'px';
+ }
+ listen(popup, 'pointerover', show);
+ listen(popup, 'focusin', show);
+ listen(popup, 'pointerout', function (event) { var button = buttonAt(event.target); if (button && !button.contains(event.relatedTarget)) hide(); });
+ listen(popup, 'focusout', hide);
+ listen(popup, 'click', hide, true);
+ listen(window, 'resize', hide);
+ listen(document, 'scroll', hide, true);
+ return { hide: hide, destroy: function () { hide(); listeners.forEach(function (remove) { remove(); }); tooltip.remove(); } };
+ }
function acMenuClose() {
qpDiag('menu:close:before', { menuClass: exploreBtn.className });
exploreMenu.close();
@@ -4001,6 +4055,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
};
var sessLastExploreSig = ''; // 面板选项渲染签名(内容未变不重建保留 tooltip 状态)
var sessLastQpSig = ''; // 增强页列表渲染签名(内容/批量模式/选中集未变不重建)
+ var qpSortCleanup = null;
+ registerDisposer(function () { if (qpSortCleanup) qpSortCleanup(); qpSortCleanup = null; });
function applySessionModule(d) {
if (!d || !d.ok) return;
sessState.stash = !!d.stashEnabled;
@@ -4052,6 +4108,100 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}).finally(function () { el.disabled = false; });
}
+ // Preview by moving the existing rows (and their listeners); persist only
+ // on drop. Layout offsets ignore FLIP transforms, avoiding hover jitter.
+ function createQuickPhraseSorter(list, commit, reportError) {
+ var dragging = null, original = [], saving = false, disposed = false;
+ var listeners = [], animations = new Map(), scrollFrame = null, pointerY = 0;
+ function listen(target, name, handler, options) {
+ target.addEventListener(name, handler, options);
+ listeners.push(function () { target.removeEventListener(name, handler, options); });
+ }
+ function rows() { return Array.from(list.querySelectorAll('.wbs-qp-row')); }
+ function cancelAnimations() { animations.forEach(function (a) { a.cancel(); }); animations.clear(); }
+ function move(change) {
+ var items = rows(), tops = items.map(function (row) { return row.getBoundingClientRect().top; });
+ cancelAnimations();
+ var scrollTop = list.scrollTop;
+ change();
+ list.scrollTop = scrollTop;
+ if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
+ items.forEach(function (row, index) {
+ var delta = tops[index] - row.getBoundingClientRect().top;
+ if (row === dragging || !delta || !row.animate) return;
+ var animation = row.animate([{ transform: 'translateY(' + delta + 'px)' }, { transform: 'translateY(0)' }], { duration: 160, easing: 'cubic-bezier(.2,.8,.2,1)' });
+ animations.set(row, animation);
+ animation.onfinish = function () { if (animations.get(row) === animation) animations.delete(row); };
+ });
+ }
+ function preview(y) {
+ if (!dragging) return;
+ var localY = y - list.getBoundingClientRect().top - list.clientTop + list.scrollTop;
+ var before = rows().find(function (row) { return row !== dragging && localY < row.offsetTop + row.offsetHeight / 2; }) || null;
+ if (dragging.nextElementSibling === before) return;
+ move(function () { list.insertBefore(dragging, before); });
+ }
+ function stopScroll() { if (scrollFrame !== null) cancelAnimationFrame(scrollFrame); scrollFrame = null; }
+ function scrollStep() {
+ scrollFrame = null;
+ if (!dragging) return;
+ var rect = list.getBoundingClientRect(), edge = Math.min(28, rect.height / 4);
+ var speed = pointerY < rect.top + edge ? -6 : pointerY > rect.bottom - edge ? 6 : 0;
+ if (!speed || pointerY < rect.top || pointerY > rect.bottom) return;
+ var previous = list.scrollTop;
+ list.scrollTop = Math.max(0, Math.min(list.scrollHeight - list.clientHeight, previous + speed));
+ if (list.scrollTop !== previous) { preview(pointerY); scrollFrame = requestAnimationFrame(scrollStep); }
+ }
+ function finish() {
+ stopScroll();
+ if (dragging) dragging.classList.remove('wbs-qp-dragging');
+ dragging = null;
+ }
+ function restore(order) { move(function () { order.forEach(function (row) { list.appendChild(row); }); }); }
+ function cancel() { if (!dragging) return; finish(); restore(original); }
+ rows().forEach(function (row) {
+ var handle = row.querySelector('[data-qp-drag]');
+ if (!handle) return;
+ listen(handle, 'dragstart', function (event) {
+ event.stopPropagation();
+ if (saving || disposed) { event.preventDefault(); return; }
+ cancelAnimations();
+ original = rows(); dragging = row;
+ event.dataTransfer.setData('text/plain', row.getAttribute('data-id'));
+ event.dataTransfer.effectAllowed = 'move';
+ var rect = row.getBoundingClientRect();
+ if (event.dataTransfer.setDragImage) event.dataTransfer.setDragImage(row, event.clientX - rect.left, event.clientY - rect.top);
+ row.classList.add('wbs-qp-dragging');
+ });
+ listen(handle, 'dragend', function (event) { event.stopPropagation(); cancel(); });
+ });
+ listen(list, 'dragover', function (event) {
+ if (!dragging) return;
+ event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = 'move';
+ pointerY = event.clientY; preview(pointerY);
+ if (scrollFrame === null) scrollFrame = requestAnimationFrame(scrollStep);
+ });
+ listen(list, 'dragleave', function (event) { if (!list.contains(event.relatedTarget)) stopScroll(); });
+ listen(list, 'drop', function (event) {
+ if (!dragging) return;
+ event.preventDefault(); event.stopPropagation(); preview(event.clientY);
+ var ordered = rows(), previous = original.slice();
+ finish();
+ if (ordered.every(function (row, i) { return row === previous[i]; })) return;
+ saving = true; list.setAttribute('aria-busy', 'true');
+ Promise.resolve().then(function () { return commit(ordered.map(function (row) { return row.getAttribute('data-id'); })); })
+ .catch(function (error) { if (!disposed) { restore(previous); reportError(error); } })
+ .finally(function () { saving = false; if (!disposed) list.removeAttribute('aria-busy'); });
+ });
+ listen(document, 'keydown', function (event) {
+ if (dragging && event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); cancel(); }
+ }, true);
+ listen(window, 'blur', cancel);
+ return function () {
+ disposed = true; finish(); cancelAnimations(); list.removeAttribute('aria-busy');
+ listeners.forEach(function (remove) { remove(); });
+ };
+ }
/** 增强页快捷短语列表渲染(含批量模式) */
function renderQpList() {
var pane1 = enhancePane;
@@ -4064,6 +4214,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
(phrases.length ? phrases.map(function (p) { return p.id + ':' + p.text; }).join('|') : 'empty');
if (sig === sessLastQpSig) return;
sessLastQpSig = sig;
+ if (qpSortCleanup) { qpSortCleanup(); qpSortCleanup = null; }
var barEl = pane1.querySelector('#wbs-qp-batchbar');
var countEl = pane1.querySelector('#wbs-qp-batch-count');
var batchBtn = pane1.querySelector('#wbs-qp-batch');
@@ -4091,7 +4242,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var checked = sessState.qpSel[ph.id] ? ' checked' : '';
var cb = sessState.qpBatch ? '<input type="checkbox" class="wbs-qp-check" data-id="' + escAttr(ph.id) + '"' + checked + '>' : '';
html +=
- '<div class="wbs-qp-row" data-id="' + escAttr(ph.id) + '">' +
+ '<div class="wbs-qp-row" data-id="' + escAttr(ph.id) + '" draggable="false">' +
+ (sessState.qpBatch ? '' : '<button type="button" class="wbs-qp-drag" draggable="true" data-qp-drag="' + escAttr(ph.id) + '" title="拖动排序" aria-label="拖动排序"><svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><circle cx="5" cy="4" r="1"/><circle cx="11" cy="4" r="1"/><circle cx="5" cy="8" r="1"/><circle cx="11" cy="8" r="1"/><circle cx="5" cy="12" r="1"/><circle cx="11" cy="12" r="1"/></svg></button>') +
cb +
'<span class="wbs-qp-text" title="' + escAttr(ph.text) + '">' + esc(ph.text) + '</span>' +
'<span class="wbs-qp-actions">' +
@@ -4100,7 +4252,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</span>' +
'</div>';
}
+ var listScrollTop = listEl.scrollTop;
listEl.innerHTML = html;
+ listEl.scrollTop = listScrollTop;
+ if (!sessState.qpBatch) {
+ qpSortCleanup = createQuickPhraseSorter(listEl, function (ordered) {
+ return api('/api/quick-phrase-reorder', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ids: ordered }) })
+ .then(function (d) { if (!d || !d.ok) throw new Error((d && d.error) || 'daemon 未确认'); applySessionModule(d); });
+ }, function (error) { toast('排序失败: ' + (error.message || error), true, root); syncSessionModule(); });
+ }
var checks = listEl.querySelectorAll('.wbs-qp-check');
for (var c = 0; c < checks.length; c++) {
checks[c].addEventListener('change', function () {
@@ -4128,6 +4288,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var sig = phrases.length ? phrases.map(function (p) { return p.id + ':' + p.text; }).join('|') : 'empty';
if (sig === sessLastExploreSig) return;
sessLastExploreSig = sig;
+ qpInsertTooltip.hide();
if (!phrases.length) {
listHost.innerHTML = '<div class="wbs-qp-empty wbs-qp-empty-menu">暂无快捷短语</div>';
return;
@@ -4135,8 +4296,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var html = '';
for (var i = 0; i < phrases.length; i++) {
var ph = phrases[i];
- html += '<div class="wbs-explore-item" data-qp-send="' + escAttr(ph.id) + '">' +
- '<span class="wbs-explore-it">' + esc(ph.text) + '</span>' +
+ html += '<div class="wbs-explore-item" data-qp-send="' + escAttr(ph.id) + '" role="listitem">' +
+ '<span class="wbs-explore-it" role="button" tabindex="0">' + esc(ph.text) + '</span>' +
+ '<button type="button" class="wbs-explore-insert" data-qp-insert="' + escAttr(ph.id) + '" aria-describedby="wbs-qp-insert-tooltip" aria-label="仅插入到对话框"><svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 3.5h10a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H8l-3 2v-2H3a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1z"/><path d="M5 6h6M5 8.5h4"/></svg></button>' +
'<span class="wbs-explore-tip"><span class="wbs-explore-tip-body">' + esc(ph.text) + '</span></span>' +
'</div>';
}
@@ -4168,6 +4330,27 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
tipK.addEventListener('mouseenter', function () { if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; } });
tipK.addEventListener('mouseleave', hideTipDelayed);
}
+ var insertK = itemK.querySelector('[data-qp-insert]');
+ if (insertK) insertK.addEventListener('click', function (ev) {
+ ev.preventDefault(); ev.stopPropagation();
+ var insertPhrase = sessState.phrases.find(function (p) { return p.id === this.getAttribute('data-qp-insert'); }, this);
+ if (!insertPhrase) return;
+ var editor = findComposer();
+ if (!editor) { toast('未找到输入框', true, root); return; }
+ editor.focus();
+ api('/api/quick-phrase-insert', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text: insertPhrase.text }),
+ }).then(function (result) {
+ if (!result || !result.ok) throw new Error((result && result.error) || 'daemon 未确认');
+ acMenuClose();
+ }).catch(function (error) { toast('插入失败: ' + (error.message || error), true, root); });
+ });
+ var sendKeyTarget = itemK.querySelector('.wbs-explore-it');
+ if (sendKeyTarget) sendKeyTarget.addEventListener('keydown', function (ev) {
+ if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); itemK.click(); }
+ });
itemK.addEventListener('click', function (eve) {
qpDiag('click:start', { phraseId: itemK.getAttribute('data-qp-send'), target: eve.target && eve.target.className || '' });
eve.stopPropagation();
@@ -6731,7 +6914,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<span class="wbs-acct-stat-divider"></span>' +
'<div class="wbs-acct-stat"><span>总积分</span><strong id="wbs-acct-total">-</strong></div>' +
'<button class="wbs-acct-eye" type="button" data-act="credit-summary" title="汇总" aria-label="积分汇总" aria-expanded="false">' + CREDIT_SUMMARY_ICON + '</button>' +
- '<button class="wbs-acct-eye" type="button" data-act="model-rate-limit-summary" title="模型限流" aria-label="模型限流" aria-expanded="false">' + MODEL_RATE_LIMIT_ICON + '</button>' +
+ '<button class="wbs-acct-eye" type="button" data-act="model-rate-limit-summary" title="模型限制" aria-label="模型限制" aria-expanded="false">' + MODEL_RATE_LIMIT_ICON + '</button>' +
'</div>' +
'<div class="wbs-acct-actions">' +
'<button class="wbs-acct-io wbs-acct-icon" type="button" data-act="token-stats" title="用量统计" aria-label="用量统计">' + TOKEN_STATS_ICON + '</button>' +
@@ -9324,7 +9507,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
else if (job.status === 'done') detail += ' · 新同步 ' + (Number(job.copied) || 0) + ',已存在 ' + (Number(job.skipped) || 0);
else if (job.status === 'conflict') detail += ' · ' + (Number(job.conflicts) || 1) + ' 个会话已分叉,已保留双方内容';
else if (job.status === 'partial') detail += ' · 有 ' + ((Number(job.failed) || 0) + (Number(job.partial) || 0)) + ' 项需要留意';
- else if (job.status === 'error') detail += ' · 请稍后重试';
+ else if (job.status === 'error') detail += ' · ' + (job.error || '同步任务异常中断,请稍后重新同步');
if (job.warning) detail += ' · ' + job.warning;
box.className = 'wbs-sess-copy-progress is-' + String(job.status || 'running');
box.querySelector('.wbs-sess-copy-title').textContent = title;
@@ -13356,20 +13539,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function acNotifyLimit(snapshot) {
- if (!snapshot || (!snapshot.rateLimited && !snapshot.quotaExhausted)) return;
- var reason = snapshot.rateLimited ? 'model-rate-limited' : 'quota-exhausted';
+ if (!snapshot || (!snapshot.rateLimited && !snapshot.usageLimited && !snapshot.quotaExhausted)) return;
+ var reason = snapshot.rateLimited ? 'model-rate-limited' : (snapshot.usageLimited ? 'model-usage-limited' : 'quota-exhausted');
var key = [snapshot.conversationId || '', snapshot.assistantId || '', reason, snapshot.errorResetAt || ''].join('|');
if (acLimitToastSeen[key]) return;
acLimitToastSeen[key] = true;
var message = wbsTranslateString(
- snapshot.rateLimited ? '当前模型已触发频率限制,已停止自动发送' : '当前账号积分已耗尽',
+ snapshot.rateLimited ? '当前模型已触发频率限制,已停止自动发送' : (snapshot.usageLimited ? '当前模型用量已达限制,已停止自动发送' : '当前账号积分已耗尽'),
WBS_LANGUAGE
);
- if (snapshot.rateLimited) {
+ if (snapshot.rateLimited || snapshot.usageLimited) {
var model = String(snapshot.errorModelName || snapshot.errorRequestModelId || '').trim();
if (model) message += ',' + wbsTranslateString('模型:', WBS_LANGUAGE) + model;
if (snapshot.errorResetAt) {
- message += ',' + wbsTranslateString('预计解封:', WBS_LANGUAGE) + fmtDateTime(snapshot.errorResetAt);
+ message += ',' + wbsTranslateString(snapshot.usageLimited ? '预计恢复:' : '预计解封:', WBS_LANGUAGE) + fmtDateTime(snapshot.errorResetAt);
}
}
toast(message, true, root);
@@ -13838,9 +14021,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function acRecordModelRateLimit(snapshot) {
- if (!snapshot || !snapshot.rateLimited || Number(snapshot.errorCode) !== 6004) return;
- var modelId = String(snapshot.errorRequestModelId || 'unknown-model').slice(0, 160);
+ if (!snapshot) return;
var code = Number(snapshot.errorCode);
+ if ((code !== 6000 && code !== 6004) || (code === 6004 && !snapshot.rateLimited) ||
+ (code === 6000 && snapshot.limitType !== 'usage')) return;
+ var modelId = String(snapshot.errorRequestModelId || 'unknown-model').slice(0, 160);
var signature = [snapshot.conversationId, snapshot.assistantId, modelId, code, snapshot.errorResetAt || ''].join('|');
if (acRateLimitRecorded[signature]) return;
acRateLimitRecorded[signature] = 'pending';
@@ -13858,7 +14043,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
modelId: modelId,
modelName: snapshot.errorModelName || modelId,
resetAt: snapshot.errorResetAt || null,
- reasonCode: 6004,
+ reasonCode: code,
source: 'renderer-error',
}),
}).then(function () {
@@ -13909,6 +14094,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
errorModelName: modelId,
errorResetAt: normalizedError && normalizedError.resetAt,
quotaExhausted: !!(normalizedError && normalizedError.quotaExhausted),
+ usageLimited: !!(normalizedError && normalizedError.usageLimited),
rateLimited: !!(normalizedError && normalizedError.rateLimited),
authFailure: !!(normalizedError && normalizedError.authFailure),
nonRetryableError: !!(normalizedError && normalizedError.nonRetryable),
@@ -15883,13 +16069,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return tag ? '<span class="wbs-checkin-slot">' + tag + '</span>' : '';
}
+ function modelLimitKind(record) {
+ return Number(record && record.reasonCode) === 6000
+ ? wbsTranslateString('用量限制', WBS_LANGUAGE)
+ : wbsTranslateString('频率限制', WBS_LANGUAGE);
+ }
+
+ function modelLimitResetLabel(record, unknown) {
+ var key = Number(record && record.reasonCode) === 6000 ? '预计恢复' : '预计解封';
+ return wbsTranslateString(key + (unknown ? ':时间未知' : ':'), WBS_LANGUAGE);
+ }
+
function modelRateLimitTip(record) {
var name = String(record && (record.modelName || record.modelId) || '未知模型');
var reset = record && record.resetAt ? Number(record.resetAt) : 0;
var line = reset && isFinite(reset)
- ? wbsTranslateString('预计解封:', WBS_LANGUAGE) + fmtDateTimeSeconds(reset) + '(' + wbsTranslateString(fmtCreditExpiry(reset), WBS_LANGUAGE) + ')'
- : wbsTranslateString('预计解封:时间未知', WBS_LANGUAGE);
- return name + '\n' + line;
+ ? modelLimitResetLabel(record, false) + fmtDateTimeSeconds(reset) + '(' + wbsTranslateString(fmtCreditExpiry(reset), WBS_LANGUAGE) + ')'
+ : modelLimitResetLabel(record, true);
+ return name + '\n' + modelLimitKind(record) + '\n' + line;
}
function modelRateLimitBadgeHtml(a) {
@@ -15898,7 +16095,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}) : [];
if (!records.length) return '';
var details = records.map(modelRateLimitTip).join('\n\n');
- var label = records.length === 1 ? wbsTranslateString('模型限流', WBS_LANGUAGE) : wbsTranslateString('模型限流·', WBS_LANGUAGE) + records.length;
+ var label = records.length === 1 ? wbsTranslateString('模型限制', WBS_LANGUAGE) : wbsTranslateString('模型限制·', WBS_LANGUAGE) + records.length;
var attr = esc(details).replace(/"/g, '&quot;');
var uid = escAttr(a && a.uid || '');
return '<span class="wbs-model-rate-limit-slot"><button type="button" class="wbs-model-rate-limit wbs-ck wbs-checkin-tag ok" data-uid="' + uid + '" aria-label="' + attr + '" aria-controls="wbs-status-popover" aria-expanded="false">' + esc(label) + '</button></span>';
@@ -15914,11 +16111,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var resetText = reset && isFinite(reset) ? fmtDateTimeSeconds(reset) : wbsTranslateString('时间未知', WBS_LANGUAGE);
var remaining = reset && isFinite(reset) ? '(' + wbsTranslateString(fmtCreditExpiry(reset), WBS_LANGUAGE) + ')' : '';
return '<div class="wbs-daily-detail wbs-model-rate-limit-detail"><i class="rate-limit"></i>' +
- '<span>' + wbsTranslateString('模型限流', WBS_LANGUAGE) + '</span><b class="wbs-model-rate-limit-model">' + esc(name) + '</b>' +
- '<span>' + wbsTranslateString('预计解封', WBS_LANGUAGE) + '</span><b class="wbs-model-rate-limit-reset">' + esc(resetText + remaining) + '</b></div>';
+ '<span>' + modelLimitKind(record) + '</span><b class="wbs-model-rate-limit-model">' + esc(name) + '</b>' +
+ '<span>' + modelLimitResetLabel(record, !reset) + '</span><b class="wbs-model-rate-limit-reset">' + esc(reset ? resetText + remaining : wbsTranslateString('时间未知', WBS_LANGUAGE)) + '</b></div>';
}).join('');
- return '<div class="wbs-daily-popover-head"><strong>' + wbsTranslateString('模型频率限制', WBS_LANGUAGE) + '</strong><span>' + wbsTranslateString('账号状态', WBS_LANGUAGE) + '</span></div>' +
- (rows || '<div class="wbs-daily-popover-empty">' + wbsTranslateString('当前没有有效的模型限流记录', WBS_LANGUAGE) + '</div>');
+ return '<div class="wbs-daily-popover-head"><strong>' + wbsTranslateString('模型限制', WBS_LANGUAGE) + '</strong><span>' + wbsTranslateString('账号状态', WBS_LANGUAGE) + '</span></div>' +
+ (rows || '<div class="wbs-daily-popover-empty">' + wbsTranslateString('当前没有有效的模型限制记录', WBS_LANGUAGE) + '</div>');
}
function modelRateLimitSummaryPopoverHtml(accounts) {
@@ -15932,14 +16129,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var rows = records.map(function (record) {
var name = String(record.modelName || record.modelId || '未知模型');
var reset = record.resetAt ? Number(record.resetAt) : 0;
+ var hasReset = !!reset && isFinite(reset);
var resetText = reset && isFinite(reset) ? fmtDateTimeSeconds(reset) : wbsTranslateString('时间未知', WBS_LANGUAGE);
var remaining = reset && isFinite(reset) ? '(' + wbsTranslateString(fmtCreditExpiry(reset), WBS_LANGUAGE) + ')' : '';
- return '<div class="wbs-model-rate-limit-summary-row"><b class="wbs-model-rate-limit-model">' + esc(name) + '</b><span class="wbs-model-rate-limit-reset-label">' + wbsTranslateString('预计解封', WBS_LANGUAGE) + '</span><b class="wbs-model-rate-limit-reset">' + esc(resetText + remaining) + '</b></div>';
+ return '<div class="wbs-model-rate-limit-summary-row"><b class="wbs-model-rate-limit-model">' + esc(name) + '</b><span>' + modelLimitKind(record) + '</span><span class="wbs-model-rate-limit-reset-label">' + modelLimitResetLabel(record, false) + '</span><b class="wbs-model-rate-limit-reset">' + esc(hasReset ? resetText + remaining : wbsTranslateString('时间未知', WBS_LANGUAGE)) + '</b></div>';
}).join('');
groups.push('<section class="wbs-model-rate-limit-account-group"><div class="wbs-model-rate-limit-account-head"><strong>' + esc(accountName) + '</strong><span>' + records.length + wbsTranslateString(' 个模型', WBS_LANGUAGE) + '</span></div>' + rows + '</section>');
});
- return '<div class="wbs-daily-popover-head"><strong>' + wbsTranslateString('模型频率限制', WBS_LANGUAGE) + '</strong><span>' + wbsTranslateString('{n} 个账号', WBS_LANGUAGE).replace('{n}', groups.length) + '</span></div>' +
- (groups.join('') || '<div class="wbs-daily-popover-empty">' + wbsTranslateString('当前没有有效的模型限流记录', WBS_LANGUAGE) + '</div>');
+ return '<div class="wbs-daily-popover-head"><strong>' + wbsTranslateString('模型限制', WBS_LANGUAGE) + '</strong><span>' + wbsTranslateString('{n} 个账号', WBS_LANGUAGE).replace('{n}', groups.length) + '</span></div>' +
+ (groups.join('') || '<div class="wbs-daily-popover-empty">' + wbsTranslateString('当前没有有效的模型限制记录', WBS_LANGUAGE) + '</div>');
}
function creditBlockHtml(credits, segments, account) {
@@ -16356,7 +16554,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function sessionCopySummaryText(job) {
return '同步 ' + (Number(job && job.copied) || 0) +
- ' · 失败 ' + (sessionCopyFailedItems(job) + (Number(job && job.conflicts) || 0)) +
+ (job && job.status === 'error' ? ' · 任务失败' : ' · 失败 ' + (sessionCopyFailedItems(job) + (Number(job && job.conflicts) || 0))) +
(job && job.warning ? ' · ' + job.warning : '');
}
@@ -16366,7 +16564,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function sessionCopyNoticeGroups(job) {
- var details = Array.isArray(job && job.details) ? job.details : [];
+ var details = Array.isArray(job && job.details) ? job.details.slice() : [];
+ if (job && job.status === 'error') details.push({ status: 'failed', label: '同步任务', error: job.error || '同步任务异常中断,请稍后重新同步', taskFailure: true });
return {
copied: details.filter(function (item) {
return String(item && item.status || '') === 'copied';
@@ -16431,7 +16630,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var mask = document.createElement('div');
mask.className = 'wbs-modal-mask wbs-session-copy-details-modal';
mask.setAttribute('role', 'presentation');
- var details = Array.isArray(job.details) ? job.details : [];
+ var groups = sessionCopyNoticeGroups(job);
+ var details = groups.copied.concat(groups.failed);
var statusLabels = { copied: '已同步', skipped: '已跳过', partial: '部分失败', failed: '失败', conflict: '未同步', running: '处理中' };
var tabDefs = [
{ id: 'copied', label: '成功', count: details.filter(function (item) { return item && item.status === 'copied'; }).length },
@@ -16472,7 +16672,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
tab.setAttribute('aria-selected', active ? 'true' : 'false');
});
};
- renderTab('copied');
+ renderTab(job.status === 'error' ? 'failed' : 'copied');
mask.querySelectorAll('[data-session-copy-tab]').forEach(function (tab) {
tab.addEventListener('click', function () { renderTab(tab.getAttribute('data-session-copy-tab')); });
});
@@ -16541,7 +16741,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var sourceLabel = sessionCopyAccountLabel(job.sourceUid, job.sourceName);
var targetLabel = accountName || sessionCopyAccountLabel(job.targetUid, job.targetName);
var status = active ? '正在把已标记的会话从「' + sourceLabel + '」同步到「' + targetLabel + '」' :
- job.status === 'error' ? '同步任务未完成,请稍后重试' : '';
+ job.status === 'error' ? (job.error || '同步任务异常中断,请稍后重新同步') : '';
node.className = 'wbs-session-copy-notice is-' + String(job.status || 'running');
node.querySelector('.wbs-session-copy-title').textContent = title;
node.querySelector('.wbs-session-copy-route').textContent = sourceLabel + ' → ' + targetLabel;
@@ -16567,7 +16767,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
track.setAttribute('aria-valuetext', title + ',' + processed + '/' + total);
node.querySelector('.wbs-session-copy-fill').style.width = percent + '%';
placeSessionCopyNotice();
- if (!active && !notice.closeScheduled) {
+ if (job.status === 'error') node.querySelector('.wbs-session-copy-countdown').textContent = '请查看明细';
+ if (!active && job.status !== 'error' && !notice.closeScheduled) {
notice.closeScheduled = true;
var copiedCount = Math.max(0, Number(job && job.copied) || 0);
var failedCount = sessionCopyFailedItems(job) + (Number(job && job.conflicts) || 0);
@@ -18051,7 +18252,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
':is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings:not(:where([data-wbs-appearance="light"] *,.wbs-panel-light *)),:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-checkin-tag.ok:not(:where([data-wbs-appearance="light"] *,.wbs-panel-light *)){--wbs-badge-bg:rgba(255,255,255,.085);--wbs-badge-fg:var(--wb-color-text-primary,#f6f5ff);background:var(--wbs-badge-bg);border:1px solid rgba(255,255,255,.12);color:var(--wbs-badge-fg);box-shadow:inset 0 1px 0 rgba(255,255,255,.08);backdrop-filter:blur(12px) saturate(1.08);-webkit-backdrop-filter:blur(12px) saturate(1.08)}:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings:not(:where([data-wbs-appearance="light"] *,.wbs-panel-light *)){--wbs-liquid-bg:rgba(255,255,255,.12);--wbs-liquid-ink:#f6f5ff}:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings:not(:where([data-wbs-appearance="light"] *,.wbs-panel-light *)):hover,:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings:not(:where([data-wbs-appearance="light"] *,.wbs-panel-light *))[aria-expanded="true"]{background:rgba(255,255,255,.14);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 3px 10px rgba(0,0,0,.12)}',
'.wbs-checkin-tag.fail{background:rgba(239,68,68,.1);color:#dc2626}',
'.wbs-model-rate-limit-slot{display:inline-flex;align-items:center;min-width:0}.wbs-model-rate-limit{appearance:none;-webkit-appearance:none;font:inherit;cursor:pointer;transition:background-color .15s,box-shadow .15s,color .15s}.wbs-model-rate-limit:hover,.wbs-model-rate-limit[aria-expanded="true"]{background:color-mix(in srgb,var(--wbs-badge-bg) 84%,white);box-shadow:0 2px 8px rgba(0,0,0,.14)}.wbs-model-rate-limit:focus-visible{outline:2px solid color-mix(in srgb,var(--wbs-badge-bg) 45%,transparent);outline-offset:2px}',
- '.wbs-status-popover.is-rate-limit{width:500px;max-width:calc(100vw - 16px);overflow-x:auto}.wbs-status-popover.is-rate-limit-summary{width:360px;max-width:calc(100vw - 16px);overflow-x:auto}.wbs-model-rate-limit-detail{grid-template-columns:8px auto minmax(0,1fr) auto auto;gap:7px}.wbs-model-rate-limit-detail b{white-space:nowrap;overflow-wrap:normal}.wbs-model-rate-limit-detail .wbs-model-rate-limit-model{text-align:left}.wbs-model-rate-limit-detail i.rate-limit{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-model-rate-limit-account-group{padding:7px 0 2px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.1))}.wbs-model-rate-limit-account-group:first-of-type{padding-top:0;border-top:0}.wbs-model-rate-limit-account-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 2px 2px}.wbs-model-rate-limit-account-head strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}.wbs-model-rate-limit-account-head span{flex:0 0 auto;color:var(--wb-icon-tertiary,#7c818b);font-size:10px;white-space:nowrap}.wbs-model-rate-limit-summary-row{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,auto);align-items:center;gap:7px;min-height:28px;margin-top:4px;padding:0 8px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent)}.wbs-model-rate-limit-summary-row>span{color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-model-rate-limit-summary-row>b{min-width:0;font-size:11px;font-weight:650;white-space:nowrap;overflow-wrap:normal}.wbs-model-rate-limit-summary-row .wbs-model-rate-limit-model{text-align:left}.wbs-model-rate-limit-summary-row .wbs-model-rate-limit-reset{text-align:right}',
+ '.wbs-status-popover.is-rate-limit{width:500px;max-width:calc(100vw - 16px);overflow-x:auto}.wbs-status-popover.is-rate-limit-summary{width:360px;max-width:calc(100vw - 16px);overflow-x:auto}.wbs-model-rate-limit-detail{grid-template-columns:8px auto minmax(0,1fr) auto auto;gap:7px}.wbs-model-rate-limit-detail b{white-space:nowrap;overflow-wrap:normal}.wbs-model-rate-limit-detail .wbs-model-rate-limit-model{text-align:left}.wbs-model-rate-limit-detail i.rate-limit{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-model-rate-limit-account-group{padding:7px 0 2px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.1))}.wbs-model-rate-limit-account-group:first-of-type{padding-top:0;border-top:0}.wbs-model-rate-limit-account-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 2px 2px}.wbs-model-rate-limit-account-head strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}.wbs-model-rate-limit-account-head span{flex:0 0 auto;color:var(--wb-icon-tertiary,#7c818b);font-size:10px;white-space:nowrap}.wbs-model-rate-limit-summary-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto minmax(0,auto);align-items:center;gap:7px;min-height:28px;margin-top:4px;padding:0 8px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent)}.wbs-model-rate-limit-summary-row>span{color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-model-rate-limit-summary-row>b{min-width:0;font-size:11px;font-weight:650;white-space:nowrap;overflow-wrap:normal}.wbs-model-rate-limit-summary-row .wbs-model-rate-limit-model{text-align:left}.wbs-model-rate-limit-summary-row .wbs-model-rate-limit-reset{text-align:right}',
':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-model-rate-limit:hover,:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-model-rate-limit[aria-expanded="true"]{background:rgba(255,255,255,.14);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 3px 10px rgba(0,0,0,.12)}',
'.wbs-ck.pending{color:var(--wb-icon-tertiary,#999)}',
'.wbs-ck.fail{color:#f53f3f}',
@@ -18147,7 +18348,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-explore-card{position:relative;padding:8px;border-radius:12px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 62%,transparent);backdrop-filter:blur(18px) saturate(1.3);-webkit-backdrop-filter:blur(18px) saturate(1.3);border:1px solid var(--wb-border-subtle,#ececec);box-shadow:0 12px 32px rgba(0,0,0,.18);color:var(--wb-color-text-primary,#1f1f1f);cursor:default}',
'html[data-wbs-theme-id="nebula"] .wbs-explore-card{background:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 88%,transparent);background-color:color-mix(in srgb,var(--wb-bg-popover,#1a1729) 88%,transparent);box-shadow:0 14px 36px rgba(0,0,0,.38)}',
'.wbs-explore-item{position:relative;display:flex;align-items:center;gap:8px;padding:9px 10px;border-radius:8px;font-size:12px;color:var(--wb-color-text-primary,#1f1f1f);line-height:1.4;cursor:pointer}',
- '.wbs-explore-it{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
+ '.wbs-explore-insert{display:flex;align-items:center;justify-content:center;position:absolute;right:7px;top:50%;transform:translateY(-50%);width:26px;height:26px;border:1px solid var(--wb-border-subtle,#ddd);border-radius:6px;background:var(--wb-bg-primary,#fff);color:var(--wb-icon-secondary,#666);opacity:0;pointer-events:none;cursor:pointer}',
+ '.wbs-explore-item:hover .wbs-explore-insert,.wbs-explore-item:focus-within .wbs-explore-insert{opacity:1;pointer-events:auto}',
+ '.wbs-explore-it:focus-visible,.wbs-explore-insert:focus-visible{outline:2px solid var(--wb-accent-color,var(--wb-button-primary-bg,#555));outline-offset:1px}',
+ '.wbs-explore-insert:hover{color:var(--wb-color-text-primary,#222);background:var(--wb-bg-hover,#f3f3f3)}',
+ '.wbs-explore-it{flex:1;min-width:0;padding-right:34px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
'.wbs-explore-item:hover{background:color-mix(in srgb,var(--wb-bg-hover,#f3f3f3) 76%,transparent)}',
/* 选项 hover:antd 风格 tooltip(半透明毛玻璃小气泡,出现在选项左侧,完全展示文字) */
'.wbs-explore-tip{position:absolute;right:calc(100% + 10px);top:50%;transform:translateY(-50%);display:block;width:max-content;padding:5px 11px;border-radius:8px;font-size:11px;line-height:1.35;white-space:normal;word-break:break-word;max-width:240px;color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-popover,#fff);border:1px solid color-mix(in srgb,var(--wb-border-subtle,#ececec) 65%,transparent);box-shadow:0 6px 20px rgba(0,0,0,.16);opacity:0;visibility:hidden;transition:opacity .15s ease;pointer-events:none;z-index:2}',
@@ -18174,8 +18379,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-qp-batchbar{display:inline-flex;align-items:center;gap:6px;margin-right:8px}',
'.wbs-qp-batch-count{font-size:11px;color:var(--wb-color-text-secondary,#666)}',
'.wbs-qp-batch-action{color:#d64545}',
- '.wbs-qp-list{display:flex;flex-direction:column;max-height:220px;overflow-y:auto}',
+ '.wbs-qp-list{position:relative;display:flex;flex-direction:column;max-height:220px;overflow-y:auto;overflow-anchor:none}',
'.wbs-qp-row{display:flex;align-items:center;gap:8px;padding:5px 8px;border-bottom:1px solid var(--wb-border-subtle,#eee)}',
+ '.wbs-qp-drag{display:flex;align-items:center;justify-content:center;width:22px;height:24px;padding:0;border:0;border-radius:5px;background:transparent;color:var(--wb-icon-secondary,#777);cursor:grab;flex:0 0 auto}',
+ '.wbs-qp-drag:active{cursor:grabbing}.wbs-qp-row.wbs-qp-dragging{opacity:.45;background:var(--wb-bg-hover,#f3f3f3);outline:1px dashed var(--wb-border-default,#ccc);outline-offset:-2px}.wbs-qp-list[aria-busy="true"] .wbs-qp-drag{cursor:wait}',
'.wbs-qp-row:hover{background:color-mix(in srgb,var(--wb-bg-hover,#f3f3f3) 45%,transparent)}',
'.wbs-qp-check{margin:0;width:14px;height:14px;flex:0 0 auto;accent-color:var(--wb-button-primary-bg,#1f1f1f)}',
'.wbs-qp-text{flex:1;font-size:12px;line-height:1.5;color:var(--wb-color-text-primary,#1f1f1f);overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;white-space:nowrap;word-break:break-all}',
@@ -18289,7 +18496,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-sess-copy-progress{box-sizing:border-box;margin:0 0 8px;padding:9px 10px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 82%,transparent);box-shadow:0 2px 8px rgba(0,0,0,.04)}',
'.wbs-sess-copy-progress[hidden]{display:none!important}.wbs-sess-copy-head{display:flex;align-items:center;gap:6px;min-width:0}.wbs-sess-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex:0 0 20px;border-radius:6px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 9%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-sess-copy-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11.5px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-sess-copy-detail{margin:4px 0 6px 26px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;line-height:1.35;color:var(--wb-icon-tertiary,#8a8f98)}.wbs-sess-copy-track{height:4px;margin-left:26px;overflow:hidden;border-radius:999px;background:var(--wb-bg-tertiary,#e9eaed)}.wbs-sess-copy-fill{display:block;height:100%;width:0;border-radius:inherit;background:var(--wb-accent-blue,var(--wb-button-primary-bg,#1f1f1f));transition:width .2s ease}.wbs-sess-copy-progress.is-done .wbs-sess-copy-fill{background:#2f9e63}.wbs-sess-copy-progress.is-partial .wbs-sess-copy-fill{background:#d48a19}.wbs-sess-copy-progress.is-error .wbs-sess-copy-fill{background:#d84a4a}',
+ '.wbs-sess-copy-progress.is-error .wbs-sess-copy-detail{white-space:normal;overflow-wrap:anywhere}',
'html.cb-dark .wbs-sess-copy-progress,html[data-theme="dark"] .wbs-sess-copy-progress,body[data-vscode-theme-name*="dark" i] .wbs-sess-copy-progress{border-color:var(--wb-border-default,rgba(255,255,255,.14));background:color-mix(in srgb,var(--wb-bg-secondary,#25262a) 88%,transparent);box-shadow:0 3px 12px rgba(0,0,0,.18)}',
+ ':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-sess-copy-title{color:var(--wb-color-text-primary,#f2f3f5)}',
'.wbs-sess-refresh{display:flex;align-items:center;justify-content:center;flex-shrink:0;padding:7px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:12px;cursor:pointer;line-height:1;transition:all .15s}',
'.wbs-sess-refresh:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-sess-bbtn{display:inline-flex;align-items:center;justify-content:center;gap:4px;padding:7px 12px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:12px;cursor:pointer;line-height:1;transition:all .15s}',
@@ -18539,6 +18748,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-telemetry-help:hover,.wbs-telemetry-help:focus{color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-telemetry-tooltip{position:absolute;z-index:20;left:0;top:calc(100% + 7px);width:245px;padding:7px 9px;border:1px solid var(--wb-border-default,rgba(0,0,0,.14));border-radius:7px;background:var(--wb-bg-primary,#fff);box-shadow:0 6px 18px rgba(0,0,0,.14);color:var(--wb-color-text-primary,#1f1f1f);font-size:11px;font-weight:400;line-height:1.5;white-space:normal;opacity:0;visibility:hidden;pointer-events:none;transform:translateY(-2px);transition:opacity .12s,transform .12s,visibility .12s}',
'.wbs-telemetry-help:hover .wbs-telemetry-tooltip,.wbs-telemetry-help:focus .wbs-telemetry-tooltip{opacity:1;visibility:visible;transform:translateY(0)}',
+ '.wbs-qp-insert-tooltip{position:fixed;z-index:2147483647;box-sizing:border-box;width:max-content;max-width:calc(100vw - 16px);transform:none;overflow-wrap:anywhere}.wbs-qp-insert-tooltip.is-visible{opacity:1;visibility:visible;transform:none}',
+ '.wbs-explore-action-tip .wbs-explore-tip{opacity:0!important;visibility:hidden!important;pointer-events:none!important}',
+ 'html.cb-dark .wbs-qp-insert-tooltip,html[data-theme="dark"] .wbs-qp-insert-tooltip,body[data-vscode-theme-name*="dark" i] .wbs-qp-insert-tooltip{background:var(--wb-bg-popover,#202126);color:var(--wb-color-text-primary,#f2f3f5);border-color:var(--wb-border-default,rgba(255,255,255,.16));box-shadow:0 6px 18px rgba(0,0,0,.4)}',
'.wbs-fork-tooltip{position:fixed;z-index:2147483647;box-sizing:border-box;width:max-content;max-width:min(255px,calc(100vw - 16px));transform:none;overflow-wrap:anywhere;white-space:normal}.wbs-fork-tooltip.is-visible{opacity:1;visibility:visible;transform:none}',
'.wbs-fork-tooltip-title{display:block;font-size:14px;font-weight:600;line-height:1.35}.wbs-fork-tooltip-description{display:block;margin-top:3px;font-size:11px;line-height:1.5}',
'html.cb-dark .wbs-fork-tooltip,html[data-theme="dark"] .wbs-fork-tooltip,body[data-vscode-theme-name*="dark" i] .wbs-fork-tooltip{background:var(--wb-bg-popover,#202126);color:var(--wb-color-text-primary,#f2f3f5);border-color:var(--wb-border-default,rgba(255,255,255,.16));box-shadow:0 6px 18px rgba(0,0,0,.4)}',
diff --git a/scripts/lib.js b/scripts/lib.js
index 5d8e116..86a4cf8 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -12,6 +12,7 @@
*/
'use strict';
+const { accountIdentity } = require('./account-identity');
const fs = require('fs');
const os = require('os');
const path = require('path');
@@ -380,6 +381,8 @@ function authRecordFromJson(file, json, { strict = DYNAMIC_AUTH_DISCOVERY } = {}
uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '',
phone: wdCompatText(acct.phoneNumber),
type: typeof acct.type === 'string' ? acct.type : '',
+ enterpriseId: String(acct.enterpriseId || '').trim(),
+ accountId: accountIdentity(acct),
raw: json,
file,
authFileName: file ? path.basename(file) : '',
@@ -1500,6 +1503,44 @@ function deleteAutoCopyMapping(dataDir, lineageOrUid, targetUid, maybeSessionId)
function logFile(dataDir) {
return path.join(dataDir, 'daemon.log');
}
+function migrateAccountIdentities(dataDir) {
+ const dir = accountsDir(dataDir);
+ let names;
+ try { names = fs.readdirSync(dir).filter(name => name.endsWith('.info')); } catch (_) { return; }
+ let meta = null;
+ for (const name of names) {
+ const file = path.join(dir, name);
+ const info = parseAuthFile(file, { strict: false });
+ if (!info || name !== info.uid + '.info' || info.accountId === info.uid) continue;
+ const target = path.join(dir, info.accountId + '.info');
+ // Keep a pre-existing scoped backup and preserve the old bytes for recovery.
+ if (fs.existsSync(target)) fs.renameSync(file, file + '.legacy.' + crypto.randomUUID());
+ else fs.renameSync(file, target);
+ if (!meta) meta = readMeta(dataDir);
+ rememberAccountIdentity(meta, info.uid, info.accountId);
+ meta.accounts[info.accountId] = Object.assign({}, meta.accounts[info.uid], meta.accounts[info.accountId], {
+ uid: info.accountId, rawUid: info.uid, type: info.type, enterpriseId: info.enterpriseId,
+ });
+ delete meta.accounts[info.uid];
+ // Historical uid-only session links have no reliable login-context owner.
+ // Retain a recovery snapshot, then retire just this owner's links so a later
+ // personal login cannot silently inherit the enterprise's synchronization.
+ if (meta.autoCopy) {
+ if (!meta.retiredAccountSyncRules) meta.retiredAccountSyncRules = {};
+ if (!meta.retiredAccountSyncRules[info.accountId]) meta.retiredAccountSyncRules[info.accountId] = JSON.parse(JSON.stringify(meta.autoCopy));
+ const config = ensureAutoCopyMeta(meta);
+ delete config.sessionIndex[info.uid];
+ for (const lineage of Object.values(config.sessions)) {
+ lineage.members = (lineage.members || []).filter(member => member.uid !== info.uid);
+ }
+ for (const key of Object.keys(config.copies)) {
+ try { if (JSON.parse(key)[1] === info.uid) delete config.copies[key]; } catch (_) {}
+ }
+ }
+ }
+ if (meta) writeMeta(dataDir, meta);
+}
+
function backupPath(dataDir, uid) {
return path.join(accountsDir(dataDir), `${uid}.info`);
}
@@ -1615,16 +1656,27 @@ function readAuthFile(file = currentAuthFile()) {
/** 更新 meta.json(uid -> nickname/uin/phone/时间)。preserveBinding:备份扫描路径
* 不漂移「账号 -> 登录文件」绑定——auth 目录里的个性化历史存档(带时间戳)即使
* 残留 lastLogin 标记,也不得覆盖切换路径建立的绑定关系。 */
+function knownAccountIdentities(dataDir) { return readMeta(dataDir).accountIdentities || {}; }
+function rememberAccountIdentity(meta, rawUid, uid) {
+ if (!meta.accountIdentities || typeof meta.accountIdentities !== 'object') meta.accountIdentities = {};
+ if (!Array.isArray(meta.accountIdentities[rawUid])) meta.accountIdentities[rawUid] = [];
+ if (!meta.accountIdentities[rawUid].includes(uid)) meta.accountIdentities[rawUid].push(uid);
+}
function updateMeta(dataDir, info, { preserveBinding = false } = {}) {
const meta = readMeta(dataDir);
const now = Date.now();
- const prev = meta.accounts[info.uid] || {};
+ const id = info.accountId || accountIdentity(info);
+ rememberAccountIdentity(meta, info.rawUid || info.uid, id);
+ const prev = meta.accounts[id] || {};
let authFileName = info.authFileName || prev.authFileName || '';
if (preserveBinding && prev.authFileName && info.authFileName && prev.authFileName !== info.authFileName) {
authFileName = prev.authFileName;
}
- meta.accounts[info.uid] = {
- uid: info.uid,
+ meta.accounts[id] = {
+ uid: id,
+ rawUid: info.uid,
+ type: info.type || '',
+ enterpriseId: info.enterpriseId || '',
nickname: info.nickname || prev.nickname || '',
uin: info.uin || prev.uin || '',
phone: info.phone || prev.phone || '',
@@ -1641,8 +1693,9 @@ function updateMeta(dataDir, info, { preserveBinding = false } = {}) {
}
function backupAuthFile(dataDir, file, log = () => {}) {
+ migrateAccountIdentities(dataDir);
const info = readAuthFile(file);
- const dest = backupPath(dataDir, info.uid);
+ const dest = backupPath(dataDir, info.accountId);
const tmp = dest + '.tmp';
// [wd-compat] 密文信封原样落盘;需要查询/刷新时才在内存中解密。
// 这样不会在 WorkDaddy 目录制造明文 token 副本,也能保留旧版明文 auth 文件。
@@ -1663,6 +1716,7 @@ function backupAuthFile(dataDir, file, log = () => {}) {
function backupCurrent(dataDir, log = () => {}) {
if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号文件备份`);
ensureDirs(dataDir, log);
+ migrateAccountIdentities(dataDir);
const records = listAuthRecords();
if (!records.length) throw new Error('未找到有效的登录信息文件');
const current = resolveCurrentAuth();
@@ -1670,7 +1724,7 @@ function backupCurrent(dataDir, log = () => {}) {
let backedUp = 0;
for (const record of records) {
const authoritative = current.file && samePath(record.file, current.file);
- const existingBackup = fs.existsSync(backupPath(dataDir, record.uid));
+ const existingBackup = fs.existsSync(backupPath(dataDir, record.accountId));
if (existingBackup && !authoritative) continue; // 历史存档不覆盖已有备份
const info = backupAuthFile(dataDir, record.file, log);
backedUp += 1;
@@ -1705,13 +1759,13 @@ function resolveAuthTarget(dataDir, uid, authJson) {
return target;
}
const records = listAuthRecords();
- const matching = records.filter((item) => item.uid === String(uid));
+ const matching = records.filter((item) => item.accountId === String(uid));
if (matching.length === 1) return matching[0].file;
const channelMatches = records.filter(sameChannel);
const canonical = channelMatches.find((item) => AUTH_FILE && samePath(item.file, AUTH_FILE));
if (canonical) return canonical.file;
if (channelMatches.length === 1) return channelMatches[0].file;
- const legacyRecord = String(record.uid || '') === String(uid) &&
+ const legacyRecord = String(record.accountId || record.uid || '') === String(uid) &&
!record.authFileName && !record.authDomain && !record.authIssuer;
// legacy 账号(动态发现上线前备份)没有属于自己的文件记录,其唯一正确的落点就是
// 官方固定登录文件(AUTH_FILE);无论该文件当前是否被占用,用户显式切换即意图覆盖。
@@ -1759,6 +1813,7 @@ function setAccountNote(dataDir, value) {
function listAccounts(dataDir) {
if (!ACTIVE_PROFILE.capabilities.accounts) return [];
migrateLegacyDataDir(dataDir);
+ migrateAccountIdentities(dataDir);
const dir = accountsDir(dataDir);
let names = [];
try {
@@ -1793,6 +1848,8 @@ function listAccounts(dataDir) {
item.nickname = wdCompatText(acct.nickname);
item.phone = wdCompatText(acct.phoneNumber);
item.uin = typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '';
+ item.rawUid = String(acct.uid || uid);
+ item.enterpriseId = String(acct.enterpriseId || '').trim();
item.type = typeof acct.type === 'string' ? acct.type : '';
item.enterpriseName = typeof acct.enterpriseName === 'string' ? acct.enterpriseName.trim() : '';
}
@@ -1821,7 +1878,7 @@ function deleteAuthFilesForUid(uid, log = () => {}) {
if (!AUTH_FILE) return { removed: 0 };
if (!DYNAMIC_AUTH_DISCOVERY) {
const record = parseAuthFile(AUTH_FILE, { strict: false });
- if (record && record.uid === uid && fs.existsSync(AUTH_FILE)) {
+ if (record && record.accountId === uid && fs.existsSync(AUTH_FILE)) {
fs.unlinkSync(AUTH_FILE);
log(`[delete] 已删除固定登录文件 ${path.basename(AUTH_FILE)}`);
return { removed: 1 };
@@ -1836,7 +1893,7 @@ function deleteAuthFilesForUid(uid, log = () => {}) {
if (!safeAuthFileName(name)) continue;
const file = path.join(dir, name);
const record = parseAuthFile(file);
- if (record && record.uid === uid && fs.existsSync(file)) {
+ if (record && record.accountId === uid && fs.existsSync(file)) {
try {
fs.unlinkSync(file);
removed += 1;
@@ -1856,7 +1913,7 @@ function deleteAccount(dataDir, uid, log = () => {}) {
const current = resolveCurrentAuth();
if (current.file && !current.ambiguous) {
const record = parseAuthFile(current.file, { strict: false });
- if (record && record.uid === uid) {
+ if (record && record.accountId === uid) {
throw new Error('不能删除当前登录的账号(请先退出登录或切换到其他账号)');
}
}
@@ -1894,6 +1951,7 @@ function deleteAccount(dataDir, uid, log = () => {}) {
function switchTo(dataDir, uid, log = () => {}) {
if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号切换`);
migrateLegacyDataDir(dataDir, log);
+ migrateAccountIdentities(dataDir);
// 不再用「当前 auth 目录是否 ambiguous」一票否决:切换写入的目标文件由
// resolveAuthTarget 精确决定(meta.json 记录 / 唯一 uid 匹配),目标无法唯一
// 确定时它自己会拒绝,避免历史 lastLogin 残留导致已登录账号切不回去。
@@ -1904,7 +1962,7 @@ function switchTo(dataDir, uid, log = () => {}) {
const raw = fs.readFileSync(src, 'utf8');
const json = wdCompatDecryptAuthJson(JSON.parse(raw)); // [wd-compat] 校验前解密;写回仍用 raw 原字节
const acct = json.account || (Array.isArray(json.accounts) && json.accounts[0]);
- if (!acct || acct.uid !== uid) {
+ if (!acct || accountIdentity(acct) !== uid) {
throw new Error('备份文件校验失败:uid 不匹配,已中止切换');
}
const target = resolveAuthTarget(dataDir, uid, json);
@@ -1945,7 +2003,9 @@ function switchTo(dataDir, uid, log = () => {}) {
// Legacy call shape retained for source-compatible launchers: retireLogoutMarker(log);
retireLogoutMarker(log, target);
updateMeta(dataDir, {
- uid: acct.uid,
+ uid: String(acct.uid),
+ type: acct.type,
+ enterpriseId: acct.enterpriseId,
nickname: wdCompatText(acct.nickname),
uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '',
phone: wdCompatText(acct.phoneNumber),
@@ -1955,7 +2015,7 @@ function switchTo(dataDir, uid, log = () => {}) {
});
const switchName = wdCompatText(acct.nickname) || uid;
log(`[switch] 已切换登录账号为 ${switchName} (${uid})`);
- return { uid: acct.uid, nickname: wdCompatText(acct.nickname), uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '', authFile: target };
+ return { uid, rawUid: String(acct.uid), type: acct.type, enterpriseId: acct.enterpriseId, nickname: wdCompatText(acct.nickname), uin: typeof acct.uin === 'string' || typeof acct.uin === 'number' ? acct.uin : '', authFile: target };
}
module.exports = {
@@ -2011,6 +2071,8 @@ module.exports = {
importModels,
logFile,
backupPath,
+ migrateAccountIdentities,
+ knownAccountIdentities,
backupAuthFile,
retireLogoutMarker,
ensureDirs,
diff --git a/scripts/persona.js b/scripts/persona.js
index b5b5239..a2875fd 100644
--- a/scripts/persona.js
+++ b/scripts/persona.js
@@ -12,6 +12,11 @@ const MAX_FILE_SIZE = 20 * 1024 * 1024;
const PERSONA_MODES = ['unset', 'shared', 'independent'];
function validUid(uid) { return typeof uid === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(uid); }
+// Enterprise persona directory naming is owned by WorkBuddy. Never project a
+// WorkDaddy backup id into its filesystem or guess a personal directory.
+function scopedAccount(accounts = [], uid) {
+ return accounts.find(account => String(account.uid) === String(uid) && account.rawUid && account.rawUid !== account.uid);
+}
function personaDir(root, uid) {
if (!validUid(uid)) throw new Error('账号格式无效');
return path.join(resolveTrustedRoot(root), `user-${uid}-personal`);
@@ -73,6 +78,7 @@ function scopedLayout(root) {
}
function inspectPersona(options) {
const { dataRoot, targetUid, accounts = [] } = options;
+ if (scopedAccount(accounts, targetUid)) return { uid: targetUid, status: 'unsupported', eligible: false, sources: [] };
const dir = personaDir(dataRoot, targetUid);
if (!accounts.some(a => String(a.uid) === targetUid)) throw new Error('账号不存在');
if (!scopedLayout(dataRoot)) return { uid: targetUid, status: 'legacy', eligible: false, sources: [] };
@@ -88,7 +94,7 @@ function inspectPersona(options) {
const sources = [];
for (const account of accounts) {
const uid = String(account.uid);
- if (!validUid(uid) || uid === targetUid || uid === 'legacy') continue;
+ if (!validUid(uid) || uid === targetUid || uid === 'legacy' || scopedAccount(accounts, uid)) continue;
const sourceFiles = snapshot(personaDir(dataRoot, uid));
if (usableSource(sourceFiles)) sources.push({ uid, nickname: String(account.nickname || uid), files: IDENTITY_FILES.filter(name => nonempty(sourceFiles, name)) });
}
@@ -152,7 +158,7 @@ function listPersonaSources({ dataRoot, accounts = [] }) {
const sources = [];
for (const account of [...accounts.filter(a => a.uid !== 'legacy'), { uid: 'legacy', nickname: '升级前共用的设置' }]) {
const uid = String(account.uid || '');
- if (!validUid(uid)) continue;
+ if (!validUid(uid) || scopedAccount(accounts, uid)) continue;
const files = snapshot(uid === 'legacy' ? resolveTrustedRoot(dataRoot) : personaDir(dataRoot, uid));
const available = usableSource(files);
if (uid === 'legacy' && !available) continue;
@@ -230,6 +236,7 @@ function applySharedPersona(options, sourceFiles, settings) {
}
function configurePersona(options) {
const settings = readPersonaSettings(options.backupRoot);
+ if (options.mode === 'shared' && scopedAccount(options.accounts, options.currentUid)) throw new Error('企业身份的个性化目录尚未确认,暂不支持共享个性化');
if (!['shared', 'independent'].includes(options.mode)) throw new Error('个性化模式无效');
if (options.mode === 'independent' || (settings.mode === 'shared' && options.mode === 'shared' && !options.sourceUid)) {
return { settings: writePersonaSettings(options.backupRoot, { ...settings, mode: options.mode, noticeDismissed: true,
@@ -253,6 +260,7 @@ function syncSharedPersonaForSwitch(options) {
// The login page has no auth uid. Resume from the last shared projection so
// edits made before logout survive, without adopting another logged-in user.
const sourceUid = options.sourceUid || settings.activeUid;
+ if (scopedAccount(options.accounts, sourceUid) || scopedAccount(options.accounts, options.targetUid)) return { skipped: true };
if (sourceUid === options.targetUid) return { skipped: true };
if (settings.activeUid !== sourceUid) throw new Error('当前账号已变化,请在账号设置中重新选择共享来源');
if (!options.accounts.some(a => String(a.uid) === options.targetUid)) throw new Error('目标账号不存在');
diff --git a/scripts/session-copy-error.js b/scripts/session-copy-error.js
new file mode 100644
index 0000000..5851149
--- /dev/null
+++ b/scripts/session-copy-error.js
@@ -0,0 +1,16 @@
+'use strict';
+const { AMBIGUOUS_SESSION_ACCOUNT } = require('./account-identity');
+// Allowlisted explanations only: arbitrary exception text may contain SQL rows,
+// auth material or user input. Never send that text to the UI or task log.
+function sanitizeSessionCopyError(error) {
+ if (error && error.code === 'WBS_AMBIGUOUS_SESSION_ACCOUNT') return AMBIGUOUS_SESSION_ACCOUNT;
+ const text = String(error && (error.code || error.message) || error || '');
+ if (/SQLITE_BUSY|SQLITE_LOCKED/i.test(text)) return '会话数据库正被占用,请稍后重新同步';
+ if (/EACCES|EPERM/i.test(text)) return '没有读取或写入会话文件的权限,请检查文件权限后重新同步';
+ if (/ENOENT/i.test(text)) return '会话数据库或文件不存在,请确认 WorkBuddy 已正常启动后重新同步';
+ if (/ENOSPC/i.test(text)) return '磁盘空间不足,请释放空间后重新同步';
+ if (/SQLITE_CORRUPT|SQLITE_NOTADB/i.test(text)) return '会话数据库无法读取,请先检查 WorkBuddy 是否能正常打开会话';
+ if (/SQLITE_ERROR/i.test(text)) return '会话数据库结构不兼容,请更新 WorkDaddy 后重新同步';
+ return '同步任务异常中断,请稍后重新同步;若仍失败,请反馈客户端版本及同步阶段';
+}
+module.exports = { sanitizeSessionCopyError };
diff --git a/test/account-identity.test.js b/test/account-identity.test.js
new file mode 100644
index 0000000..ab7a012
--- /dev/null
+++ b/test/account-identity.test.js
@@ -0,0 +1,114 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const vm = require('node:vm');
+const { accountIdentity, createSessionAccountResolver } = require('../scripts/account-identity');
+const { parameterCount, createSessionDb } = require('../scripts/session-db');
+const lib = require('../scripts/lib');
+const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+
+test('personal upgrades keep their backup key; enterprises have independent stable keys', () => {
+ for (const type of ['', 'personal', 'pro', 'free', 'enterprise-trial']) {
+ assert.equal(accountIdentity({ uid: 'owner', type }), 'owner');
+ }
+ const first = accountIdentity({ uid: 'owner', type: 'ultimate', enterpriseId: 'company-a' });
+ assert.match(first, /^wdent_[a-f0-9]{64}$/);
+ assert.equal(accountIdentity({ uid: 'owner', type: 'exclusive', enterpriseId: 'company-a' }), first);
+ assert.notEqual(accountIdentity({ uid: 'owner', type: 'ultimate', enterpriseId: 'company-b' }), first);
+ assert.notEqual(accountIdentity({ uid: 'owner', type: 'ultimate' }), 'owner');
+});
+
+function harness(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-identity-sql-'));
+ t.after(() => fs.rmSync(root, { force: true, recursive: true }));
+ const db = createSessionDb({ dbPath: path.join(root, 'sessions.db') });
+ const accounts = [];
+ const ctx = { fs, path, DATA_DIR: root, parameterCount, SESSION_DB: db, CODEBUDDY_SESSIONS: null,
+ listAccounts: () => accounts.slice(), knownAccountIdentities: lib.knownAccountIdentities, createSessionAccountResolver };
+ vm.runInNewContext(daemon.slice(daemon.indexOf('let sessionAccountResolverCache ='), daemon.indexOf('// WorkBuddy 将会话正文保存在')), ctx);
+ return { root, db, ctx, accounts };
+}
+
+test('session SQL uses raw official owners for queries and writes while returning backup ids', async t => {
+ const { db, ctx, accounts } = harness(t);
+ const uid = accountIdentity({ uid: 'official-owner', enterpriseId: 'company' });
+ accounts.push({ uid, rawUid: 'official-owner' });
+ await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT, title TEXT)');
+ await ctx.sqliteRun('INSERT INTO sessions (id,user_id,title) VALUES (?,?,?)', ['s', uid, uid]);
+ const actual = await db.all('SELECT * FROM sessions');
+ assert.equal(actual[0].user_id, 'official-owner');
+ assert.equal(actual[0].title, uid, 'a user title that resembles an alias must stay unchanged');
+ const rows = await ctx.sqliteQuery("SELECT * FROM sessions WHERE title = ? AND user_id = ? AND '?' = '?'", [uid, uid]);
+ assert.equal(rows[0].user_id, uid);
+ await ctx.sqliteRun('UPDATE sessions SET user_id = ?, title = ? WHERE id = ?', [uid, 'edited', 's']);
+ assert.equal((await db.all('SELECT * FROM sessions'))[0].user_id, 'official-owner');
+});
+
+test('same official uid contexts block reads and mutations before SQL and remain blocked after backup deletion', async t => {
+ const { root, ctx, accounts } = harness(t);
+ const company = accountIdentity({ uid: 'same', enterpriseId: 'company' });
+ accounts.push({ uid: company, rawUid: 'same' });
+ fs.writeFileSync(path.join(root, 'meta.json'), JSON.stringify({ accounts: {}, accountIdentities: { same: ['same', company] } }));
+ let writes = 0;
+ ctx.SESSION_DB = { run() { writes++; }, all: async () => [{ id: 's', user_id: 'same' }] };
+ assert.throws(() => ctx.sqliteRun('INSERT INTO sessions (id,user_id,title) VALUES (?,?,?)', ['s', company, 'title']), { code: 'WBS_AMBIGUOUS_SESSION_ACCOUNT' });
+ await assert.rejects(ctx.sqliteQuery('SELECT * FROM sessions WHERE user_id = ?', [company]), { code: 'WBS_AMBIGUOUS_SESSION_ACCOUNT' });
+ await assert.rejects(ctx.sqliteQuery('SELECT * FROM sessions'), { code: 'WBS_AMBIGUOUS_SESSION_ACCOUNT' });
+ assert.equal(writes, 0);
+});
+
+test('ambiguous synchronization stops during planning before changing session lineage or files', async t => {
+ const { root, ctx, accounts } = harness(t);
+ const company = accountIdentity({ uid: 'same', enterpriseId: 'company' });
+ accounts.push({ uid: 'same', rawUid: 'same' }, { uid: company, rawUid: 'same' });
+ Object.assign(ctx, lib, { DATA_DIR: root, listAccounts: () => accounts.slice() });
+ const start = daemon.indexOf('async function buildAutoCopyPlan(');
+ vm.runInNewContext(daemon.slice(start, daemon.indexOf('const autoCopyJobs', start)), ctx);
+ await assert.rejects(ctx.buildAutoCopyPlan('same', company), { code: 'WBS_AMBIGUOUS_SESSION_ACCOUNT' });
+ assert.equal(fs.existsSync(path.join(root, 'meta.json')), false);
+});
+
+test('account imports keep personal and enterprise contexts through encrypted export roundtrips', async t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-identity-import-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const personal = { account: { uid: 'same-import', type: 'personal' }, auth: { accessToken: 'fixture-only', domain: 'https://www.workbuddy.cn' } };
+ const enterprise = structuredClone(personal);
+ Object.assign(enterprise.account, { type: 'ultimate', enterpriseId: 'company-import' });
+ const context = { ...lib, fs, DATA_DIR: root, log() {}, req: { method: 'POST' }, p: '/api/accounts/import', res: {},
+ json: (_, status, value) => ({ status, ...value }), readBody: async () => ({ format: 'plain-json', content: JSON.stringify([personal, enterprise]) }) };
+ const start = daemon.indexOf(" if (req.method === 'POST' && p === '/api/accounts/import')");
+ const route = '(async () => {' + daemon.slice(start, daemon.indexOf(' // 清空输入框', start)) + '})()';
+ const imported = await vm.runInNewContext(route, context);
+ assert.equal(imported.count, 2);
+ assert.equal(lib.listAccounts(root).length, 2);
+ const items = imported.imported.map(uid => ({ uid, info: fs.readFileSync(lib.backupPath(root, uid), 'utf8') }));
+ // The export encryption layer is independent of identities; exercise its real codec.
+ const { createEncryptedExport, openEncryptedExport } = require('../scripts/secure-transfer');
+ const encrypted = createEncryptedExport('accounts', { exportType: 'WorkDaddy-accounts', version: 2, accounts: items }, 'fixture-password');
+ const target = path.join(root, 'roundtrip');
+ context.DATA_DIR = target;
+ context.openEncryptedExport = openEncryptedExport;
+ context.readBody = async () => ({ content: encrypted, password: 'fixture-password' });
+ const restored = await vm.runInNewContext(route, context);
+ assert.equal(restored.count, 2);
+ for (const item of items) assert.equal(fs.readFileSync(lib.backupPath(target, item.uid), 'utf8'), item.info);
+});
+
+test('seamless login saves enterprise credentials under their scoped backup identity', t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-identity-oauth-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const context = { ...lib, fs, DATA_DIR: root, accountIdentity, log() {}, normTs: value => value || null, currentAuthFile: () => null };
+ const start = daemon.indexOf('function buildSeamlessAuthFile(');
+ vm.runInNewContext(daemon.slice(start, daemon.indexOf('function scheduleOAuthStateCleanup', start)), context);
+ const saveStart = daemon.indexOf('function saveSeamlessAccount(');
+ vm.runInNewContext(daemon.slice(saveStart, daemon.indexOf('\n}', saveStart) + 2), context);
+ const uid = accountIdentity({ uid: 'same-oauth', type: 'ultimate', enterpriseId: 'company' });
+ const result = context.saveSeamlessAccount({ accessToken: 'fixture-only' }, { uid: 'same-oauth', type: 'ultimate', enterpriseId: 'company' });
+ assert.equal(result.uid, uid);
+ const stored = JSON.parse(fs.readFileSync(lib.backupPath(root, uid), 'utf8'));
+ assert.equal(stored.account.uid, 'same-oauth');
+ assert.equal(lib.listAccounts(root)[0].uid, uid);
+});
diff --git a/test/account-snapshot-reload.test.js b/test/account-snapshot-reload.test.js
index 0cad55d..c898482 100644
--- a/test/account-snapshot-reload.test.js
+++ b/test/account-snapshot-reload.test.js
@@ -4,6 +4,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
+const { accountIdentity } = require('../scripts/account-identity');
const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
const oldSnapshot = { version: 1, uid: 'old', nickname: '旧账号', type: 'enterprise', savedAt: 1, editionType: 'free', enterpriseId: 'old-company' };
function harness(options = {}) {
@@ -26,7 +27,7 @@ function harness(options = {}) {
const raw = new URL(location.href).searchParams.get('accountSnapshot');
initialAccount = raw ? JSON.parse(decodeURIComponent(raw)) : null;
};
- const ctx = {
+ const ctx = { accountIdentity,
PROFILE: { kind: options.kind || 'workbuddy' }, cdp: { connected: true },
setTimeout, clearTimeout, URL, log: line => logs.push(line),
armPendingReloadInjection: () => { armed = true; return { ready: options.ready || Promise.resolve(true) }; },
diff --git a/test/account-switch-session-rules.test.js b/test/account-switch-session-rules.test.js
index c47c407..c871eba 100644
--- a/test/account-switch-session-rules.test.js
+++ b/test/account-switch-session-rules.test.js
@@ -5,11 +5,13 @@ const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const lib = require('../scripts/lib');
+const resolver = require('../scripts/account-identity').createSessionAccountResolver([]);
+const sessionAccountAmbiguous = uid => { try { resolver.assertUnambiguous(uid); return false; } catch (_) { return true; } };
const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
function harness(rules, owner = 'source') {
const jobs = [], events = [];
- const ctx = vm.createContext({
+ const ctx = vm.createContext({ sessionAccountAmbiguous,
DATA_DIR: 'fixture', log() {}, isAutoCopySessionSelected: lib.isAutoCopySessionSelected,
isValidSessionId: id => !!id,
readBody: async req => req.body,
@@ -88,7 +90,7 @@ const compat = require('../scripts/workbuddy-compat');
function rendererCapture(profileId, adapter, window = {}) {
const node = { __reactFiber$test: { memoizedProps: { adapter }, return: null } };
- const context = vm.createContext({
+ const context = vm.createContext({ sessionAccountAmbiguous,
PROFILE_ID: profileId, CAPS: { enhance: false }, window,
WBS_COMPAT: compat, URL, location: { href: 'https://client.invalid/agentManager.html' },
document: { querySelector: selector => selector === '.chat-container' ? node : null, querySelectorAll: () => [] },
diff --git a/test/auth-discovery.test.js b/test/auth-discovery.test.js
index f24ed38..73b1770 100644
--- a/test/auth-discovery.test.js
+++ b/test/auth-discovery.test.js
@@ -512,3 +512,59 @@ test('soft logout can be retried after the login file was removed and login was
assert.equal(unknown.file, null);
} finally { fs.rmSync(f.root, { recursive: true, force: true }); }
});
+
+
+test('personal and enterprise backups sharing an official uid survive switching and deletion independently', () => {
+ const f = fixture();
+ try {
+ const file = path.join(f.authDir, 'workbuddy-desktop.info');
+ const personal = auth('same-user', 'https://www.workbuddy.cn', true);
+ personal.account.type = 'personal';
+ const enterprise = structuredClone(personal);
+ Object.assign(enterprise.account, { type: 'ultimate', enterpriseId: 'company-one', enterpriseName: '公司一' });
+ fs.writeFileSync(file, JSON.stringify(personal));
+ run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR)');
+ fs.writeFileSync(file, JSON.stringify(enterprise));
+ const accounts = run(f.root, f.dataDir, 'lib.backupCurrent(process.env.WBSWITCH_DATA_DIR); process.stdout.write(JSON.stringify(lib.listAccounts(process.env.WBSWITCH_DATA_DIR)))');
+ assert.equal(accounts.length, 2);
+ const company = accounts.find(a => a.enterpriseId === 'company-one');
+ assert.ok(company);
+ assert.notEqual(company.uid, 'same-user');
+ assert.equal(company.rawUid, 'same-user');
+ const switched = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.switchTo(process.env.WBSWITCH_DATA_DIR,"same-user")))');
+ assert.equal(switched.uid, 'same-user');
+ assert.equal(JSON.parse(fs.readFileSync(file)).account.type, 'personal');
+ run(f.root, f.dataDir, `lib.switchTo(process.env.WBSWITCH_DATA_DIR,${JSON.stringify(company.uid)})`);
+ assert.equal(JSON.parse(fs.readFileSync(file)).account.enterpriseId, 'company-one');
+ run(f.root, f.dataDir, 'lib.deleteAccount(process.env.WBSWITCH_DATA_DIR,"same-user")');
+ assert.equal(JSON.parse(fs.readFileSync(file)).account.enterpriseId, 'company-one');
+ assert.equal(run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.listAccounts(process.env.WBSWITCH_DATA_DIR)))').length, 1);
+ const known = run(f.root, f.dataDir, 'process.stdout.write(JSON.stringify(lib.knownAccountIdentities(process.env.WBSWITCH_DATA_DIR)))');
+ assert.deepEqual(known['same-user'].sort(), ['same-user', company.uid].sort(), 'removing a backup must retain the known ownership ambiguity');
+ } finally { fs.rmSync(f.root, { recursive: true, force: true }); }
+});
+
+test('legacy enterprise backups migrate without changing auth bytes, preserving notes and independent rules', () => {
+ const f = fixture();
+ try {
+ fs.mkdirSync(path.join(f.dataDir, 'accounts'), { recursive: true });
+ const enterprise = auth('legacy-company', 'https://www.workbuddy.cn');
+ Object.assign(enterprise.account, { type: 'ultimate', enterpriseId: 'company-one' });
+ const original = JSON.stringify(enterprise, null, 2);
+ fs.writeFileSync(path.join(f.dataDir, 'accounts', 'legacy-company.info'), original);
+ fs.writeFileSync(path.join(f.dataDir, 'meta.json'), JSON.stringify({ accounts: { 'legacy-company': { note: '保留备注', sort: 2 } } }));
+ const result = run(f.root, f.dataDir, `
+ const d=process.env.WBSWITCH_DATA_DIR;
+ lib.setAutoCopyRule(d,{uid:'legacy-company',kind:'session',key:'shared-session',enabled:true});
+ const accounts=lib.listAccounts(d); const company=accounts[0];
+ process.stdout.write(JSON.stringify({company, rules:lib.getAutoCopyRules(d,company.uid), again:lib.listAccounts(d)}));
+ `);
+ assert.equal(result.company.rawUid, 'legacy-company');
+ assert.notEqual(result.company.uid, 'legacy-company');
+ assert.equal(result.company.note, '保留备注');
+ assert.equal(result.company.sort, 2);
+ assert.deepEqual(result.rules.sessionIds, [], 'ambiguous uid-only sync rules must not be inherited by enterprise identity');
+ assert.equal(result.again.length, 1);
+ assert.equal(fs.readFileSync(path.join(f.dataDir, 'accounts', result.company.uid + '.info'), 'utf8'), original);
+ } finally { fs.rmSync(f.root, { recursive: true, force: true }); }
+});
diff --git a/test/auto-continue.test.js b/test/auto-continue.test.js
index f0eb950..b43f78a 100644
--- a/test/auto-continue.test.js
+++ b/test/auto-continue.test.js
@@ -283,6 +283,10 @@ function acSupported(platform) {
classifyAutoContinueControllerSnapshot({ assistantId: 'req-a-assistant', error: true, errorCode: 6004, rateLimited: true }),
{ trigger: false, reason: 'model-rate-limited' },
);
+ assert.deepStrictEqual(
+ classifyAutoContinueControllerSnapshot({ assistantId: 'req-a-assistant', error: true, errorCode: 6000, usageLimited: true }),
+ { trigger: false, reason: 'model-usage-limited' },
+ );
assert.deepStrictEqual(
classifyAutoContinueControllerSnapshot({ assistantId: 'req-a-assistant', manualStop: true }),
{ trigger: false, reason: 'manual-stop' },
@@ -311,7 +315,10 @@ function acSupported(platform) {
assert.ok(Number.isFinite(normalized.resetAt));
assert.equal(Object.prototype.hasOwnProperty.call(normalized, 'message'), false);
assert.deepStrictEqual(classifyAutoContinueError({ code: 14018 }), {
- quotaExhausted: true, rateLimited: false, authFailure: false, nonRetryable: true, code: 14018,
+ quotaExhausted: true, usageLimited: false, rateLimited: false, authFailure: false, nonRetryable: true, code: 14018,
+ });
+ assert.deepStrictEqual(classifyAutoContinueError({ code: 6000 }), {
+ quotaExhausted: false, usageLimited: true, rateLimited: false, authFailure: false, nonRetryable: true, code: 6000,
});
console.log('✓ 官方 14018/6004 错误码停止自动继续,错误快照不保留原文');
}
diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.js
index 2f7e714..1577a47 100644
--- a/test/automation-checkin.test.js
+++ b/test/automation-checkin.test.js
@@ -114,10 +114,11 @@ test('panel refresh exposes an explicit current-account check-in reconciliation
assert.match(ui, /current\.checkin = \{ ok: !!result\.ok/);
});
-test('model rate limit route and account snapshots expose only structured 6004 records', () => {
+test('model rate limit route accepts only supported structured business codes', () => {
assert.match(source, /p === '\/api\/model-rate-limit'/);
const route = source.slice(source.indexOf("p === '/api/model-rate-limit'"), source.indexOf("if (req.method === 'GET' && p === '/api/accounts')"));
- assert.match(route, /reasonCode !== 6004/);
+ assert.match(route, /\[6000, 6004\]\.includes\(reasonCode\)/);
+ assert.match(route, /\[model-rate-limit\] WARN/);
assert.match(route, /modelName/);
assert.doesNotMatch(route, /body\.message|body\.response|body\.raw/);
const accounts = source.slice(source.indexOf("if (req.method === 'GET' && p === '/api/accounts')"), source.indexOf('// 查询指定账号的剩余积分'));
@@ -127,7 +128,7 @@ test('model rate limit route and account snapshots expose only structured 6004 r
test('model rate limit reports are deduplicated across accounts by model and reset time', () => {
const route = source.slice(source.indexOf("p === '/api/model-rate-limit'"), source.indexOf("if (req.method === 'GET' && p === '/api/accounts')"));
- assert.match(route, /hasModelRateLimitElsewhere\(\{ uid, modelId, resetAt, now \}\)/);
+ assert.match(route, /hasModelRateLimitElsewhere\(\{ uid, modelId, resetAt, reasonCode, now \}\)/);
assert.match(route, /skipped: 'duplicate-across-accounts'/);
assert.match(route, /resetAt !== null/);
});
diff --git a/test/automation-safety-review.test.js b/test/automation-safety-review.test.js
index 74b4bd4..241ad55 100644
--- a/test/automation-safety-review.test.js
+++ b/test/automation-safety-review.test.js
@@ -52,6 +52,7 @@ test('safety review route resolves the stored task and the row button uses it wi
assert.match(daemon, /createSafetyReviewTask\(DATA_DIR, id\)/);
assert.match(inject, /data-auto-review=/);
assert.match(inject, /\/api\/automations\/safety-review/);
- const row = inject.slice(inject.indexOf("row.innerHTML = '<div class=\"wbs-auto-row-head\">'"), inject.indexOf('list.appendChild(row);'));
+ const rowStart = inject.indexOf("row.innerHTML = '<div class=\"wbs-auto-row-head\">'");
+ const row = inject.slice(rowStart, inject.indexOf('list.appendChild(row);', rowStart));
assert.ok(row.indexOf('data-auto-review=') < row.indexOf('data-auto-enabled='));
});
diff --git a/test/codebuddy-compat.test.js b/test/codebuddy-compat.test.js
index f059323..b298633 100644
--- a/test/codebuddy-compat.test.js
+++ b/test/codebuddy-compat.test.js
@@ -61,7 +61,7 @@ test('CodeBuddy does not preflight-block native session recovery', () => {
test('CodeBuddy restores a lost native session from a validated backup', () => {
assert.match(daemon, /recoverCodeBuddyNativeSession/);
assert.match(daemon, /session = await recoverCodeBuddyNativeSession\(\)/);
- assert.match(daemon, /writeCodeBuddyNativeState\(String\(session\.account\.uid\), false\)/);
+ assert.match(daemon, /writeCodeBuddyNativeState\(accountIdentity\(session\.account\), false\)/);
assert.match(daemon, /writeCodeBuddyNativeState\(beforeLogout && beforeLogout\.uid \|\| '', true\)/);
});
test('CodeBuddy HTML compatibility keeps the official innerHTML sink unchanged', () => {
diff --git a/test/codebuddy-files.test.js b/test/codebuddy-files.test.js
index 0e53d36..ab2f169 100644
--- a/test/codebuddy-files.test.js
+++ b/test/codebuddy-files.test.js
@@ -15,6 +15,14 @@ function fixture(t) {
fs.writeFileSync(path.join(base,'source','messages','message.json'),JSON.stringify({id:'message',role:'user',message:'fixture',extra:{conversationId:'source'}}));
return {root,files,base};
}
+test('backup aliases resolve to official owners before native history paths are constructed',t=>{
+ const {root,base}=fixture(t);
+ const files=createCodeBuddyFiles({root,sync,resolveAccountUid:uid=>uid==='enterprise-backup'?'user-a':uid});
+ files.register({id:'source',user_id:'enterprise-backup',cwd:'/fixture'});
+ assert.equal(files.snapshot(null,'source').records.length,1);
+ assert.ok(files.collect('source').every(file=>file.source.startsWith(base)));
+ assert.equal(fs.existsSync(path.join(root,'enterprise-backup')),false);
+});
test('native history copy uses the shared guarded transaction and publishes a complete workspace index',async t=>{
const {root,files}=fixture(t);
const source=files.snapshot(null,'source',['target']),target=files.snapshot(null,'target',['source']);
diff --git a/test/credit-usage-store.test.js b/test/credit-usage-store.test.js
index dd671b5..1bb5178 100644
--- a/test/credit-usage-store.test.js
+++ b/test/credit-usage-store.test.js
@@ -139,6 +139,16 @@ test('stores multiple model rate limits and removes expired reset times', async
assert.deepEqual(afterExpiry.u1, [{ modelId: 'gpt-5.6', modelName: 'GPT-5.6', resetAt: null, observedAt: 1100, source: 'renderer-error', reasonCode: 6004 }]);
});
+test('model limit de-duplication keeps usage and frequency business codes distinct', async (t) => {
+ const tmp = tempStore();
+ t.after(() => fs.rmSync(tmp.dir, { recursive: true, force: true }));
+ await tmp.store.saveModelRateLimit({ uid: 'u1', modelId: 'model-x', modelName: 'Model X', resetAt: 5000, observedAt: 1000, reasonCode: 6004, source: 'renderer-error' });
+ assert.equal(await tmp.store.hasModelRateLimitElsewhere({ uid: 'u2', modelId: 'model-x', resetAt: 5000, reasonCode: 6004, now: 4000 }), true);
+ assert.equal(await tmp.store.hasModelRateLimitElsewhere({ uid: 'u2', modelId: 'model-x', resetAt: 5000, reasonCode: 6000, now: 4000 }), false);
+ await tmp.store.saveModelRateLimit({ uid: 'u1', modelId: 'usage-model', modelName: 'Usage Model', resetAt: null, observedAt: 1000, reasonCode: 6000, source: 'renderer-error' });
+ assert.equal((await tmp.store.listModelRateLimits(['u1'], 4000).then(rows => rows.u1)).find(row => row.modelId === 'usage-model').reasonCode, 6000);
+});
+
test('detects an active matching model limit owned by another account', async (t) => {
const tmp = tempStore();
t.after(() => fs.rmSync(tmp.dir, { recursive: true, force: true }));
diff --git a/test/model-rate-limit.test.js b/test/model-rate-limit.test.js
index bd0acc6..f1ca132 100644
--- a/test/model-rate-limit.test.js
+++ b/test/model-rate-limit.test.js
@@ -3,9 +3,45 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
const vm = require('node:vm');
const inject = require('../scripts/inject.js');
+const { createCreditUsageStore } = require('../scripts/credit-usage-store.js');
const source = fs.readFileSync(require.resolve('../scripts/inject.js'), 'utf8');
+const daemonSource = fs.readFileSync(require.resolve('../scripts/daemon.js'), 'utf8');
+
+function modelLimitRouteHarness(t) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-model-limit-route-'));
+ t.after(() => fs.rmSync(dataDir, { recursive: true, force: true }));
+ const logs = [];
+ const context = {
+ URL,
+ HOST: '127.0.0.1',
+ DATA_DIR: dataDir,
+ PROFILE: { id: 'workbuddy-cn' },
+ CREDIT_USAGE_STORE: createCreditUsageStore({ dbPath: path.join(dataDir, 'credit-usage.db'), profileId: 'workbuddy-cn' }),
+ isAllowedApiOrigin: () => true,
+ isApiRequestAuthorized: () => true,
+ readBody: request => Promise.resolve(request.body),
+ json: (_, status, body) => ({ status, body }),
+ listAccounts: () => [{ uid: 'synthetic-user' }],
+ log: line => logs.push(line),
+ };
+ const start = daemonSource.indexOf('function handleApi(req, res)');
+ const end = daemonSource.indexOf('\n\n// ===== 电脑休眠控制', start);
+ assert.ok(start >= 0 && end > start, 'daemon API handler source missing');
+ vm.createContext(context);
+ vm.runInContext(daemonSource.slice(start, end), context);
+ return {
+ logs,
+ dataDir,
+ store: context.CREDIT_USAGE_STORE,
+ request: body => context.handleApi({
+ method: 'POST', url: '/api/model-rate-limit', headers: { host: '127.0.0.1' }, body,
+ }, {}),
+ };
+}
function capError(overrides = {}) {
return {
@@ -32,6 +68,21 @@ test('cap reset wall clock uses UTC+8 on every client timezone', () => {
assert.equal(result.resetAt, Date.parse('2026-10-16T17:21:48+08:00'));
});
+test('model usage limit 6000 is distinct from frequency limit 6004', () => {
+ const usage = inject.normalizeAutoContinueError({
+ code: 500, requestModelId: 'deepseek-v4.1-flash', message: 'Request failed',
+ terminal: { bizCode: 6000, details: '用量限制,请稍后再试' },
+ });
+ assert.equal(usage.code, 6000);
+ assert.equal(usage.rateLimited, false);
+ assert.equal(usage.usageLimited, true);
+ assert.equal(usage.quotaExhausted, false);
+ assert.equal(usage.nonRetryable, true);
+ const frequency = inject.normalizeAutoContinueError(capError());
+ assert.equal(frequency.rateLimited, true);
+ assert.equal(frequency.quotaExhausted, false);
+});
+
test('cap statistics subscribe without auto-continue, catch terminal warnings and clean up', () => {
const listeners = new Set();
let state = { model: 'deepseek-v4.1-flash' };
@@ -70,6 +121,24 @@ test('cap statistics subscribe without auto-continue, catch terminal warnings an
assert.equal(records.length, 2, 'disposed timers cannot report');
});
+test('model usage limit observer records business code 6000 separately', () => {
+ const listeners = new Set();
+ const records = [];
+ const state = { model: 'deepseek-v4.1-flash', error: {
+ code: 6000, requestModelId: 'deepseek-v4.1-flash', message: '用量限制',
+ } };
+ const observer = inject.createModelRateLimitObserver({
+ discover: () => [{ conversationId: 'usage-session', sessionStore: {
+ getState: () => state, subscribe: fn => { listeners.add(fn); return () => listeners.delete(fn); },
+ } }],
+ record: value => records.push(value), setInterval: () => 1, clearInterval() {},
+ });
+ assert.equal(records.length, 1);
+ assert.equal(records[0].errorCode, 6000);
+ assert.equal(records[0].limitType, 'usage');
+ observer.destroy();
+});
+
function reporterContext(api) {
const start = source.indexOf(' function acRecordModelRateLimit(');
const end = source.indexOf('\n function acControllerSnapshot(', start);
@@ -109,10 +178,41 @@ test('failed cap writes and current-account lookups are retried; successful writ
}
});
+test('model usage and frequency limit reports preserve their business codes', async () => {
+ const posts = [];
+ const context = reporterContext(async (route, options) => {
+ if (route === '/api/current') return { uid: 'synthetic-user' };
+ posts.push(JSON.parse(options.body));
+ return { ok: true };
+ });
+ for (const errorCode of [6000, 6004]) {
+ context.acRecordModelRateLimit({ conversationId: 'session-' + errorCode, assistantId: 'assistant-' + errorCode,
+ errorCode, rateLimited: errorCode === 6004, limitType: errorCode === 6000 ? 'usage' : 'frequency', errorRequestModelId: 'model-test', errorResetAt: null });
+ }
+ await flush();
+ assert.deepEqual(posts.map(post => post.reasonCode), [6000, 6004]);
+});
+
+test('daemon model-limit route stores 6000 and 6004 and warns on unsupported codes', async t => {
+ const h = modelLimitRouteHarness(t);
+ for (const [reasonCode, modelId] of [[6000, 'usage-model'], [6004, 'frequency-model']]) {
+ const result = await h.request({ uid: 'synthetic-user', modelId, modelName: modelId, reasonCode, resetAt: null });
+ assert.equal(result.status, 200);
+ assert.equal(result.body.ok, true);
+ }
+ const records = await h.store.listModelRateLimits(['synthetic-user']);
+ assert.deepEqual(records['synthetic-user'].map(record => [record.modelId, record.reasonCode]), [
+ ['frequency-model', 6004], ['usage-model', 6000],
+ ]);
+ const rejected = await h.request({ uid: 'synthetic-user', modelId: 'other-model', reasonCode: 6001, resetAt: null });
+ assert.equal(rejected.status, 400);
+ assert.ok(h.logs.some(line => line.includes('[model-rate-limit] WARN 拒绝上报: unsupported-reason-code')));
+});
+
test('statistics never submit a generic HTTP 429 as a business cap 6004', async () => {
let calls = 0;
const context = reporterContext(async () => { calls++; return {}; });
- for (const errorCode of [null, 429, 14018]) {
+ for (const errorCode of [null, 429, 14018, 6001]) {
context.acRecordModelRateLimit({ rateLimited: true, errorCode });
}
await flush();
@@ -124,6 +224,36 @@ test('cap observer starts independently and is disposed on reinjection', () => {
assert.ok(/registerDisposer\(function \(\) \{ modelRateLimitObserver\.destroy\(\); \}\)/.test(source));
});
+test('account limit UI distinguishes usage limits from frequency limits', () => {
+ assert.match(source, /Number\(record && record\.reasonCode\) === 6000[\s\S]{0,120}用量限制/);
+ assert.match(source, /频率限制/);
+ const start = source.indexOf(' function modelLimitKind(record) {');
+ const end = source.indexOf(' function creditBlockHtml(', start);
+ assert.ok(start >= 0 && end > start, 'model limit renderers missing');
+ const context = {
+ WBS_LANGUAGE: 'zh', state: { mask: false },
+ wbsTranslateString: value => value,
+ fmtDateTimeSeconds: () => '2026-11-03 12:00:00',
+ fmtCreditExpiry: () => '10 分钟后',
+ esc: value => String(value),
+ accountDisplayName: account => account.nickname,
+ };
+ vm.createContext(context);
+ vm.runInContext(source.slice(start, end), context);
+ context.account = { nickname: 'test account', modelRateLimits: [
+ { modelId: 'usage-model', modelName: 'Usage Model', reasonCode: 6000, resetAt: 0 },
+ { modelId: 'frequency-model', modelName: 'Frequency Model', reasonCode: 6004, resetAt: 1793707200000 },
+ ] };
+ const detail = vm.runInContext('modelRateLimitPopoverHtml(account)', context);
+ const summary = vm.runInContext('modelRateLimitSummaryPopoverHtml([account])', context);
+ for (const html of [detail, summary]) {
+ assert.match(html, /用量限制/);
+ assert.match(html, /频率限制/);
+ assert.match(html, /预计恢复/);
+ assert.match(html, /预计解封/);
+ }
+});
+
test('renderer cap cleanup calls the native timer API with a valid receiver', () => {
const start = source.indexOf(' var modelRateLimitObserver = createModelRateLimitObserver({');
const end = source.indexOf('\n registerDisposer(', start);
diff --git a/test/persona-sharing.test.js b/test/persona-sharing.test.js
index 618c3d6..4452c71 100644
--- a/test/persona-sharing.test.js
+++ b/test/persona-sharing.test.js
@@ -16,6 +16,18 @@ function fixture(t) {
const enable = () => p.configurePersona({...options,mode:'shared',sourceUid:'a',revision:p.listPersonaSources(options)[0].revision});
return {options,file,write,enable};
}
+test('scoped enterprise identities never project backup ids into official personal directories', t => {
+ const f = fixture(t);
+ const uid = require('../scripts/account-identity').accountIdentity({uid:'a',enterpriseId:'company'});
+ f.options.accounts.push({uid,rawUid:'a'});
+ f.enable();
+ assert.equal(p.inspectPersona({...f.options,targetUid:uid}).eligible,false);
+ assert.equal(p.listPersonaSources(f.options).some(source=>source.uid===uid),false);
+ assert.equal(p.syncSharedPersonaForSwitch({...f.options,sourceUid:'a',targetUid:uid}).skipped,true);
+ assert.throws(()=>p.configurePersona({...f.options,currentUid:uid,mode:'shared'}),/企业身份/);
+ assert.equal(fs.existsSync(p.personaDir(f.options.dataRoot,uid)),false);
+ assert.equal(fs.readFileSync(f.file('a','USER.md'),'utf8'),'aUSER.md');
+});
test('dismissal persists without selecting a mode and can later enable sharing', t => {
const f=fixture(t);
p.dismissPersonaNotice(f.options.backupRoot);
diff --git a/test/quick-phrase-drag.test.js b/test/quick-phrase-drag.test.js
new file mode 100644
index 0000000..d28e2e9
--- /dev/null
+++ b/test/quick-phrase-drag.test.js
@@ -0,0 +1,207 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const path = require('node:path');
+const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+const renderStart = source.indexOf(' function renderQpList() {');
+const helperStart = source.indexOf(' function createQuickPhraseSorter(');
+const end = source.indexOf(' /** 发送按钮面板选项', renderStart);
+const settle = () => new Promise(resolve => setImmediate(resolve));
+
+function harness({ batch = false, reducedMotion = false, save } = {}) {
+ let rows = [], html = '', nextFrame = 0;
+ const calls = [], applied = [], errors = [], animations = [], frames = new Map();
+ function element(attrs = {}, parent = null) {
+ const listeners = new Map(), classes = new Set();
+ return { attrs, parent, listeners,
+ getAttribute: name => attrs[name] ?? null,
+ setAttribute(name, value) { attrs[name] = value; },
+ removeAttribute(name) { delete attrs[name]; },
+ classList: { add: c => classes.add(c), remove: c => classes.delete(c), contains: c => classes.has(c) },
+ addEventListener(name, handler) { if (!listeners.has(name)) listeners.set(name, new Set()); listeners.get(name).add(handler); },
+ removeEventListener(name, handler) { listeners.get(name)?.delete(handler); },
+ closest(selector) {
+ if (selector === '.wbs-qp-row' && attrs.class === 'wbs-qp-row') return this;
+ if (selector === '[data-qp-drag]' && attrs['data-qp-drag']) return this;
+ return parent?.closest(selector) || null;
+ },
+ contains(node) { for (; node; node = node.parent) if (node === this) return true; return false; },
+ getBoundingClientRect() { return { top: 100 + (this.offsetTop || 0) - list.scrollTop, left: 0, height: 40, width: 300, bottom: 140 + (this.offsetTop || 0) - list.scrollTop }; },
+ animate(keyframes, options) {
+ const animation = { node: this, keyframes, options, cancelled: false, cancel() { this.cancelled = true; } };
+ animations.push(animation); return animation;
+ },
+ };
+ }
+ const attrsOf = markup => Object.fromEntries([...markup.matchAll(/([\w-]+)="([^"]*)"/g)].map(m => [m[1], m[2]]));
+ const list = Object.assign(element(), {
+ scrollTop: 0, clientTop: 0, clientHeight: 120,
+ querySelectorAll: selector => selector === '.wbs-qp-row' ? [...rows] : [],
+ insertBefore(row, ref) { rows.splice(rows.indexOf(row), 1); const index = ref ? rows.indexOf(ref) : rows.length; rows.splice(index, 0, row); return row; },
+ appendChild(row) { return this.insertBefore(row, null); },
+ getBoundingClientRect: () => ({ top: 100, bottom: 220, left: 0, right: 300, height: 120, width: 300 }),
+ });
+ Object.defineProperties(list, {
+ scrollHeight: { get: () => rows.length * 40 },
+ innerHTML: { get: () => html, set(value) {
+ html = value;
+ rows = [...value.matchAll(/<div (class="wbs-qp-row"[^>]*)>([\s\S]*?)<\/div>/g)].map(m => {
+ const row = element(attrsOf(m[1]), list);
+ const handleMarkup = m[2].match(/<button ([^>]*data-qp-drag[^>]*)>/);
+ row.handle = handleMarkup ? element(attrsOf(handleMarkup[1]), row) : null;
+ row.edit = element({ class: 'wbs-qp-icon-btn' }, row);
+ row.querySelector = selector => selector === '[data-qp-drag]' ? row.handle : null;
+ Object.defineProperties(row, {
+ offsetTop: { get: () => rows.indexOf(row) * 40 }, offsetHeight: { get: () => 40 },
+ nextElementSibling: { get: () => rows[rows.indexOf(row) + 1] || null },
+ });
+ return row;
+ });
+ } },
+ });
+ const document = element(), window = Object.assign(element(), { matchMedia: () => ({ matches: reducedMotion }) });
+ const context = {
+ enhancePane: { querySelector: selector => selector === '#wbs-qp-list' ? list : null },
+ sessState: { qpBatch: batch, qpSel: {}, phrases: ['a', 'b', 'c'].map(id => ({ id, text: id })) },
+ sessLastQpSig: '', qpSortCleanup: null, escAttr: String, esc: String, MODEL_EDIT_SVG: '', TRASH_SVG: '',
+ api: async (route, options) => { calls.push({ route, body: JSON.parse(options.body) }); return save ? save() : { ok: true }; },
+ applySessionModule: data => applied.push(data), toast: message => errors.push(message), syncSessionModule() {}, root: {},
+ document, window, requestAnimationFrame(fn) { const id = ++nextFrame; frames.set(id, fn); return id; }, cancelAnimationFrame: id => frames.delete(id),
+ };
+ vm.runInNewContext((helperStart < 0 ? '' : source.slice(helperStart, source.lastIndexOf(' /** 增强页快捷短语列表', renderStart))) + source.slice(renderStart, end), context);
+ context.renderQpList();
+ const data = new Map();
+ const dataTransfer = { setData: (key, value) => data.set(key, value), getData: key => data.get(key) || '', setDragImage() {} };
+ function event(target, clientY = 120) {
+ return { target, dataTransfer, clientY, clientX: 12, defaultPrevented: false,
+ preventDefault() { this.defaultPrevented = true; }, stopPropagation() { this.stopped = true; } };
+ }
+ function emit(target, name, ev = event(target)) {
+ for (let node = target; node; node = node.parent) {
+ for (const handler of node.listeners.get(name) || []) handler.call(node, ev);
+ if (ev.stopped) break;
+ }
+ return ev;
+ }
+ function dragFrom(hitTarget) {
+ let target = hitTarget;
+ while (target && target.attrs.draggable !== 'true') target = target.parent;
+ return target ? emit(target, 'dragstart') : null;
+ }
+ function over(index, after = true) {
+ const row = rows[index];
+ const y = row.getBoundingClientRect().top + (after ? 32 : 8);
+ emit(row, 'dragover', event(row, y)); return y;
+ }
+ async function drop(index, after = true) {
+ const y = over(index, after);
+ // Moving the DOM row can change the browser's drop target. Use the current
+ // row at the pointer, as Chromium does, not the pre-preview row reference.
+ const hit = rows[Math.min(rows.length - 1, Math.floor((y - 100 + list.scrollTop) / 40))];
+ emit(hit, 'drop', event(hit, y)); await settle();
+ }
+ return { get rows() { return rows; }, calls, applied, errors, animations, frames, list, document, window, context,
+ order: () => rows.map(row => row.attrs['data-id']), dragFrom, over, drop, emit, event,
+ destroy: () => context.qpSortCleanup?.(),
+ };
+}
+
+test('handle drag previews and animates the new order before drop, without saving', () => {
+ const h = harness();
+ assert.equal(h.dragFrom(h.rows[0].handle)?.defaultPrevented, false);
+ h.over(1);
+ assert.deepEqual(h.order(), ['b', 'a', 'c']);
+ assert.equal(h.calls.length, 0);
+ assert.deepEqual(Array.from(h.context.sessState.phrases, p => p.id), ['a', 'b', 'c']);
+ assert.ok(h.animations.some(a => a.node.attrs['data-id'] === 'b' && a.options.duration > 0));
+ h.over(1); h.over(1);
+ assert.deepEqual(h.order(), ['b', 'a', 'c'], 'repeated dragover at the placeholder must not jitter');
+});
+
+test('a real handle drag persists the preview once, even if drop targets the moving row', async () => {
+ const h = harness(); h.dragFrom(h.rows[0].handle); await h.drop(1);
+ assert.deepEqual(h.calls, [{ route: '/api/quick-phrase-reorder', body: { ids: ['b', 'a', 'c'] } }]);
+ assert.equal(h.applied.length, 1);
+ h.emit(h.rows[1].handle, 'dragend');
+ assert.deepEqual(h.order(), ['b', 'a', 'c'], 'dragend after drop must not undo saved order');
+});
+
+test('upward preview and drop keep every phrase once', async () => {
+ const h = harness(); h.dragFrom(h.rows[2].handle); await h.drop(0, false);
+ assert.deepEqual(h.order(), ['c', 'a', 'b']);
+ assert.deepEqual(h.calls[0].body.ids, ['c', 'a', 'b']);
+});
+
+test('cancel or drop outside restores the original order without saving', () => {
+ for (const cancel of ['dragend', 'Escape']) {
+ const h = harness(), handle = h.rows[0].handle; h.dragFrom(handle); h.over(1);
+ if (cancel === 'dragend') h.emit(handle, 'dragend');
+ else h.emit(h.document, 'keydown', { ...h.event(h.document), key: 'Escape' });
+ assert.deepEqual(h.order(), ['a', 'b', 'c']); assert.equal(h.calls.length, 0);
+ assert.ok(h.rows.every(row => !row.classList.contains('wbs-qp-dragging')));
+ }
+});
+
+test('failed save rolls the preview back and reports the failure', async () => {
+ const h = harness({ save: () => ({ ok: false, error: 'test rejection' }) });
+ h.dragFrom(h.rows[0].handle); await h.drop(1);
+ assert.deepEqual(h.order(), ['a', 'b', 'c']); assert.equal(h.errors.length, 1); assert.equal(h.applied.length, 0);
+ assert.equal(h.list.getAttribute('aria-busy'), null);
+});
+
+test('a pending save prevents a second drag', async () => {
+ let resolve; const h = harness({ save: () => new Promise(r => { resolve = r; }) });
+ h.dragFrom(h.rows[0].handle); await h.drop(1);
+ assert.equal(h.dragFrom(h.rows[0].handle).defaultPrevented, true);
+ resolve({ ok: true }); await settle();
+ assert.equal(h.dragFrom(h.rows[0].handle).defaultPrevented, false);
+});
+
+test('reduced-motion still previews order but skips animation', () => {
+ const h = harness({ reducedMotion: true }); h.dragFrom(h.rows[0].handle); h.over(1);
+ assert.deepEqual(h.order(), ['b', 'a', 'c']); assert.equal(h.animations.length, 0);
+});
+
+test('destroy cancels animations and removes sorter listeners', () => {
+ const h = harness(); h.dragFrom(h.rows[0].handle); h.over(1); h.destroy();
+ assert.ok(h.animations.every(a => a.cancelled)); assert.equal(h.frames.size, 0);
+ for (const node of [h.list, h.document, h.window, ...h.rows.map(row => row.handle)]) {
+ for (const name of ['dragstart', 'dragend', 'dragover', 'drop', 'dragleave', 'keydown', 'blur']) assert.equal(node.listeners.get(name)?.size || 0, 0);
+ }
+});
+
+test('edit controls, foreign drags, and batch-selection rows cannot reorder', () => {
+ const h = harness(); assert.equal(h.dragFrom(h.rows[0].edit), null);
+ h.over(1); assert.deepEqual(h.order(), ['a', 'b', 'c']); assert.equal(h.calls.length, 0);
+ const batch = harness({ batch: true }); assert.ok(batch.rows.every(row => !row.handle)); assert.equal(batch.dragFrom(batch.rows[0]), null);
+});
+
+test('dropping back on the same row does not call the API', async () => {
+ const h = harness(); h.dragFrom(h.rows[0].handle); await h.drop(0);
+ assert.equal(h.calls.length, 0);
+});
+
+test('dragging at the edge scrolls the list and keeps previewing without saving', () => {
+ const h = harness(), handle = h.rows[0].handle;
+ h.list.clientHeight = 60;
+ h.list.getBoundingClientRect = () => ({ top: 100, bottom: 160, height: 60 });
+ h.dragFrom(handle); h.over(1, false);
+ for (let i = 0; i < 12 && h.frames.size; i++) {
+ const [id, fn] = h.frames.entries().next().value; h.frames.delete(id); fn();
+ }
+ assert.equal(h.list.scrollTop, 60);
+ assert.deepEqual(h.order(), ['b', 'c', 'a']); assert.equal(h.calls.length, 0);
+ h.emit(handle, 'dragend'); assert.equal(h.frames.size, 0);
+ assert.deepEqual(h.order(), ['a', 'b', 'c']);
+});
+
+test('a list rebuild disposes the active drag and its animations', () => {
+ const h = harness(), oldHandle = h.rows[0].handle;
+ h.dragFrom(oldHandle); h.over(1);
+ h.context.sessState.qpBatch = true; h.context.renderQpList();
+ assert.ok(h.rows.every(row => !row.handle));
+ assert.ok(h.animations.every(a => a.cancelled)); assert.equal(h.frames.size, 0);
+ assert.equal(oldHandle.listeners.get('dragend')?.size, 0); assert.equal(h.calls.length, 0);
+});
diff --git a/test/quick-phrase-order.test.js b/test/quick-phrase-order.test.js
new file mode 100644
index 0000000..59c3b64
--- /dev/null
+++ b/test/quick-phrase-order.test.js
@@ -0,0 +1,58 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+
+const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
+const start = source.indexOf('function reorderQuickPhrases(ids) {');
+const end = source.indexOf('\nfunction normalizeQuickPhraseIds', start);
+assert.ok(start >= 0 && end > start);
+
+function createHarness() {
+ let state = {
+ stashEnabled: true,
+ phraseEnabled: true,
+ themeTakeoverEnabled: true,
+ phrases: [{ id: 'a', text: 'A' }, { id: 'b', text: 'B' }, { id: 'c', text: 'C' }],
+ };
+ const context = {
+ readSessionState: () => structuredClone(state),
+ writeSessionState(next) { state = structuredClone(next); },
+ };
+ vm.runInNewContext(source.slice(start, end), context);
+ return { context, getState: () => state };
+}
+
+test('quick phrase reorder persists an exact permutation and keeps phrase records intact', () => {
+ const h = createHarness();
+ const result = h.context.reorderQuickPhrases(['c', 'a', 'b']);
+ assert.deepEqual(Array.from(result.phrases, item => [item.id, item.text]), [['c', 'C'], ['a', 'A'], ['b', 'B']]);
+ assert.deepEqual(Array.from(h.getState().phrases, item => item.id), ['c', 'a', 'b']);
+});
+
+test('quick phrase reorder rejects duplicates, missing IDs, and stale lists without writing', () => {
+ for (const ids of [['a', 'a', 'c'], ['a', 'b'], ['a', 'b', 'other']]) {
+ const h = createHarness();
+ assert.throws(() => h.context.reorderQuickPhrases(ids), /无效|已变化/);
+ assert.deepEqual(Array.from(h.getState().phrases, item => item.id), ['a', 'b', 'c']);
+ }
+});
+
+test('quick phrase insert uses CDP text input and never invokes send', async () => {
+ const start = source.indexOf('async function insertQuickPhraseIntoComposer(text) {');
+ const end = source.indexOf('\nfunction normalizeQuickPhraseIds', start);
+ const calls = [];
+ const context = { cdp: { connected: true }, cdpSend: async (...args) => calls.push(args) };
+ vm.runInNewContext(source.slice(start, end), context);
+ assert.equal((await context.insertQuickPhraseIntoComposer('first\nsecond')).inserted, true);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0][0], 'Input.insertText');
+ assert.equal(calls[0][1].text, 'first\nsecond');
+ context.cdp.connected = false;
+ await assert.rejects(context.insertQuickPhraseIntoComposer('not inserted'), /CDP 未连接/);
+ await assert.rejects(context.insertQuickPhraseIntoComposer(' '), /短语不能为空/);
+ assert.equal(calls.length, 1);
+});
diff --git a/test/quick-phrase-popover.test.js b/test/quick-phrase-popover.test.js
index 0ebf4b7..cbf14b2 100644
--- a/test/quick-phrase-popover.test.js
+++ b/test/quick-phrase-popover.test.js
@@ -4,6 +4,39 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
+test('quick phrase popover keeps direct-send cells and exposes a non-sending insert action', () => {
+ const renderStart = source.indexOf(' function renderExploreOptions() {');
+ const renderEnd = source.indexOf(' /** 新增/编辑快捷短语弹窗', renderStart);
+ const render = source.slice(renderStart, renderEnd);
+ assert.match(render, /data-qp-insert/);
+ assert.match(render, /api\('\/api\/quick-phrase-insert'/);
+ assert.match(render, /var editor = findComposer\(\);[\s\S]*editor\.focus\(\)/);
+ assert.match(render, /stopPropagation\(\)/);
+ assert.match(render, /data-qp-send/);
+ assert.match(render, /api\('\/api\/quick-phrase-send'/);
+ assert.match(render, /sendKeyTarget\.addEventListener\('keydown'/);
+});
+
+test('quick phrase manager persists drag order through the dedicated reorder API', () => {
+ const renderStart = source.indexOf(' function renderQpList() {');
+ const renderEnd = source.indexOf(' /** 发送按钮面板选项', renderStart);
+ const render = source.slice(renderStart, renderEnd);
+ assert.match(render, /class="wbs-qp-row" data-id="[\s\S]*?draggable="false"/);
+ assert.match(render, /class="wbs-qp-drag" draggable="true" data-qp-drag=/);
+ assert.match(render, /qpSortCleanup = createQuickPhraseSorter\(listEl/);
+ assert.doesNotMatch(render, /if \(!ev\.target\.closest\('\[data-qp-drag\]'\)\) \{ ev\.preventDefault\(\); return; \}/);
+ assert.match(render, /api\('\/api\/quick-phrase-reorder'/);
+ assert.match(render, /sessState\.qpBatch/);
+});
+
+test('quick phrase insert action renders a speech bubble icon', () => {
+ const start = source.indexOf("html += '<div class=\"wbs-explore-item\"");
+ const end = source.indexOf("'<span class=\"wbs-explore-tip\"", start);
+ const markup = source.slice(start, end);
+ assert.match(markup, /data-qp-insert/);
+ assert.match(markup, /<path d="M3 3\.5h10a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H8l-3 2v-2H3a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1z"/);
+});
+
test('quick phrase popup escapes composer stacking, bridges hover, and cleans up on reinjection', () => {
const timers = new Map(); let nextTimer = 0;
function element(rect = { width: 280, height: 100 }) {
@@ -23,7 +56,8 @@ test('quick phrase popup escapes composer stacking, bridges hover, and cleans up
const context = { CAPS: {}, document, window, mountPersistentOverlay: node=>document.body.appendChild(node), setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; }, clearTimeout: id => timers.delete(id) };
const start = source.indexOf(' function mountExplorePopover(');
vm.runInNewContext(source.slice(start, source.indexOf(' function acMenuClose()', start)), context);
- const menu = context.mountExplorePopover(button, popup);
+ let closeCalls = 0;
+ const menu = context.mountExplorePopover(button, popup, () => { closeCalls++; });
assert.equal(popup.parentElement, document.body);
button.listeners.get('mouseenter')();
assert.equal(popup.classList.contains('is-open'), true);
@@ -42,7 +76,59 @@ test('quick phrase popup escapes composer stacking, bridges hover, and cleans up
assert.equal(timers.size, 0);
for (const target of [button, popup, window, document]) assert.equal(target.listeners.size, 0);
assert.equal(popup.isConnected, false);
+ assert.ok(closeCalls > 0, 'closing the menu must also hide the action tooltip');
const zIndex = selector => Number(source.match(new RegExp('\\.' + selector + '\\{[^}]*?z-index:(\\d+)'))[1]);
assert.ok(zIndex('wbs-explore-pop') > zIndex('wbs-session-usage-popover'));
assert.ok(zIndex('wbs-explore-pop') < zIndex('wbs-root'));
});
+
+test('insert button uses the WorkDaddy custom tooltip instead of native title', () => {
+ const button = source.match(/<button type="button" class="wbs-explore-insert"[^>]+>/)[0];
+ assert.doesNotMatch(button, /\btitle=/);
+ assert.match(button, /aria-describedby="wbs-qp-insert-tooltip"/);
+ assert.match(button, /aria-label="仅插入到对话框"/);
+ assert.match(source, /wbs-telemetry-tooltip wbs-qp-insert-tooltip/);
+ assert.match(source, /wbs-qp-insert-tooltip', '仅插入到对话框'/);
+ assert.match(source, /html\.cb-dark \.wbs-qp-insert-tooltip/);
+ assert.match(source, /html\[data-theme="dark"\] \.wbs-qp-insert-tooltip/);
+});
+
+test('custom insert tooltip follows hover/focus, stays inside viewport, and cleans up', () => {
+ function element(parent = null) {
+ const classes = new Set(), listeners = new Map();
+ return { parent, style: {}, attrs: {}, listeners, offsetWidth: 150, offsetHeight: 30,
+ classList: { add: key => classes.add(key), remove: key => classes.delete(key), contains: key => classes.has(key) },
+ setAttribute(key, value) { this.attrs[key] = value; },
+ addEventListener(name, fn) { listeners.set(name, fn); }, removeEventListener(name) { listeners.delete(name); },
+ contains(node) { for (; node; node = node.parent) if (node === this) return true; return false; },
+ closest(selector) { return selector === '[data-qp-insert]' && this.insert ? this : this.parent?.closest(selector); },
+ getBoundingClientRect: () => ({ left: 330, top: 360, bottom: 384, width: 24 }),
+ remove() { this.removed = true; },
+ };
+ }
+ const popup = element(), button = Object.assign(element(popup), { insert: true }), svg = element(button);
+ const document = element(), window = Object.assign(element(), { innerWidth: 360, innerHeight: 400 });
+ let tooltip;
+ const context = { document, window, el() { return tooltip = element(); }, mountPersistentOverlay() {}, applyI18n() {} };
+ const start = source.indexOf(' function mountQuickPhraseInsertTooltip(');
+ vm.runInNewContext(source.slice(start, source.indexOf(' function acMenuClose()', start)), context);
+ const controller = context.mountQuickPhraseInsertTooltip(popup);
+ popup.listeners.get('focusin')({ target: button });
+ assert.equal(tooltip.classList.contains('is-visible'), false, 'closed menu must not leave a tooltip visible');
+ popup.classList.add('is-open');
+ popup.listeners.get('pointerover')({ target: svg });
+ assert.equal(tooltip.classList.contains('is-visible'), true);
+ assert.equal(tooltip.style.left, '202px'); assert.equal(tooltip.style.top, '323px');
+ assert.equal(popup.classList.contains('wbs-explore-action-tip'), true, 'suppress the phrase tooltip while showing the action');
+ popup.listeners.get('pointerout')({ target: svg, relatedTarget: button });
+ assert.equal(tooltip.classList.contains('is-visible'), true, 'moving between icon and button must not flicker');
+ popup.listeners.get('pointerout')({ target: button, relatedTarget: popup });
+ assert.equal(tooltip.classList.contains('is-visible'), false);
+ popup.listeners.get('focusin')({ target: button });
+ assert.equal(tooltip.classList.contains('is-visible'), true);
+ document.listeners.get('scroll')();
+ assert.equal(tooltip.classList.contains('is-visible'), false);
+ controller.destroy();
+ assert.equal(tooltip.removed, true);
+ for (const node of [popup, document, window]) assert.equal(node.listeners.size, 0);
+});
diff --git a/test/session-copy-job-error.test.js b/test/session-copy-job-error.test.js
new file mode 100644
index 0000000..73dd537
--- /dev/null
+++ b/test/session-copy-job-error.test.js
@@ -0,0 +1,46 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const crypto = require('node:crypto');
+const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+test('a planning failure has a distinct task error, safe cause and visible details with zero item failures', async () => {
+ const ctx = { crypto, Date, autoCopyJobs: new Map(), autoCopyQueue: [], autoCopyWorkerRunning: false,
+ yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => { throw Error('SQLITE_BUSY'); },
+ log() {}, recordAccountSyncResult() {}, pruneAutoCopyJobs() {},
+ sanitizeSessionCopyError: require('../scripts/session-copy-error').sanitizeSessionCopyError,
+ setTimeout: () => ({ unref() {} }),
+ };
+ vm.runInNewContext(daemon.slice(daemon.indexOf('function runAutoCopyQueue('), daemon.indexOf('function activeAutoCopyJob(')), ctx);
+ const job = ctx.startAutoCopyJob('a', 'b', []);
+ await job.completion;
+ const publicJob = ctx.publicAutoCopyJob(job);
+ assert.equal(publicJob.status, 'error');
+ assert.equal(publicJob.failed, 0);
+ assert.equal(publicJob.taskFailed, true);
+ assert.match(publicJob.error, /占用/);
+ const ui = {};
+ vm.runInNewContext(inject.slice(inject.indexOf(' function sessionCopyFailedItems('), inject.indexOf(' function renderSessionCopyNoticeSummary(')), ui);
+ assert.match(ui.sessionCopySummaryText(publicJob), /任务失败/);
+ assert.equal(ui.sessionCopyNoticeGroups(publicJob).failed[0].label, '同步任务');
+ assert.match(ui.sessionCopyNoticeGroups(publicJob).failed[0].error, /占用/);
+ assert.match(inject, /\.wbs-sess-copy-progress\.is-error \.wbs-sess-copy-detail\{[^}]*white-space:normal/,
+ 'a task-level cause must wrap instead of being ellipsized in the panel');
+});
+
+test('sync task errors never expose SQL, credentials, composer contents or local paths', () => {
+ const { sanitizeSessionCopyError } = require('../scripts/session-copy-error');
+ for (const sensitive of [
+ 'SQLITE_ERROR: SELECT private_conversation FROM sessions token=secret',
+ 'unexpected composer text or database row payload',
+ 'EACCES: permission denied, open /Users/private/secret-file',
+ 'Authorization: Bearer synthetic-secret',
+ ]) {
+ const safe = sanitizeSessionCopyError(Error(sensitive));
+ assert.doesNotMatch(safe, /secret|private|SELECT|composer|Bearer/);
+ assert.ok(safe.length > 0);
+ }
+});
diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.js
index c4a9566..30a2f84 100644
--- a/test/session-delete-confinement.test.js
+++ b/test/session-delete-confinement.test.js
@@ -1,3 +1,4 @@
+const assertSessionAccountIdentity = require('../scripts/account-identity').createSessionAccountResolver([]).assertUnambiguous;
'use strict';
const test = require('node:test');
@@ -15,7 +16,7 @@ function loadSessionDeleteHelpers(fsImpl = fs) {
const end = source.indexOf('\nfunction json(', start);
assert.notEqual(start, -1, 'daemon must define the session ID validation boundary');
assert.notEqual(end, -1, 'session deletion helpers must remain before json()');
- const context = { codeBuddyFiles: null, fs: fsImpl, path, log() {} };
+ const context = { assertSessionAccountIdentity, codeBuddyFiles: null, fs: fsImpl, path, log() {} };
vm.runInNewContext(
source.slice(start, end) +
'\nthis.helpers = { isValidSessionId, matchedSessionIds, resolveManagedSessionTarget, deleteSessionFiles };',
@@ -261,7 +262,7 @@ test('delete route refuses while account switching or session copy holds the ope
const source = fs.readFileSync(daemonPath, 'utf8');
const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/delete')");
const end = source.indexOf(' // 恢复会话:', start);
- const ctx = vm.createContext({
+ const ctx = vm.createContext({ assertSessionAccountIdentity,
codeBuddyFiles: null,
req: { method: 'POST' },
p: '/api/sessions/delete',
@@ -288,7 +289,7 @@ test('delete route accepts more than 100 session IDs in one request', async (t)
const source = fs.readFileSync(daemonPath, 'utf8');
const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/delete')");
const end = source.indexOf(' // 恢复会话:', start);
- const ctx = vm.createContext({codeBuddyFiles:null,
+ const ctx = vm.createContext({ assertSessionAccountIdentity,codeBuddyFiles:null,
...loadSessionDeleteHelpers(),
normalizeSessionIdBatch,
collectLineageMembersForDelete: (_dataDir, requested) => requested.map((id) => ({ id })),
@@ -333,7 +334,7 @@ test('delete route removes recorded copies across accounts from both DB and file
const source = fs.readFileSync(daemonPath, 'utf8');
const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/delete')");
const end = source.indexOf(' // 恢复会话:', start);
- const ctx = vm.createContext({codeBuddyFiles:null,
+ const ctx = vm.createContext({ assertSessionAccountIdentity,codeBuddyFiles:null,
...loadSessionDeleteHelpers(),
normalizeSessionIdBatch,
collectLineageMembersForDelete: lib.collectLineageMembersForDelete,
diff --git a/test/session-deletion-sync.test.js b/test/session-deletion-sync.test.js
index 8ce09d7..48602cf 100644
--- a/test/session-deletion-sync.test.js
+++ b/test/session-deletion-sync.test.js
@@ -1,3 +1,4 @@
+const assertSessionAccountIdentity = require('../scripts/account-identity').createSessionAccountResolver([]).assertUnambiguous;
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
@@ -98,7 +99,7 @@ test('renderer deletion route rejects a stale account and reconciles missed dele
const start = source.indexOf(" if (req.method === 'POST' && p === '/api/sessions/dirty')");
const end = source.indexOf('\n }', start) + 4;
const calls = [];
- const context = {
+ const context = { assertSessionAccountIdentity,
readBody: async req => req.body, currentAccount: () => ({ uid: 'one' }),
json: (_, status, body) => ({ status, body }), isValidSessionId: id => /^[a-z-]+$/.test(id),
markSessionDirty: (...args) => calls.push(['dirty', ...args]), markSessionDirtyBaseline() {},
diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.js
index 4765cb8..c3b9064 100644
--- a/test/session-sync-daemon.test.js
+++ b/test/session-sync-daemon.test.js
@@ -9,6 +9,9 @@ const crypto = require('node:crypto');
const lib = require('../scripts/lib.js');
const sessionSync = require('../scripts/session-sync.js');
const { createDirtyIndex } = require('../scripts/session-dirty.js');
+const { createSessionAccountResolver } = require('../scripts/account-identity');
+const { sanitizeSessionCopyError } = require('../scripts/session-copy-error');
+const assertSessionAccountIdentity = createSessionAccountResolver([]).assertUnambiguous;
const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
const base = [{ type: 'message', role: 'user', content: [{ text: 'question' }] }, { type: 'message', role: 'assistant', content: [{ text: 'answer' }] }];
function harness(t, withPlanner = false, withDeletions = false) {
@@ -24,7 +27,7 @@ function harness(t, withPlanner = false, withDeletions = false) {
}
const syncCacheMap = new Map();
const dirtyIndex = createDirtyIndex(); dirtyIndex.markBaseline('one');
- const ctx = { codeBuddyFiles: null, ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' }, createDirtyIndex,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, sessionSync, fs, path, crypto, DATA_DIR: root, PROFILE: { dataRoot: root, kind: 'workbuddy' }, createDirtyIndex,
sessionCopyRowRevision: row => JSON.stringify([
String(row && row.id || ''), String(row && row.user_id || ''),
Number(row && row.updated_at || 0), Number(row && row.last_activity_at || 0),
@@ -187,7 +190,7 @@ test('stale active-session lifecycle markers are cleared after an equal payload
sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),
targetRevision: revision(targetRow),
});
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
...lib, fs, path, DATA_DIR: root, PROFILE: { dataRoot: root }, sessionSync,
createDirtyIndex, getSessionSyncCache: () => new Map(),
setTimeout, clearTimeout,
@@ -282,7 +285,7 @@ test('automatic copy planning drops revision-stable mappings before workers', as
targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision(target),
});
let targetQueries = 0;
- const makeContext = () => ({ ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
+ const makeContext = () => ({ assertSessionAccountIdentity, ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => { if (String(params[0]) === 'two') targetQueries++; return [String(params[0]) === 'one' ? { ...sourceRow } : { ...target }]; } });
const start = source.indexOf('function sessionCopyContentRevision(');
let ctx = makeContext();
@@ -330,7 +333,7 @@ test('initialized clean mappings ignore legacy source revision drift', async t =
sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),
targetRevision: revision(targetRow),
});
- const ctx = { codeBuddyFiles: null, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }],
@@ -357,7 +360,7 @@ test('automatic copy planning reuses a stable cross-account mapping without a wo
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(previousSource), targetRevision: revision(target),
});
- const ctx = { codeBuddyFiles: null, ...lib, DATA_DIR: root, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, DATA_DIR: root, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...target }] };
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
@@ -385,7 +388,7 @@ test('automatic copy planning ignores target activation lifecycle drift', async
lib.setAutoCopyMapping(root, lineage, 'two', {
targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision({ ...sourceRow, id: 'b', user_id: 'two' }),
});
- const ctx = { codeBuddyFiles: null, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? sourceRow : targetRow],
@@ -416,7 +419,7 @@ test('source activation-only updated_at drift clears dirty state without a snaps
targetRevision: revision(targetRow),
});
let snapshotReads = 0;
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
...lib, fs, path, DATA_DIR: root, PROFILE: { dataRoot: root }, createDirtyIndex,
setTimeout, clearTimeout, getSessionSyncCache: () => new Map(),
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
@@ -436,7 +439,7 @@ test('source activation-only updated_at drift clears dirty state without a snaps
test('active sync status ignores a recent job for another target account', () => {
const start = source.indexOf('function activeAutoCopyJob(');
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
Date: { now: () => 10000 },
autoCopyJobs: new Map([
['other', { id: 'other', targetUid: 'two', status: 'done', finishedAt: 9900, startedAt: 9000 }],
@@ -456,7 +459,7 @@ test('explicitly requested open session is planned without regular auto-copy rul
custom_title: '', status: 'completed', created_at: 1, updated_at: 7, last_activity_at: 7,
};
const targetRow = { ...sourceRow, id: 'other-session', user_id: 'two' };
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
...lib, fs, path, DATA_DIR: root,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: row => JSON.stringify([
@@ -496,7 +499,7 @@ test('requested unchanged open session resolves its mapping without entering the
sourceRevision: revision(sourceRow), targetRevision: revision(targetRow),
});
let targetQueries = 0;
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
...lib, fs, path, DATA_DIR: root, createDirtyIndex,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
sessionCopyRowRevision: revision,
@@ -522,7 +525,7 @@ test('stable mappings clear legacy lifecycle dirty markers before planning', asy
const targetRow = { ...sourceRow, id: 'b', user_id: 'two' };
const revision = row => JSON.stringify([String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0), String(row.status || ''), String(row.title || ''), String(row.custom_title || '')]);
lib.setAutoCopyMapping(root, lineage, 'two', { targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision(targetRow) });
- const ctx = { codeBuddyFiles: null, ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision, sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }] };
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision, sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }] };
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 0);
@@ -578,7 +581,7 @@ test('manual and automatic switching bypass session activity while retaining ope
const start = source.indexOf('async function assertSessionSyncIdle(');
const end = source.indexOf('let automationAccountSwitchTail', start);
assert.ok(start >= 0 && end > start);
- const ctx = { codeBuddyFiles: null, accountSwitchInProgress: false, cdp: { connected: true }, PROFILE: { kind: 'workbuddy' }, autoCopyWorkerRunning: false, autoCopyQueue: [], sessionCopyLocks: new Map(),
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, accountSwitchInProgress: false, cdp: { connected: true }, PROFILE: { kind: 'workbuddy' }, autoCopyWorkerRunning: false, autoCopyQueue: [], sessionCopyLocks: new Map(),
cdpSend: async () => ({ result: { value: true } }) };
vm.runInNewContext(source.slice(start, end), ctx);
await assert.rejects(ctx.assertSessionSyncIdle(['source', 'target']), /会话仍在运行/);
@@ -607,7 +610,7 @@ test('manual and automatic switching bypass session activity while retaining ope
test('mixed sync jobs continue after divergence and report every result', async () => {
const results = ['conflict', 'copied', 'skipped', 'error'];
let sizeReads = 0;
- const ctx = { codeBuddyFiles: null, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => results.map((_, i) => ({ id: String(i) })),
copySessionRecord: async row => { const status = results[Number(row.id)]; if (status === 'error') throw Error('fixture failure'); return { status, branched: status === 'copied', copiedBytes: status === 'copied' ? 123456 : 0, totalBytes: 123456, warning: status === 'copied' ? 'large session advisory' : '' }; },
sessionSync: { readSessionSizes: async () => { sizeReads++; return new Map(); } },
@@ -639,7 +642,7 @@ test('mixed sync jobs continue after divergence and report every result', async
test('active session copy retries transient file races and preserves its target id', async () => {
let attempts = 0;
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
DATA_DIR: 'fixture-data',
PROFILE: { dataRoot: 'fixture-root' },
@@ -666,7 +669,7 @@ test('active session copy retries transient file races and preserves its target
test('active session copy keeps waiting through a longer renderer flush', async () => {
let attempts = 0;
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
@@ -693,7 +696,7 @@ test('active session copy keeps waiting through a longer renderer flush', async
test('unchanged requested session resolves its target without entering the copy worker', async () => {
let copies = 0;
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
@@ -714,7 +717,7 @@ test('unchanged requested session resolves its target without entering the copy
for (const error of ['会话消息文件没有消息,未同步', '会话消息文件为空,未同步']) test('empty message sessions are skipped instead of shown as sync failures: ' + error, async () => {
let cleared = 0;
- const ctx = { codeBuddyFiles: null,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError,
crypto,
PROFILE: { dataRoot: 'fixture-root' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
@@ -739,7 +742,7 @@ for (const error of ['会话消息文件没有消息,未同步', '会话消息
test('an empty automatic copy plan does not wait for renderer injection', async () => {
const planningYields = [];
let rendererWaits = 0;
- const ctx = { codeBuddyFiles: null, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async options => {
planningYields.push(options);
if (!options || options.waitForInjection !== false) rendererWaits++;
@@ -760,7 +763,7 @@ test('an empty automatic copy plan does not wait for renderer injection', async
test('automatic session sync uses a bounded worker pool', async () => {
let running = 0;
let peak = 0;
- const ctx = { codeBuddyFiles: null, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => Array.from({ length: 8 }, (_, id) => ({ id: String(id) })),
copySessionRecord: async row => {
running++;
@@ -782,7 +785,7 @@ test('automatic session sync uses a bounded worker pool', async () => {
});
test('automatic session sync aggregates copied bytes independently across workers', async () => {
- const ctx = { codeBuddyFiles: null, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, PROFILE: { dataRoot: 'fixture-root' }, autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {}, buildAutoCopyPlan: async () => Array.from({ length: 8 }, (_, id) => ({ id: String(id) })),
copySessionRecord: async () => {
await new Promise(resolve => setTimeout(resolve, 2));
@@ -1054,7 +1057,7 @@ test('copy completion preserves timestamps of concurrent source and target dirty
for (const duringCopy of [false, true]) test('deleting the active session never reopens its old mapping or blocks later automation: ' + duringCopy, async () => {
let attempts = 0;
- const ctx = { codeBuddyFiles: null, crypto, DATA_DIR: 'fixture', PROFILE: { dataRoot: 'fixture' },
+ const ctx = { codeBuddyFiles: null, assertSessionAccountIdentity, sanitizeSessionCopyError, crypto, DATA_DIR: 'fixture', PROFILE: { dataRoot: 'fixture' },
autoCopyJobs: new Map(), autoCopyQueue: [], Date,
yieldAutoCopyToRenderer: async () => {},
buildAutoCopyPlan: async () => duringCopy ? [{ id: 'a', lineageId: 'lineage' }] : [],
diff --git a/test/token-refresh-persistence.test.js b/test/token-refresh-persistence.test.js
index 9189e28..f47d433 100644
--- a/test/token-refresh-persistence.test.js
+++ b/test/token-refresh-persistence.test.js
@@ -6,6 +6,7 @@ const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const vm = require('node:vm');
+const { accountIdentity } = require('../scripts/account-identity');
const test = require('node:test');
const { normalizeTimestamp, shouldRefreshAccessToken, refreshAuthToken } = require('../scripts/token-refresh');
const { PROFILES } = require('../scripts/profiles');
@@ -87,7 +88,7 @@ function daemonHarness(t, options = {}) {
? compat.wdCompatDecryptAuthJson(stored) : stored), { mode: 0o600 });
let requests = 0;
let failWrite = false;
- const context = {
+ const context = { accountIdentity,
...compat, fs: { ...fs, writeFileSync(...args) {
if (failWrite && String(args[0]).startsWith(file)) throw new Error('fixture write failure');
return fs.writeFileSync(...args);
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index bcaf585..56073ab 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -1324,7 +1324,7 @@ test('DevTools proxy uses the same persisted CDP port fallback as its URL endpoi
const daemon = read('daemon.js');
assert.match(daemon, /const upstreamPort = cdp\.port \|\| readCdpPortFile\(\) \|\| CDP_PORT_HINT \|\| 9222/);
assert.match(daemon, /devtoolsPort = cdp\.port \|\| readCdpPortFile\(\) \|\| CDP_PORT_HINT \|\| 9222/);
- assert.match(daemon, /uid\.length > 200.*\[\\\\\/\\0\]/);
+ assert.match(daemon, /\^\[A-Za-z0-9_\-\]\{1,128\}\$/);
});
test('automatic updates use the GitHub asset digest and fail closed without one', () => {
@@ -1354,7 +1354,7 @@ test('account export asks for a non-empty password and import supports an option
assert.match(daemon, /version:\s*2/);
assert.match(daemon, /EXPORT_PASSPHRASE/);
assert.match(daemon, /const authRecord = parseAuthJson\(j\)/);
- assert.match(daemon, /if \(!authRecord \|\| authRecord\.uid !== uid\) continue/);
+ assert.match(daemon, /suppliedUid !== authRecord\.uid && suppliedUid !== authRecord\.accountId/);
assert.match(inject, /title:\s*'导出账号'[\s\S]*requirePassword:\s*true/);
assert.match(inject, /旧版导出文件可留空/);
assert.match(inject, /type="password"/);