Skip to content

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

release: merge 1.2.12 changes

[email protected]dcf30acb46ea
diff --git a/scripts/assets/dmg-layout/codedaddy-cn.DS_Store b/scripts/assets/dmg-layout/codedaddy-cn.DS_Store
new file mode 100644
index 0000000..3a32712
Binary files /dev/null and b/scripts/assets/dmg-layout/codedaddy-cn.DS_Store differ
diff --git a/scripts/assets/dmg-layout/codedaddy.DS_Store b/scripts/assets/dmg-layout/codedaddy.DS_Store
new file mode 100644
index 0000000..4b5e4a9
Binary files /dev/null and b/scripts/assets/dmg-layout/codedaddy.DS_Store differ
diff --git a/scripts/assets/dmg-layout/workdaddy-ai.DS_Store b/scripts/assets/dmg-layout/workdaddy-ai.DS_Store
index 2f1c3a7..fecce98 100644
Binary files a/scripts/assets/dmg-layout/workdaddy-ai.DS_Store and b/scripts/assets/dmg-layout/workdaddy-ai.DS_Store differ
diff --git a/scripts/assets/dmg-layout/workdaddy.DS_Store b/scripts/assets/dmg-layout/workdaddy.DS_Store
index 98ac4bb..b08ea9c 100644
Binary files a/scripts/assets/dmg-layout/workdaddy.DS_Store and b/scripts/assets/dmg-layout/workdaddy.DS_Store differ
diff --git a/scripts/automation.js b/scripts/automation.js
index 16a8670..c03a76f 100644
--- a/scripts/automation.js
+++ b/scripts/automation.js
@@ -77,7 +77,7 @@ for (const [id, zh, en, example, descriptionZh, descriptionEn] of [
['logic.forEach', '循环列表', 'Iterate list', {op:'logic.forEach',items:'{{vars.items}}',steps:[]}, '遍历最多 1000 项,使用 vars.item 和 vars.index,退出后恢复上下文。', 'Iterate up to 1000 entries via vars.item and vars.index; restore context on exit.'],
['logic.break', '退出循环', 'Break loop', {op:'logic.break'}, '退出最近一层列表、重复或账号循环。', 'Exit the nearest list, repeat or account loop.'],
['logic.waitUntil', '等待条件', 'Wait for condition', {op:'logic.waitUntil',timeoutMs:10000,intervalMs:250,steps:[],condition:{left:'{{vars.ready}}',operator:'truthy'}}, '立即执行查询步骤并检查条件;超时失败,可取消。', 'Immediately run polling steps and check a condition; cancellable with timeout.'],
- ['session.create', '新建会话并发送', 'Create and send', {op:'session.create',message:'你好',model:'deepseek-v4.1-flash',saveAs:'receipt'}, '保存现有新建页草稿后发送第一条消息;V2 可选 model(精确模型 ID),发送后恢复原新建任务模型偏好。返回绑定账号、会话和请求的回执。', 'Preserve a New Task draft and send the first message. V2 accepts an optional model ID and restores the New Task model preference after sending. Returns an account/conversation/request receipt.'],
+ ['session.create', '新建会话并发送', 'Create and send', {op:'session.create',message:'你好',model:'deepseek-v4.1-flash',cwd:'/Users/me/project',saveAs:'receipt'}, '保存现有新建页草稿后发送第一条消息;V2 可选 model(精确模型 ID),发送后恢复原新建任务模型偏好;V2 可选 cwd(绝对路径)或 workspace(侧栏工作区名)指定新会话的工作目录,不指定则落在 WorkBuddy 默认目录(~/WorkBuddy/<时间戳>);工作区不存在或绑定校验不通过时拒绝发送,不会退回默认目录。返回绑定账号、会话和请求的回执。', 'Preserve a New Task draft and send the first message. V2 accepts an optional model ID and restores the New Task model preference after sending. V2 also accepts an optional cwd (absolute path) or workspace (sidebar workspace name) to bind the new conversation to that working directory; without it the conversation lands in the WorkBuddy default directory (~/WorkBuddy/<timestamp>). A missing workspace or a failed binding check aborts the send instead of falling back to the default directory. Returns an account/conversation/request receipt.'],
['session.send', '向指定可见会话发送', 'Send to visible session', {op:'session.send',conversationId:'{{vars.receipt.conversationId}}',message:'继续',model:'deepseek-v4.1-flash',saveAs:'receipt'}, '仅发送到已挂载且选中的指定会话;V2 可选 model(精确模型 ID),切换后会话保留该模型。草稿非空时拒绝,未确认发送不会自动重发。', 'Send only to a selected mounted conversation. V2 accepts an optional model ID, which remains selected in the conversation. Reject occupied drafts and never automatically resend unconfirmed sends.'],
['session.wait', '等待指定回复完成', 'Wait for bound reply', {op:'session.wait',receipt:'{{vars.receipt}}',timeoutMs:180000}, '按回执绑定账号、会话和请求等待完成;失败、取消或身份变化时退出。', 'Wait by account/conversation/request receipt; fail on errors, cancellation or identity changes.'],
['state.checkpoint', '保存检查点', 'Save checkpoint', {op:'state.checkpoint',key:'progress',value:{done:'{{vars.done}}'}}, '显式保存进度,使用 state.get 恢复;不会自动重放发送或其他副作用。', 'Explicitly save progress; restore with state.get. Never automatically replay sends or other side effects.'],
@@ -422,6 +422,16 @@ function validateSteps(steps, depth = 0, schemaVersion = 1) {
if (schemaVersion < 2) throw new Error('指定会话模型需要自动化协议 V2');
normalizeAutomationModelId(step.model);
}
+ if (op === 'session.create' && (Object.hasOwn(step, 'cwd') || Object.hasOwn(step, 'workspace'))) {
+ if (schemaVersion < 2) throw new Error('指定新会话工作目录需要自动化协议 V2');
+ if (Object.hasOwn(step, 'cwd')) {
+ if (typeof step.cwd !== 'string' || !step.cwd.trim()) throw new Error('cwd 必须是非空字符串工作目录路径');
+ if (!/^(?:[A-Za-z]:[\\/]|\/|\\\\|\{\{)/.test(step.cwd.trim())) throw new Error('cwd 必须是绝对路径');
+ }
+ if (Object.hasOwn(step, 'workspace') && (typeof step.workspace !== 'string' || !step.workspace.trim())) {
+ throw new Error('workspace 必须是非空字符串工作区名称');
+ }
+ }
if (['logic.sequence', 'logic.repeat', 'logic.retry', 'logic.catch', 'logic.forEach', 'logic.waitUntil', 'account.forEach'].includes(op)) validateSteps(step.steps || [], depth + 1, schemaVersion);
if (op === 'logic.retry' && /\"op\"\s*:\s*\"session\.(create|send|sendCurrent)\"/.test(JSON.stringify(step.steps || []))) throw new Error('会话发送不能放入 retry,避免重复发送');
if (op === 'logic.catch') validateSteps(step.onError || [], depth + 1, schemaVersion);
@@ -579,7 +589,7 @@ function capabilityText(language = 'zh') {
'DOM 等待:dom.wait 可使用 seconds 做固定等待;或使用 locator、until:{state:"visible"|"hidden"|"attached"|"detached"|"clickable"}、timeoutMs 等待元素状态。until 还支持 text 包含匹配或 attribute/value 相等。locators 数组提供依次回退的定位器;readText 最多 100000 字符。iframe 内目前只支持读取,不支持点击与输入。DOM 读取结果可用 saveAs 保存。',
'HTTP 输入:method、url、query、headers、body、timeoutMs(500-60000)、saveAs。响应:{ok,status,headers,text,json},正文最多 1 MiB。http.request 不允许自定义 Authorization/Cookie;http.requestAsAccount 只对当前客户端官方 HTTPS origin 注入账号登录态;禁止跨域、非默认端口、URL 用户名密码。重定向不会自动跟随。body/query/headers 支持递归模板。默认非 2xx 返回 ok:false 供分支判断;throwOnHttpError:true 抛错以配合 retry(支持 backoff,默认 1)。停止会中止 HTTP 和等待。',
'运行日志:log.write 使用固定 message 和 params 命名标量参数,例如 {account} 对应 params.account:"{{account.uid}}"。会脱敏手机号和常见令牌格式,拒绝敏感字段路径;不要在 message 中写凭据。运行日志不弹通知,单次运行不按条数截断;daemon 重启后内存中的运行记录会清空。',
- '会话:session.create 新建并发送第一条消息;session.send 仅向选中且无草稿的指定 conversationId 发送。V2 两者均可选 model(精确模型 ID,支持模板),切换未确认则拒绝发送;create 发送后恢复新建任务模型偏好,send 保留会话模型。返回 {accountUid,conversationId,userMessageId,requestId,baselineAssistantId} 回执,saveAs 保存。session.wait 接受 receipt(默认 vars.session)、timeoutMs(最长 300000)、contains,按回执监听。未知发送结果不会自动重发;发送不能嵌套 retry。session.sendCurrent/waitReply 是兼容别名,前者实际上新建会话。仅支持挂载的可见会话,不支持后台任意会话发送。',
+ '会话:session.create 新建并发送第一条消息;session.send 仅向选中且无草稿的指定 conversationId 发送。V2 两者均可选 model(精确模型 ID,支持模板),切换未确认则拒绝发送;create 发送后恢复新建任务模型偏好,send 保留会话模型。V2 的 create 还可选 cwd(绝对路径,支持模板)或 workspace(侧栏工作区显示名)把新会话落到指定工作目录;两者都不给时落在 WorkBuddy 默认目录 ~/WorkBuddy/<时间戳>。指定工作目录时会在发送前校验新建任务页绑定是否一致,工作区不存在或绑定不符会直接失败,绝不退回默认目录。返回 {accountUid,conversationId,userMessageId,requestId,baselineAssistantId} 回执,saveAs 保存。session.wait 接受 receipt(默认 vars.session)、timeoutMs(最长 300000)、contains,按回执监听。未知发送结果不会自动重发;发送不能嵌套 retry。session.sendCurrent/waitReply 是兼容别名,前者实际上新建会话。仅支持挂载的可见会话,不支持后台任意会话发送。',
'V3 账号循环:account.forEach 可选 prepare 数组(仅 account.status、state.get、vars.set、time.now、value.number、log.write),先在每个账号上下文执行,再判断 condition={left,operator,right};条件不满足则不切换、不执行 steps。V1/V2/V3 的 switch:true 均等待前序同步、页面刷新和本次同步成功才执行 steps;失败/部分成功/未解决冲突终止,大小提醒不影响成功。运行接口继续立即返回 202;run-status 的 phase/sync 展示等待和进度;停止请求以 stopRequested 标记,安全收尾完成后才变为 cancelled。',
'状态作用域:state.get/state.set 的 scope 支持 task(默认)或 account;所有状态首先按任务 ID 隔离;account scope 再按 uid 隔离。V2 state.set 可设置 ttlMs,过期后 state.get 返回空值并清理。key 必填;state.get 可配 saveAs。',
'通知:notify.toast 使用 react-hot-toast,从窗口底部向上弹出;level 支持 info、success、warning、error、loading。可选 duration(1000–60000 毫秒)、id、saveAs;相同 id 更新提示,notify.dismiss 用 id 关闭。id 按本次运行隔离,任务结束自动清理 loading。notify.afterAllTasks 已废弃,仅兼容旧任务;新任务不要使用。',
@@ -604,7 +614,7 @@ function capabilityText(language = 'zh') {
'DOM waits: use seconds for a fixed delay, or locator plus until:{state:"visible"|"hidden"|"attached"|"detached"|"clickable"} and timeoutMs. until also accepts text containment or attribute/value equality. locators supplies ordered fallbacks; readText is capped at 100000 characters. Iframes support reads only, not clicks or input. DOM read results can be stored with saveAs.',
'HTTP input: method, url, query, headers, body, timeoutMs (500-60000), saveAs. Response: {ok,status,headers,text,json}; body is capped at 1 MiB. http.request rejects Authorization/Cookie; http.requestAsAccount injects credentials only for current-profile official HTTPS origins, rejecting foreign origins, ports and URL credentials. Redirects are not followed. body/query/headers resolve recursive templates. Non-2xx returns ok:false by default; throwOnHttpError:true enables retry (backoff defaults to 1). Cancellation aborts HTTP and waits.',
'Run logs: log.write takes a fixed message and named scalar params; {account} reads params.account:"{{account.uid}}". Phone and common token patterns are redacted, and sensitive paths are rejected. Never put credentials in message. Run logs do not show notifications and are not truncated by entry count; in-memory runs are cleared on daemon restart.',
- 'Sessions: session.create creates by sending the first message; session.send targets only a selected conversationId with an empty composer. In V2 both accept an optional model (exact model ID, templates supported) and refuse to send if the switch is unconfirmed. create restores the New Task model preference after sending; send keeps the model selected in the conversation. Returns {accountUid,conversationId,userMessageId,requestId,baselineAssistantId}; saveAs persists the receipt in variables. session.wait accepts receipt (default vars.session), timeoutMs (up to 300000), contains. Unconfirmed sends are never automatically retried; sends cannot be nested in retry. sendCurrent/waitReply are legacy aliases; sendCurrent creates a new conversation. Only mounted visible sessions are supported.',
+ 'Sessions: session.create creates by sending the first message; session.send targets only a selected conversationId with an empty composer. In V2 both accept an optional model (exact model ID, templates supported) and refuse to send if the switch is unconfirmed. create restores the New Task model preference after sending; send keeps the model selected in the conversation. V2 session.create also accepts an optional cwd (absolute path, templates supported) or workspace (sidebar workspace display name) to bind the new conversation to that working directory; without either it lands in the WorkBuddy default directory ~/WorkBuddy/<timestamp>. When a working directory is requested the New Task binding is verified right before sending: a missing workspace or a mismatched binding aborts the send instead of falling back to the default directory. Returns {accountUid,conversationId,userMessageId,requestId,baselineAssistantId}; saveAs persists the receipt in variables. session.wait accepts receipt (default vars.session), timeoutMs (up to 300000), contains. Unconfirmed sends are never automatically retried; sends cannot be nested in retry. sendCurrent/waitReply are legacy aliases; sendCurrent creates a new conversation. Only mounted visible sessions are supported.',
'V3 account loops: account.forEach accepts prepare (only account.status, state.get, vars.set, time.now, value.number, log.write) and condition={left,operator,right}, evaluated in each account context before any physical switch. A false condition skips switching and steps. switch:true in V1/V2/V3 waits for prior sync, page reload and successful inbound sync. Partial/failed/unresolved sync stops execution; size warnings do not. Run requests still return 202; run-status exposes phase/sync progress and stopRequested while cancellation drains safely.',
'State scope: state.get/state.set scope is task (default) or account. State is isolated by task ID and account scope adds the uid. V2 state.set accepts ttlMs; expired values are removed and state.get returns empty. key is required; state.get accepts saveAs.',
'Notifications: notify.toast uses react-hot-toast at bottom-center. level is info, success, warning, error, or loading. Optional duration (1000–60000 ms), id, and saveAs; reuse id to update, notify.dismiss with id to dismiss. IDs are scoped to a run; unfinished loading notifications are cleared when the run ends. notify.afterAllTasks is deprecated and retained only for saved tasks. Do not generate it for new tasks.',
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 7bc170b..a1dedea 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 markdown-preview.js renderer-api-bridge.js codebuddy-native.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-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.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 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 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 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-picker.js token-refresh.js session-db.js session-fork.js session-sync.js session-dirty.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 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 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.
@@ -162,6 +162,22 @@ BUILT_ARCH_PRIORITY="$(/usr/libexec/PlistBuddy -c 'Print :LSArchitecturePriority
if [ "$BUILT_ARCH_PRIORITY" != "$LS_ARCH_PRIORITY" ]; then exit 3; fi
sed -i.bak "s|^PROFILE=.*|PROFILE=\"${PROFILE}\"|" "$PACKAGE_APP/Contents/MacOS/launcher"
rm -f "$PACKAGE_APP/Contents/MacOS/launcher.bak"
+# macOS launcher 缺少 profile 环境变量兜底修复:launchd 注册失败时仍必须让
+# daemon 看到与 plist 相同的 profile/data/port,否则 cdp-targets.js 无法归属企业版页面。
+python3 - "$PACKAGE_APP/Contents/MacOS/launcher" <<'PY'
+from pathlib import Path
+import sys
+
+path = Path(sys.argv[1])
+source = path.read_text(encoding='utf-8')
+old = ' nohup "$NODE_BIN" "$SCRIPTS_DIR/daemon.js" >> "$DATA_DIR/daemon.log" 2>&1 &'
+new = ' WBSWITCH_DATA_DIR="$DATA_DIR" WBSWITCH_PORT="$UI_PORT" WBSWITCH_PROFILE="$PROFILE" nohup "$NODE_BIN" "$SCRIPTS_DIR/daemon.js" >> "$DATA_DIR/daemon.log" 2>&1 &'
+if old in source:
+ source = source.replace(old, new, 1)
+elif new not in source:
+ raise SystemExit('macOS launcher 缺少 profile 环境变量兜底修复锚点')
+path.write_text(source, encoding='utf-8', newline='')
+PY
# 企业版可能在 /Applications 下使用不同的 .app 名称。把官方路径优先、
# profile 过滤的自动发现逻辑同步进产物 launcher;这样壳内 launcher 与
# scripts/relaunch-with-cdp.sh 的行为一致。
@@ -546,10 +562,12 @@ else
# 产物保留与 Finder 布局版本一致的观感。默认取仓库内的布局源(scripts/assets/dmg-layout)。
DSSTORE_SOURCE="${WORKDADDY_DSSTORE_SOURCE:-}"
if [ -z "$DSSTORE_SOURCE" ]; then
- DSSTORE_FALLBACK="scripts/assets/dmg-layout/workdaddy.DS_Store"
- if [ "$PROFILE" = "workbuddy-ai" ]; then
- DSSTORE_FALLBACK="scripts/assets/dmg-layout/workdaddy-ai.DS_Store"
- fi
+ case "$PROFILE" in
+ workbuddy-ai) DSSTORE_FALLBACK="scripts/assets/dmg-layout/workdaddy-ai.DS_Store" ;;
+ codebuddy-cn) DSSTORE_FALLBACK="scripts/assets/dmg-layout/codedaddy-cn.DS_Store" ;;
+ codebuddy-intl) DSSTORE_FALLBACK="scripts/assets/dmg-layout/codedaddy.DS_Store" ;;
+ *) DSSTORE_FALLBACK="scripts/assets/dmg-layout/workdaddy.DS_Store" ;;
+ esac
if [ -f "$DIR/$DSSTORE_FALLBACK" ]; then
DSSTORE_SOURCE="$DIR/$DSSTORE_FALLBACK"
fi
diff --git a/scripts/builtin/automations/close-buddy-popups.json b/scripts/builtin/automations/close-buddy-popups.json
index cee66fd..20fdc06 100644
--- a/scripts/builtin/automations/close-buddy-popups.json
+++ b/scripts/builtin/automations/close-buddy-popups.json
@@ -1,9 +1,10 @@
{
"schemaVersion": 1,
"id": "buddy-fuel-station-close-on-account-switch",
- "revision": 2,
+ "revision": 3,
"upgradeFromContentHashes": [
- "7409d4d92618b59326e56629f4d9ba804ae30a4e36d7d5ed156042b9a3a744bd"
+ "7409d4d92618b59326e56629f4d9ba804ae30a4e36d7d5ed156042b9a3a744bd",
+ "9c47a98a2fd9e50263290126ea3702df05d690f950b097a4a61871b6cd7bce77"
],
"name": "页面就绪后自动关闭首页弹窗",
"description": "页面就绪后立即检查首页弹窗与运营位,每 300 毫秒补查,持续约 30 秒;重新出现的弹窗继续关闭,快速切换账号时重新检测新页面。",
@@ -50,6 +51,7 @@
},
{
"op": "notify.toast",
+ "id": "fuel-close",
"level": "success",
"message": "识别到 Buddy 加油站弹窗,已关闭"
}
@@ -81,6 +83,7 @@
},
{
"op": "notify.toast",
+ "id": "playbooks-close",
"level": "success",
"message": "已关闭相关玩法推荐,今日不再展示"
}
@@ -126,6 +129,7 @@
},
{
"op": "notify.toast",
+ "id": "growth-close",
"level": "success",
"message": "已关闭「做任务赢积分好礼」入口"
}
@@ -183,6 +187,7 @@
},
{
"op": "notify.toast",
+ "id": "activity-close",
"level": "success",
"message": "已关闭首页活动弹窗"
}
diff --git a/scripts/codebuddy-files.js b/scripts/codebuddy-files.js
index c012d92..2879840 100644
--- a/scripts/codebuddy-files.js
+++ b/scripts/codebuddy-files.js
@@ -118,16 +118,49 @@ function createCodeBuddyFiles({root, sync}) {
for(const [,relative] of bases(id))await visit(relative);
return {totalBytes,fingerprint:hash(JSON.stringify(markers))};
}
- function tokenOptions(ids) {
- const owners=new Map();
- for(const id of ids) {
- if(!rows.has(id))continue;
- const file=safe(bases(id)[0][1]+'/index.json');
- if(fs.existsSync(file))owners.set(file,id);
+ // CodeDaddy keeps each conversation's request log inside the owning account's
+ // history tree. Statistics read that tree instead of the live session
+ // registry: a conversation deleted in the client keeps its files, and history
+ // left by an older install has no session record at all — both still hold real
+ // token usage that must not vanish from a day's totals. The owning directory
+ // names the account, so an unregistered session stays attributed.
+ // Walking a large history costs ~150ms, so the last index is reused briefly:
+ // range switches and re-opens within the window stay instant, while the
+ // panel's refresh button passes {refresh:true} to re-walk and always sees a
+ // session that just finished. File contents are still re-checked by
+ // token-stats through mtime/size, this window only caches the file list.
+ const TOKEN_INDEX_TTL_MS = 15000;
+ let tokenIndex = null;
+ function tokenOptions(options={}) {
+ const excludedOwners = new Set((Array.isArray(options.excludeOwners) ? options.excludeOwners : [])
+ .map(value => String(value || '').trim()).filter(validId));
+ const excludedKey = [...excludedOwners].sort().join('\0');
+ if (!options.refresh && tokenIndex && tokenIndex.excludedKey === excludedKey &&
+ Date.now() - tokenIndex.at < TOKEN_INDEX_TTL_MS) return tokenIndex.value;
+ const files=[],owners=new Map(),accounts={};
+ function directories(dir) {
+ try {return fs.readdirSync(dir,{withFileTypes:true}).filter(entry=>entry.isDirectory()&&!entry.isSymbolicLink());}
+ catch(_) {return [];}
}
- return {files:[...owners.keys()],source:'local-codebuddy-requests',
- sourceSession:file=>owners.get(file),
+ for(const owner of directories(root)) {
+ if(!validId(owner.name))continue;
+ if(excludedOwners.has(owner.name))continue;
+ const history=path.join(root,owner.name,'CodeBuddyIDE',owner.name,'history');
+ for(const workspace of directories(history)) {
+ const base=path.join(history,workspace.name);
+ for(const session of directories(base)) {
+ if(!validId(session.name))continue;
+ const file=path.join(base,session.name,'index.json');
+ if(!fs.existsSync(file))continue;
+ files.push(file);owners.set(file,session.name);accounts[session.name]=owner.name;
+ }
+ }
+ }
+ const value = {files,source:'local-codebuddy-requests',sessionAccounts:accounts,
+ sourceSession:file=>owners.get(file) || '',
readRecords:text=>{const index=parseIndex(text);return Array.isArray(index.requests)?index.requests:[];}};
+ tokenIndex = {at:Date.now(),excludedKey,value};
+ return value;
}
function collect(id) {
return [...snapshot(null,id).files].map(([key,file])=>({path:key.replace('/__session__/','/'+id+'/'),source:file.sourcePath,size:file.size}));
diff --git a/scripts/codebuddy-native-recovery.js b/scripts/codebuddy-native-recovery.js
new file mode 100644
index 0000000..d6132cf
--- /dev/null
+++ b/scripts/codebuddy-native-recovery.js
@@ -0,0 +1,33 @@
+'use strict';
+
+// Choose only from backups that the active profile has already accepted. The
+// caller still validates and writes the complete session through CodeBuddy's
+// native service; this module never handles token contents.
+function chooseRecoveryUid(accounts, state, primaryUid) {
+ if (state && state.explicitLogout === true) return '';
+ const valid = (Array.isArray(accounts) ? accounts : [])
+ .filter(account => account && account.authValid === true && /^[A-Za-z0-9_-]{1,128}$/.test(String(account.uid || '')));
+ const byUid = new Map(valid.map(account => [String(account.uid), account]));
+ const remembered = state && String(state.uid || '');
+ if (remembered && byUid.has(remembered)) return remembered;
+ const primary = String(primaryUid || '');
+ if (primary && byUid.has(primary)) return primary;
+ valid.sort((a, b) => Number(b.lastRefreshTime || 0) - Number(a.lastRefreshTime || 0));
+ return valid[0] ? String(valid[0].uid) : '';
+}
+
+async function recoverNativeSession({ native, accounts, state, primaryUid, readSession }) {
+ if (!native || typeof readSession !== 'function') return null;
+ const uid = chooseRecoveryUid(accounts, state, primaryUid);
+ if (!uid) return null;
+ const session = await readSession(uid);
+ const result = await native.replace(session);
+ if (!result || result.uid !== uid) throw new Error('CodeBuddy 原生会话恢复未确认');
+ const restored = await native.read();
+ if (!restored || String(restored.account && restored.account.uid || '') !== uid) {
+ throw new Error('CodeBuddy 原生会话恢复复核失败');
+ }
+ return { uid, session: restored };
+}
+
+module.exports = { chooseRecoveryUid, recoverNativeSession };
diff --git a/scripts/codebuddy-native.js b/scripts/codebuddy-native.js
index bb8d85f..6d0f33e 100644
--- a/scripts/codebuddy-native.js
+++ b/scripts/codebuddy-native.js
@@ -23,8 +23,10 @@ async function replaceNativeSession(session) {
else await this.storageService.remove(this.getStorageKey(), -1);
};
let succeeded = false;
+ let persistedNewSession = false;
try {
await persist(session);
+ persistedNewSession = session !== null;
this.currentSession = session || undefined;
this.refreshFailureRetryCount = 0;
this._onDidChangeSession.fire(this.currentSession);
@@ -33,7 +35,12 @@ async function replaceNativeSession(session) {
return {uid:session ? String(session.account.uid) : null};
} catch (_) {
try {
- await persist(previous);
+ // A failed store may have touched an unknown encrypted record. Only
+ // remove a newly written session after the write itself completed and
+ // the later publish failed; never turn an uncertain write failure into
+ // deletion of the native login state.
+ if (previous) await persist(previous);
+ else if (persistedNewSession) await persist(null);
this.currentSession = previous;
this._onDidChangeSession.fire(previous);
this.scheduleRefresh();
diff --git a/scripts/credit-history-sync.js b/scripts/credit-history-sync.js
index 7dd1fd2..1ab9121 100644
--- a/scripts/credit-history-sync.js
+++ b/scripts/credit-history-sync.js
@@ -39,8 +39,17 @@ function createCreditHistorySync(options) {
cache.set(key(row.uid, row.date), { ...row, models });
}
} catch (_) { /* Absent or invalid cache: query the official API. */ }
- function persist() {
+ const persistIntervalMs = Number.isFinite(options.persistIntervalMs) && options.persistIntervalMs >= 0
+ ? options.persistIntervalMs : 2000;
+ let lastPersistAt = 0;
+ // Rewriting the whole cache after every gap is cheap for a few accounts but
+ // repeats a multi-megabyte write for dozens of them. Throttle it and force
+ // one write at the end of the job: a crash then only loses the last seconds.
+ function persist(force) {
if (!options.cacheFile) return;
+ const at = clock().getTime();
+ if (!force && lastPersistAt && at - lastPersistAt < persistIntervalMs) return;
+ lastPersistAt = at;
const tmp = options.cacheFile + '.tmp';
try {
fs.mkdirSync(path.dirname(options.cacheFile), { recursive: true, mode: 0o700 });
@@ -150,6 +159,7 @@ function createCreditHistorySync(options) {
active.completed++;
active.percent = Math.floor(active.completed / active.total * 100);
}
+ persist(true);
active.running = false;
active.current = '';
active.percent = 100;
diff --git a/scripts/credit-usage-store.js b/scripts/credit-usage-store.js
index 2ce7e90..adf64c0 100644
--- a/scripts/credit-usage-store.js
+++ b/scripts/credit-usage-store.js
@@ -369,6 +369,24 @@ function createCreditUsageStore(options = {}) {
try { fs.chmodSync(dbPath, 0o600); } catch (_) {}
}
+ async function hasModelRateLimitElsewhere({ uid, modelId, resetAt, 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 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 > ?
+ LIMIT 1`,
+ [profileId, accountUid, id, reset, timestamp]
+ );
+ return rows.length > 0;
+ }
+
async function listModelRateLimits(uids, now) {
await initialize();
const accountUids = Array.from(new Set((Array.isArray(uids) ? uids : []).map((uid) => validIdentity(uid, 'uid'))));
@@ -414,6 +432,7 @@ function createCreditUsageStore(options = {}) {
saveHistoryUsage,
saveDailyCheckin,
saveModelRateLimit,
+ hasModelRateLimitElsewhere,
listModelRateLimits,
};
}
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 39c1b54..622254c 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -162,6 +162,7 @@ const plat = require('./platform.js');
const { readWorkBuddyTarget } = require('./workbuddy-target.js');
const { BINDING, createRendererApiBridge, rendererBridgeSource } = require('./renderer-api-bridge.js');
const { createCodeBuddyNative } = require('./codebuddy-native.js');
+const { recoverNativeSession } = require('./codebuddy-native-recovery.js');
const { createCodeBuddySessionStore } = require('./codebuddy-session-store.js');
const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget, selectIdeTargets } = require('./cdp-targets.js');
const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');
@@ -223,6 +224,30 @@ const PROFILE = getProfile();
const DATA_DIR = defaultDataDir();
const codeBuddyFiles = PROFILE.kind === 'codebuddy' ? createCodeBuddyFiles({root: PROFILE.historyRoot, sync:sessionSync}) : null;
if (codeBuddyFiles) sessionSync = codeBuddyFiles.sync;
+
+// CN and international CodeBuddy share the history tree, but their WorkDaddy
+// account stores are profile-specific. Exclude owners known to the sibling
+// profile so local Token statistics do not mix the two clients. Unknown owners
+// stay eligible because they may be deleted or left by an older installation
+// of the active profile.
+function codeBuddyProfileOwnerIds(profileId) {
+ try {
+ const accountsDir = path.join(profileDataDir(getProfile(profileId)), 'accounts');
+ return new Set(fs.readdirSync(accountsDir)
+ .filter(name => /^[-A-Za-z0-9_]{1,200}\.info$/.test(name))
+ .map(name => name.slice(0, -5)));
+ } catch (_) {
+ return new Set();
+ }
+}
+function codeBuddyForeignOwnerIds() {
+ if (PROFILE.kind !== 'codebuddy') return [];
+ const sibling = PROFILE.id === 'codebuddy-cn' ? 'codebuddy-intl' :
+ PROFILE.id === 'codebuddy-intl' ? 'codebuddy-cn' : '';
+ if (!sibling) return [];
+ const currentOwners = codeBuddyProfileOwnerIds(PROFILE.id);
+ return [...codeBuddyProfileOwnerIds(sibling)].filter(owner => !currentOwners.has(owner));
+}
const codeBuddyNative = PROFILE.kind === 'codebuddy' ? createCodeBuddyNative({profile: PROFILE, WebSocketCtor}) : null;
const accountCreditCache = createAccountCreditCache(DATA_DIR);
const thirdPartyModels = createThirdPartyImport({ targetFile: workbuddyModelsFile(), dataDir: DATA_DIR });
@@ -385,6 +410,8 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.24:账号轮换恢复真实积分段消耗检测,仅推荐缓存中到期时间最近的可用账号。
// 1.2.25:首页弹窗任务补齐成长/活动入口,并按 renderer 页面身份修复重连后的 pageReady 触发。
// 1.2.26:无效账号备份不再显示可点击的切换按钮,导入路径拒绝写入无效认证数据。
+// 1.2.27:CodeBuddy 原生会话丢失时,在安全存储恢复后自动从已确认备份恢复,退出登录保留显式抑制标记。
+// 1.2.28:Windows 更新安装器启动幂等,避免下载完成后的按钮竞态重复拉起 Setup.exe。
// 1.2.43:自动化支持从 GitHub/Gitee 发现、缓存、去重并导入公开任务;签到不再作为内置任务安装。
// 1.2.44:会话复制不再拆分重复血缘,缺失登记时认领已有副本;会话页显示可恢复进度,用量统计弹窗改版。
// 1.2.45:自动化协议 V2 增加通用运行上下文、TTL/UUID/数值能力;账号页增加每日任务三环进度。
@@ -439,8 +466,22 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 扩展宿主 indexCache(TTL 5min)不因外部写 index.json 失效,侧边栏
// 此前要等缓存过期或重启才显示同步的会话。
// 1.2.11:账号切换刷新只依赖页面重载与同步完成后的列表刷新,避免官方列表重复合并。
-const DAEMON_VERSION = '1.2.11';
-const DAEMON_BUILD_ID = 'release-1.2.11-20261001-account-reload-list-codebuddy-pr345';
+// 1.2.13:CodeDaddy 用量统计改为扫描官方历史树(含客户端已删除与无登记的会话,
+// 按拥有目录归属账号),弹窗增加刷新按钮,修复部分日期 Token 记为 0;
+// Token 统计复用 15s 内的枚举结果并跳过无变化缓存重写,积分历史同步
+// 改为节流落盘(任务结束前强制写一次)。
+// 1.2.14:隐藏 WorkBuddy 后台定时任务、收紧会话删除锁,并在账号切换时重建 renderer 首屏 accountSnapshot。
+// 1.2.14:自动化发送点击触发页面重渲染时,忽略已执行点击返回的 Promise was collected,
+// 继续等待本轮会话回执,避免把已发送消息误报为失败。
+// 1.2.15:补充侧栏会话变化检测,保留多账号同步资格,避免旧会话漏同步及首个目标消费更新标记。
+// 1.2.16:首页弹窗清理任务跨页面重跑时复用任务级 toast,避免重复点击新建任务堆叠相同提示。
+// 1.2.17:模型限流记录在守护进程侧跨账号去重,避免同步会话的历史 429 重复归属。
+// 1.2.18:检测客户端更新后丢失 CDP,并提供安全退出后的一键恢复入口。
+// 1.2.18:自动化 session.create 可选 cwd(绝对路径)/ workspace(侧栏工作区名)指定新会话
+// 工作目录;工作区不存在或绑定校验不通过时拒绝发送,不退回默认目录。
+// 1.2.20:CodeBuddy 原生安全存储不可用时保护已有加密会话,并给出钥匙串/密钥环修复提示。
+const DAEMON_VERSION = '1.2.28';
+const DAEMON_BUILD_ID = 'release-1.2.28-20261011-windows-installer-dedupe';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -685,6 +726,7 @@ const updateState = {
};
let updateTimer = null;
let updateDownloadPromise = null;
+let updateApplyPromise = null;
// 启动时读取上次成功的更新源(粘性源):下次检查优先用它,避免 GitHub 不通时每次都白等一次超时。
try {
@@ -1437,6 +1479,24 @@ function extractAppFromDmg(dmgPath) {
// 安装:macOS 继续使用 apply-update.sh;Windows 打开已校验的可见 Setup.exe,
// 由 Inno Setup 确认 WorkBuddy 已退出、替换文件并启动新版。
function applyUpdate() {
+ if (updateState.status === 'installer-opened' && updateState.attemptId) {
+ updateDebug('installer-already-open', { attemptId: updateState.attemptId, assetName: updateState.assetName });
+ return Promise.resolve({
+ ok: true,
+ opened: true,
+ alreadyOpen: true,
+ status: 'installer-opened',
+ message: '安装程序已打开,请到任务栏选择安装窗口完成安装',
+ });
+ }
+ if (updateApplyPromise) return updateApplyPromise;
+ updateApplyPromise = applyUpdateOnce().finally(() => {
+ updateApplyPromise = null;
+ });
+ return updateApplyPromise;
+}
+
+function applyUpdateOnce() {
if (IS_PORTABLE_WIN) return Promise.reject(new Error('便携版不能运行安装式更新,请手动下载新版 ZIP'));
if (!updateState.downloaded) {
updateDebug('apply-error', { stage: 'preflight', error: '尚未下载完成', latest: updateState.latest });
@@ -1522,7 +1582,7 @@ function applyUpdate() {
updateState.status = 'installer-opened';
updateState.message = '安装程序已打开';
updateDebug('installer-opened', { attemptId: attempt.id, pid: child.pid, assetName: updateState.assetName });
- resolve({ ok: true, opened: true, status: 'installer-opened', message: '安装程序已打开,请按提示完成安装' });
+ resolve({ ok: true, opened: true, status: 'installer-opened', message: '安装程序已打开,请到任务栏选择安装窗口完成安装' });
});
});
}
@@ -1736,12 +1796,71 @@ function releaseDaemonLock() {
let backupTimer = null;
let nativeAuthSyncTail = Promise.resolve();
+const CODEBUDDY_NATIVE_STATE_FILE = path.join(DATA_DIR, 'codebuddy-native-state.json');
+function readCodeBuddyNativeState() {
+ if (!codeBuddyNative) return null;
+ try {
+ const state = JSON.parse(fs.readFileSync(CODEBUDDY_NATIVE_STATE_FILE, 'utf8'));
+ if (!state || typeof state !== 'object' || Array.isArray(state)) return null;
+ return {
+ uid: typeof state.uid === 'string' ? state.uid : '',
+ explicitLogout: state.explicitLogout === true,
+ };
+ } catch (_) { return null; }
+}
+function writeCodeBuddyNativeState(uid, explicitLogout = false) {
+ if (!codeBuddyNative) return;
+ try {
+ fs.mkdirSync(path.dirname(CODEBUDDY_NATIVE_STATE_FILE), { recursive: true, mode: 0o700 });
+ const temp = `${CODEBUDDY_NATIVE_STATE_FILE}.tmp.${process.pid}`;
+ fs.writeFileSync(temp, JSON.stringify({
+ uid: typeof uid === 'string' ? uid : '',
+ explicitLogout: explicitLogout === true,
+ updatedAt: Date.now(),
+ }) + '\n', { mode: 0o600 });
+ fs.renameSync(temp, CODEBUDDY_NATIVE_STATE_FILE);
+ try { fs.chmodSync(CODEBUDDY_NATIVE_STATE_FILE, 0o600); } catch (_) {}
+ } catch (_) {}
+}
+function readCodeBuddyBackupSession(uid) {
+ const file = accountBackupFile(uid);
+ if (!fs.existsSync(file)) throw new Error('账号备份不存在');
+ 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)) {
+ throw new Error('账号备份无效或不属于当前地区');
+ }
+ if (!wdCompatAuthToken(session.auth)) throw new Error('账号备份中无可用 accessToken');
+ return session;
+}
+async function recoverCodeBuddyNativeSession() {
+ if (!codeBuddyNative) return null;
+ const recovered = await recoverNativeSession({
+ native: codeBuddyNative,
+ accounts: listAccounts(DATA_DIR),
+ state: readCodeBuddyNativeState(),
+ primaryUid: primaryAccountStore.get(),
+ readSession: readCodeBuddyBackupSession,
+ });
+ if (!recovered) return null;
+ writeCodeBuddyNativeState(recovered.uid, false);
+ log(`[sync] CodeBuddy 原生登录态已自动恢复 uid=${recovered.uid}`);
+ return recovered.session;
+}
function syncCodeBuddyAuth() {
const work = nativeAuthSyncTail.catch(() => {}).then(async () => {
- const session = await codeBuddyNative.read();
+ let session = await codeBuddyNative.read();
if (!session || !session.account || !session.auth) {
- if (fs.existsSync(AUTH_FILE)) fs.unlinkSync(AUTH_FILE);
- return null;
+ // A previous 1.2.12 daemon could delete the native-current file after a
+ // transient native read failure. Restore the last confirmed account (or
+ // the selected primary/newest valid backup) through CodeBuddy's official
+ // service instead of asking the user to log in again.
+ session = await recoverCodeBuddyNativeSession();
+ if (!session) {
+ if (fs.existsSync(AUTH_FILE)) fs.unlinkSync(AUTH_FILE);
+ return null;
+ }
}
if (!/^[A-Za-z0-9_-]{1,128}$/.test(String(session.account.uid || ''))) throw new Error('原生账号标识无效');
const content = JSON.stringify(session);
@@ -1753,6 +1872,7 @@ function syncCodeBuddyAuth() {
fs.renameSync(temp, AUTH_FILE);
fs.chmodSync(AUTH_FILE, 0o600);
}
+ writeCodeBuddyNativeState(String(session.account.uid), false);
return session;
});
nativeAuthSyncTail = work;
@@ -1766,6 +1886,10 @@ async function switchAccountForProfile(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 (!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 未确认账号切换');
const current = await syncCodeBuddyAuth();
@@ -2067,6 +2191,12 @@ async function cdpMouseClick(source, x, y, extra = {}, options = {}) {
await cdpSend('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });
}
+// 只移动指针、不按键。用于让 hover-only 的控件显形(例如侧栏工作区的「新建任务」按钮)。
+async function cdpMouseMove(source, x, y, extra = {}) {
+ log('[cdp-focus-diagnostics] mouse-move:dispatch ' + JSON.stringify({ source, x, y, extra, targetUrl: cdp.targetUrl }));
+ await cdpSend('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y });
+}
+
function cdpSend(method, params = {}, _retry = 0) {
if (!cdp.ws || cdp.ws.readyState !== 1) return Promise.reject(new Error('CDP 未连接'));
const id = ++cdp.id;
@@ -2494,6 +2624,62 @@ function reloadIdeWorkbenchWindows(reason) {
return scheduled > 0;
}
+// [客户端调试端口丢失检测] 配套状态与判定(纯函数部分可单测,见 test/client-debug-relaunch.test.js)。
+// 背景:WorkBuddy 官方自动更新后自行重启,新进程丢失 --remote-debugging-port,
+// daemon 表现为"进程在跑但 CDP 不可达",cdpLoop 会无限重试。连续命中阈值后
+// 标记 needsDebugRelaunch,由 /api/status 与根路径状态页向用户暴露并提供一键恢复。
+// 为 VM 切片单测,以下块只依赖 log / Date,不依赖 workBuddyRunning(由调用方注入结果)。
+// __wbsClientDebugStateBlockStart
+const CLIENT_DEBUG_MISS_THRESHOLD = 3;
+const clientDebugState = { consecutiveMiss: 0, needsDebugRelaunch: false, updatedAt: 0 };
+
+function resetClientDebugState() {
+ clientDebugState.consecutiveMiss = 0;
+ if (clientDebugState.needsDebugRelaunch) {
+ clientDebugState.needsDebugRelaunch = false;
+ clientDebugState.updatedAt = Date.now();
+ }
+ return clientDebugState;
+}
+
+// clientRunning: true=进程在跑 / false=没跑 / null=未知(探测失败时不计数,避免误报)
+function updateClientDebugState({ cdpConnected, clientRunning }) {
+ if (cdpConnected || clientRunning === false) {
+ return resetClientDebugState();
+ }
+ if (clientRunning !== true) return clientDebugState;
+ clientDebugState.consecutiveMiss += 1;
+ if (clientDebugState.consecutiveMiss >= CLIENT_DEBUG_MISS_THRESHOLD && !clientDebugState.needsDebugRelaunch) {
+ clientDebugState.needsDebugRelaunch = true;
+ clientDebugState.updatedAt = Date.now();
+ log('[cdp] 检测到 WorkBuddy 正在运行但调试端口不可达(疑似官方自动更新后重启),请在状态页一键恢复');
+ }
+ return clientDebugState;
+}
+// __wbsClientDebugStateBlockEnd
+
+function safeClientRunning() {
+ try {
+ // workBuddyRunning() deliberately treats a failed non-Windows probe as
+ // "still running" for destructive account operations. The diagnostic
+ // state must preserve that uncertainty as null, otherwise a broken pgrep
+ // or /proc probe can manufacture a recovery warning.
+ if (IS_WIN) {
+ const binary = resolveWorkBuddyBinary();
+ if (!binary) return null;
+ return verifiedWindowsWorkBuddyProcesses(binary).length > 0;
+ }
+ if (IS_LINUX) {
+ return linuxWorkBuddyPids(WORKBUDDY_BINARY).length > 0;
+ }
+ const result = spawnSync('pgrep', ['-f', WORKBUDDY_APP], { stdio: 'ignore', timeout: 5000 });
+ if (result.error || result.status === null) return null;
+ return result.status === 0;
+ } catch (_) {
+ return null;
+ }
+}
+
async function cdpLoop() {
for (;;) {
if (!cdp.connected) {
@@ -2503,6 +2689,15 @@ async function cdpLoop() {
log(`[cdp] 连接异常: ${e.message}`);
}
}
+ // [客户端调试端口丢失检测] WorkBuddy 官方自动更新器装完更新会自行重启应用,
+ // 新进程不再带 --remote-debugging-port:此时进程在跑、CDP 永远连不上,
+ // 表现为右下角机器人按钮消失且无任何可操作的提示。这里只做检测与状态暴露,
+ // 不静默杀进程;恢复由用户在状态页一键触发(POST /api/client/relaunch)。
+ try {
+ updateClientDebugState({ cdpConnected: cdp.connected, clientRunning: safeClientRunning() });
+ } catch (e) {
+ log(`[cdp] 客户端状态探测异常: ${e.message}`);
+ }
// [CodeBuddy IDE 状态栏] IDE 主窗口浮层独立于主连接扫描注入(详见 ideSyncScan)
ideSyncScan().catch((e) => log(`[cdp-ide] IDE 扫描异常: ${e.message}`));
await new Promise((r) => setTimeout(r, CDP_RECONNECT_MS));
@@ -2537,9 +2732,27 @@ async function reloadWorkBuddyPage(options = {}) {
} catch (error) {
log(`[cdp] 获取主页面 frame 失败,将在页面加载完成后注入: ${error.message}`);
}
+ let navigationPlan = null;
+ if (options.account && PROFILE.kind === 'workbuddy') {
+ try {
+ navigationPlan = await withTimeout(readRendererAccountSnapshot(options.account.uid), 10000, '读取切换后的 WorkBuddy 账号');
+ } catch (_) {
+ log('[cdp] 账号快照导航失败,回退页面刷新');
+ }
+ }
const pending = armPendingReloadInjection(frameId);
try {
- await withTimeout(cdpSend('Page.reload', { ignoreCache: false }), 10000, '刷新 WorkBuddy 页面');
+ let navigated = false;
+ if (navigationPlan) {
+ try {
+ const navigation = await withTimeout(cdpSend('Page.navigate', { url: navigationPlan.url }), 10000, '导航 WorkBuddy 页面');
+ if (navigation && navigation.errorText) throw new Error(navigation.errorText);
+ navigated = true;
+ } catch (_) {
+ log('[cdp] 账号快照导航失败,回退页面刷新');
+ }
+ }
+ if (!navigated) await withTimeout(cdpSend('Page.reload', { ignoreCache: false }), 10000, '刷新 WorkBuddy 页面');
if (options.waitForInjection === false) return true;
const mounted = await pending.ready;
if (!mounted) log('[cdp] 页面重载后组件未在 5 秒内确认挂载,继续后台流程');
@@ -2550,6 +2763,44 @@ async function reloadWorkBuddyPage(options = {}) {
}
}
+// WorkBuddy 在创建 renderer 时从 URL 的 accountSnapshot 做首屏 hydrate。
+// Page.reload 会保留旧 URL,因此切账号必须用切换后的实时 profile 生成新地址。
+async function readRendererAccountSnapshot(expectedUid) {
+ const uid = String(expectedUid || '').trim();
+ if (!uid) throw new Error('切换账号缺少 uid');
+ const result = await cdpSend('Runtime.evaluate', {
+ expression: `(async function () {
+ var profile = null;
+ try {
+ var account = globalThis.wb && globalThis.wb.account;
+ if (account && typeof account.profile === 'function') profile = await account.profile();
+ } catch (_) {}
+ if (!profile || typeof profile !== 'object') return { error: 'profile-unavailable' };
+ var value = String(profile.uid || '').trim();
+ if (!value) return { error: 'profile-missing-uid' };
+ return { uid: value, nickname: profile.nickname, type: profile.type,
+ editionType: profile.editionType, enterpriseId: profile.enterpriseId,
+ enterpriseName: profile.enterpriseName, enterpriseUserName: profile.enterpriseUserName,
+ avatarUrl: profile.avatarUrl, isPro: profile.isPro, isAdmin: profile.isAdmin,
+ oneidAccountId: profile.oneidAccountId, enableArdotDesign: profile.enableArdotDesign,
+ showDefaultPermission: profile.showDefaultPermission, href: location.href };
+ })()`,
+ 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 (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() };
+ 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];
+ }
+ const url = new URL(profile.href);
+ url.searchParams.set('accountSnapshot', encodeURIComponent(JSON.stringify(snapshot)));
+ return { snapshot, url: url.href };
+}
+
const WORKBUDDY_TARGET = IS_WIN ? null : readWorkBuddyTarget({ dataDir: DATA_DIR, profileId: PROFILE.id });
// 三平台的应用标识(WORKBUDDY_BINARY 用于 pgrep/pkill 精确匹配与直接启动):
// macOS : 二进制在 <X.app>/Contents/MacOS/Electron,WORKBUDDY_APP 是 .app 包路径
@@ -3517,7 +3768,7 @@ function automationSwitchAccount(account, options = {}) {
if (options.isCancelled && options.isCancelled()) throw new Error('任务已停止');
const acct = await switchAccountForProfile(uid);
pendingAutomationAccountSwitch = { account: { uid: acct.uid, nickname: acct.nickname } };
- await reloadWorkBuddyPage();
+ await reloadWorkBuddyPage({ account: acct });
if (pendingAutomationAccountSwitch) {
const switchEvent = pendingAutomationAccountSwitch;
pendingAutomationAccountSwitch = null;
@@ -3547,6 +3798,12 @@ function automationSwitchAccount(account, options = {}) {
automationAccountSwitchTail = run.catch(() => {});
return run;
}
+function automationNotificationNamespace(task, runId) {
+ // Navigation-scoped popup cleanup is intentionally restartable. Its success
+ // notices describe the popup, so a task-level namespace lets a repeated page
+ // navigation update the existing toast instead of stacking another copy.
+ return taskIsPassiveCleanup(task) ? 'automation-task:' + task.id : 'automation:' + runId;
+}
function startAutomationRun(task, event = null) {
if (event && (event.navigationSerial == null || event.pageSessionId == null)) event = { ...event, navigationSerial: event.navigationSerial == null ? mainFrameNavigationSerial : event.navigationSerial, pageSessionId: event.pageSessionId || cdpPageSessionId };
if (automationRuns.size > 200) {
@@ -3630,7 +3887,15 @@ function startAutomationRun(task, event = null) {
const modelId = detail.model === undefined ? null : normalizeAutomationModelId(detail.model);
if (op === 'session.create') await withInput(() => ensureAutomationNewTask({ guard: () => {
if (isCancelled() || (currentAccount() || {}).uid !== accountUid) throw new Error('发送前账号或运行状态已变化');
- } }));
+ }, cwd: detail.cwd, workspace: detail.workspace }));
+ // 指定工作目录时,落点已由 ensureAutomationNewTask 校验(不一致会在发送前抛错);
+ // 这里把页面真实显示的绑定名写进运行日志,便于事后追溯「这个会话到底落哪了」。
+ if (op === 'session.create' && (detail.cwd || detail.workspace)) {
+ const boundSurface = await readAutomationAgentSurface(false).catch(() => null);
+ if (boundSurface && boundSurface.boundWorkspace) {
+ appendRunLog('session:workspace:bound:' + String(boundSurface.boundWorkspace).slice(0, 60));
+ }
+ }
let before = await readSession();
// New Task has no conversation controller until WorkBuddy accepts the first
// send. Keep the first controller it mounts as the send baseline; after that,
@@ -3754,7 +4019,7 @@ function startAutomationRun(task, event = null) {
return result;
} finally { completionReportRunning = false; }
};
- const runNotifier = createAutomationNotifier(automationNotifyToast, 'automation:' + id);
+ const runNotifier = createAutomationNotifier(automationNotifyToast, automationNotificationNamespace(task, id));
run.cleanupNotifications = runNotifier.cleanup;
const publicAccounts = () => listAccounts(DATA_DIR).map(a => ({uid:a.uid,nickname:a.nickname,isPrimary:primaryAccountStore.get()===a.uid}));
const publicCurrent = () => { const a = currentAccount(); return a ? {uid:a.uid,nickname:a.nickname,isPrimary:primaryAccountStore.get()===a.uid} : null; };
@@ -4695,7 +4960,7 @@ async function prepareSessionExport(ids) {
const selectedIds = normalizeSessionIdBatch(ids);
if (!selectedIds.length) throw new Error('未选择会话');
const rows = await sqliteQuery(
- 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id IN (' + sqlPlaceholders(selectedIds) + ') AND deleted_at IS NULL;',
+ 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id IN (' + sqlPlaceholders(selectedIds) + ') AND deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0;',
selectedIds
);
const byId = new Map(rows.map((row) => [String(row.id), row]));
@@ -4970,10 +5235,10 @@ function scheduleSessionDirtySave() {
}, 250);
if (typeof state.timer.unref === 'function') state.timer.unref();
}
-function markSessionDirty(uid, sessionId, event) {
+function markSessionDirty(uid, sessionId, event, at) {
const state = sessionDirtyState || (getSessionDirtyIndex(), sessionDirtyState);
const before = state.index.get(uid, sessionId);
- const marker = state.index.mark(uid, sessionId, event);
+ const marker = state.index.mark(uid, sessionId, event, at);
if (marker && (!before || before.at !== marker.at || before.event !== marker.event)) {
state.dirty = true;
scheduleSessionDirtySave();
@@ -5111,15 +5376,34 @@ async function copySessionRecord(src, targetUid, options = {}) {
const perform = async () => {
await yieldAutoCopyToRenderer();
const readRow = async (id, uid) => (await sqliteQuery(
- 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id = ? AND user_id = ? AND deleted_at IS NULL LIMIT 1;', [id, uid]
+ 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE id = ? AND user_id = ? AND deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0 LIMIT 1;', [id, uid]
))[0];
const sourceRow = await readRow(src.id, sourceUid);
if (!sourceRow) throw new Error('源会话已变化,请重试');
const sourceContextWindow = await readSessionContextWindow(sourceRow.id);
const dirtyIndex = typeof getSessionDirtyIndex === 'function' ? getSessionDirtyIndex() : null;
const dirtyMarker = options.auto && dirtyIndex ? dirtyIndex.get(sourceUid, sourceRow.id) : null;
- const clearAutoDirty = () => {
- if (options.auto && dirtyMarker && typeof clearSessionDirty === 'function') clearSessionDirty(sourceUid, sourceRow.id, dirtyMarker.at);
+ const finishAutoDirty = (targetId, changed = false) => {
+ if (!options.auto) return;
+ if (changed && typeof markSessionDirty === 'function') {
+ // A pairwise copy is not an acknowledgement from every account. Keep
+ // both updated members eligible for other destinations, including a
+ // later return through an already-synchronised account. Per-target
+ // mapping revisions still suppress workers for completed pairs.
+ const retain = (uid, id) => {
+ const current = dirtyIndex && dirtyIndex.get(uid, id);
+ if (!current || current.event !== 'sessionSynced') {
+ // Preserve the timestamp of a concurrent renderer update.
+ markSessionDirty(uid, id, 'sessionSynced', current ? current.at : undefined);
+ }
+ };
+ retain(sourceUid, sourceRow.id);
+ if (targetId) retain(targetUid, targetId);
+ return;
+ }
+ if (dirtyMarker && dirtyMarker.event !== 'sessionSynced' && typeof clearSessionDirty === 'function') {
+ clearSessionDirty(sourceUid, sourceRow.id, dirtyMarker.at);
+ }
};
const mapping = getAutoCopyMapping(DATA_DIR, lineageId, targetUid);
const ids = new Set(getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid));
@@ -5138,7 +5422,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
if (!candidates.length && (!mapping || !mapping.targetId) && sourceRow.cwd) {
try {
const fallbackRows = await sqliteQuery(
- 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE deleted_at IS NULL AND user_id = ? AND cwd = ? AND title = ? AND custom_title = ?;',
+ 'SELECT ' + SESSION_COPY_COLUMNS.join(',') + ' FROM sessions WHERE deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0 AND user_id = ? AND cwd = ? AND title = ? AND custom_title = ?;',
[targetUid, sourceRow.cwd, sourceRow.title || '', sourceRow.custom_title || '']
);
for (const row of fallbackRows || []) {
@@ -5171,7 +5455,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
const totalBytes = Number(mapping.totalBytes);
const warning = (Number.isFinite(sourceBytes) ? sourceBytes : 0) > 100 * 1024 * 1024
? '会话超过 100 MB,同步可能较慢' : '';
- clearAutoDirty();
+ finishAutoDirty(existingMappingTarget.id);
return {
status: 'skipped', sourceId: sourceRow.id, targetId: existingMappingTarget.id,
branched: false, failedFiles: 0, warning,
@@ -5231,7 +5515,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
});
});
const warning = left.totalBytes > 100 * 1024 * 1024 ? '会话超过 100 MB,同步可能较慢' : '';
- clearAutoDirty();
+ finishAutoDirty(targetId, runtimeRepairBytes > 0);
return { status: runtimeRepairBytes ? 'copied' : 'skipped', sourceId: src.id, targetId, branched: false, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes: left.totalBytes, copiedBytes: runtimeRepairBytes };
}
let right = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, targetId, aliases, syncCache);
@@ -5318,7 +5602,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
sourceBytes: left.totalBytes, totalBytes,
});
});
- clearAutoDirty();
+ finishAutoDirty(targetId, changed);
return { status: changed ? 'copied' : 'skipped', sourceId: src.id, targetId, branched: branched && changed, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes, copiedBytes };
};
// One lineage lock also serializes manual copy and reverse-direction updates.
@@ -5346,7 +5630,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
if (!rules.allSessions && !rules.sessionIds.length && !rules.workspaces.length && !requested.size) return [];
const rows = await sqliteQuery(
'SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id ' +
- 'FROM sessions WHERE deleted_at IS NULL AND user_id = ? ORDER BY created_at DESC;',
+ 'FROM sessions WHERE deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0 AND user_id = ? ORDER BY created_at DESC;',
[source]
);
const workspaceSet = new Set(rules.workspaces.map(canonicalWorkspace));
@@ -5370,6 +5654,9 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
if (typeof dirtyIndex.get !== 'function' || typeof clearSessionDirty !== 'function') return false;
const marker = dirtyIndex.get(source, row.id);
if (!marker) return false;
+ // This target is current, but other members may still need the synced
+ // content. Retain that eligibility while skipping this completed pair.
+ if (marker.event === 'sessionSynced') return true;
// Markers written by the pre-1.2.139 lifecycle signature can survive a
// reload even though both persisted revisions prove the mapping is clean.
// Clear only that proven no-op; a changed source revision remains dirty.
@@ -6099,6 +6386,8 @@ const PUBLIC_API_PATHS = new Set([
'/api/about/',
'/api/update-check',
'/api/update-status',
+ // 一键恢复重启:仅 loopback 可达,权限等同于本地 launcher;由用户在状态页确认触发,不静默执行。
+ '/api/client/relaunch',
]);
function isAllowedApiOrigin(origin) {
@@ -6724,6 +7013,58 @@ function automationAgentSurfaceExpression(focusComposer) {
clone.querySelectorAll('[data-slate-placeholder="true"],[data-slate-zero-width]').forEach(function(node){node.remove()});
return String(clone.innerText||clone.textContent||'').replace(/[\\uFEFF\\u200B]/g,'').trim();
}
+ function centerOf(el){var r=el.getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2}}
+ function hitTest(el,pt){try{var t=document.elementFromPoint(pt.x,pt.y);return !!(t&&(t===el||el.contains(t)||t.contains(el)))}catch(_){return false}}
+ // WorkBuddy 的侧栏工作区(空间)分组把 cwd 放在 React fiber 的 props 上;
+ // 只用 DOM 文本匹配会在重名/改名时出错,所以以 fiber 上的 cwd 为准。
+ function fiberProps(el){
+ try{
+ var key=Object.keys(el).find(function(k){return k.indexOf('__reactFiber$')===0||k.indexOf('__reactInternalInstance$')===0});
+ if(!key)return null;
+ var node=el[key];
+ for(var depth=0;depth<12&&node;depth++,node=node.return){
+ var props=node.memoizedProps;
+ if(props&&typeof props.cwd==='string'&&props.cwd.trim())return props;
+ }
+ }catch(_){}
+ return null;
+ }
+ var workspaces=[];
+ Array.from(document.querySelectorAll('.collapsible-section')).forEach(function(section){
+ var btn=section.querySelector('button.workspace-new-task-button');
+ if(!btn)return;
+ var props=fiberProps(section);
+ if(!props)return;
+ var header=section.querySelector('.collapsible-section-header');
+ var btnPoint=centerOf(btn);
+ workspaces.push({
+ cwd:props.cwd,
+ displayName:String(props.displayName||'').trim(),
+ groupKey:String(props.groupKey||''),
+ header:header?{x:header.getBoundingClientRect().left+Math.min(60,header.getBoundingClientRect().width/2),y:header.getBoundingClientRect().top+header.getBoundingClientRect().height/2}:null,
+ button:btnPoint,
+ // 「新建任务」按钮是 hover-only:未悬停时 visibility:hidden,点击会落空。
+ clickable:visible(btn)&&hitTest(btn,btnPoint)
+ });
+ });
+ // 新建任务页输入框底部的工作区选择器,即 WorkBuddy 当前绑定的 cwd 显示名。
+ // 显示名可能被宽度截断(加省略号),data-text 一般是未截断的原文,两者都带上。
+ var pickerEl=document.querySelector('.cr-workspace-picker');
+ var pickerLabel=pickerEl?pickerEl.querySelector('.cr-input-footer-item__label'):null;
+ var boundWorkspace=null,boundWorkspaceFull=null,boundWorkspaceCwd=null;
+ if(pickerEl){
+ var labelText=String((pickerLabel&&pickerLabel.textContent)||'').trim();
+ var labelData=String((pickerLabel&&pickerLabel.getAttribute('data-text'))||'').trim();
+ boundWorkspace=labelText||labelData||null;
+ boundWorkspaceFull=labelData||labelText||null;
+ var pickerCwd=(pickerEl.getAttribute('data-cwd')||pickerEl.getAttribute('data-workspace-cwd')||'').trim();
+ var labelCwd=pickerLabel&&(pickerLabel.getAttribute('data-cwd')||pickerLabel.getAttribute('data-workspace-cwd')||'');
+ if(pickerCwd||String(labelCwd||'').trim()) boundWorkspaceCwd=pickerCwd||String(labelCwd).trim();
+ if(!boundWorkspaceCwd){
+ var pickerProps=fiberProps(pickerEl)||fiberProps(pickerLabel);
+ if(pickerProps&&typeof pickerProps.cwd==='string') boundWorkspaceCwd=pickerProps.cwd.trim()||null;
+ }
+ }
var activeNewTask=Array.from(document.querySelectorAll('button.conversation-list-tab-button.active,button.conversation-list-tab-button.conversation-list-tab-button-box')).some(function(el){return visible(el)&&isNewTask(el)&&(/\\bactive\\b/.test(typeof el.className==='string'?el.className:'')||el.getAttribute('aria-selected')==='true')});
var composers=Array.from(document.querySelectorAll('[contenteditable="true"],textarea')).filter(visible);
var composer=composers.find(function(el){return !!el.closest('.wb-home-composer')})||(activeNewTask?composers[0]:null);
@@ -6734,13 +7075,13 @@ function automationAgentSurfaceExpression(focusComposer) {
if(!newTaskReady){
var candidates=Array.from(document.querySelectorAll('button.workspace-new-task-button,button.conversation-list-tab-button.conversation-list-tab-button-box,button.conversation-list-tab-button,button[aria-label="新建任务"],button[aria-label="New Task"]'));
var target=candidates.find(function(el){return visible(el)&&isNewTask(el)});
- if(target){var b=target.getBoundingClientRect();button={x:b.left+b.width/2,y:b.top+b.height/2}}
+ if(target){button=centerOf(target)}
}
if(ready&&composer&&${focusComposer ? 'true' : 'false'}){
composer.focus();
if(composer.tagName!=='TEXTAREA'){var selection=window.getSelection();var range=document.createRange();range.selectNodeContents(composer);selection.removeAllRanges();selection.addRange(range)}
}
- return {ready:ready,newTaskReady:newTaskReady,activeNewTask:activeNewTask,hasComposer:!!composer,composerText:composerText(composer),button:button};
+ return {ready:ready,newTaskReady:newTaskReady,activeNewTask:activeNewTask,hasComposer:!!composer,composerText:composerText(composer),button:button,boundWorkspace:boundWorkspace,boundWorkspaceFull:boundWorkspaceFull,boundWorkspaceCwd:boundWorkspaceCwd,workspaces:workspaces};
})()`;
}
@@ -6752,12 +7093,140 @@ async function readAutomationAgentSurface(focusComposer = false) {
return response && response.result && response.result.value;
}
+// 归一化工作目录:去掉尾部分隔符,便于与 fiber 上的 cwd 精确比对。
+function normalizeAutomationWorkspaceCwd(value) {
+ const raw = String(value == null ? '' : value).trim();
+ if (!raw) return '';
+ const trimmed = raw.replace(/[\\/]+$/, '');
+ return trimmed || raw;
+}
+
+function automationWorkspaceEntryMatches(entry, cwd, name) {
+ if (!entry) return false;
+ const wantedCwd = normalizeAutomationWorkspaceCwd(cwd);
+ const wantedName = String(name || '').trim();
+ const entryCwd = normalizeAutomationWorkspaceCwd(entry.cwd);
+ const entryName = String(entry.displayName || '').trim();
+ if (wantedCwd && wantedName) return entryCwd === wantedCwd && entryName === wantedName;
+ if (wantedCwd) return entryCwd === wantedCwd;
+ return !!wantedName && entryName === wantedName;
+}
+
+// 工作区显示名可能被侧栏截断(尾随省略号),此时用前缀比对;未被截断的标签必须完全一致,
+// 否则「smartbox」和「smartbox-ui-vue3」这类互为前缀的工作区名会被误判成同一个。
+function automationWorkspaceLabelMatches(label, expected) {
+ const a = String(label || '').trim();
+ const b = String(expected || '').trim();
+ if (!a || !b) return false;
+ if (a === b) return true;
+ if (!/[\u2026]$|\.{3}$/.test(a)) return false;
+ const base = a.replace(/(?:[\u2026]|\.{3})$/, '').trim();
+ return !!base && b.startsWith(base);
+}
+
+// 新建任务页的绑定可能同时暴露「截断显示名」和「完整名」两种标签,任一匹配即算绑定成功。
+function automationWorkspaceBoundMatches(surface, expected, expectedCwd = '') {
+ if (!surface) return false;
+ const wantedCwd = normalizeAutomationWorkspaceCwd(expectedCwd);
+ const boundCwd = normalizeAutomationWorkspaceCwd(surface.boundWorkspaceCwd);
+ if (wantedCwd && boundCwd) return boundCwd === wantedCwd;
+ const labels = [surface.boundWorkspace, surface.boundWorkspaceFull];
+ return labels.some((label) => automationWorkspaceLabelMatches(label, expected));
+}
+
+// 把「新建任务」页切到指定工作区(cwd / 工作区名)。
+//
+// 为什么不能只靠下发提示词里的 `cd ...`:WorkBuddy 的「新建任务」默认工作目录是
+// `~/WorkBuddy/<时间戳>`,靠提示词事后找补既晚又不可靠。侧栏每个工作区分组自带一个
+// 「新建任务」按钮,点它会走 WorkBuddy 自己的 `initializeWorkspace(cwd)` +
+// `handleNewConversation(cwd)`,这才是把新会话真正落到目标目录的唯一入口。
+// 该按钮是 hover-only(未悬停时 visibility:hidden),所以必须先移动指针再点击。
+async function navigateAutomationWorkspace({ cwd, workspace, guard }) {
+ const wantCwd = normalizeAutomationWorkspaceCwd(cwd);
+ const wantName = String(workspace || '').trim();
+ if (!wantCwd && !wantName) return { ok: false, skipped: true };
+ const describe = wantCwd || wantName;
+ let lastNames = '';
+ const deadline = Date.now() + 20000;
+ while (Date.now() < deadline) {
+ if (guard) await guard();
+ const probe = await readAutomationAgentSurface(false).catch(() => null);
+ if (probe) {
+ const workspaces = Array.isArray(probe.workspaces) ? probe.workspaces : [];
+ lastNames = workspaces.map((item) => item.displayName).filter(Boolean).join(', ');
+ const entry = workspaces.find((item) => automationWorkspaceEntryMatches(item, wantCwd, wantName));
+ if (entry) {
+ const expectedLabel = String(entry.displayName || '').trim() || describe;
+ const sameLabelEntries = expectedLabel
+ ? workspaces.filter((item) => String(item.displayName || '').trim() === expectedLabel)
+ : [];
+ const ambiguousLabel = sameLabelEntries.length > 1;
+ // 已经绑在目标工作区上:不需要再点,避免多余的导航把草稿/会话切走。
+ if (automationWorkspaceBoundMatches(probe, expectedLabel, wantCwd) && (!ambiguousLabel || probe.boundWorkspaceCwd)) {
+ return { ok: true, already: true, bound: probe.boundWorkspace, boundCwd: probe.boundWorkspaceCwd, label: expectedLabel, cwd: entry.cwd };
+ }
+ if (!entry.header) throw new Error('目标工作区分组缺少可悬停的标题,无法唤出「新建任务」');
+ await cdpMouseMove('automation:workspaceHover', entry.header.x, entry.header.y);
+ const clickDeadline = Date.now() + 5000;
+ let clicked = false;
+ while (Date.now() < clickDeadline) {
+ if (guard) await guard();
+ const fresh = await readAutomationAgentSurface(false).catch(() => null);
+ const freshEntry = fresh && (fresh.workspaces || []).find((item) => automationWorkspaceEntryMatches(item, wantCwd, wantName));
+ if (freshEntry && freshEntry.clickable) {
+ await cdpMouseClick('automation:workspaceNewTask', freshEntry.button.x, freshEntry.button.y);
+ clicked = true;
+ break;
+ }
+ await sleep(150);
+ }
+ if (!clicked) throw new Error('工作区 ' + expectedLabel + ' 的「新建任务」入口悬停后仍不可点击');
+ const bindDeadline = Date.now() + 15000;
+ while (Date.now() < bindDeadline) {
+ if (guard) await guard();
+ const after = await readAutomationAgentSurface(false).catch(() => null);
+ if (after && automationWorkspaceBoundMatches(after, expectedLabel, wantCwd) && (!ambiguousLabel || after.boundWorkspaceCwd)) {
+ return { ok: true, bound: after.boundWorkspace, boundCwd: after.boundWorkspaceCwd, label: expectedLabel, cwd: entry.cwd };
+ }
+ // 目标工作区可能已经跳走(例如被其它工作区的新建任务覆盖),重新找入口再点一次。
+ if (after && after.boundWorkspace) {
+ const again = (after.workspaces || []).find((item) => automationWorkspaceEntryMatches(item, wantCwd, wantName));
+ if (again && again.header) {
+ await cdpMouseMove('automation:workspaceHover', again.header.x, again.header.y);
+ if (again.clickable) await cdpMouseClick('automation:workspaceNewTask', again.button.x, again.button.y);
+ }
+ }
+ await sleep(200);
+ }
+ throw new Error('已点击工作区 ' + expectedLabel + ' 的「新建任务」,但新建任务页未绑定到该目录(绑定校验失败)');
+ }
+ }
+ await sleep(200);
+ }
+ throw new Error('未在侧栏找到工作区 ' + describe + (lastNames ? '(当前可见:' + lastNames + ')' : '(侧栏未暴露工作区分组)'));
+}
+
async function ensureAutomationNewTask(options = {}) {
if (!cdp.connected) throw new Error('CDP 未连接');
+ // 指定工作目录(cwd / 工作区名)时,先走侧栏工作区自己的「新建任务」入口,
+ // 让 WorkBuddy 把新会话绑定到目标目录;不指定则沿用默认(~/WorkBuddy/<时间戳>)。
+ let boundWorkspace = null;
+ let boundWorkspaceCwd = null;
+ let workspaceLabel = '';
+ if (options.cwd || options.workspace) {
+ const navigated = await navigateAutomationWorkspace({ cwd: options.cwd, workspace: options.workspace, guard: options.guard });
+ boundWorkspace = navigated && navigated.bound || null;
+ boundWorkspaceCwd = navigated && navigated.boundCwd || null;
+ workspaceLabel = navigated && navigated.label || String(options.workspace || '').trim()
+ || normalizeAutomationWorkspaceCwd(options.cwd).split('/').filter(Boolean).pop() || '';
+ if (boundWorkspace) log('[automation-workspace] bound=' + String(boundWorkspace).slice(0, 60));
+ }
let surface = null;
let clicked = false;
let readySince = null;
let settled = false;
+ let workspaceError = null;
+ const wantsWorkspace = !!(options.cwd || options.workspace);
const started = Date.now();
// Injection can finish before WorkBuddy's account route mounts its sidebar.
// Wait for both the entry and destination; never send into a project composer.
@@ -6775,7 +7244,20 @@ async function ensureAutomationNewTask(options = {}) {
if (Date.now() - readySince >= 400) { settled = true; break; }
} else {
readySince = null;
- if (!clicked && surface && surface.button) {
+ if (wantsWorkspace) {
+ // 指定了工作目录:绝不点「随便哪个」新建任务入口。侧栏里任何一个工作区的按钮
+ // 都能切走当前工作区,只有目标工作区自己的按钮才是对的。
+ if (!clicked) {
+ try {
+ const again = await navigateAutomationWorkspace({ cwd: options.cwd, workspace: options.workspace, guard: options.guard });
+ if (again && again.bound) boundWorkspace = again.bound;
+ if (again && again.boundCwd) boundWorkspaceCwd = again.boundCwd;
+ clicked = true;
+ } catch (error) {
+ workspaceError = error;
+ }
+ }
+ } else if (!clicked && surface && surface.button) {
await cdpMouseClick('automation:ensureNewTask', surface.button.x, surface.button.y);
clicked = true;
}
@@ -6783,8 +7265,18 @@ async function ensureAutomationNewTask(options = {}) {
await sleep(200);
}
if (options.guard) await options.guard();
- if ((!surface || !surface.newTaskReady) && !clicked) throw new Error('未找到 WorkBuddy 的新建任务入口');
- if (!settled) throw new Error('新建任务页面未准备完成,拒绝发送到当前会话');
+ if ((!surface || !surface.newTaskReady) && !clicked) throw workspaceError || new Error('未找到 WorkBuddy 的新建任务入口');
+ if (!settled) throw workspaceError || new Error('新建任务页面未准备完成,拒绝发送到当前会话');
+ // 指定了工作目录时,落草稿之前再核一次绑定:中途任何导航(含用户手动点击)都可能把
+ // 新建任务页切到别的工作区,此时宁可失败也不能把消息发进错误的目录。
+ if (wantsWorkspace) {
+ const expected = workspaceLabel || boundWorkspace || '';
+ if (!automationWorkspaceBoundMatches(surface, expected, options.cwd)) {
+ const shown = surface.boundWorkspace || surface.boundWorkspaceFull || '(无)';
+ throw new Error('新建任务页当前绑定工作区为 ' + shown + ',与目标 ' + expected + ' 不一致,已停止发送');
+ }
+ boundWorkspace = surface.boundWorkspace || surface.boundWorkspaceFull || boundWorkspace;
+ }
const originalDraftText = surface.composerText;
// WorkBuddy retains the home draft. Preserve it through the existing local
// stash before trusted editor commands replace it; never log the contents.
@@ -6814,18 +7306,18 @@ async function ensureAutomationNewTask(options = {}) {
}
if (!surface || surface.composerText) surface = await readAutomationAgentSurface(false);
if (!surface || !surface.newTaskReady || surface.composerText) throw new Error('新建任务输入框尚未清空,原草稿已保留在暂存');
- return surface;
+ return boundWorkspace ? Object.assign({}, surface, { boundWorkspace, boundWorkspaceCwd }) : surface;
}
let automationAgentCreating = false;
-async function openNewAutomationAgentTask(prompt) {
+async function openNewAutomationAgentTask(prompt, options = {}) {
if (!cdp.connected) throw new Error('CDP 未连接');
if (automationAgentCreating) throw new Error('正在创建 Agent 任务,请稍候');
const text = String(prompt || '').trim();
if (!text || text.length > 50000) throw new Error('Agent 提示词为空或过长');
automationAgentCreating = true;
try {
- await ensureAutomationNewTask();
+ await ensureAutomationNewTask({ cwd: options.cwd, workspace: options.workspace });
// Reuse the tested Slate multiline input and official send-button path.
await sendStashToComposer({ content: { text, items: [] } });
for (let attempt = 0; attempt < 25; attempt++) {
@@ -7513,16 +8005,6 @@ async function restoreNativeAppearanceByCdp() {
await cdpSend('Runtime.evaluate', {
expression: `(async function () {
var WBS_UID = ${JSON.stringify(uid)};
- // 多账号文件同时存在时 daemon 可能无法唯一解析当前 auth;页面 URL
- // 仍带有 WorkBuddy 正在展示的 accountSnapshot,优先用它定位快照。
- try {
- var rawAccount = new URL(location.href).searchParams.get('accountSnapshot');
- for (var decodeAttempt = 0; rawAccount && decodeAttempt < 3; decodeAttempt++) {
- try { rawAccount = decodeURIComponent(rawAccount); } catch (_) { break; }
- }
- var pageAccount = JSON.parse(rawAccount || 'null');
- if (pageAccount && /^[A-Za-z0-9_-]{1,160}$/.test(String(pageAccount.uid || ''))) WBS_UID = String(pageAccount.uid);
- } catch (_) {}
var snapshotKey = 'workdaddy.theme.native-snapshot::' + WBS_UID;
var rawSnapshot = localStorage.getItem(snapshotKey);
if (!rawSnapshot) return { restored: false };
@@ -7847,14 +8329,6 @@ async function applyThemeByCdp(id, options = {}) {
window.__wbsThemeAppearanceGuardToken = (window.__wbsThemeAppearanceGuardToken || 0) + 1;
} catch (_) {}
var WBS_UID = ${JSON.stringify(uid || null)};
- try {
- var rawAccount = new URL(location.href).searchParams.get('accountSnapshot');
- for (var decodeAttempt = 0; rawAccount && decodeAttempt < 3; decodeAttempt++) {
- try { rawAccount = decodeURIComponent(rawAccount); } catch (_) { break; }
- }
- var pageAccount = JSON.parse(rawAccount || 'null');
- if (pageAccount && /^[A-Za-z0-9_-]{1,160}$/.test(String(pageAccount.uid || ''))) WBS_UID = String(pageAccount.uid);
- } catch (_) {}
// WorkDaddy 自定义主题已应用标记:theme-patches 里部分规则用 html[data-wbs-theme] 限定
// 只在 WorkDaddy 内置自定义主题下生效(官方默认主题不激活)。
try { h.setAttribute('data-wbs-theme', ${id === 'default' || id === 'dark' ? "'0'" : "'1'"}); } catch (e) {}
@@ -8238,6 +8712,12 @@ async function clearComposerByCdp() {
*/
async function sendStashToComposer(record) {
if (!cdp.connected) throw new Error('CDP 未连接,无法发送');
+ // A successful click may destroy the old renderer realm before CDP can
+ // return its result. Retry/ignore this only after the send click (or while
+ // confirming that click), where retrying the action could duplicate a message.
+ const isRendererNavigationRace = (error) => /Promise was collected|Execution context was destroyed|Cannot find (?:default execution context|context with specified id)/i.test(
+ String(error && error.message || error),
+ );
log('[quick-phrase-diagnostics] composer:start ' + JSON.stringify({ targetUrl: cdp.targetUrl, itemCount: record && record.content && Array.isArray(record.content.items) ? record.content.items.length : 0 }));
// 等待 AI 空闲:若正在回复,最多等 60 秒;期间前端会提示"等待空闲"
const idle = await waitAiIdle(60000, record.isCancelled ? 100 : 500, record.isCancelled);
@@ -8629,7 +9109,16 @@ async function sendStashToComposer(record) {
const value = submitted.result && submitted.result.value;
if (!value || !value.ok) throw new Error((value && value.error) || 'CodeBuddy 未确认点击发送');
} else {
- await cdpMouseClick('automation:sendPhrase', sv.x, sv.y, { textLen: text.length, button: sv });
+ try {
+ await cdpMouseClick('automation:sendPhrase', sv.x, sv.y, { textLen: text.length, button: sv });
+ } catch (error) {
+ // The official send handler can navigate/rebuild the renderer immediately
+ // after the click. CDP then reports that the Promise or old execution
+ // context was collected even though the message was already submitted.
+ // Do not click again: continue with the receipt/composer confirmation.
+ if (!isRendererNavigationRace(error)) throw error;
+ log('[quick-phrase-diagnostics] send-click navigation race: ' + String(error && error.message || error));
+ }
}
const submittedComposerExpr = `(function(){/* composer-after-submit */
try {
@@ -8654,7 +9143,7 @@ async function sendStashToComposer(record) {
submitState = response.result && response.result.value;
if (submitState && submitState.ok && !submitState.hasContent) break;
} catch (error) {
- if (!/Execution context was destroyed|Cannot find (?:default execution context|context with specified id)/i.test(String(error && error.message || error))) throw error;
+ if (!isRendererNavigationRace(error)) throw error;
}
}
if (!submitState || !submitState.ok || submitState.hasContent) {
@@ -9480,7 +9969,11 @@ function handleApi(req, res) {
if (codeBuddyNative) return (async () => {
await syncCodeBuddyAuth();
if (fs.existsSync(AUTH_FILE)) backupCurrent(DATA_DIR, log);
+ // Keep an explicit user logout from being mistaken for the 1.2.12
+ // native-session loss that the automatic recovery path repairs.
+ const beforeLogout = currentAccount();
if (!await codeBuddyNative.logout()) throw new Error('CodeBuddy 未确认退出');
+ writeCodeBuddyNativeState(beforeLogout && beforeLogout.uid || '', true);
await syncCodeBuddyAuth();
return json(res, 200, {ok:true,quit:false,relaunched:false});
})().catch(error => json(res, 500, {ok:false,error:error.message}));
@@ -9609,6 +10102,13 @@ function handleApi(req, res) {
port: cdp.port,
error: cdp.error,
},
+ client: {
+ // 客户端进程是否在跑 / 调试端口是否可达 / 是否命中"更新后丢失调试端口"状态
+ running: safeClientRunning(),
+ cdpReachable: cdp.connected,
+ needsDebugRelaunch: clientDebugState.needsDebugRelaunch,
+ debugStateUpdatedAt: clientDebugState.updatedAt || null,
+ },
batch: {
running: batchState.running,
total: batchState.total,
@@ -9627,6 +10127,31 @@ function handleApi(req, res) {
return json(res, 200, status);
}
+ // 一键恢复:客户端在运行但调试端口丢失时(通常是官方自动更新后重启),
+ // 用带 --remote-debugging-port 的方式重启客户端以恢复注入。
+ // 放在 PUBLIC_API_PATHS:仅 loopback 可达,与 launcher 同等权限;
+ // 不做静默自动重启,由用户在状态页确认后触发。
+ if (req.method === 'POST' && p === '/api/client/relaunch') {
+ // The flag is deliberately sticky until CDP recovers, so re-check the
+ // process immediately before acting. A stale flag or an unknown probe
+ // must never turn this diagnostic action into an unsolicited launch.
+ const clientRunning = safeClientRunning();
+ if (clientRunning !== true) {
+ return json(res, 409, { ok: false, error: '客户端未在运行,无需重启' });
+ }
+ return (async () => {
+ // Electron is single-instance: spawning the executable while the
+ // update-restarted process is still alive can silently hand the new
+ // arguments to the old instance. Reuse the existing verified shutdown
+ // path before starting the debug-enabled process.
+ await quitWorkBuddy();
+ await relaunchWorkBuddy();
+ resetClientDebugState();
+ log('[cdp] 用户通过一键恢复重启了客户端,等待调试端口恢复');
+ return json(res, 202, { ok: true, pending: true });
+ })().catch((e) => json(res, 500, { ok: false, error: String((e && e.message) || e) }));
+ }
+
// The existing local API authorization gate requires the current profile token.
// Renderer sends no input, account, session or device payload to this route.
if (req.method === 'POST' && p === '/api/usage') {
@@ -9727,10 +10252,14 @@ function handleApi(req, res) {
if (!account) 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' });
+ const now = Date.now();
const resetAt = body && body.resetAt === null ? null : Number(body && body.resetAt);
- if (resetAt !== null && (!Number.isSafeInteger(resetAt) || resetAt < Date.now() - 86400000 || resetAt > Date.now() + 90 * 86400000)) {
+ if (resetAt !== null && (!Number.isSafeInteger(resetAt) || resetAt < now - 86400000 || resetAt > now + 90 * 86400000)) {
return json(res, 400, { ok: false, error: '解封时间无效' });
}
+ if (resetAt !== null && await CREDIT_USAGE_STORE.hasModelRateLimitElsewhere({ uid, modelId, resetAt, now })) {
+ return json(res, 200, { ok: true, skipped: 'duplicate-across-accounts' });
+ }
await CREDIT_USAGE_STORE.saveModelRateLimit({
uid, modelId,
modelName: String(body && body.modelName || '').slice(0, 256),
@@ -9882,11 +10411,22 @@ function handleApi(req, res) {
if (url.searchParams.get('cacheStatus') === '1') return json(res, 200, { ok: true, cacheReady: tokenStatsCacheReady(PROFILE.dataRoot, codeBuddyFiles ? {cacheFile:path.join(DATA_DIR,'token-stats-cache.json')} : {}) });
const days = Math.max(1, Math.min(90, Number(url.searchParams.get('days') || 7)));
const accounts = listAccounts(DATA_DIR);
- return sqliteQuery('SELECT id, user_id FROM sessions WHERE deleted_at IS NULL;')
- .then((rows) => {
- const sessionAccounts = Object.fromEntries(rows.map((row) => [String(row.id || ''), String(row.user_id || '')]).filter((item) => item[0] && item[1]));
+ // CodeDaddy history trees name their own owner, so its usage no longer
+ // depends on the live session registry: conversations deleted in the client
+ // keep their files, and history without a session record must not blank out
+ // a day. Other clients keep resolving owners through the sessions table.
+ const historyOptions = codeBuddyFiles ? codeBuddyFiles.tokenOptions({
+ refresh: url.searchParams.get('refresh') === '1',
+ excludeOwners: codeBuddyForeignOwnerIds(),
+ }) : null;
+ const owners = historyOptions ? Promise.resolve(historyOptions.sessionAccounts)
+ : sqliteQuery('SELECT id, user_id FROM sessions WHERE deleted_at IS NULL;')
+ .then((rows) => Object.fromEntries(rows.map((row) => [String(row.id || ''), String(row.user_id || '')]).filter((item) => item[0] && item[1])));
+ return owners
+ .then((sessionAccounts) => {
const stats = scanTokenStatsCached(PROFILE.dataRoot, {
- ...(codeBuddyFiles ? {...codeBuddyFiles.tokenOptions(rows.map(row=>row.id)),cacheFile:path.join(DATA_DIR,'token-stats-cache.json')} : {}),
+ ...(historyOptions || {}),
+ ...(codeBuddyFiles ? {cacheFile:path.join(DATA_DIR,'token-stats-cache.json')} : {}),
days,
account: url.searchParams.get('account') || '',
model: url.searchParams.get('model') || '',
@@ -10383,7 +10923,7 @@ function handleApi(req, res) {
const uid = uidParam === null ? (((currentAccount() || {}).uid || '').trim()) : uidParam.trim();
const range = url.searchParams.get('range') || '7d';
const rangeMs = sessionRangeMs(range);
- const clauses = ["deleted_at IS NULL"];
+ const clauses = ["deleted_at IS NULL", "COALESCE(is_background_automation, 0) = 0"];
const params = [];
if (uid) { clauses.push('user_id = ?'); params.push(uid); }
// 时间筛选和排序按最近活动/修改时间;旧记录缺字段时回退到创建时间。
@@ -10794,7 +11334,7 @@ function handleApi(req, res) {
try {
const rows = await sqliteQuery(
'SELECT ' + SESSION_COPY_COLUMNS.join(',') +
- " FROM sessions WHERE id = ? AND (user_id = ? OR user_id = '') AND deleted_at IS NULL LIMIT 1;",
+ " FROM sessions WHERE id = ? AND (user_id = ? OR user_id = '') AND deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0 LIMIT 1;",
[id, uid]
);
if (!rows.length) return json(res, 404, { ok: false, error: '当前账号下没有该会话' });
@@ -10820,7 +11360,7 @@ function handleApi(req, res) {
try {
// 1) 取出源会话(含 cwd 用于定位消息文件)
const srcRows = await sqliteQuery(
- "SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id FROM sessions WHERE id IN (" + sqlPlaceholders(ids) + ") AND deleted_at IS NULL;",
+ "SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id FROM sessions WHERE id IN (" + sqlPlaceholders(ids) + ") AND deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0;",
ids
);
if (!srcRows.length) return json(res, 404, { ok: false, error: '源会话不存在' });
@@ -10858,7 +11398,7 @@ function handleApi(req, res) {
try {
const placeholders = sqlPlaceholders(ids);
const before = await sqliteQuery(
- 'SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ') AND deleted_at IS NULL;',
+ 'SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ') AND deleted_at IS NULL AND COALESCE(is_background_automation, 0) = 0;',
ids
);
await sqliteRun(
@@ -10901,7 +11441,15 @@ function handleApi(req, res) {
catch (e) { return json(res, 400, { ok: false, error: e.message }); }
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
if (!ids.every(isValidSessionId)) return json(res, 400, { ok: false, error: '包含无效的会话 ID' });
+ let releaseSessionSync = null;
try {
+ // A copy worker may have already read the source row and be about to
+ // insert/update the destination. Hold the same operation gate used by
+ // account switching so deletion cannot race that write and resurrect
+ // an old task or title after the delete request completes.
+ if (typeof assertAccountSwitchIdle === 'function') {
+ releaseSessionSync = await assertAccountSwitchIdle();
+ }
// 展开目标会话所在的 lineage:其他账号自动复制出的同源副本一并级联删除,
// 避免删除后切走再切回时被 auto-copy 原样复制回来(会话「复活」)。
const requestedSet = new Set(ids.map(String));
@@ -10909,7 +11457,7 @@ function handleApi(req, res) {
const memberIds = Array.from(new Set(members.map((m) => m.id).filter((id) => isValidSessionId(id))));
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 + ');', memberIds);
+ const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ') AND COALESCE(is_background_automation, 0) = 0;', memberIds);
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 || '')));
@@ -10940,7 +11488,10 @@ function handleApi(req, res) {
log(`[sessions-delete] 已真实删除 ${matchedIds.length} 个会话(DB + ${filesRemoved} 项文件,级联副本 ${cascaded})`);
return json(res, 200, { ok: true, deleted: matchedIds.length, requested: ids.length, cascaded, filesRemoved, rulesRemoved });
} catch (e) {
- return json(res, 500, { ok: false, error: e.message });
+ const status = /账号正在切换|会话同步尚未完成/.test(String(e && e.message || '')) ? 409 : 500;
+ return json(res, status, { ok: false, error: e.message });
+ } finally {
+ if (releaseSessionSync) releaseSessionSync();
}
});
}
@@ -11498,7 +12049,7 @@ function handleApi(req, res) {
// readiness promise (which can take the full 5s timeout on a slow
// renderer). The pending injection remains in place and the copy
// worker will yield on it before touching session files.
- await reloadWorkBuddyPage({ waitForInjection: false });
+ await reloadWorkBuddyPage({ waitForInjection: false, account: acct });
reloaded = true;
log('[switch] 已通过 CDP 刷新 WorkBuddy 窗口');
// 某些 renderer 不发送 Page.loadEventFired;给正常 load 事件
@@ -11719,6 +12270,19 @@ function startServer() {
if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
// web/ 调试界面已移除(web 目录不再打包),根路径返回自包含的状态提示页
const c = currentAccount();
+ const needRelaunch = clientDebugState.needsDebugRelaunch;
+ const warnBlock = needRelaunch
+ ? '<div style="max-width:420px;margin:18px auto 0;padding:14px 16px;border:1px solid #7a4a1f;border-radius:10px;background:#2a1c0e;text-align:left">' +
+ '<p style="margin:0 0 8px;color:#f0b35e;font-weight:600">⚠ 检测到客户端需要恢复</p>' +
+ '<p style="margin:0 0 12px;color:#d8c9b0;font-size:13px;line-height:1.6">WorkBuddy 正在运行,但未以调试模式启动(通常是官方自动更新后自行重启导致),WorkDaddy 无法注入面板。点击下方按钮将以调试模式重启客户端,恢复右下角机器人按钮。</p>' +
+ '<button id="wbs-relaunch" style="padding:8px 18px;border:0;border-radius:8px;background:#1f8a4c;color:#fff;font-size:14px;cursor:pointer">重新启动客户端并恢复</button>' +
+ '<p id="wbs-relaunch-msg" style="margin:8px 0 0;color:#9a9aa0;font-size:12px"></p></div>' +
+ '<script>(function(){var b=document.getElementById("wbs-relaunch"),m=document.getElementById("wbs-relaunch-msg");' +
+ 'b.onclick=function(){b.disabled=true;m.textContent="正在重启客户端…";' +
+ 'fetch("/api/client/relaunch",{method:"POST"}).then(function(r){return r.json();}).then(function(j){' +
+ 'm.textContent=j.ok?"已发送重启指令,请等待客户端重新出现":"恢复失败:"+(j.error||"未知错误");b.disabled=false;}).catch(function(e){' +
+ 'm.textContent="请求失败:"+e.message;b.disabled=false;});};})();</script>'
+ : '';
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(
'<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + WORKDADDY_INSTALL_NAME + '</title>' +
@@ -11726,7 +12290,8 @@ function startServer() {
'<div style="text-align:center"><h1 style="margin:0 0 8px">' + WORKDADDY_INSTALL_NAME + ' v' + DAEMON_VERSION + '</h1>' +
'<p style="color:#9a9aa0;margin:0">面板入口:' + PROFILE.name + ' 右下角机器人按钮</p>' +
'<p style="color:#555;font-size:12px;margin-top:16px">守护进程运行中 · CDP ' + (cdp.connected ? '已连接' : '未连接') +
- (c && c.nickname ? ' · 当前账号:' + String(c.nickname).replace(/</g, '&lt;') : '') + '</p></div></body></html>'
+ (c && c.nickname ? ' · 当前账号:' + String(c.nickname).replace(/</g, '&lt;') : '') + '</p>' + warnBlock +
+ '</div></body></html>'
);
}
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
diff --git a/scripts/inject.js b/scripts/inject.js
index 3eef860..f21d6a7 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -1421,8 +1421,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var WBS_LANGUAGE_KEY = 'workdaddy.ui.language';
var WBS_ACCOUNT_MASK_KEY = 'workdaddy.account.mask.' + PROFILE_ID;
var WBS_INITIAL_AUTO_COPY_ALL_KEY = 'workdaddy.initial.autoCopyAllSessions.' + PROFILE_ID;
+ 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 = {
'账号备注': 'Account note',
+ '鼠标悬浮显示账号备注': 'Show account note on hover',
'查看或编辑账号备注': 'View or edit account note',
'暂无备注,点击添加…': 'No note yet. Click to add…',
'未保存 ·': 'Unsaved ·',
@@ -1500,7 +1503,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'派出前当前 Buddy 查询失败': 'Could not load current Buddy before departure', '旅行地点查询失败': 'Could not load travel destinations', 'Buddy 派出失败': 'Buddy departure failed',
'账号 {account}:Buddy 已派出旅行': 'Account {account}: Buddy departed', '账号 {account}:暂无可用旅行地点': 'Account {account}: No travel destinations available', '账号 {account}:尚未选择 Buddy,暂不派出': 'Account {account}: No Buddy selected; skipping departure',
'账号 {account}:今天已经处理过旅行,跳过': 'Account {account}: Travel already handled today; skipping', '账号 {account}:旅行处理失败:{reason}': 'Account {account}: Travel failed: {reason}', '部分账号 Buddy 操作失败,请查看运行记录': 'Some Buddy actions failed. Check the run log.',
- ' 分支到新会话': ' Start a new conversation here', '账号设置': 'Account settings', '排序方式': 'Sort by', '积分不足时的账号切换建议': 'Suggest switching accounts when credits run low',
+ ' 分支到新会话': ' Start a new conversation here', '账号设置': 'Account settings', '悬浮窗口': 'Hover popovers', '排序方式': 'Sort by', '积分不足时的账号切换建议': 'Suggest switching accounts when credits run low',
'查询失败,请重新选择时间重试': 'Query failed. Select a time range to retry.',
'查询已中断,请重新选择时间重试': 'Query interrupted. Select a time range to retry.',
'无法读取查询进度,请重新选择时间重试': 'Could not read progress. Select a time range to retry.',
@@ -1588,6 +1591,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
"Token 用量仅统计本机记录,在不同电脑上查看的数据可能不一致。": "Token usage only includes records on this computer. Figures may differ between computers.",
"会话输入框非空,未覆盖草稿、未发送": "The composer contains a draft. Nothing was overwritten or sent.",
'页面就绪': 'Page ready', '删除选中的': 'Delete selected', '删除中…': 'Deleting…', '删除该自动化任务?': 'Delete this automation task?', '删除选中的自动化任务?': 'Delete selected automation tasks?', '删除后无法恢复。': 'This cannot be undone.', '清除': 'Clear', '清除日志': 'Clear logs', '清除运行日志?': 'Clear run logs?', '仅清除已结束的运行记录。': 'Only completed run records will be cleared.', '清除日志失败': 'Failed to clear logs', '任务已启用': 'Task enabled', '任务已停用': 'Task disabled', '发送中': 'Sending',
+ '鼠标悬浮显示成长计划': 'Show growth plan on hover',
'成长计划读取中': 'Growth plan is loading', '成长计划暂不可用': 'Growth plan is unavailable',
'Buddy 今日旅行已完成': 'Buddy finished traveling today', 'Buddy 旅行中': 'Buddy is traveling', 'Buddy 待领取礼物': 'Buddy gift pending', 'Buddy 已归来,待领奖': 'Buddy returned; reward pending', 'Buddy 在家': 'Buddy is home', 'Buddy 尚未解锁': 'Buddy is not unlocked',
'成长任务': 'Growth tasks', '状态暂不可用': 'Status unavailable', '暂不可用': 'Unavailable', '今日旅行已完成': "Today's travel is complete", '旅行中,预计': 'Traveling, expected ', ' 归来': ' return', '旅行中': 'Traveling', '即将归来': 'Returning soon',
@@ -1811,6 +1815,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'当前模型已触发频率限制,已停止自动发送': 'This model is rate limited; 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.',
'停止旧服务…': 'Stopping old service…', '发现新版本,准备更新…': 'New version available; preparing to update…',
'已应用主题「': 'Theme applied: “', '已恢复官方头像': 'Restored the official avatar', '已应用官方头像': 'Applied the official avatar',
'头像已更新 ✓': 'Avatar updated ✓', '头像处理失败:': 'Avatar processing failed:',
@@ -1956,7 +1961,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'切换中…': 'Switching…', 'Token 用量统计': 'Token usage statistics', ' 分钟后': ' minutes', ' 小时后': ' hours', ' 天后': ' days',
'未设置时间': 'no expiry time', '时间': 'Time', '近 7 天': 'Last 7 days', '近 30 天': 'Last 30 days', '近 90 天': 'Last 90 days',
'账号': 'Account', '全部账号': 'All accounts', '模型': 'Model', '全部模型': 'All models', '刷新': 'Refresh', '刷新统计': 'Refresh statistics', '开始日期': 'From', '结束日期': 'To',
- '每日趋势': 'Daily trend', '暂无趋势数据': 'No trend data', '模型排行': 'Model ranking', ' 次': ' calls', '暂无模型数据': 'No model data', '暂无账号数据': 'No account data'
+ '每日趋势': 'Daily trend', '暂无趋势数据': 'No trend data', '模型排行': 'Model ranking', ' 次': ' calls', '暂无模型数据': 'No model data', '暂无账号数据': 'No account data',
+ // —— 第十六批:客户端调试端口丢失(官方自动更新后重启)状态页与一键恢复 ——
+ '检测到客户端需要恢复': 'Client recovery needed',
+ 'WorkBuddy 正在运行,但未以调试模式启动(通常是官方自动更新后自行重启导致),WorkDaddy 无法注入面板。点击下方按钮将以调试模式重启客户端,恢复右下角机器人按钮。': 'WorkBuddy is running but was not started in debug mode (usually after an official auto-update restart), so WorkDaddy cannot inject the panel. Click the button below to relaunch the client in debug mode and restore the robot button.',
+ '重新启动客户端并恢复': 'Relaunch client and recover',
+ '正在重启客户端…': 'Relaunching client…',
+ '已发送重启指令,请等待客户端重新出现': 'Relaunch requested. Waiting for the client to come back.',
+ '恢复失败:': 'Recovery failed: ', '请求失败:': 'Request failed: ',
+ '客户端未在运行,无需重启': 'Client is not running; no relaunch needed',
+ // —— 第十六批:自动化「新建任务」指定工作区(daemon 侧校验/报错文案) ——
+ '工作区': 'Workspace', '(无)': '(none)',
};
function wbsSystemLanguage() {
var value = String((navigator && (navigator.language || navigator.userLanguage)) || '').toLowerCase();
@@ -2224,6 +2239,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var TOKEN_STATS_ICON =
'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
'<path d="M4 19V5M4 19h16"/><path d="m7 15 3-4 3 2 5-7"/></svg>';
+ // 用量统计刷新:环形箭头(线条风,currentColor 跟随主题)
+ var USAGE_REFRESH_ICON =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
+ '<path d="M20.5 12a8.5 8.5 0 1 1-2.3-5.8"/><path d="M20.5 4.5V9H16"/></svg>';
// 脱敏小眼睛:睁眼 = 明文可见(点击后隐藏);闭眼(斜线) = 已脱敏(点击后显示明文)
var EYE_SVG =
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
@@ -5159,6 +5178,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (messageNavigation) messageNavigation.sync();
scheduleForkButtons();
scheduleFabPos();
+ if (typeof syncGlassComposerTriggerBackgrounds === 'function') syncGlassComposerTriggerBackgrounds();
watchRow();
syncStash(); // 页面切换(欢迎页↔聊天页)后立即重算暂存按钮显隐
if (!findActionRow()) return;
@@ -5166,6 +5186,30 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
syncQueueTags();
wrapQueueReorder();
}
+ // 官方新版 teams 工具条会把背景直接写在 tooltip 触发器的元素样式上,
+ // 主题 CSS 即使带 !important 也可能被 React 重渲染后的内联值盖回去。
+ // 毛玻璃主题下按实际节点写入内联透明背景,并在节点重建时重新应用。
+ function syncGlassComposerTriggerBackgrounds() {
+ var html = document.documentElement;
+ var glass = html && html.getAttribute('data-wbs-theme-id') === 'nebula';
+ var selector = '.teams-container .cr-input-toolbar__right > span.cr-voice-trigger-tooltip,' +
+ '.teams-container .cr-input-toolbar__right > span.cr-context-usage-tooltip-trigger,' +
+ '.teams-container .cr-input-toolbar__right > span.cr-enhance-button-tooltip';
+ document.querySelectorAll(selector).forEach(function (node) {
+ if (glass) {
+ node.style.setProperty('background', 'transparent', 'important');
+ node.style.setProperty('background-color', 'transparent', 'important');
+ node.style.setProperty('box-shadow', 'none', 'important');
+ node.setAttribute('data-wbs-glass-trigger-patched', '1');
+ }
+ else if (node.getAttribute('data-wbs-glass-trigger-patched') === '1') {
+ node.style.removeProperty('background');
+ node.style.removeProperty('background-color');
+ node.style.removeProperty('box-shadow');
+ node.removeAttribute('data-wbs-glass-trigger-patched');
+ }
+ });
+ }
function onInputSync() { if (!alive) return; guardSessionChange(); scheduleFabPos(); syncStash(); syncQueueTags(); wrapQueueReorder(); }
syncThemeAuditRoot();
if (themeAudit) setBuildInterval(syncThemeAuditRoot, 1200);
@@ -5207,7 +5251,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (typeof MutationObserver !== 'undefined') {
bodyObserver = new MutationObserver(scheduleDomChange);
bodyObserver.observe(document.body, { childList: true, subtree: true });
+ var glassThemeObserver = new MutationObserver(syncGlassComposerTriggerBackgrounds);
+ glassThemeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-wbs-theme-id'] });
+ registerDisposer(function () { glassThemeObserver.disconnect(); });
}
+ syncGlassComposerTriggerBackgrounds();
syncStash(); // 初始检查
scheduleForkButtons();
setBuildTimeout(wrapQueueReorder, 800);
@@ -5220,32 +5268,74 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var fabSnapTimer = null;
var FAB_DRAG_THRESHOLD = 6;
var FAB_EDGE_GAP = 22;
- // v2 deliberately ignores the pre-drag/anchor coordinates. Those values
- // could place the button at the top edge (where WorkBuddy's toolbar
- // intercepts the hit), leaving a visible but unusable robot after upgrade.
- var FAB_POSITION_KEY = 'wbs-fab-bottom-v2-' + PROFILE_ID;
- var FAB_LEGACY_POSITION_KEY = 'wbs-fab-bottom-' + PROFILE_ID;
+ // The robot belongs to the conversation area, not to the window, so the
+ // anchor is that element's bottom-right corner. Anchoring to the component
+ // keeps the button beside the chat when the sidebar collapses, the window
+ // resizes, or a right-hand detail panel opens.
+ var FAB_ANCHOR_SELECTORS = [
+ '.teams-container.is-mac .conversation-shell',
+ '.conversation-shell',
+ '.conversation-shell__main',
+ '.teams-main-content',
+ ];
+ // v3 re-anchors the button to the conversation area. v2 stored a
+ // viewport-relative bottom offset, which parked the robot mid-screen
+ // (253px) even though it was asked to sit in the corner; that stale offset
+ // is dropped on purpose. The pre-drag v1 coordinates stay ignored for the
+ // reason recorded before: they could pin the robot under WorkBuddy's
+ // toolbar, leaving it visible but unusable after an upgrade.
+ var FAB_POSITION_KEY = 'wbs-fab-bottom-v3-' + PROFILE_ID;
+ var FAB_RETIRED_POSITION_KEYS = [
+ 'wbs-fab-bottom-v2-' + PROFILE_ID,
+ 'wbs-fab-bottom-' + PROFILE_ID,
+ ];
function readFabBottom() {
try {
var raw = localStorage.getItem(FAB_POSITION_KEY);
var value = Number(raw);
if (raw !== null && raw !== '' && isFinite(value)) return value;
- // Remove the old coordinate so a later downgrade/reinjection cannot
- // immediately restore the broken top-edge position.
- localStorage.removeItem(FAB_LEGACY_POSITION_KEY);
+ for (var i = 0; i < FAB_RETIRED_POSITION_KEYS.length; i++) {
+ // Drop retired coordinates so a downgrade/reinjection cannot restore
+ // a position whose reference point the anchor no longer means.
+ localStorage.removeItem(FAB_RETIRED_POSITION_KEYS[i]);
+ }
return null;
} catch (_) { return null; }
}
+ function readFabAnchorNode() {
+ for (var i = 0; i < FAB_ANCHOR_SELECTORS.length; i++) {
+ var node = document.querySelector(FAB_ANCHOR_SELECTORS[i]);
+ if (!node) continue;
+ var rect = node.getBoundingClientRect();
+ if (rect && rect.width > 0 && rect.height > 0) return node;
+ }
+ return null;
+ }
+
+ // Distance from the viewport edges to the anchor's bottom-right corner plus
+ // the visual gap. Without a usable anchor the viewport corner is the floor.
+ function fabAnchorOffsets() {
+ var node = readFabAnchorNode();
+ if (!node) return { right: FAB_EDGE_GAP, bottom: FAB_EDGE_GAP };
+ var rect = node.getBoundingClientRect();
+ return {
+ right: Math.max(FAB_EDGE_GAP, Math.round(window.innerWidth - rect.right) + FAB_EDGE_GAP),
+ bottom: Math.max(FAB_EDGE_GAP, Math.round(window.innerHeight - rect.bottom) + FAB_EDGE_GAP),
+ };
+ }
+
function clampFabBottom(bottom, height) {
- var max = Math.max(FAB_EDGE_GAP, window.innerHeight - height - FAB_EDGE_GAP);
- return Math.max(FAB_EDGE_GAP, Math.min(max, Number(bottom) || FAB_EDGE_GAP));
+ var floor = fabAnchorOffsets().bottom;
+ var max = Math.max(floor, window.innerHeight - height - FAB_EDGE_GAP);
+ return Math.max(floor, Math.min(max, Number(bottom) || floor));
}
function clampFabRight(right, width) {
- var max = Math.max(FAB_EDGE_GAP, window.innerWidth - width - FAB_EDGE_GAP);
- return Math.max(FAB_EDGE_GAP, Math.min(max, Number(right) || FAB_EDGE_GAP));
+ var floor = fabAnchorOffsets().right;
+ var max = Math.max(floor, window.innerWidth - width - FAB_EDGE_GAP);
+ return Math.max(floor, Math.min(max, Number(right) || floor));
}
function applyFabPosition(fab, right, bottom) {
@@ -5269,13 +5359,38 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
positionFab();
});
}
+ // The conversation area is rebuilt and resized by WorkBuddy (session
+ // switches, detail panel motion), so re-resolve the node and watch its box
+ // instead of trusting the element captured at injection time.
+ var fabAnchorObserver = null;
+ var fabAnchorObserverNode = null;
+ function ensureFabAnchorObserver() {
+ if (typeof ResizeObserver !== 'function') return;
+ var node = readFabAnchorNode();
+ if (node && node === fabAnchorObserverNode && node.isConnected) return;
+ if (fabAnchorObserver) fabAnchorObserver.disconnect();
+ fabAnchorObserverNode = node;
+ if (!node) return;
+ if (!fabAnchorObserver) {
+ fabAnchorObserver = new ResizeObserver(function () { scheduleFabPos(); });
+ }
+ fabAnchorObserver.observe(node);
+ }
+ registerDisposer(function () {
+ if (!fabAnchorObserver) return;
+ fabAnchorObserver.disconnect();
+ fabAnchorObserver = null;
+ fabAnchorObserverNode = null;
+ });
function positionFab() {
var fab = root.querySelector('.wbs-fab');
if (!fab) return;
+ ensureFabAnchorObserver();
if (fab.classList.contains('hidden')) return; // 面板打开时保持隐藏
if (fabDrag) return;
+ var anchor = fabAnchorOffsets();
var saved = readFabBottom();
- applyFabPosition(fab, FAB_EDGE_GAP, saved == null ? FAB_EDGE_GAP : saved);
+ applyFabPosition(fab, anchor.right, saved == null ? anchor.bottom : saved);
}
setBuildTimeout(scheduleFabPos, 600); // 首屏定位
@@ -6436,6 +6551,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function rotationReminderEnabled() {
try { return localStorage.getItem(rotationReminderKey) !== '0'; } catch (_) { return true; }
}
+ function accountNoteHoverEnabled() {
+ try { return localStorage.getItem(WBS_ACCOUNT_NOTE_HOVER_KEY) !== '0'; } catch (_) { return true; }
+ }
+ function growthPlanHoverEnabled() {
+ try { return localStorage.getItem(WBS_GROWTH_PLAN_HOVER_KEY) !== '0'; } catch (_) { return true; }
+ }
+ // 关闭「鼠标悬浮显示账号备注」后,悬浮账号名不应再露出编辑铅笔与提示底框,
+ // 否则悬浮看起来仍在响应。点击(aria-expanded)与键盘聚焦仍保留该操作提示。
+ function applyAccountNoteHoverState() {
+ if (!root) return;
+ root.classList.toggle('wbs-acct-note-hover-off', !accountNoteHoverEnabled());
+ }
+ applyAccountNoteHoverState();
// 账号 pane 初始化:顶部 导出/导入 工具栏 + 列表容器 + 底部退出登录按钮(原 foot 的 logout 迁移到账号 tab)
if (accountsPane) {
accountsPane.innerHTML =
@@ -6566,12 +6694,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div data-fixed-order>' +
'<div class="wbs-account-order-list" role="list" aria-label="固定账号顺序"></div></div>' +
'<label class="wbs-account-settings-toggle"><span>积分不足时的账号切换建议</span><span class="wbs-switch"><input type="checkbox" data-rotation-reminder><span class="wbs-switch-slider"></span></span></label>' +
+ '<div class="wbs-account-settings-section">悬浮窗口</div>' +
+ '<label class="wbs-account-settings-toggle"><span>鼠标悬浮显示账号备注</span><span class="wbs-switch"><input type="checkbox" data-account-note-hover><span class="wbs-switch-slider"></span></span></label>' +
+ '<label class="wbs-account-settings-toggle"><span>鼠标悬浮显示成长计划</span><span class="wbs-switch"><input type="checkbox" data-growth-plan-hover><span class="wbs-switch-slider"></span></span></label>' +
'<div class="wbs-password-error" role="alert"></div><div class="wbs-modal-actions">' +
'<button class="wbs-modal-btn" type="button" data-order-cancel>取消</button>' +
'<button class="wbs-modal-btn wbs-modal-ok" type="button" data-order-save>保存</button></div></div>';
panel.appendChild(mask);
var list = mask.querySelector('.wbs-account-order-list');
mask.querySelector('[data-rotation-reminder]').checked = rotationReminderEnabled();
+ mask.querySelector('[data-account-note-hover]').checked = accountNoteHoverEnabled();
+ mask.querySelector('[data-growth-plan-hover]').checked = growthPlanHoverEnabled();
var busy = false, dragged = null;
function close() {
if (busy) return;
@@ -6649,6 +6782,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
mask.querySelector('[data-order-save]').addEventListener('click', function () {
if (busy) return;
var reminder = mask.querySelector('[data-rotation-reminder]').checked;
+ var noteHover = mask.querySelector('[data-account-note-hover]').checked;
+ var growthHover = mask.querySelector('[data-growth-plan-hover]').checked;
busy = true;
mask.querySelectorAll('button,input').forEach(function (node) { node.disabled = true; });
mask.querySelector('[data-order-save]').textContent = '保存中…';
@@ -6658,7 +6793,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var ranks = new Map(); ordered.forEach(function (a, index) { ranks.set(a.uid, index + 1); });
state.accounts.forEach(function (a) { a.sort = ranks.get(a.uid) || 0; });
try { localStorage.setItem(rotationReminderKey, reminder ? '1' : '0'); } catch (_) {}
+ try { localStorage.setItem(WBS_ACCOUNT_NOTE_HOVER_KEY, noteHover ? '1' : '0'); } catch (_) {}
+ try { localStorage.setItem(WBS_GROWTH_PLAN_HOVER_KEY, growthHover ? '1' : '0'); } catch (_) {}
+ applyAccountNoteHoverState();
if (!reminder) closeRotationNotice();
+ if (!noteHover && typeof closeAccountNotePopover === 'function') closeAccountNotePopover();
+ if (!growthHover && typeof closeDailyProgressPopover === 'function') closeDailyProgressPopover();
sortAccountsByCreditExpiry(); reorderAccountCards();
busy = false; close();
}).catch(function (error) {
@@ -6955,7 +7095,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
listen(accountsPane, 'mouseover', function (event) {
var button = trigger(event.target);
- if (button && !button.contains(event.relatedTarget)) show(button, false);
+ if (accountNoteHoverEnabled() && button && !button.contains(event.relatedTarget)) show(button, false);
});
listen(accountsPane, 'mouseout', function (event) {
var button = trigger(event.target);
@@ -7066,7 +7206,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
setBuildInterval(updateDailyTravelCountdowns, 1000);
listen(accountsPane, 'mouseover', function (event) {
var ring = findRing(event.target);
- if (!ring || ring === activeRing) return;
+ if (!growthPlanHoverEnabled() || !ring || ring === activeRing) return;
show(ring, false);
});
listen(accountsPane, 'mouseout', function (event) {
@@ -7102,6 +7242,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
listen(popup, 'mouseleave', function () { dailyPopoverHovered = false; deferHide(); });
listen(popup, 'pointerdown', function (event) { event.stopPropagation(); });
listen(popup, 'click', function (event) {
+ var closeButton = event.target && event.target.closest ? event.target.closest('[data-wbs-daily-close]') : null;
+ if (closeButton && popup.contains(closeButton) && (!closeButton.hasAttribute || closeButton.hasAttribute('data-wbs-daily-close'))) {
+ event.preventDefault();
+ event.stopPropagation();
+ hide(true);
+ return;
+ }
var button = event.target && event.target.closest ? event.target.closest('[data-wbs-growth-official],[data-wbs-claimed-toggle]') : null;
if (!button || !popup.contains(button)) return;
event.preventDefault();
@@ -7899,7 +8046,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
mask.id = 'wbs-token-stats-modal';
mask.className = 'wbs-modal-mask wbs-usage-modal-mask';
mask.innerHTML = '<div class="wbs-modal wbs-token-stats-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-token-stats-title">' +
- '<div class="wbs-usage-header"><div class="wbs-token-stats-head"><div class="wbs-modal-title" id="wbs-token-stats-title">用量统计</div></div>' +
+ '<div class="wbs-usage-header"><div class="wbs-token-stats-head"><div class="wbs-modal-title" id="wbs-token-stats-title">用量统计</div>' +
+ '<button class="wbs-icon-btn wbs-usage-refresh" type="button" data-usage-refresh title="刷新统计" aria-label="刷新统计">' + USAGE_REFRESH_ICON + '</button></div>' +
'<div class="wbs-usage-tabs"><button type="button" class="active" data-usage-tab="credit">积分</button><button type="button" data-usage-tab="token">Token</button></div></div><div class="wbs-usage-scroll wbs-usage-dashboard">' +
'<div data-usage-pane="token" hidden>' + usageTimeSegmentHtml('token') +
'<div class="wbs-token-source-note">Token 用量仅统计本机记录,在不同电脑上查看的数据可能不一致。</div>' +
@@ -7910,6 +8058,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" data-token-close>关闭</button></div></div>';
root.appendChild(mask);
var body = mask.querySelector('.wbs-token-stats-body');
+ var refreshButton = mask.querySelector('[data-usage-refresh]');
var creditPollTimer = null;
var focusBefore = document.activeElement;
function closeStats() {
@@ -7928,6 +8077,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}, true);
registerDisposer(closeStats);
mask.querySelector('[data-token-close]').addEventListener('click', closeStats);
+ // 刷新重跑当前页签的查询:Token 重新统计本机记录,积分重新查询官方用量。
+ refreshButton.addEventListener('click', function () {
+ if (mask.querySelector('[data-usage-tab].active').getAttribute('data-usage-tab') === 'credit') loadCredits();
+ else load(true);
+ });
mask.addEventListener('click', function (event) { event.stopPropagation(); if (event.target === mask) closeStats(); });
['pointerdown', 'pointerup', 'keyup', 'keypress'].forEach(function (name) { mask.addEventListener(name, function (event) { event.stopPropagation(); }); });
mask.addEventListener('keydown', function (event) {
@@ -8013,6 +8167,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!busy) creditBody.style.visibility = '';
creditSyncOverlay.hidden = !busy || !showOverlay;
mask.querySelectorAll('[data-credit-days]').forEach(function (button) { button.disabled = busy; });
+ refreshButton.disabled = busy;
mask.querySelector('.wbs-credit-query-content').setAttribute('aria-busy', String(busy));
}
function creditQueryFailed(message) {
@@ -8102,17 +8257,18 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
});
});
- function load() {
+ function load(force) {
if (tokenBusy) return;
tokenBusy = true;
var serial = ++tokenReadSerial;
mask.querySelectorAll('[data-token-days]').forEach(function (button) { button.disabled = true; });
+ refreshButton.disabled = true;
overlay.hidden = false;
body.innerHTML = '<div class="wbs-token-stats-loading" role="status">正在读取 Token 用量…</div>';
if (firstLoadTimer) { clearTimeout(firstLoadTimer); firstLoadTimer = null; }
var loadingLabel = overlay.querySelector('span');
loadingLabel.hidden = true;
- var query = '/api/token-stats?days=' + encodeURIComponent(usageDays('token'));
+ var query = '/api/token-stats?days=' + encodeURIComponent(usageDays('token')) + (force ? '&refresh=1' : '');
api('/api/token-stats?cacheStatus=1').then(function (metadata) {
if (!mask.isConnected || serial !== tokenReadSerial) return null;
if (!metadata.cacheReady) {
@@ -8153,7 +8309,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}), { account: tokenNames, model: Object.create(null) }, tokenTrendState, formatTokenCount);
hasStats = true;
- }).catch(function (error) { if (!mask.isConnected || serial !== tokenReadSerial) return; if (hasStats) toast('读取失败:' + (error.message || error), true, root); else body.innerHTML = '<div class="wbs-token-stats-empty">读取失败:' + esc(error.message || error) + '</div>'; }).finally(function () { if (!mask.isConnected || serial !== tokenReadSerial) return; tokenBusy = false; if (firstLoadTimer) { clearTimeout(firstLoadTimer); firstLoadTimer = null; } mask.querySelectorAll('[data-token-days]').forEach(function (button) { button.disabled = false; }); overlay.hidden = true; });
+ }).catch(function (error) { if (!mask.isConnected || serial !== tokenReadSerial) return; if (hasStats) toast('读取失败:' + (error.message || error), true, root); else body.innerHTML = '<div class="wbs-token-stats-empty">读取失败:' + esc(error.message || error) + '</div>'; }).finally(function () { if (!mask.isConnected || serial !== tokenReadSerial) return; tokenBusy = false; if (firstLoadTimer) { clearTimeout(firstLoadTimer); firstLoadTimer = null; } mask.querySelectorAll('[data-token-days]').forEach(function (button) { button.disabled = false; }); refreshButton.disabled = false; overlay.hidden = true; });
}
if (mask.querySelector('[data-usage-tab].active').getAttribute('data-usage-tab') === 'credit') loadCredits(); else load();
}
@@ -10831,8 +10987,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
+ var windowsInstallerOpening = false;
function openWindowsInstaller(prog, btn) {
- if (!btn) return;
+ if (!btn || windowsInstallerOpening) return;
+ windowsInstallerOpening = true;
btn.disabled = true;
btn.textContent = '正在打开…';
appendUpdateLog(prog, '正在打开已校验的安装程序…');
@@ -10843,8 +11001,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
throw rejected;
}
btn.textContent = '安装程序已打开';
- appendUpdateLog(prog, '安装程序已打开,请按提示退出 WorkBuddy 并完成安装。');
+ appendUpdateLog(prog, '安装程序已打开,请到任务栏选择安装窗口;按提示退出 WorkBuddy 后完成安装。');
}).catch(function (error) {
+ windowsInstallerOpening = false;
btn.disabled = false;
btn.textContent = '打开安装程序';
var failure = formatUpdateFailure(error, '无法打开安装程序');
@@ -10853,7 +11012,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
- function showWindowsInstallerReady(prog, btn, card, timer) {
+ function showWindowsInstallerReady(prog, btn, card, timer, keepDisabled) {
if (timer) clearInterval(timer);
appendUpdateLog(prog, '即将打开安装包…');
var bar = card ? card.querySelector('#wbs-update-bar') : null;
@@ -10861,14 +11020,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (bar) bar.style.display = '';
if (barFill) barFill.style.width = '100%';
if (btn) {
- btn.disabled = false;
+ btn.disabled = !!keepDisabled;
btn.textContent = '打开安装程序';
- btn.onclick = function () { openWindowsInstaller(prog, btn); };
+ btn.onclick = keepDisabled ? null : function () { openWindowsInstaller(prog, btn); };
}
}
function openWindowsInstallerAfterDownload(prog, btn, card, timer, resolve, reject) {
- showWindowsInstallerReady(prog, btn, card, timer);
+ if (windowsInstallerOpening) return;
+ windowsInstallerOpening = true;
+ showWindowsInstallerReady(prog, btn, card, timer, true);
api('/api/update-apply', { method: 'POST' }).then(function (result) {
if (!result || !result.ok || !result.opened) {
var rejected = new Error(formatUpdateFailure(result, '无法打开安装程序'));
@@ -10882,6 +11043,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
resolve(true);
}).catch(function (error) {
+ windowsInstallerOpening = false;
var failure = formatUpdateFailure(error, '无法打开安装程序');
appendUpdateLog(prog, failure);
try { toast(failure, true, root); } catch (_) {}
@@ -11473,7 +11635,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
fab.classList.remove('is-dragging');
fab.classList.add('is-snapping');
- applyFabPosition(fab, FAB_EDGE_GAP, bottom);
+ applyFabPosition(fab, fabAnchorOffsets().right, bottom);
syncAutomationStopPosition();
try { localStorage.setItem(FAB_POSITION_KEY, String(Math.round(bottom))); } catch (_) {}
fabDrag = null;
@@ -11708,6 +11870,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var themeSelectionSerial = 0;
function syncThemeSelection(id) {
currentThemeId = ALLOWED_THEMES.indexOf(id) >= 0 ? id : 'default';
+ if (typeof syncGlassComposerTriggerBackgrounds === 'function') syncGlassComposerTriggerBackgrounds();
if (themePane) themePane.querySelectorAll('#wbs-theme-seg input[name="wbs-theme"]').forEach(function (input) {
input.checked = input.value === currentThemeId;
input.closest('.wbs-theme-opt').classList.toggle('active', input.checked);
@@ -12375,10 +12538,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var sessionDirtyUnsubscribe = null;
var sessionDirtyRetryTimer = null;
var sessionDirtyUid = '';
+ var sessionDirtyDisposed = false;
api('/api/current').then(function (current) {
sessionDirtyUid = String(current && current.uid || '').trim();
}).catch(function () {});
- var sessionDirtyTracker = createSessionDirtyTracker(function (payload) {
+ function sendSessionDirtyEvents(payload) {
+ if (sessionDirtyDisposed) return;
var body = payload && Array.isArray(payload) ? { events: payload } : (payload || {});
if (sessionDirtyUid) body.uid = sessionDirtyUid;
api('/api/sessions/dirty', {
@@ -12386,7 +12551,39 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
}).catch(function () {});
- });
+ }
+ var sessionDirtyTracker = createSessionDirtyTracker(sendSessionDirtyEvents);
+ // WorkBuddy 5.7.6 can expose an empty, silent sessionsResource. Keep the
+ // sidebar baseline separate so late resource snapshots cannot reset it.
+ var sessionDirtySidebarTracker = createSessionDirtyTracker(sendSessionDirtyEvents);
+ var sessionDirtySidebarSeen = Object.create(null);
+ var sessionDirtySidebarPrimed = false;
+ function pollSessionDirtySidebar() {
+ if (sessionDirtyDisposed || !WBS_COMPAT || typeof WBS_COMPAT.findConversationListRecords !== 'function') return;
+ var records;
+ try { records = WBS_COMPAT.findConversationListRecords(document); } catch (_) { return; }
+ if (!Array.isArray(records) || !records.length) return;
+ var updates = records.map(function (record) {
+ var value = record || {};
+ return {
+ id: String(value.id || value.sessionId || value.conversationId || '').trim(),
+ title: String(value.title || value.name || ''),
+ customTitle: String(value.customTitle || value.custom_title || ''),
+ updatedAt: Number(value.sortAt || value.updatedAt || value.updated_at || 0),
+ };
+ }).filter(function (update) { return !!update.id; });
+ if (!updates.length) return;
+ if (!sessionDirtySidebarPrimed) {
+ sessionDirtySidebarTracker.baseline(updates);
+ sessionDirtySidebarPrimed = true;
+ } else {
+ updates.forEach(function (update) {
+ update.event = sessionDirtySidebarSeen[update.id] ? 'sessionUpdated' : 'sessionCreated';
+ sessionDirtySidebarTracker.observe(update);
+ });
+ }
+ updates.forEach(function (update) { sessionDirtySidebarSeen[update.id] = true; });
+ }
function sessionDirtyResourceRecords(resource) {
if (!resource || typeof resource.list !== 'function') return null;
try {
@@ -12414,11 +12611,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
sessionDirtyTracker.observe(update);
});
var snapshot = sessionDirtyResourceRecords(resource);
- if (snapshot) snapshot.then(function (records) { sessionDirtyTracker.baseline(records); }).catch(function () {});
+ if (snapshot) snapshot.then(function (records) {
+ if (!sessionDirtyDisposed) sessionDirtyTracker.baseline(records);
+ }).catch(function () {});
return true;
}
bindSessionDirtyMonitor();
+ pollSessionDirtySidebar();
+ var sessionDirtySidebarTimer = setInterval(pollSessionDirtySidebar, 5000);
registerDisposer(function () {
+ sessionDirtyDisposed = true;
+ clearInterval(sessionDirtySidebarTimer);
+ sessionDirtySidebarTracker.destroy();
+ sessionDirtySidebarSeen = Object.create(null);
if (sessionDirtyRetryTimer) { clearTimeout(sessionDirtyRetryTimer); sessionDirtyRetryTimer = null; }
if (typeof sessionDirtyUnsubscribe === 'function') {
try { sessionDirtyUnsubscribe(); } catch (_) {}
@@ -15326,7 +15531,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var pad = function (value) { return String(value).padStart(2, '0'); };
var refreshedAt = time && !isNaN(time.getTime()) ? pad(time.getHours()) + ':' + pad(time.getMinutes()) + ':' + pad(time.getSeconds()) : '尚未刷新';
var spinner = refreshing ? '<i class="wbs-daily-refresh-spinner" aria-hidden="true"></i>' : '';
- var head = '<div class="wbs-daily-popover-head"><strong>成长计划</strong><span class="wbs-daily-refresh-time">' + spinner + (time ? '刷新于 ' : '') + refreshedAt + '</span></div>';
+ var head = '<div class="wbs-daily-popover-head"><strong>成长计划</strong><span class="wbs-daily-popover-head-actions"><span class="wbs-daily-refresh-time">' + spinner + (time ? '刷新于 ' : '') + refreshedAt + '</span><button type="button" class="wbs-daily-popover-close" data-wbs-daily-close title="关闭成长计划" aria-label="关闭成长计划"><svg aria-hidden="true" viewBox="0 0 16 16"><path d="M3 3l10 10M13 3 3 13"/></svg></button></span></div>';
if (!progress) return head + '<div class="wbs-daily-popover-empty">正在刷新成长计划与 Buddy 旅行状态…</div>';
if (progress.status !== 'ready') return head + '<div class="wbs-daily-popover-empty">刷新失败,移开后再次悬浮即可重试</div>';
var growth = progress.growth || {};
@@ -16912,8 +17117,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
css.id = 'wbs-style';
css.textContent = [
'.wbs-root{position:fixed;right:22px;bottom:22px;z-index:2147483647;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-size:13px;color:#1f1f1f;-webkit-font-smoothing:antialiased}',
- '.wbs-root,.wbs-status-popover,.wbs-credit-summary-popover,#wbs-token-stats-modal{--wbs-primary:#22c55e;--wbs-primary-rgb:34,197,94;--wbs-primary-ink:#22c55e;--wbs-primary-soft:rgba(34,197,94,.09);--wbs-primary-soft-hover:rgba(34,197,94,.14)}',
- 'html[data-wbs-theme-id="dark"] .wbs-root,html[data-wbs-theme-id="dark"] .wbs-status-popover,html[data-wbs-theme-id="dark"] .wbs-credit-summary-popover,html[data-wbs-theme-id="dark"] #wbs-token-stats-modal,html[data-wbs-theme-id="cyber-purple"] .wbs-root,html[data-wbs-theme-id="cyber-purple"] .wbs-status-popover,html[data-wbs-theme-id="cyber-purple"] .wbs-credit-summary-popover,html[data-wbs-theme-id="cyber-purple"] #wbs-token-stats-modal,html[data-wbs-theme-id="nebula"] .wbs-root,html[data-wbs-theme-id="nebula"] .wbs-status-popover,html[data-wbs-theme-id="nebula"] .wbs-credit-summary-popover,html[data-wbs-theme-id="nebula"] #wbs-token-stats-modal,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-root,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-status-popover,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-credit-summary-popover,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) #wbs-token-stats-modal{--wbs-primary:#7f77dd;--wbs-primary-rgb:127,119,221;--wbs-primary-ink:#7f77dd;--wbs-primary-soft:rgba(127,119,221,.12);--wbs-primary-soft-hover:rgba(127,119,221,.18)}',
+ '.wbs-root,.wbs-status-popover,.wbs-credit-summary-popover,#wbs-token-stats-modal{--wbs-primary:#22c55e;--wbs-primary-rgb:34,197,94;--wbs-primary-ink:#22c55e;--wbs-primary-soft:rgba(34,197,94,.09);--wbs-primary-soft-hover:rgba(34,197,94,.14);--wbs-series-2:#2563eb;--wbs-series-3:#d2760f;--wbs-series-4:#c026d3;--wbs-series-5:#0d9488;--wbs-series-6:#dc2626;--wbs-series-7:#7c3aed;--wbs-series-8:#7a9c1e;--wbs-series-9:#0891b2;--wbs-series-10:#7c2d12;--wbs-series-11:#db2777;--wbs-series-12:#57534e}',
+ 'html[data-wbs-theme-id="dark"] .wbs-root,html[data-wbs-theme-id="dark"] .wbs-status-popover,html[data-wbs-theme-id="dark"] .wbs-credit-summary-popover,html[data-wbs-theme-id="dark"] #wbs-token-stats-modal,html[data-wbs-theme-id="cyber-purple"] .wbs-root,html[data-wbs-theme-id="cyber-purple"] .wbs-status-popover,html[data-wbs-theme-id="cyber-purple"] .wbs-credit-summary-popover,html[data-wbs-theme-id="cyber-purple"] #wbs-token-stats-modal,html[data-wbs-theme-id="nebula"] .wbs-root,html[data-wbs-theme-id="nebula"] .wbs-status-popover,html[data-wbs-theme-id="nebula"] .wbs-credit-summary-popover,html[data-wbs-theme-id="nebula"] #wbs-token-stats-modal,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-root,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-status-popover,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) .wbs-credit-summary-popover,:is(html[data-theme="dark"],html.cb-dark,body[data-vscode-theme-name*="dark" i]) #wbs-token-stats-modal{--wbs-primary:#7f77dd;--wbs-primary-rgb:127,119,221;--wbs-primary-ink:#7f77dd;--wbs-primary-soft:rgba(127,119,221,.12);--wbs-primary-soft-hover:rgba(127,119,221,.18);--wbs-series-2:#62a8ff;--wbs-series-3:#f0a347;--wbs-series-4:#d959e8;--wbs-series-5:#3ff3e3;--wbs-series-6:#e64c4c;--wbs-series-7:#9a63f7;--wbs-series-8:#b6de5a;--wbs-series-9:#38d4fa;--wbs-series-10:#c9805c;--wbs-series-11:#f071a8;--wbs-series-12:#9f9a93}',
'.wbs-session-usage-summary{position:fixed;z-index:20;display:flex;align-items:center;justify-content:flex-start;gap:10px;box-sizing:border-box;min-height:37px;padding:3px 0 2px;border:0;border-radius:0;background:transparent;color:var(--wb-color-text-primary,#1f1f1f);font-size:14px;font-weight:400;line-height:18px;outline:none;cursor:pointer}',
'.wbs-session-usage-summary:hover,.wbs-session-usage-summary:focus-visible{background:transparent}',
'.wbs-session-usage-summary.is-hidden{visibility:hidden;opacity:0;pointer-events:none}',
@@ -17104,7 +17309,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-row1{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:7px;min-height:26px}',
'.wbs-name-group{display:flex;align-items:center;flex-wrap:wrap;gap:6px;min-width:0}.wbs-checkin-slot{display:inline-flex;align-items:center;flex-wrap:wrap;gap:5px}',
'.wbs-name{font-size:14px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f)}',
- '.wbs-account-name{position:relative;display:inline-flex;align-items:center;min-width:0;max-width:100%;margin:0;padding:0;border:0;background:transparent;font:inherit;text-align:left;cursor:pointer;isolation:isolate}.wbs-account-name .wbs-name{position:relative;z-index:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-account-name:before{content:"";position:absolute;inset:-4px -5px;border:1px solid var(--wb-border-subtle,#e5e7eb);border-radius:7px;background:var(--wb-bg-popover,#fff);box-shadow:0 2px 7px rgba(0,0,0,.08);opacity:0;transition:opacity 200ms ease;pointer-events:none}.wbs-account-name-edit{position:absolute;right:0;top:50%;z-index:2;display:flex;align-items:center;justify-content:center;width:20px;max-width:100%;height:20px;border-radius:3px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#666);opacity:0;transform:translateY(-50%);transition:opacity 200ms ease;pointer-events:none}.wbs-account-name-edit svg{width:13px;height:13px}.wbs-account-name:hover,.wbs-account-name:focus-visible,.wbs-account-name[aria-expanded="true"]{z-index:2}.wbs-account-name:hover:before,.wbs-account-name:focus-visible:before,.wbs-account-name[aria-expanded="true"]:before{opacity:1}.wbs-account-name:hover .wbs-account-name-edit,.wbs-account-name:focus-visible .wbs-account-name-edit,.wbs-account-name[aria-expanded="true"] .wbs-account-name-edit{opacity:1;pointer-events:auto}.wbs-account-name-edit:hover{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-account-name:focus-visible{outline:2px solid var(--wb-accent-primary,var(--wb-color-text-primary,#1f1f1f));outline-offset:4px;border-radius:4px}',
+ '.wbs-account-name{position:relative;display:inline-flex;align-items:center;min-width:0;max-width:100%;margin:0;padding:0;border:0;background:transparent;font:inherit;text-align:left;cursor:pointer;isolation:isolate}.wbs-account-name .wbs-name{position:relative;z-index:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-account-name:before{content:"";position:absolute;inset:-4px -5px;border:1px solid var(--wb-border-subtle,#e5e7eb);border-radius:7px;background:var(--wb-bg-popover,#fff);box-shadow:0 2px 7px rgba(0,0,0,.08);opacity:0;transition:opacity 200ms ease;pointer-events:none}.wbs-account-name-edit{position:absolute;right:0;top:50%;z-index:2;display:flex;align-items:center;justify-content:center;width:20px;max-width:100%;height:20px;border-radius:3px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#666);opacity:0;transform:translateY(-50%);transition:opacity 200ms ease;pointer-events:none}.wbs-account-name-edit svg{width:13px;height:13px}.wbs-account-name:hover,.wbs-account-name:focus-visible,.wbs-account-name[aria-expanded="true"]{z-index:2}.wbs-account-name:hover:before,.wbs-account-name:focus-visible:before,.wbs-account-name[aria-expanded="true"]:before{opacity:1}.wbs-account-name:hover .wbs-account-name-edit,.wbs-account-name:focus-visible .wbs-account-name-edit,.wbs-account-name[aria-expanded="true"] .wbs-account-name-edit{opacity:1;pointer-events:auto}.wbs-account-name-edit:hover{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-root.wbs-acct-note-hover-off .wbs-account-name:hover:not(:focus-visible):not([aria-expanded="true"]) .wbs-account-name-edit{opacity:0;pointer-events:none}.wbs-root.wbs-acct-note-hover-off .wbs-account-name:hover:not(:focus-visible):not([aria-expanded="true"]):before{opacity:0}.wbs-account-name:focus-visible{outline:2px solid var(--wb-accent-primary,var(--wb-color-text-primary,#1f1f1f));outline-offset:4px;border-radius:4px}',
'.wbs-account-note-popover{position:fixed;z-index:2147483647;box-sizing:border-box;width:280px;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);overflow:auto;padding:10px;border:1px solid var(--wb-border-subtle,#e5e7eb);border-radius:12px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 94%,transparent);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);box-shadow:0 10px 30px rgba(0,0,0,.16);color:var(--wb-color-text-primary,#1f1f1f);font:12px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overscroll-behavior:contain}.wbs-account-note-popover[hidden]{display:none}.wbs-account-note-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:7px;font-weight:600}.wbs-account-note-head .wbs-icon-btn{width:22px;height:22px}.wbs-account-note-popover textarea{display:block;box-sizing:border-box;width:100%;min-height:86px;max-height:180px;resize:vertical;padding:8px;border:1px solid var(--wb-border-default,#ddd);border-radius:8px;background:var(--wb-bg-secondary,#f7f8fa);color:inherit;font:inherit;line-height:1.6;overflow-wrap:anywhere;user-select:text}.wbs-account-note-popover textarea::placeholder{color:var(--wb-color-text-secondary,#777)}.wbs-account-note-popover textarea:focus-visible,.wbs-account-note-popover button:focus-visible{outline:2px solid var(--wb-accent-primary,var(--wb-color-text-primary,#1f1f1f));outline-offset:2px}.wbs-account-note-footer{display:flex;align-items:center;gap:6px;margin-top:9px}.wbs-account-note-footer [role="status"]{flex:1;min-width:0;overflow-wrap:anywhere;font-size:11px;color:var(--wb-color-text-secondary,#666)}.wbs-account-note-footer .wbs-modal-btn{flex:none;padding:4px 9px;font-size:11px}.wbs-account-note-footer .primary{background:var(--wb-button-primary-bg,#1f1f1f);border-color:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-account-note-footer .primary:hover:not(:disabled){background:var(--wb-button-primary-bg-hover,var(--wb-button-primary-bg,#333))}.wbs-account-note-footer button:disabled{opacity:.45;cursor:default}',
':is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-account-note-popover{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 94%,transparent);border-color:var(--wb-border-subtle,#3c3e45);color:var(--wb-color-text-primary,#f2f3f5)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-account-name:before{background:var(--wb-bg-popover,#202126);border-color:var(--wb-border-subtle,#3c3e45)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-account-name-edit{background:var(--wb-bg-popover,#202126)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) .wbs-account-note-popover textarea{background:var(--wb-bg-secondary,#292b31);border-color:var(--wb-border-default,#454750)}:is(html.cb-dark,html[data-theme="dark"],body[data-vscode-theme-name*="dark" i]) :is(.wbs-account-note-footer [role="status"],.wbs-account-name-edit){color:var(--wb-color-text-secondary,#b9bdc7)}',
'@media(prefers-reduced-motion:reduce){.wbs-account-name:before,.wbs-account-name-edit{transition:none}}',
@@ -17118,6 +17323,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-status-popover{position:fixed;z-index:2147483647;width:306px;box-sizing:border-box;padding:12px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.14));border-radius:11px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 96%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 16px 42px rgba(20,24,32,.16),inset 0 1px 0 rgba(255,255,255,.5);backdrop-filter:blur(20px) saturate(1.08);-webkit-backdrop-filter:blur(20px) saturate(1.08);font:12px/1.45 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;pointer-events:auto}.wbs-status-popover.is-daily{width:620px;max-width:calc(100vw - 16px);max-height:calc(100vh - 16px);overflow-y:auto;overscroll-behavior:contain;scrollbar-width:none}',
'.wbs-status-popover.is-daily::-webkit-scrollbar,.wbs-growth-task-list::-webkit-scrollbar{display:none}',
'.wbs-status-popover.is-passive{pointer-events:none}.wbs-status-popover.is-credit{height:auto;min-height:0;max-height:calc(100vh - 16px);overflow:auto;overflow-wrap:anywhere}.wbs-status-popover[hidden]{display:none!important}.wbs-daily-popover-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:9px}.wbs-daily-popover-head strong{font-size:13px;font-weight:700;white-space:nowrap}.wbs-daily-popover-head span{color:var(--wb-icon-tertiary,#7c818b);font-size:10px;font-variant-numeric:tabular-nums}.wbs-daily-refresh-time{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}',
+ '.wbs-daily-popover-head-actions{display:inline-flex;min-width:0;align-items:center;justify-content:flex-end;gap:6px}.wbs-daily-popover-close{display:inline-flex;width:22px;height:22px;flex:0 0 22px;align-items:center;justify-content:center;padding:0;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--wb-icon-secondary,var(--wb-color-text-secondary,#666));cursor:pointer}.wbs-daily-popover-close:hover{background:var(--wb-bg-hover,rgba(127,127,127,.12));color:var(--wb-color-text-primary,#1f1f1f)}.wbs-daily-popover-close:focus-visible{outline:2px solid var(--wb-accent-blue,var(--wb-color-text-primary,#1f1f1f));outline-offset:1px}.wbs-daily-popover-close svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round}',
'.wbs-daily-refresh-spinner{width:9px;height:9px;box-sizing:border-box;border:1.5px solid color-mix(in srgb,var(--wbs-ring-growth) 25%,transparent);border-top-color:var(--wbs-ring-growth);border-radius:50%;animation:wbs-daily-spin .72s linear infinite}@keyframes wbs-daily-spin{to{transform:rotate(360deg)}}',
'.wbs-daily-detail{display:grid;grid-template-columns:8px 72px minmax(0,1fr);align-items:center;gap:7px;min-height:31px;margin-top:5px;padding:0 9px;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-daily-detail i,.wbs-credit-tip-value i{display:block;width:8px;height:8px;border-radius:50%;background:currentColor;box-shadow:0 0 0 2px color-mix(in srgb,currentColor 17%,transparent)}.wbs-daily-detail i.growth{color:var(--wbs-ring-growth)}.wbs-daily-detail i.cat{color:var(--wbs-ring-cat)}.wbs-daily-detail i.credit{color:var(--wbs-tip-credit)}.wbs-daily-detail>span{color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-daily-detail b{min-width:0;text-align:right;font-size:11px;font-weight:650;overflow-wrap:anywhere}.wbs-daily-detail.cat-row b{white-space:nowrap;font-variant-numeric:tabular-nums}.wbs-daily-cat-value{display:flex;min-width:0;align-items:center;justify-content:flex-end;gap:8px}.wbs-travel-claim{flex:0 0 auto}',
@@ -17757,14 +17963,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
/* 账号列表容器 + 退出按钮 */
'.wbs-acct-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 14px 9px;border-bottom:1px solid var(--wb-border-subtle,#f0f0f0);background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 25%,transparent);flex-shrink:0}',
'#wbs-account-order-mask{pointer-events:auto;overscroll-behavior:contain}',
- '.wbs-account-order-modal{box-sizing:border-box;width:360px;max-width:calc(100% - 28px);max-height:calc(100% - 28px);display:flex;flex-direction:column;overflow:auto}',
- '.wbs-account-settings-section{font-size:11px;font-weight:600;color:var(--wb-color-text-secondary,#666);margin:8px 0 6px}',
- '.wbs-account-settings-toggle{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:12px 0 6px;padding:10px 0;border-top:1px solid var(--wb-border-subtle,#eee);border-bottom:1px solid var(--wb-border-subtle,#eee);font-size:12px;cursor:pointer}.wbs-account-settings-toggle>span:first-child{min-width:0;line-height:1.4}',
- '.wbs-account-order-modes{display:flex;flex-wrap:wrap;gap:10px 16px;font-size:12px}.wbs-account-order-modes label{display:flex;align-items:center;gap:5px;cursor:pointer}.wbs-account-order-modes input{margin:0;accent-color:var(--wb-button-primary-bg)}',
+ '.wbs-account-order-modal{box-sizing:border-box;width:380px;max-width:calc(100% - 28px);max-height:calc(100% - 28px);display:flex;flex-direction:column;overflow:auto;gap:0}.wbs-account-order-modal>.wbs-modal-title{margin-bottom:3px}',
+ '.wbs-account-settings-section{margin:14px 0 7px;padding-bottom:5px;border-bottom:1px solid var(--wb-border-subtle,#eee);font-size:11px;font-weight:650;line-height:1.35;color:var(--wb-color-text-secondary,#666)}.wbs-account-order-modal>.wbs-modal-title+.wbs-account-settings-section{margin-top:2px}',
+ '.wbs-account-settings-toggle{display:flex;align-items:center;justify-content:space-between;gap:14px;min-height:38px;margin:0 0 6px;padding:7px 9px;border:1px solid var(--wb-border-subtle,#eee);border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 42%,transparent);font-size:12px;cursor:pointer}.wbs-account-settings-toggle>span:first-child{min-width:0;line-height:1.45;overflow-wrap:anywhere}.wbs-account-settings-toggle .wbs-switch{flex:0 0 auto}.wbs-account-order-modal [data-fixed-order]+.wbs-account-settings-toggle{margin-top:14px}',
+ '.wbs-account-order-modes{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px;font-size:12px}.wbs-account-order-modes label{display:flex;min-width:0;align-items:center;gap:7px;padding:8px 9px;border:1px solid var(--wb-border-subtle,#eee);border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 42%,transparent);cursor:pointer;line-height:1.35}.wbs-account-order-modes label:has(input:checked){border-color:var(--wb-button-primary-bg,#1f1f1f);background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 8%,transparent)}.wbs-account-order-modes input{margin:0;accent-color:var(--wb-button-primary-bg);flex:0 0 auto}',
- '.wbs-account-order-list{margin-top:12px;max-height:min(280px,40vh);overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:5px}',
+ '.wbs-account-order-list{margin-top:9px;padding:1px;max-height:min(280px,40vh);overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:5px}',
'.wbs-account-order-row{display:flex;align-items:center;gap:8px;min-height:34px;padding:3px 8px;border:1px solid var(--wb-border-subtle);border-radius:8px;background:var(--wb-bg-secondary);font-size:12px}.wbs-account-order-row>span{flex:1;min-width:0;overflow-wrap:anywhere}.wbs-account-order-row button{cursor:grab}.wbs-account-order-row.dragging{opacity:.45}.wbs-account-order-row.drop-target{border-color:var(--wb-accent-blue);background:var(--wb-bg-hover)}',
- '.wbs-account-order-modal :is(button,input):focus-visible{outline:2px solid var(--wb-accent-blue);outline-offset:2px}.wbs-account-order-modal button:disabled{opacity:.5;cursor:default}',
+ '.wbs-account-order-modal>.wbs-modal-actions{margin-top:14px;padding-top:10px;border-top:1px solid var(--wb-border-subtle,#eee)}.wbs-account-order-modal :is(button,input):focus-visible{outline:2px solid var(--wb-accent-blue);outline-offset:2px}.wbs-account-order-modal button:disabled{opacity:.5;cursor:default}',
+ '@media(max-width:420px){.wbs-account-order-modal{width:100%;max-width:calc(100% - 20px)}.wbs-account-order-modes{grid-template-columns:1fr}}',
+ 'html[data-wbs-theme-id="nebula"] .wbs-account-note-footer .primary{background:rgba(255,255,255,.9) !important;border-color:rgba(255,255,255,.9) !important;color:#11121a !important}.wbs-account-note-footer .primary:focus-visible{outline-color:var(--wb-color-text-primary,#1f1f1f)}html[data-wbs-theme-id="nebula"] .wbs-account-note-footer .primary:disabled{background:rgba(255,255,255,.78) !important;border-color:rgba(255,255,255,.78) !important;color:#34343c !important;opacity:1 !important}',
'.wbs-initial-sync-modal{box-sizing:border-box;width:380px;max-width:calc(100% - 28px)}.wbs-initial-sync-copy{margin:-2px 0 12px;color:var(--wb-color-text-secondary,#666);font-size:11.5px;line-height:1.6;overflow-wrap:anywhere}.wbs-initial-sync-toggle{margin:0 0 10px}.wbs-initial-sync-error{min-height:17px;margin:0 0 2px}.wbs-initial-sync-modal .wbs-modal-actions{justify-content:flex-end}.wbs-initial-sync-modal .wbs-modal-ok{min-width:66px}',
'.wbs-credit-summary-popover{position:fixed;z-index:2147483647;box-sizing:border-box;width:300px;max-width:calc(100vw - 16px);padding:12px;background:var(--wb-bg-popover,var(--wb-bg-primary));color:var(--wb-color-text-primary);border:1px solid var(--wb-border-default);border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.18);font:12px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:transparent transparent;pointer-events:auto}',
'.wbs-credit-summary-head{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px}.wbs-credit-summary-head strong{font-size:13px}.wbs-credit-summary-head span,.wbs-credit-summary-foot{font-size:10px;color:var(--wb-color-text-secondary)}',
@@ -17853,10 +18061,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-token-stats-modal{width:min(980px,calc(100vw - 48px));max-width:calc(100vw - 48px);height:min(84vh,800px);max-height:calc(100vh - 48px);display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--wb-border-default,rgba(20,24,32,.14));border-radius:16px;padding:0;box-shadow:0 24px 80px rgba(15,18,24,.22)}',
'.wbs-usage-header{position:sticky;top:0;z-index:4;flex-shrink:0;padding:20px 22px 0;border-bottom:1px solid var(--wb-border-subtle,#eee);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 94%,transparent);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px)}.wbs-usage-scroll{min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;flex:1;padding:8px 22px 22px}.wbs-usage-dashboard{scrollbar-width:none}.wbs-usage-dashboard::-webkit-scrollbar{display:none}.wbs-token-stats-modal>.wbs-modal-actions{flex-shrink:0;padding:13px 22px;border-top:1px solid var(--wb-border-subtle,#eee);background:var(--wb-bg-popover,#fff)}.wbs-token-stats-modal .wbs-token-model-scroll{overflow:visible}.wbs-token-stats-modal .wbs-token-model-scroll:after{display:none}.wbs-credit-query-content{position:relative;min-height:430px}',
'.wbs-token-stats-head{display:flex;align-items:center;justify-content:space-between;gap:10px}',
+ '.wbs-usage-refresh{flex:0 0 auto}',
+ '.wbs-usage-refresh:hover:not(:disabled){background:var(--wb-bg-tertiary,#e6e8ec);color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-usage-refresh:focus-visible{outline:2px solid currentColor;outline-offset:2px}',
'.wbs-token-source-note{margin:0 0 12px;font-size:11px;line-height:1.6;color:var(--wb-icon-secondary,#667085);overflow-wrap:anywhere}',
'.wbs-usage-tabs{display:flex;gap:18px;margin:13px 0 0;border-bottom:1px solid var(--wb-border-subtle,#eee)}.wbs-usage-tabs button{border:0;border-bottom:2px solid transparent;background:transparent;color:var(--wb-icon-secondary,#667085);padding:7px 2px 9px;font:inherit;font-size:12px;cursor:pointer;transition:color .15s,border-color .15s}.wbs-usage-tabs button.active{border-bottom-color:var(--wb-color-text-primary,#1f1f1f);color:var(--wb-color-text-primary,#1f1f1f);font-weight:700}.wbs-credit-stats-note{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:10px 0;color:var(--wb-icon-secondary,#667085);font-size:11px;line-height:1.5}.wbs-credit-sync{height:26px;padding:0 9px;border:1px solid var(--wb-border-default,#e2e4e8);border-radius:7px;background:var(--wb-bg-tertiary,#f5f6f8);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;font-size:11px;cursor:pointer}.wbs-credit-sync:disabled{opacity:.6;cursor:wait}.wbs-credit-stats-body{min-height:240px}',
'.wbs-usage-period{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:16px 0 12px;color:var(--wb-color-text-secondary,#667085);font-size:11px}.wbs-usage-segment{display:inline-flex;align-items:center;gap:2px;max-width:100%;padding:3px;border:1px solid var(--wb-border-subtle,#eee);border-radius:9px;background:var(--wb-bg-tertiary,#f5f6f8)}.wbs-usage-segment button{min-width:55px;height:27px;padding:0 9px;border:0;border-radius:6px;background:transparent;color:var(--wb-color-text-secondary,#667085);font:inherit;font-size:11px;cursor:pointer;white-space:nowrap}.wbs-usage-segment button.active{background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-primary,#1f1f1f);font-weight:600;box-shadow:0 1px 4px rgba(0,0,0,.1)}.wbs-usage-segment button:disabled{opacity:.55;cursor:wait}.wbs-usage-segment button:focus-visible,.wbs-trend-legend button:focus-visible{outline:2px solid var(--wbs-primary);outline-offset:2px}',
- '.wbs-trend-panel,.wbs-usage-pie-section{--wbs-chart-base:var(--wbs-credit-theme-color,var(--wbs-primary));--wbs-trend-series-1:var(--wbs-chart-base);--wbs-trend-series-2:color-mix(in srgb,var(--wbs-chart-base) 84%,var(--wb-color-text-primary));--wbs-trend-series-3:color-mix(in srgb,var(--wbs-chart-base) 68%,var(--wb-bg-primary));--wbs-trend-series-4:color-mix(in srgb,var(--wbs-chart-base) 52%,var(--wb-bg-primary));--wbs-trend-series-5:color-mix(in srgb,var(--wbs-chart-base) 36%,var(--wb-bg-primary));--wbs-trend-series-6:color-mix(in srgb,var(--wbs-chart-base) 72%,transparent);--wbs-trend-series-7:color-mix(in srgb,var(--wbs-chart-base) 58%,var(--wb-color-text-primary));--wbs-trend-series-8:color-mix(in srgb,var(--wbs-chart-base) 44%,var(--wb-color-text-primary));--wbs-trend-series-9:color-mix(in srgb,var(--wbs-chart-base) 30%,var(--wb-color-text-primary));--wbs-trend-series-10:color-mix(in srgb,var(--wbs-chart-base) 70%,var(--wb-bg-secondary));--wbs-trend-series-11:color-mix(in srgb,var(--wbs-chart-base) 52%,transparent);--wbs-trend-series-12:color-mix(in srgb,var(--wbs-chart-base) 38%,transparent);}',
+ // 分组统计(按账号/按模型):总览沿用主题色,其余序列改用互不相同的色相,
+ // 每个色相在浅色/深色主题各有一份定义(--wbs-series-*),避免同色明度梯变难以区分。
+ '.wbs-trend-panel,.wbs-usage-pie-section{--wbs-chart-base:var(--wbs-credit-theme-color,var(--wbs-primary));--wbs-trend-series-1:var(--wbs-chart-base);--wbs-trend-series-2:var(--wbs-series-2);--wbs-trend-series-3:var(--wbs-series-3);--wbs-trend-series-4:var(--wbs-series-4);--wbs-trend-series-5:var(--wbs-series-5);--wbs-trend-series-6:var(--wbs-series-6);--wbs-trend-series-7:var(--wbs-series-7);--wbs-trend-series-8:var(--wbs-series-8);--wbs-trend-series-9:var(--wbs-series-9);--wbs-trend-series-10:var(--wbs-series-10);--wbs-trend-series-11:var(--wbs-series-11);--wbs-trend-series-12:var(--wbs-series-12)}',
'.wbs-trend-controls{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap;margin-bottom:9px}.wbs-trend-modes{flex-shrink:0}.wbs-trend-modes button{min-width:48px}.wbs-trend-legend{display:flex;align-items:center;gap:6px;flex:1;flex-wrap:wrap;min-width:140px;max-height:74px;overflow-y:auto;scrollbar-width:none}.wbs-trend-legend::-webkit-scrollbar{display:none}.wbs-trend-legend button{display:inline-flex;align-items:center;gap:6px;max-width:165px;height:27px;padding:0 8px;border:1px solid var(--wb-border-subtle,#eee);border-radius:6px;background:var(--wb-bg-popover,#fff);color:var(--wb-color-text-secondary,#667085);font:inherit;font-size:11px;cursor:pointer;opacity:.55}.wbs-trend-legend button.active{opacity:1;color:var(--wb-color-text-primary,#1f1f1f)}.wbs-trend-legend button i{flex:none;width:8px;height:8px;border-radius:50%;background:var(--wbs-series-color);color:var(--wbs-series-color)}.wbs-trend-legend button span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wbs-trend-no-series{font-size:11px;color:var(--wb-color-text-secondary,#667085)}',
'.wbs-token-stats-actions{display:flex;justify-content:flex-end;gap:7px;margin:2px 0 12px}.wbs-token-stats-actions button{height:30px;padding:0 14px;border-radius:7px;font:inherit;font-size:11px;cursor:pointer}.wbs-token-stats-search{border:1px solid var(--wb-button-primary-bg,#1f1f1f);background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}.wbs-token-stats-reset{border:1px solid var(--wb-border-default,#e2e4e8);background:var(--wb-bg-tertiary,#f5f6f8);color:var(--wb-color-text-secondary,#667085)}.wbs-token-stats-actions button:disabled{opacity:.55;cursor:wait}',
'.wbs-token-stats-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}',
diff --git a/scripts/lib.js b/scripts/lib.js
index 7a0de47..f55936a 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -112,6 +112,25 @@ function wdCompatConfiguredExe() {
}
}
+function wdCompatWindowsExeCandidates(options = {}) {
+ const pathApi = path.win32;
+ const localAppData = String(options.localAppData || process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'));
+ const profileId = String(options.profileId || process.env.WBSWITCH_PROFILE || 'workbuddy-cn').trim().toLowerCase();
+ const configured = String(options.configured || '').trim();
+ const candidates = [];
+ // CodeBuddy cannot expose WorkBuddy's storage binding. Keep both official
+ // WorkBuddy binaries available as key providers when importing their
+ // encrypted account backups into a CodeBuddy profile.
+ if (profileId === 'workbuddy-cn' || profileId === 'workbuddy-ai') {
+ if (configured) candidates.push(configured);
+ }
+ candidates.push(
+ pathApi.join(localAppData, 'Programs', 'WorkBuddy', 'WorkBuddy.exe'),
+ pathApi.join(localAppData, 'Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'),
+ );
+ return [...new Set(candidates.filter(Boolean))];
+}
+
function wdCompatExeCandidates() {
if (process.env.WORKDADDY_WB_EXE) return [process.env.WORKDADDY_WB_EXE];
const home = os.homedir();
@@ -125,13 +144,12 @@ function wdCompatExeCandidates() {
return apps;
}
if (IS_WIN) {
- const base = process.env.LOCALAPPDATA || '';
const configured = wdCompatConfiguredExe();
- return [
- ...(configured ? [configured] : []),
- path.join(base, 'Programs', 'WorkBuddy', 'WorkBuddy.exe'),
- path.join(base, 'Programs', 'WorkBuddy AI', 'WorkBuddy AI.exe'),
- ].filter(Boolean);
+ return wdCompatWindowsExeCandidates({
+ localAppData: process.env.LOCALAPPDATA || '',
+ profileId: process.env.WBSWITCH_PROFILE || 'workbuddy-cn',
+ configured,
+ });
}
return ['/opt/WorkBuddy/workbuddy', '/opt/WorkBuddy/workbuddy-ai'];
}
@@ -1868,6 +1886,7 @@ function switchTo(dataDir, uid, log = () => {}) {
module.exports = {
isWbEncryptedEnvelope, // [wd-compat]
wdCompatExeCandidates, // [wd-compat]
+ wdCompatWindowsExeCandidates, // [wd-compat]
wdCompatContainsEncryptedFields, // [wd-compat]
wdCompatText, // [wd-compat]
wdCompatAuthToken, // [wd-compat]
diff --git a/scripts/session-dirty.js b/scripts/session-dirty.js
index 2b0da5d..a477dd5 100644
--- a/scripts/session-dirty.js
+++ b/scripts/session-dirty.js
@@ -52,9 +52,15 @@ function createDirtyIndex(raw) {
const timestamp = Number(at);
if (!item || !id || !Number.isFinite(timestamp) || timestamp <= 0) return null;
const previous = item.sessions[id];
- const marker = { at: timestamp, event: String(event || 'sessionUpdated').slice(0, 40) };
+ // Once a physical member has received synced content, later renderer
+ // lifecycle notifications must not turn its cross-account eligibility
+ // back into a marker consumed by one destination. Mapping revisions
+ // decide which destinations still need work; keep the latest timestamp
+ // for concurrent-event guards.
+ const marker = { at: timestamp, event: previous && previous.event === 'sessionSynced'
+ ? 'sessionSynced' : String(event || 'sessionUpdated').slice(0, 40) };
item.sessions[id] = marker;
- return previous && previous.at === marker.at ? previous : marker;
+ return previous && previous.at === marker.at && previous.event === marker.event ? previous : marker;
},
get(uid, sessionId) {
const item = account(uid, false);
diff --git a/scripts/theme-patches.js b/scripts/theme-patches.js
index 08905ca..23e06c6 100644
--- a/scripts/theme-patches.js
+++ b/scripts/theme-patches.js
@@ -515,6 +515,12 @@ module.exports = [
desc: '毛玻璃下文件链接与代码复制控件透明:外层 tooltip 触发器不应有弹窗底色,内层文件标签使用独立的 cr-symbol 背景变量,也需单独清除。',
css: 'html[data-wbs-theme-id="nebula"] body[data-vscode-theme-name] .cr-clickable-path-tooltip-anchor,html[data-wbs-theme-id="nebula"] body[data-vscode-theme-name] .cr-clickable-path,html[data-wbs-theme-id="nebula"] body[data-vscode-theme-name] .cr-code-block__copy-tooltip,html[data-wbs-theme-id="nebula"] body[data-vscode-theme-name] .cr-code-block__copy-button{background:transparent !important;}',
},
+ {
+ id: 'patch-107',
+ themeId: 'nebula',
+ desc: '毛玻璃主题下新版 teams 输入工具条的语音、上下文用量和增强按钮触发器去掉背景色,避免右侧出现多余色块。',
+ css: ':is(html.cb-dark,html[data-theme="dark"]) body[data-vscode-theme-name] .teams-container .cr-input-toolbar__right>span:is(.cr-voice-trigger-tooltip,.cr-context-usage-tooltip-trigger,.cr-enhance-button-tooltip),body[data-vscode-theme-name="IDE Night"] .teams-container .cr-input-toolbar__right>span:is(.cr-voice-trigger-tooltip,.cr-context-usage-tooltip-trigger,.cr-enhance-button-tooltip){background:transparent !important;background-color:transparent !important;box-shadow:none !important;backdrop-filter:none !important;-webkit-backdrop-filter:none !important;}',
+ },
/* 原 patch-82(AI 端快捷短语弹层 z-index 抬升)已移入 inject.js 常驻样式:
theme-patches 仅在非默认主题时注入,默认浅色主题下会失效;层级修复不依赖主题,随注入脚本常驻更可靠。 */
];
diff --git a/scripts/toast-options.js b/scripts/toast-options.js
index b380436..f45411a 100644
--- a/scripts/toast-options.js
+++ b/scripts/toast-options.js
@@ -19,8 +19,8 @@ function normalizeToastOptions(input = {}, dismiss = false) {
}
module.exports = { normalizeToastOptions };
-// Each run owns a namespace: identical task ids cannot update/dismiss another
-// run's notifications or ordinary WorkDaddy UI notifications.
+// Each notifier uses a namespace: ordinary runs stay isolated, while callers
+// that intentionally share a task namespace can update the same status toast.
function createAutomationNotifier(send, namespace) {
const active = new Map();
let nextId = 0;
diff --git a/scripts/token-stats.js b/scripts/token-stats.js
index 96568ba..696472a 100644
--- a/scripts/token-stats.js
+++ b/scripts/token-stats.js
@@ -441,6 +441,10 @@ function scanTokenStatsCached(root, options = {}) {
const hadValidCache = usableCache(cache, now);
const currentFiles = Array.isArray(options.files) ? options.files : walkJsonl(root, options.maxFiles || 5000);
const todayFiles = {};
+ // A scan that reuses every cached file changes nothing on disk, so rewriting
+ // the (often multi-megabyte) cache only costs time. Skip it then: the cutoff
+ // may stay older than today's, which is still within the retained range.
+ let changed = !hadValidCache;
let parsedLines = 0, parseErrors = 0;
const parseErrorFiles = new Set();
for (const currentFile of currentFiles) {
@@ -456,6 +460,7 @@ function scanTokenStatsCached(root, options = {}) {
files: [currentFile] });
item = { mtimeMs: stat.mtimeMs, size: stat.size, entries: parsed.records,
parsedLines: parsed.parsedLines, parseErrors: parsed.parseErrors, parseErrorFiles: parsed.parseErrorFiles };
+ changed = true;
}
item.entries = item.entries.filter(entry => entry.timestamp >= cutoff);
todayFiles[relative] = item;
@@ -463,11 +468,18 @@ function scanTokenStatsCached(root, options = {}) {
parseErrors += item.parseErrors || 0;
for (const errorFile of item.parseErrorFiles || []) parseErrorFiles.add(errorFile);
}
+ if (hadValidCache) {
+ // A file may also appear or disappear while the scan runs.
+ const previousKeys = Object.keys(cache.todayFiles);
+ if (previousKeys.length !== Object.keys(todayFiles).length ||
+ previousKeys.some((key) => !todayFiles[key])) changed = true;
+ }
const records = Object.values(todayFiles).flatMap(item => item.entries);
const buckets = aggregateBuckets(distinctRecords(records, options));
- const cacheReady = writeCache(file, { version: CACHE_VERSION, generatedAt: now, cutoff,
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
- historicalBuckets: [], todayFiles });
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ const cacheReady = !changed && cache.cutoff === cutoff && cache.timezone === timezone
+ ? true : writeCache(file, { version: CACHE_VERSION, generatedAt: now, cutoff,
+ timezone, historicalBuckets: [], todayFiles });
const stats = aggregateCachedBuckets(buckets, { ...options, now });
return { ...stats, files: currentFiles.length, parsedLines, parseErrors,
parseErrorFiles: Array.from(parseErrorFiles), cached: hadValidCache, cacheHit: hadValidCache,
diff --git a/scripts/workbuddy-compat.js b/scripts/workbuddy-compat.js
index ccf9899..1ecbce7 100644
--- a/scripts/workbuddy-compat.js
+++ b/scripts/workbuddy-compat.js
@@ -391,14 +391,36 @@
return findModernQueueAdapter(doc) || findLegacyQueueAdapter(doc);
}
+ // The conversation-list click handler is the only public path that performs
+ // the real route transition. Its minified body is rewritten between releases,
+ // so match a group of stable string/property markers instead of one release's
+ // private symbols. Groups are OR'd with each other; markers inside a group are
+ // AND'd. Prefer the newest group first so a build that carries several marker
+ // sets is classified by the current contract.
+ var CONVERSATION_NAVIGATION_MARKER_GROUPS = [
+ // WorkBuddy >= 5.7: ConversationList loader. Dedupes on loadSession, reads
+ // options.conversationEngineRouteTarget and honours preserveListView.
+ ['preserveListView', 'conversationEngineRouteTarget', 'loadSession'],
+ // WorkBuddy <= 5.6: hover peek dismissal plus task route sync. Both symbols
+ // were dropped in 5.7, so this group only matches older renderers.
+ ['dismissHoverPeek', 'syncTaskRouteFromClick'],
+ ];
+
function functionLooksLikeConversationNavigation(value, nativeCodeBuddy) {
if (typeof value !== 'function') return false;
try {
var source = Function.prototype.toString.call(value);
if (nativeCodeBuddy && source.indexOf('SessionLoadCancelledError') >= 0 &&
source.indexOf('getPendingMessageTracker') >= 0 && source.indexOf('getInitialMessages') >= 0) return true;
- return source.indexOf('dismissHoverPeek') >= 0 &&
- source.indexOf('syncTaskRouteFromClick') >= 0;
+ for (var gi = 0; gi < CONVERSATION_NAVIGATION_MARKER_GROUPS.length; gi++) {
+ var group = CONVERSATION_NAVIGATION_MARKER_GROUPS[gi];
+ var matched = true;
+ for (var mi = 0; mi < group.length; mi++) {
+ if (source.indexOf(group[mi]) < 0) { matched = false; break; }
+ }
+ if (matched) return true;
+ }
+ return false;
} catch (_) {
return false;
}
@@ -447,9 +469,10 @@
return isSessionsResource(resource) ? resource : null;
}
- // WorkBuddy's conversation list owns the real navigation path. Prefer the
- // official SDK/navigation handler; adapter.emit is retained for older builds
- // whose list did not expose the handler through React hooks.
+ // WorkBuddy's conversation list owns the real navigation path, so prefer the
+ // official handler found in its React hooks (or the session-navigation SDK
+ // when a build exposes it). adapter.emit is retained for older builds whose
+ // list did not expose the handler at all.
function findConversationActivationApi(doc, options) {
var nativeCodeBuddy = !!(options && /^codebuddy-(cn|intl)$/.test(options.profileId));
var found = findQueueAdapter(doc);
@@ -457,18 +480,15 @@
var resource = findSessionsResource(doc);
var handler = findConversationNavigationHandler(doc, nativeCodeBuddy);
var sdkNavigate = null;
- var sdkNavigateKind = '';
try {
var conversations = typeof window !== 'undefined' && window.wb && window.wb.conversations;
+ // Only a real route transition may be treated as authoritative. The
+ // sibling `setCurrentConversation` looks similar but merely reports the
+ // active conversation to the main process; it never navigates, so a
+ // fallback onto it produced an "official-dispatched" log with no page
+ // change and retried until the activation timeout.
if (conversations && typeof conversations.navigateToSession === 'function') {
sdkNavigate = conversations.navigateToSession;
- sdkNavigateKind = 'navigateToSession';
- } else if (conversations && typeof conversations.setCurrentConversation === 'function') {
- // Current WorkBuddy exposes the official route transition under this
- // SDK name. It is authoritative even while React has not mounted the
- // sidebar handler yet, which is the common post-reload window.
- sdkNavigate = conversations.setCurrentConversation;
- sdkNavigateKind = 'setCurrentConversation';
}
} catch (_) {}
if (!handler && !sdkNavigate && (nativeCodeBuddy || !adapter || typeof adapter.emit !== 'function')) return null;
@@ -499,7 +519,7 @@
Promise.resolve(handler(id, '', false, false, nativeCodeBuddy ? undefined : {})).catch(function () {});
} else if (sdkNavigate) {
var conversationsApi = (typeof window !== 'undefined' && window.wb && window.wb.conversations) || null;
- Promise.resolve(sdkNavigate.call(conversationsApi, id, sdkNavigateKind === 'navigateToSession' ? { ensureLoaded: true } : undefined)).catch(function () {});
+ Promise.resolve(sdkNavigate.call(conversationsApi, id, { ensureLoaded: true })).catch(function () {});
} else {
adapter.emit('jump-to-conversation', {
source: 'tencent-docs',
diff --git a/test/account-snapshot-reload.test.js b/test/account-snapshot-reload.test.js
new file mode 100644
index 0000000..cace5ba
--- /dev/null
+++ b/test/account-snapshot-reload.test.js
@@ -0,0 +1,120 @@
+'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 oldSnapshot = { version: 1, uid: 'old', nickname: '旧账号', type: 'enterprise', savedAt: 1, editionType: 'free', enterpriseId: 'old-company' };
+function harness(options = {}) {
+ const url = new URL('file:///app/renderer/index.html?locale=zh-CN&windowKind=main&extra=a%26b#chat');
+ if (!options.noSnapshot) url.searchParams.set('accountSnapshot', encodeURIComponent(JSON.stringify(oldSnapshot)));
+ const location = { href: url.href };
+ const calls = [], logs = [];
+ let armed = false, settled = false, profileReads = 0, initialAccount;
+ let live = { uid: 'target', nickname: '新账号 % &', type: 'personal', editionType: 'experience', isPro: false, accessToken: 'synthetic-secret' };
+ if (Object.hasOwn(options, 'profile')) live = options.profile;
+ const renderer = { URL, location, wb: options.missingApi ? undefined : { account: { profile: async () => {
+ profileReads++;
+ if (options.profileThrows) throw new Error('synthetic-secret');
+ return live;
+ } } } };
+ const boot = () => {
+ // WorkBuddy index.html decodes once after URLSearchParams (Electron double encoding).
+ const raw = new URL(location.href).searchParams.get('accountSnapshot');
+ initialAccount = raw ? JSON.parse(decodeURIComponent(raw)) : null;
+ };
+ const ctx = {
+ 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) }; },
+ settlePendingReloadInjection: () => { settled = true; },
+ cdpSend: async (method, params) => {
+ calls.push({ method, params });
+ if (method === 'Page.getFrameTree') return { frameTree: { frame: { id: 'main' } } };
+ if (method === 'Runtime.evaluate') {
+ if (options.evaluateThrows) throw new Error('synthetic-secret');
+ if (options.exceptionDetails) return { exceptionDetails: { text: 'synthetic-secret' } };
+ return { result: { value: await vm.runInNewContext(params.expression, renderer) } };
+ }
+ assert.equal(armed, true, 'arm injection before navigation or reload');
+ if (method === 'Page.navigate') {
+ if (options.navigateThrows) throw new Error('synthetic-secret');
+ if (options.navigateError) return { errorText: 'synthetic-secret' };
+ location.href = params.url; boot(); return { frameId: 'main', loaderId: 'next' };
+ }
+ if (method === 'Page.reload') {
+ if (options.reloadThrows) throw new Error('reload failed');
+ boot(); return {};
+ }
+ throw new Error('unexpected CDP method: ' + method);
+ },
+ };
+ const start = source.indexOf('async function reloadWorkBuddyPage(');
+ vm.runInNewContext(source.slice(start, source.indexOf('\nconst WORKBUDDY_TARGET', start)), ctx);
+ return { calls, logs, location, initial: () => initialAccount, settled: () => settled, reads: () => profileReads,
+ run: (opts = {}) => ctx.reloadWorkBuddyPage({ account: opts.account === undefined ? { uid: 'target' } : opts.account, ...opts }) };
+}
+
+test('switch rebuilds the first-screen account from the matching live profile', async () => {
+ const h = harness();
+ assert.equal(await h.run(), true);
+ assert.equal(h.initial().uid, 'target');
+ assert.equal(h.initial().nickname, '新账号 % &');
+ assert.equal(h.initial().type, 'personal');
+ assert.equal(h.initial().version, 1);
+ assert.equal(h.initial().editionType, 'experience');
+ assert.equal(h.initial().isPro, false);
+ assert.ok(h.initial().savedAt > 1);
+ assert.equal(h.initial().enterpriseId, undefined, 'never inherit previous-account optional fields');
+ assert.equal(h.initial().accessToken, undefined, 'copy only the official public snapshot fields');
+ const next = new URL(h.location.href);
+ assert.equal(next.searchParams.get('locale'), 'zh-CN');
+ assert.equal(next.searchParams.get('windowKind'), 'main');
+ assert.equal(next.searchParams.get('extra'), 'a&b');
+ assert.equal(next.hash, '#chat');
+ assert.deepEqual(h.calls.map(c => c.method).filter(m => m.startsWith('Page.') && m !== 'Page.getFrameTree'), ['Page.navigate']);
+});
+
+for (const options of [
+ { missingApi: true }, { profile: null }, { profile: { uid: 'old', nickname: '旧账号', type: 'personal' } },
+ { profileThrows: true }, { evaluateThrows: true }, { exceptionDetails: true },
+ { navigateError: true }, { navigateThrows: true },
+]) test('snapshot failure falls back to reload without leaking profile or CDP details: ' + JSON.stringify(options), async () => {
+ const h = harness(options);
+ assert.equal(await h.run(), true);
+ assert.equal(h.calls.at(-1).method, 'Page.reload');
+ assert.doesNotMatch(h.logs.join('\n'), /synthetic-secret|accountSnapshot=/);
+});
+
+for (const options of [{ kind: 'codebuddy' }]) test('clients without the WorkBuddy snapshot contract keep normal reload: ' + JSON.stringify(options), async () => {
+ const h = harness(options);
+ await h.run();
+ assert.equal(h.calls.at(-1).method, 'Page.reload');
+ assert.equal(h.reads(), 0);
+});
+
+test('ordinary reload does not rewrite the account URL', async () => {
+ const h = harness();
+ await h.run({ account: null });
+ assert.equal(h.initial().uid, 'old');
+ assert.equal(h.reads(), 0);
+});
+
+test('manual switch returns without waiting for injection; automation still waits', async () => {
+ const pending = new Promise(() => {});
+ assert.equal(await harness({ ready: pending }).run({ waitForInjection: false }), true);
+ let finish, done = false;
+ const h = harness({ ready: new Promise(resolve => { finish = resolve; }) });
+ const run = h.run().then(() => { done = true; });
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(done, false);
+ finish(true); await run;
+ assert.equal(done, true);
+});
+
+test('failed fallback releases the pending injection', async () => {
+ const h = harness({ navigateError: true, reloadThrows: true });
+ await assert.rejects(h.run(), /reload failed/);
+ assert.equal(h.settled(), true);
+});
diff --git a/test/automation-checkin.test.js b/test/automation-checkin.test.js
index 439023a..c8a4fae 100644
--- a/test/automation-checkin.test.js
+++ b/test/automation-checkin.test.js
@@ -125,6 +125,13 @@ test('model rate limit route and account snapshots expose only structured 6004 r
assert.match(accounts, /modelRateLimits/);
});
+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, /skipped: 'duplicate-across-accounts'/);
+ assert.match(route, /resetAt !== null/);
+});
+
test('failed or stale cache records never suppress today\'s check-in request', async () => {
for (const cached of [
{date:'2026-09-08',ok:false,verified:false,code:0,message:'HTTP 500'},
diff --git a/test/automation-popup-dismiss.test.js b/test/automation-popup-dismiss.test.js
index eb0c868..3c5ab41 100644
--- a/test/automation-popup-dismiss.test.js
+++ b/test/automation-popup-dismiss.test.js
@@ -3,8 +3,10 @@
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 automation = require('../scripts/automation');
function runPopupTask(appearAt, failedConfirmations = 0) {
let now = 0;
@@ -75,6 +77,63 @@ test('activity fallbacks do not depend on localized text and broad popup selecto
assert.ok(values.every(value => !value.startsWith('//*[')));
});
+test('popup cleanup notifications keep one toast per popup across navigation reruns', async () => {
+ const task = JSON.parse(fs.readFileSync(path.join(__dirname, '../scripts/builtin/automations/close-buddy-popups.json'), 'utf8'));
+ const notifications = [];
+ const walk = value => {
+ if (Array.isArray(value)) return value.forEach(walk);
+ if (!value || typeof value !== 'object') return;
+ if (value.op === 'notify.toast') notifications.push(value);
+ Object.values(value).forEach(walk);
+ };
+ walk(task.steps);
+ assert.deepEqual(notifications.map(step => step.id), ['fuel-close', 'playbooks-close', 'growth-close', 'activity-close']);
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+ assert.match(source, /function automationNotificationNamespace\(task, runId\)/);
+ assert.match(source, /taskIsPassiveCleanup\(task\)\s*\?\s*'automation-task:'\s*\+\s*task\.id/);
+ const helperStart = source.indexOf('function automationNotificationNamespace(');
+ const helperEnd = source.indexOf('\nfunction startAutomationRun(', helperStart);
+ const helperContext = { taskIsPassiveCleanup: value => value.id === task.id };
+ vm.createContext(helperContext);
+ vm.runInContext(source.slice(helperStart, helperEnd), helperContext);
+ assert.equal(helperContext.automationNotificationNamespace(task, 'run-a'), 'automation-task:buddy-fuel-station-close-on-account-switch');
+ assert.equal(helperContext.automationNotificationNamespace({ id: 'custom' }, 'run-b'), 'automation:run-b');
+ const { createAutomationNotifier } = require('../scripts/toast-options');
+ const calls = [];
+ const send = async detail => { calls.push(detail); };
+ await createAutomationNotifier(send, 'automation-task:popup').show('success', '已关闭', { id: 'growth-close' });
+ await createAutomationNotifier(send, 'automation-task:popup').show('success', '已关闭', { id: 'growth-close' });
+ assert.equal(calls[0].id, calls[1].id);
+});
+
+test('popup builtin revision upgrades existing managed installs with notification ids', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-popup-builtin-'));
+ const presetPath = path.join(__dirname, '../scripts/builtin/automations/close-buddy-popups.json');
+ const oldPath = path.join(dir, 'old-popup.json');
+ try {
+ const current = JSON.parse(fs.readFileSync(presetPath, 'utf8'));
+ const old = JSON.parse(JSON.stringify(current));
+ old.revision = 2;
+ old.upgradeFromContentHashes = ['7409d4d92618b59326e56629f4d9ba804ae30a4e36d7d5ed156042b9a3a744bd'];
+ const stripIds = value => {
+ if (Array.isArray(value)) return value.forEach(stripIds);
+ if (!value || typeof value !== 'object') return;
+ if (value.op === 'notify.toast') delete value.id;
+ Object.values(value).forEach(stripIds);
+ };
+ stripIds(old.steps);
+ fs.writeFileSync(oldPath, JSON.stringify(old));
+ automation.installBuiltinTask(dir, oldPath);
+ const result = automation.installBuiltinTask(dir, presetPath);
+ const upgraded = automation.readAutomations(dir)[0];
+ assert.equal(result.status, 'upgraded');
+ assert.equal(upgraded.revision, 3);
+ assert.deepEqual(upgraded.steps[0].steps.map(step => step.steps && step.steps.find(child => child.op === 'notify.toast')?.id).filter(Boolean), ['fuel-close', 'playbooks-close', 'growth-close', 'activity-close']);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test('absent fuel popup does not delay other popups, including one rendered later', async () => {
const result = await runPopupTask(selector => selector.includes('fuel-compact') ? null : /activity-bubble|claw-welcome-activity|pointer-events: auto/.test(selector) ? 1100 : 0);
assert.deepEqual(result.clicks.map(click => click.at), [0, 0, 1200]);
@@ -190,6 +249,7 @@ test('a running cleanup stops before the next navigation begins its own cleanup'
listAccounts: () => [], currentAccount: () => null, automationSwitchAccount: noop,
automationAccountStatus: noop, automationHttpRequest: noop, automationDomAction: noop,
automationNotifyToast: noop, createAutomationNotifier: require('../scripts/toast-options').createAutomationNotifier,
+ automationNotificationNamespace: () => 'automation:test',
executeTask: async (_, deps) => { executions.push(deps); if (executions.length === 1) await active; return {}; },
};
const dispatchStart = source.indexOf('function dispatchAutomationEvent(');
diff --git a/test/automation-workspace-binding.test.js b/test/automation-workspace-binding.test.js
new file mode 100644
index 0000000..b8dabf7
--- /dev/null
+++ b/test/automation-workspace-binding.test.js
@@ -0,0 +1,172 @@
+'use strict';
+// 覆盖「新建会话落到指定工作区」:session.create 带 cwd / workspace 时,
+// 必须走侧栏工作区自己的「新建任务」入口(hover-only 按钮),并在发送前校验绑定。
+const test = require('node:test'), assert = require('node:assert/strict'), fs = require('node:fs'), vm = require('node:vm'), path = require('node:path');
+
+const source = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
+const begin = source.indexOf('function normalizeAutomationWorkspaceCwd(');
+const end = source.indexOf('let automationAgentCreating =', begin);
+assert.ok(begin > 0 && end > begin, '无法定位工作区相关实现片段');
+const slice = source.slice(begin, end);
+
+// 「脚本化页面」替身:悬停让 hover-only 按钮显形,点击让新建任务页绑定到该工作区。
+function harness({ workspaces = [], boundWorkspace = null, boundWorkspaceFull = null, boundWorkspaceCwd = null, newTaskReady = false, hasComposer = false, composerText = '', genericButton = null, bindOnClick = true, escapeFromRead = 0, escapeTo = null } = {}) {
+ const state = {
+ workspaces: workspaces.map((item) => ({ ...item })),
+ boundWorkspace, boundWorkspaceFull, boundWorkspaceCwd, newTaskReady, hasComposer, composerText,
+ button: genericButton,
+ };
+ let clock = 0, reads = 0;
+ const calls = [];
+ const find = (predicate) => state.workspaces.find(predicate);
+ const read = () => {
+ reads += 1;
+ if (escapeFromRead && escapeTo && reads >= escapeFromRead) state.boundWorkspace = state.boundWorkspaceFull = escapeTo;
+ return JSON.parse(JSON.stringify(state));
+ };
+ const ctx = {
+ cdp: { connected: true },
+ Date: { now: () => clock },
+ sleep: async (ms) => { clock += Number(ms) || 0; },
+ log: () => {},
+ automationAgentSurfaceExpression: () => '({})',
+ readAutomationAgentSurface: async () => read(),
+ cdpMouseMove: async (source, x, y) => {
+ const target = find((item) => item.header && item.header.x === x && item.header.y === y);
+ calls.push('hover:' + (target ? target.displayName : `${x},${y}`));
+ if (target) target.clickable = true;
+ },
+ cdpMouseClick: async (source, x, y) => {
+ const target = find((item) => item.button && item.button.x === x && item.button.y === y);
+ calls.push('click:' + (target ? target.displayName : `generic@${x},${y}`));
+ if (target && bindOnClick) {
+ state.boundWorkspace = target.displayName;
+ state.boundWorkspaceFull = target.displayName;
+ state.newTaskReady = true;
+ state.hasComposer = true;
+ state.composerText = '';
+ } else if (!target) {
+ // 通用「新建任务」入口同样会把页面带到新建任务态
+ state.newTaskReady = true;
+ state.hasComposer = true;
+ state.composerText = '';
+ }
+ },
+ cdpSend: async () => { calls.push('backup'); return { result: { value: { saved: true } } }; },
+ };
+ vm.runInNewContext(slice, ctx);
+ return { calls, state, time: () => clock, run: (options) => ctx.ensureAutomationNewTask({ guard: () => {}, ...options }) };
+}
+
+const ws = (displayName, cwd, x, y) => ({ displayName, cwd, groupKey: 'grouped-sub-workdir:' + cwd, header: { x, y }, button: { x: x + 100, y }, clickable: false });
+
+test('已绑定目标工作区时不再导航,直接复用当前新建任务页', async () => {
+ const h = harness({ boundWorkspace: 'project-alpha', boundWorkspaceFull: 'project-alpha', newTaskReady: true, hasComposer: true, workspaces: [ws('project-alpha', '/repo/project-alpha', 1, 1)] });
+ const surface = await h.run({ cwd: '/repo/project-alpha' });
+ assert.deepEqual(h.calls, ['backup']);
+ assert.equal(surface.boundWorkspace, 'project-alpha');
+});
+
+test('目标工作区的「新建任务」按钮是 hover-only:必须先悬停再点击', async () => {
+ const h = harness({ workspaces: [ws('other', '/repo/other', 5, 5), ws('project-alpha', '/repo/project-alpha', 1, 1)] });
+ const surface = await h.run({ cwd: '/repo/project-alpha' });
+ assert.deepEqual(h.calls, ['hover:project-alpha', 'click:project-alpha', 'backup']);
+ assert.equal(surface.boundWorkspace, 'project-alpha');
+});
+
+test('cwd 只差尾部分隔符时仍精确命中同一工作区', async () => {
+ const h = harness({ workspaces: [ws('project-alpha', '/repo/project-alpha', 1, 1)] });
+ await h.run({ cwd: '/repo/project-alpha/' });
+ assert.deepEqual(h.calls, ['hover:project-alpha', 'click:project-alpha', 'backup']);
+});
+
+test('只给 workspace 名时按显示名匹配', async () => {
+ const h = harness({ workspaces: [ws('project-beta', '/repo/project-beta', 3, 3)] });
+ const surface = await h.run({ workspace: 'project-beta' });
+ assert.deepEqual(h.calls, ['hover:project-beta', 'click:project-beta', 'backup']);
+ assert.equal(surface.boundWorkspace, 'project-beta');
+});
+
+test('指定了工作目录时绝不点通用新建任务入口,避免把工作区切走', async () => {
+ const h = harness({ workspaces: [ws('project-alpha', '/repo/project-alpha', 1, 1)], genericButton: { x: 77, y: 77 } });
+ await h.run({ cwd: '/repo/project-alpha' });
+ assert.ok(!h.calls.some((entry) => entry.includes('generic')), '不应点击通用入口,实际: ' + h.calls.join(' | '));
+ assert.deepEqual(h.calls, ['hover:project-alpha', 'click:project-alpha', 'backup']);
+});
+
+test('未指定工作目录时行为不变,沿用通用入口', async () => {
+ const h = harness({ genericButton: { x: 77, y: 77 }, workspaces: [ws('project-alpha', '/repo/project-alpha', 1, 1)] });
+ const surface = await h.run({});
+ assert.deepEqual(h.calls, ['click:generic@77,77', 'backup']);
+ assert.equal(surface.boundWorkspace, null);
+});
+
+test('侧栏没有目标工作区时明确失败,且不触碰输入框、不退回默认目录', async () => {
+ const h = harness({ workspaces: [ws('other', '/repo/other', 5, 5)] });
+ await assert.rejects(h.run({ cwd: '/repo/missing' }), /未在侧栏找到工作区/);
+ assert.ok(!h.calls.includes('backup'), '失败时不应进入草稿暂存');
+ assert.ok(!h.calls.some((entry) => entry.startsWith('click:')), '失败时不应点击任何入口');
+});
+
+test('悬停后按钮仍不可点击时明确失败', async () => {
+ const h = harness({ workspaces: [{ ...ws('project-alpha', '/repo/project-alpha', 1, 1) }] });
+ h.state.workspaces[0].header = null;
+ await assert.rejects(h.run({ cwd: '/repo/project-alpha' }), /缺少可悬停的标题/);
+});
+
+test('点击后绑定校验不通过则报错,不静默落到默认目录', async () => {
+ const h = harness({ workspaces: [ws('project-alpha', '/repo/project-alpha', 1, 1)], bindOnClick: false });
+ await assert.rejects(h.run({ cwd: '/repo/project-alpha' }), /绑定校验失败/);
+ assert.ok(!h.calls.includes('backup'));
+});
+
+test('cwd 与 workspace 指向不同工作区时拒绝发送', async () => {
+ const h = harness({ workspaces: [ws('project-alpha', '/repo/project-alpha', 1, 1), ws('project-beta', '/repo/project-beta', 3, 3)] });
+ await assert.rejects(h.run({ cwd: '/repo/project-alpha', workspace: 'project-beta' }), /未在侧栏找到工作区/);
+ assert.ok(!h.calls.includes('backup'));
+});
+
+test('发送前最终校验:新建任务页被切到别的工作区则停止发送', async () => {
+ // 导航阶段一切正常,落在最终校验之前把绑定切走
+ const h = harness({ workspaces: [ws('project-alpha', '/repo/project-alpha', 1, 1)], escapeFromRead: 6, escapeTo: 'other' });
+ await assert.rejects(h.run({ cwd: '/repo/project-alpha' }), /不一致/);
+ assert.ok(!h.calls.includes('backup'), '最终校验失败前不应进入草稿暂存');
+});
+
+test('工作区显示名被侧栏截断时仍能确认绑定', async () => {
+ const h = harness({ boundWorkspace: 'project-alpha-mob…', boundWorkspaceFull: 'project-alpha-mobile', newTaskReady: true, hasComposer: true, workspaces: [ws('project-alpha-mobile', '/repo/project-alpha-mobile', 1, 1)] });
+ const surface = await h.run({ cwd: '/repo/project-alpha-mobile' });
+ assert.equal(surface.boundWorkspace, 'project-alpha-mob…');
+});
+
+test('纯函数:cwd 归一化 / 条目匹配 / 标签匹配', async () => {
+ const ctx = vm.createContext({ Date, cdp: {} });
+ vm.runInContext(slice, ctx);
+ assert.equal(ctx.normalizeAutomationWorkspaceCwd('/repo/project-alpha/'), '/repo/project-alpha');
+ assert.equal(ctx.normalizeAutomationWorkspaceCwd('/repo/project-alpha///'), '/repo/project-alpha');
+ assert.equal(ctx.normalizeAutomationWorkspaceCwd(' '), '');
+ assert.equal(ctx.normalizeAutomationWorkspaceCwd('/'), '/');
+
+ const entry = { cwd: '/repo/project-alpha', displayName: 'project-alpha' };
+ assert.equal(ctx.automationWorkspaceEntryMatches(entry, '/repo/project-alpha', ''), true);
+ assert.equal(ctx.automationWorkspaceEntryMatches(entry, '/repo/project-alpha/', ''), true);
+ assert.equal(ctx.automationWorkspaceEntryMatches(entry, '/repo/project-alpha', 'project-alpha'), true);
+ assert.equal(ctx.automationWorkspaceEntryMatches(entry, '/repo/project-alpha', 'other'), false);
+ assert.equal(ctx.automationWorkspaceEntryMatches(entry, '/repo/other', ''), false);
+ assert.equal(ctx.automationWorkspaceEntryMatches(entry, '', 'project-alpha'), true);
+ assert.equal(ctx.automationWorkspaceEntryMatches(entry, '', 'other'), false);
+ assert.equal(ctx.automationWorkspaceEntryMatches(null, '/repo/project-alpha', ''), false);
+
+ assert.equal(ctx.automationWorkspaceLabelMatches('project-alpha', 'project-alpha'), true);
+ assert.equal(ctx.automationWorkspaceLabelMatches('project-alpha-mob…', 'project-alpha-mobile'), true);
+ assert.equal(ctx.automationWorkspaceLabelMatches('project-alpha-mob...', 'project-alpha-mobile'), true);
+ assert.equal(ctx.automationWorkspaceLabelMatches('project-alpha', 'project-beta'), false);
+ // 未截断的标签必须全等:互为前缀的工作区名不能互相顶包
+ assert.equal(ctx.automationWorkspaceLabelMatches('project-alpha-mob', 'project-alpha-mobile'), false);
+ assert.equal(ctx.automationWorkspaceLabelMatches('', 'project-alpha'), false);
+
+ assert.equal(ctx.automationWorkspaceBoundMatches({ boundWorkspace: 'project-alpha' }, 'project-alpha'), true);
+ assert.equal(ctx.automationWorkspaceBoundMatches({ boundWorkspace: 'project-alpha-mob…', boundWorkspaceFull: 'project-alpha-mobile' }, 'project-alpha-mobile'), true);
+ assert.equal(ctx.automationWorkspaceBoundMatches({ boundWorkspace: 'other' }, 'project-alpha'), false);
+ assert.equal(ctx.automationWorkspaceBoundMatches(null, 'project-alpha'), false);
+});
diff --git a/test/automation.test.js b/test/automation.test.js
index a0d7efc..22ed659 100644
--- a/test/automation.test.js
+++ b/test/automation.test.js
@@ -283,6 +283,14 @@ test('automation session sends only after entering the WorkBuddy new-task surfac
assert.match(inject, /\.wbs-auto-icon\.is-running[^}]*opacity:1/);
});
+test('session.create workspace binding fields are validated as a V2 absolute-path contract', () => {
+ const base = { id: 'workspace-binding', name: 'workspace-binding', steps: [{ op: 'session.create', message: 'hello' }] };
+ assert.throws(() => validateTask({ ...base, steps: [{ op: 'session.create', message: 'hello', cwd: '/repo/app' }] }), /自动化协议 V2/);
+ assert.throws(() => validateTask({ ...base, schemaVersion: 2, steps: [{ op: 'session.create', message: 'hello', cwd: 'relative/path' }] }), /绝对路径/);
+ assert.throws(() => validateTask({ ...base, schemaVersion: 2, steps: [{ op: 'session.create', message: 'hello', workspace: ' ' }] }), /非空字符串/);
+ assert.doesNotThrow(() => validateTask({ ...base, schemaVersion: 2, steps: [{ op: 'session.create', message: 'hello', cwd: '/repo/app', workspace: 'app' }] }));
+});
+
test('automation DOM locators traverse open shadow roots and task rows expose logs', () => {
const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');
diff --git a/test/client-debug-relaunch.test.js b/test/client-debug-relaunch.test.js
new file mode 100644
index 0000000..8b7cace
--- /dev/null
+++ b/test/client-debug-relaunch.test.js
@@ -0,0 +1,113 @@
+'use strict';
+// 客户端调试端口丢失检测(自动更新后重启丢 --remote-debugging-port)单测。
+// 切片来源:scripts/daemon.js 内 __wbsClientDebugStateBlockStart/End 标记块。
+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/daemon.js'), 'utf8');
+const START = '// __wbsClientDebugStateBlockStart';
+const END = '// __wbsClientDebugStateBlockEnd';
+const block = source.slice(source.indexOf(START), source.indexOf(END));
+
+function harness() {
+ const logs = [];
+ const context = vm.createContext({
+ log: (...args) => { logs.push(args.join(' ')); },
+ Date,
+ console,
+ });
+ vm.runInContext(block, context);
+ return {
+ logs,
+ state: () => vm.runInContext('clientDebugState', context),
+ update: (input) => vm.runInContext(
+ `updateClientDebugState(${JSON.stringify(input)})`, context),
+ threshold: vm.runInContext('CLIENT_DEBUG_MISS_THRESHOLD', context),
+ };
+}
+
+test('阈值常量为 3(约 15 秒,cdpLoop 5 秒一轮)', () => {
+ const h = harness();
+ assert.equal(h.threshold, 3);
+});
+
+test('CDP 已连接时重置计数与标记', () => {
+ const h = harness();
+ h.update({ cdpConnected: false, clientRunning: true });
+ h.update({ cdpConnected: false, clientRunning: true });
+ assert.equal(h.state().consecutiveMiss, 2);
+ h.update({ cdpConnected: true, clientRunning: true });
+ assert.equal(h.state().consecutiveMiss, 0);
+ assert.equal(h.state().needsDebugRelaunch, false);
+});
+
+test('客户端未运行时重置计数与标记', () => {
+ const h = harness();
+ h.update({ cdpConnected: false, clientRunning: true });
+ h.update({ cdpConnected: false, clientRunning: false });
+ assert.equal(h.state().consecutiveMiss, 0);
+ assert.equal(h.state().needsDebugRelaunch, false);
+});
+
+test('进程在跑但 CDP 不可达:连续命中阈值后标记 needsDebugRelaunch', () => {
+ const h = harness();
+ h.update({ cdpConnected: false, clientRunning: true });
+ assert.equal(h.state().needsDebugRelaunch, false);
+ h.update({ cdpConnected: false, clientRunning: true });
+ assert.equal(h.state().needsDebugRelaunch, false);
+ h.update({ cdpConnected: false, clientRunning: true });
+ assert.equal(h.state().needsDebugRelaunch, true);
+ assert.ok(h.state().updatedAt > 0);
+ assert.ok(h.logs.some((line) => line.includes('调试端口不可达')));
+});
+
+test('标记后继续命中不会重复打日志', () => {
+ const h = harness();
+ for (let i = 0; i < 5; i++) h.update({ cdpConnected: false, clientRunning: true });
+ const hits = h.logs.filter((line) => line.includes('调试端口不可达')).length;
+ assert.equal(hits, 1);
+ assert.equal(h.state().needsDebugRelaunch, true);
+});
+
+test('探测失败(未知)时不计数,避免误报', () => {
+ const h = harness();
+ h.update({ cdpConnected: false, clientRunning: null });
+ h.update({ cdpConnected: false, clientRunning: null });
+ h.update({ cdpConnected: false, clientRunning: null });
+ assert.equal(h.state().consecutiveMiss, 0);
+ assert.equal(h.state().needsDebugRelaunch, false);
+});
+
+test('恢复后(CDP 连上)标记被清除', () => {
+ const h = harness();
+ for (let i = 0; i < 3; i++) h.update({ cdpConnected: false, clientRunning: true });
+ assert.equal(h.state().needsDebugRelaunch, true);
+ h.update({ cdpConnected: true, clientRunning: true });
+ assert.equal(h.state().needsDebugRelaunch, false);
+ assert.equal(h.state().consecutiveMiss, 0);
+});
+
+test('一键恢复先走安全退出,再启动带 CDP 的客户端', () => {
+ const start = source.indexOf("p === '/api/client/relaunch'");
+ assert.ok(start >= 0);
+ const route = source.slice(start, start + 1800);
+ const stop = route.indexOf('await quitWorkBuddy()');
+ const relaunch = route.indexOf('await relaunchWorkBuddy()');
+ assert.ok(stop >= 0, '恢复路由必须先退出已运行的客户端');
+ assert.ok(relaunch > stop, '恢复路由必须在安全退出后再启动客户端');
+ assert.match(route, /json\(res, 202, \{ ok: true, pending: true \}\)/);
+ assert.match(route, /const clientRunning = safeClientRunning\(\)/);
+ assert.match(route, /if \(clientRunning !== true\)/);
+});
+
+test('客户端探测失败不会沿用破坏性操作的“按仍在运行处理”语义', () => {
+ const start = source.indexOf('function safeClientRunning()');
+ const end = source.indexOf('\n}\n\nasync function cdpLoop', start);
+ assert.ok(start >= 0 && end > start);
+ const helper = source.slice(start, end);
+ assert.match(helper, /result\.error \|\| result\.status === null/);
+ assert.match(helper, /return null/);
+});
diff --git a/test/codebuddy-compat.test.js b/test/codebuddy-compat.test.js
index 38b922e..fe01e79 100644
--- a/test/codebuddy-compat.test.js
+++ b/test/codebuddy-compat.test.js
@@ -31,6 +31,24 @@ test('CodeBuddy injection compiles with all shared pages and the CSP-compatible
assert.ok(script.includes('CodeDaddy CN'));assert.ok(script.includes('root.__wbsHTML ='));
assert.ok(script.includes('__wbsLocalApiRequest'));
});
+test('CodeBuddy account switching explains an unavailable imported WorkBuddy credential', () => {
+ const start = daemon.indexOf('async function switchAccountForProfile');
+ const end = daemon.indexOf('\nfunction scheduleBackup', start);
+ const source = daemon.slice(start, end);
+ assert.match(source, /wdCompatAuthToken\(session\.auth\)/);
+ assert.match(source, /账号备份中的加密凭据无法解密,请在 WorkBuddy 侧重新登录后再导出/);
+ assert.match(source, /账号备份中无 accessToken/);
+});
+test('CodeBuddy does not preflight-block native session recovery', () => {
+ assert.doesNotMatch(daemon, /assertCodeBuddyNativeStorageAvailable/);
+ assert.match(daemon, /let session = await codeBuddyNative\.read\(\);/);
+});
+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\(beforeLogout && beforeLogout\.uid \|\| '', true\)/);
+});
test('CodeBuddy HTML compatibility keeps the official innerHTML sink unchanged', () => {
const start = daemon.indexOf(" const trustedTypesBootstrap =");
const end = daemon.indexOf(" let source =", start);
diff --git a/test/codebuddy-files.test.js b/test/codebuddy-files.test.js
index 0a58628..0e53d36 100644
--- a/test/codebuddy-files.test.js
+++ b/test/codebuddy-files.test.js
@@ -95,3 +95,53 @@ test('size and invalidation probes use metadata without reading conversation bod
assert.match(await files.sync.readSessionQuickFingerprintAsync(null,'source'),/^[a-f0-9]{64}$/);
}finally{fs.readFileSync=read;}
});
+
+// 客户端删除的会话在登记表里只剩墓碑,旧安装遗留的历史甚至没有记录:用量统计
+// 必须按账号历史树读取,否则对应日期的 Token 会凭空变成 0。
+test('usage collection reads account history trees including deleted or unregistered sessions',async t=>{
+ const {root,files,base}=fixture(t);
+ const cwd='/fixture';
+ const gone=path.join(root,'user-b','CodeBuddyIDE','user-b','history',crypto.createHash('md5').update(path.normalize(cwd)).digest('hex'),'gone');
+ fs.mkdirSync(path.join(gone,'messages'),{recursive:true});
+ fs.writeFileSync(path.join(gone,'index.json'),JSON.stringify({messages:[],requests:[{
+ id:'request-1',type:'craft',state:'complete',startedAt:Date.parse('2026-09-20T10:00:00+08:00'),
+ usage:{inputTokens:10,outputTokens:2},
+ }]}));
+ const options=files.tokenOptions();
+ assert.deepEqual(options.files.map(file=>path.relative(root,file)).sort(),[
+ path.join('user-a','CodeBuddyIDE','user-a','history',path.basename(base),'source','index.json'),
+ path.join('user-b','CodeBuddyIDE','user-b','history',crypto.createHash('md5').update(path.normalize(cwd)).digest('hex'),'gone','index.json'),
+ ]);
+ assert.equal(options.sourceSession(path.join(base,'source','index.json')),'source');
+ assert.equal(options.sessionAccounts.gone,'user-b');
+ const {scanTokenStatsCached}=require('../scripts/token-stats.js');
+ const stats=scanTokenStatsCached(root,{...options,days:7,now:Date.parse('2026-09-21T12:00:00+08:00'),accountOptions:[{uid:'user-b'}]});
+ assert.deepEqual(stats.totals,{input:10,output:2,cacheRead:0,cacheWrite:0,total:12,calls:1});
+ assert.equal(stats.accounts[0].account,'user-b');
+});
+
+// 枚举整棵历史树约 150ms;窗口内复用结果,刷新(refresh)必须重新扫描,
+// 否则刚刚结束的会话在点击刷新后仍然看不到。
+test('history index is reused inside the window and re-walked on refresh',async t=>{
+ const {root,files}=fixture(t);
+ assert.equal(files.tokenOptions({refresh:true}).files.length,1);
+ const late=path.join(root,'user-b','CodeBuddyIDE','user-b','history',crypto.createHash('md5').update('/fixture').digest('hex'),'late');
+ fs.mkdirSync(path.join(late,'messages'),{recursive:true});
+ fs.writeFileSync(path.join(late,'index.json'),JSON.stringify({messages:[],requests:[]}));
+ assert.equal(files.tokenOptions().files.length,1,'the cached index must be reused inside the window');
+ assert.equal(files.tokenOptions({refresh:true}).files.length,2,'refresh must re-walk the history tree');
+ assert.equal(files.tokenOptions().files.length,2,'the refreshed index becomes the cached one');
+});
+
+test('token history excludes owners belonging to the other CodeBuddy profile',async t=>{
+ const {root,files,base}=fixture(t);
+ const foreign=path.join(root,'user-b','CodeBuddyIDE','user-b','history',path.basename(path.dirname(base)),'foreign');
+ fs.mkdirSync(foreign,{recursive:true});
+ fs.writeFileSync(path.join(foreign,'index.json'),JSON.stringify({messages:[],requests:[]}));
+ const all=files.tokenOptions({refresh:true});
+ assert.equal(all.files.length,2);
+ const filtered=files.tokenOptions({excludeOwners:['user-b']});
+ assert.equal(filtered.files.length,1);
+ assert.equal(filtered.sessionAccounts.foreign,undefined);
+ assert.equal(filtered.sourceSession(path.join(foreign,'index.json')),'');
+});
diff --git a/test/codebuddy-native-recovery.test.js b/test/codebuddy-native-recovery.test.js
new file mode 100644
index 0000000..5a83ee2
--- /dev/null
+++ b/test/codebuddy-native-recovery.test.js
@@ -0,0 +1,40 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { chooseRecoveryUid, recoverNativeSession } = require('../scripts/codebuddy-native-recovery.js');
+
+const accounts = [
+ { uid: 'old', authValid: true, lastRefreshTime: 10 },
+ { uid: 'newest', authValid: true, lastRefreshTime: 30 },
+ { uid: 'broken', authValid: false, lastRefreshTime: 90 },
+];
+
+test('native recovery prefers the last confirmed account', () => {
+ assert.equal(chooseRecoveryUid(accounts, { uid: 'old' }, ''), 'old');
+});
+
+test('native recovery falls back to the selected primary account', () => {
+ assert.equal(chooseRecoveryUid(accounts, { uid: 'missing' }, 'old'), 'old');
+});
+
+test('native recovery uses the newest valid backup when old state is missing', () => {
+ assert.equal(chooseRecoveryUid(accounts, null, ''), 'newest');
+});
+
+test('native recovery is disabled after an explicit logout', () => {
+ assert.equal(chooseRecoveryUid(accounts, { explicitLogout: true }, 'old'), '');
+});
+
+test('native recovery writes through the official service and verifies the result', async () => {
+ const calls = [];
+ const native = {
+ replace: async session => { calls.push(['replace', session.account.uid]); return { uid: session.account.uid }; },
+ read: async () => ({ account: { uid: 'newest' }, auth: { accessToken: 'redacted-fixture' } }),
+ };
+ const result = await recoverNativeSession({
+ native, accounts, state: null, primaryUid: '',
+ readSession: async uid => ({ account: { uid }, auth: { accessToken: 'redacted-fixture' } }),
+ });
+ assert.equal(result.uid, 'newest');
+ assert.deepEqual(calls, [['replace', 'newest']]);
+});
diff --git a/test/codebuddy-native.test.js b/test/codebuddy-native.test.js
index efbe1ed..efcd6a0 100644
--- a/test/codebuddy-native.test.js
+++ b/test/codebuddy-native.test.js
@@ -19,6 +19,15 @@ test('invalid backups never reach native storage',async()=>{
const s=service();await assert.rejects(replaceNativeSession.call(s,{account:{uid:'x'}}),/无效/);assert.deepEqual(s.events,[]);
});
+test('a failed native write never deletes the previous encrypted session', async () => {
+ const s = service();
+ s.storeSession = async session => { if (session === next) throw new Error('storage unavailable'); s.events.push('store:'+session.account.uid); };
+ s.storageService = { remove: async () => s.events.push('remove') };
+ await assert.rejects(replaceNativeSession.call(s, next), /原登录态/);
+ assert.deepEqual(s.events, ['store:old','notify:old','schedule']);
+ assert.equal(s.currentSession, original);
+});
+
test('a failed switch from logged-out state removes the new encrypted identity', async () => {
const s = service(); s.currentSession = undefined;
s.storageService = {remove:async () => s.events.push('remove')};
diff --git a/test/credit-history-sync.test.js b/test/credit-history-sync.test.js
index dbb2de6..a969b86 100644
--- a/test/credit-history-sync.test.js
+++ b/test/credit-history-sync.test.js
@@ -161,6 +161,24 @@ test('after midnight only yesterday snapshot and new day are fetched, not settle
assert.equal(requests.length,2);assert.equal(requests[1].startTime.getTime(),new Date(2026,8,12).getTime());
});
+test('credit cache writes are throttled and forced once when the job ends', async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-credit-persist-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const cacheFile = path.join(dir, 'cache.json');
+ let current = now, writes = 0;
+ const original = fs.writeFileSync;
+ fs.writeFileSync = function (file, ...rest) { if (String(file).endsWith('.tmp')) writes++; return original.call(this, file, ...rest); };
+ t.after(() => { fs.writeFileSync = original; });
+ // 每个账号整体重写一次缓存文件;节流窗口内只写一次,任务结束前再强制写一次。
+ const sync = createCreditHistorySync({ cacheFile, now: () => current, persistIntervalMs: 60000,
+ getAccessToken: async uid => uid, fetchUsage: async () => { current = new Date(current.getTime() + 1000); return { records: [] }; } });
+ sync.start({ accounts: [{ uid: 'a' }, { uid: 'b' }, { uid: 'c' }], days: 1 });
+ const state = await settle(sync);
+ assert.equal(state.completed, 3);
+ assert.equal(writes, 2, 'one throttled write plus the forced final write');
+ assert.equal(JSON.parse(fs.readFileSync(cacheFile, 'utf8')).daily.length, 3, 'the forced write must persist every account');
+});
+
test('failed gap remains missing and retry does not fetch successful accounts again', async () => {
let failing=true;const calls=[];
const sync=createCreditHistorySync({now:()=>now,getAccessToken:async uid=>uid,fetchUsage:async o=>{calls.push(o.accessToken);if(failing&&o.accessToken==='b')throw Error('timeout');return {records:[]};}});
diff --git a/test/credit-usage-store.test.js b/test/credit-usage-store.test.js
index ff9f730..dd671b5 100644
--- a/test/credit-usage-store.test.js
+++ b/test/credit-usage-store.test.js
@@ -138,3 +138,14 @@ test('stores multiple model rate limits and removes expired reset times', async
const afterExpiry = await tmp.store.listModelRateLimits(['u1', 'u2'], 6000);
assert.deepEqual(afterExpiry.u1, [{ modelId: 'gpt-5.6', modelName: 'GPT-5.6', resetAt: null, observedAt: 1100, source: 'renderer-error', reasonCode: 6004 }]);
});
+
+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 }));
+ 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, now: 4000 }), true);
+ assert.equal(await tmp.store.hasModelRateLimitElsewhere({ uid: 'u1', modelId: 'model-x', resetAt: 5000, now: 4000 }), false);
+ assert.equal(await tmp.store.hasModelRateLimitElsewhere({ uid: 'u2', modelId: 'model-x', resetAt: 6000, now: 4000 }), false);
+ assert.equal(await tmp.store.hasModelRateLimitElsewhere({ uid: 'u2', modelId: 'model-x', resetAt: 5000, now: 5000 }), false);
+});
diff --git a/test/macos-dmg-layout.test.js b/test/macos-dmg-layout.test.js
index c7d3ea6..b4bdb3c 100644
--- a/test/macos-dmg-layout.test.js
+++ b/test/macos-dmg-layout.test.js
@@ -65,6 +65,13 @@ test('macOS launcher keeps official WorkBuddy targets out of enterprise mode', (
assert.match(buildSource, /PLIST_STALE/);
});
+test('macOS package patches profile context into the launchd nohup fallback', () => {
+ const patch = buildSource.slice(buildSource.indexOf('macOS launcher 缺少 profile 环境变量兜底修复'));
+ assert.match(patch, /WBSWITCH_DATA_DIR="\$DATA_DIR"/);
+ assert.match(patch, /WBSWITCH_PORT="\$UI_PORT"/);
+ assert.match(patch, /WBSWITCH_PROFILE="\$PROFILE"/);
+});
+
test('macOS packages include every SVG loaded by the injected UI builder', () => {
const daemon = fs.readFileSync(path.join(repoRoot, 'scripts/daemon.js'), 'utf8');
const builder = daemon.slice(daemon.indexOf('function buildInjectScript()'), daemon.indexOf('function buildInjectScript()') + 5000);
diff --git a/test/panel-theme-controls.test.js b/test/panel-theme-controls.test.js
index 731ca65..393dafb 100644
--- a/test/panel-theme-controls.test.js
+++ b/test/panel-theme-controls.test.js
@@ -61,14 +61,14 @@ test('account order is centered in the panel and always shows names without numb
assert.match(modal, /账号设置/);
assert.match(modal, /data-rotation-reminder/);
assert.match(modal, /积分不足时的账号切换建议/);
- assert.doesNotMatch(modal, /账号备注|data-note-uid/);
+ assert.doesNotMatch(modal, /data-note-uid/);
assert.match(modal, /\/api\/accounts\/order/);
assert.match(source, /!rotationReminderEnabled\(\) \|\| state\.open \|\| state\.rotationNotice/);
});
test('account switching advice defaults on but keeps explicit opt-out', () => {
const fragment = section(' var rotationReminderKey = ', ' // 账号 pane 初始化');
const settings = new Map();
- const context = { PROFILE_ID: 'workbuddy-cn', localStorage: {
+ const context = { PROFILE_ID: 'workbuddy-cn', root: { classList: { toggle() {} } }, localStorage: {
getItem: key => settings.get(key) ?? null,
} };
vm.runInNewContext(fragment, context);
@@ -78,6 +78,84 @@ test('account switching advice defaults on but keeps explicit opt-out', () => {
settings.set('workdaddy.account.rotationReminder.workbuddy-cn', '1');
assert.equal(context.rotationReminderEnabled(), true);
});
+
+test('account settings persist hover visibility for note and growth popovers', () => {
+ const fragment = section(' var rotationReminderKey = ', ' // 账号 pane 初始化');
+ assert.match(source, /WBS_ACCOUNT_NOTE_HOVER_KEY = 'workdaddy\.account\.noteHover\.' \+ PROFILE_ID/);
+ assert.match(source, /WBS_GROWTH_PLAN_HOVER_KEY = 'workdaddy\.account\.growthPlanHover\.' \+ PROFILE_ID/);
+ assert.match(fragment, /function accountNoteHoverEnabled\(\)[\s\S]*localStorage\.getItem\(WBS_ACCOUNT_NOTE_HOVER_KEY\) !== '0'/);
+ assert.match(fragment, /function growthPlanHoverEnabled\(\)[\s\S]*localStorage\.getItem\(WBS_GROWTH_PLAN_HOVER_KEY\) !== '0'/);
+ const settings = new Map();
+ const context = { PROFILE_ID: 'workbuddy-cn', WBS_ACCOUNT_NOTE_HOVER_KEY: 'workdaddy.account.noteHover.workbuddy-cn', WBS_GROWTH_PLAN_HOVER_KEY: 'workdaddy.account.growthPlanHover.workbuddy-cn', root: { classList: { toggle() {} } }, localStorage: {
+ getItem: key => settings.get(key) ?? null,
+ } };
+ vm.runInNewContext(fragment, context);
+ assert.equal(context.accountNoteHoverEnabled(), true);
+ assert.equal(context.growthPlanHoverEnabled(), true);
+ settings.set('workdaddy.account.noteHover.workbuddy-cn', '0');
+ settings.set('workdaddy.account.growthPlanHover.workbuddy-cn', '0');
+ assert.equal(context.accountNoteHoverEnabled(), false);
+ assert.equal(context.growthPlanHoverEnabled(), false);
+
+ const modal = section('function openAccountOrderModal()', 'function setupCreditSummary()');
+ assert.match(modal, /data-account-note-hover/);
+ assert.match(modal, /data-growth-plan-hover/);
+ assert.match(modal, /鼠标悬浮显示账号备注/);
+ assert.match(modal, /鼠标悬浮显示成长计划/);
+ assert.match(modal, /localStorage\.setItem\(WBS_ACCOUNT_NOTE_HOVER_KEY, noteHover \? '1' : '0'\)/);
+ assert.match(modal, /localStorage\.setItem\(WBS_GROWTH_PLAN_HOVER_KEY, growthHover \? '1' : '0'\)/);
+ assert.match(source, /accountNoteHoverEnabled\(\) && button && !button\.contains\(event\.relatedTarget\)/);
+ assert.match(source, /!growthPlanHoverEnabled\(\) \|\| !ring \|\| ring === activeRing/);
+
+ assert.match(fragment, /function applyAccountNoteHoverState\(\)/);
+ assert.match(fragment, /classList\.toggle\('wbs-acct-note-hover-off', !accountNoteHoverEnabled\(\)\)/);
+ assert.match(modal, /applyAccountNoteHoverState\(\)/);
+ assert.match(source, /\.wbs-root\.wbs-acct-note-hover-off \.wbs-account-name:hover:not\(:focus-visible\):not\(\[aria-expanded="true"\]\) \.wbs-account-name-edit\{opacity:0;pointer-events:none\}/);
+});
+
+test('disabling the hover preview removes the account name edit affordance from hover only', () => {
+ const fragment = section(' var rotationReminderKey = ', ' // 账号 pane 初始化');
+ const settings = new Map();
+ const classes = new Set();
+ const context = {
+ PROFILE_ID: 'workbuddy-cn',
+ WBS_ACCOUNT_NOTE_HOVER_KEY: 'workdaddy.account.noteHover.workbuddy-cn',
+ WBS_GROWTH_PLAN_HOVER_KEY: 'workdaddy.account.growthPlanHover.workbuddy-cn',
+ localStorage: { getItem: key => settings.get(key) ?? null },
+ root: { classList: { toggle(name, on) { if (on) classes.add(name); else classes.delete(name); } } },
+ };
+ vm.runInNewContext(fragment, context);
+ // Default is on, so hovering keeps revealing the edit affordance.
+ assert.equal(classes.has('wbs-acct-note-hover-off'), false);
+ settings.set('workdaddy.account.noteHover.workbuddy-cn', '0');
+ context.applyAccountNoteHoverState();
+ assert.equal(classes.has('wbs-acct-note-hover-off'), true);
+ settings.set('workdaddy.account.noteHover.workbuddy-cn', '1');
+ context.applyAccountNoteHoverState();
+ assert.equal(classes.has('wbs-acct-note-hover-off'), false);
+});
+test('growth plan popover has an accessible close button and glass note save contrast', () => {
+ const growth = section('function dailyProgressPopoverHtml(', 'function updateDailyProgressCells()');
+ assert.match(growth, /data-wbs-daily-close/);
+ assert.match(growth, /aria-label="关闭成长计划"/);
+ const daily = section('function setupDailyProgressPopover()', 'function setupModelRateLimitPopover()');
+ assert.match(daily, /closest\('\[data-wbs-daily-close\]'\)/);
+ assert.match(source, /html\[data-wbs-theme-id="nebula"\] \.wbs-account-note-footer \.primary\{background:rgba\(255,255,255,\.9\) !important/);
+});
+test('account settings modal uses grouped controls that wrap on narrow windows', () => {
+ assert.match(source, /\.wbs-account-order-modes\{display:grid;grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/);
+ assert.match(source, /\.wbs-account-settings-toggle\{display:flex;align-items:center;justify-content:space-between/);
+ assert.match(source, /\.wbs-account-order-modal \[data-fixed-order\]\+\.wbs-account-settings-toggle\{margin-top:14px\}/);
+ assert.match(source, /@media\(max-width:420px\)\{\.wbs-account-order-modal\{width:100%/);
+});
+test('glass composer triggers receive an inline transparent background after teams remounts', () => {
+ assert.match(source, /function syncGlassComposerTriggerBackgrounds\(\)/);
+ assert.match(source, /node\.style\.setProperty\('background', 'transparent', 'important'\)/);
+ assert.match(source, /node\.style\.setProperty\('background-color', 'transparent', 'important'\)/);
+ assert.match(source, /\.cr-context-usage-tooltip-trigger/);
+ assert.match(source, /glassThemeObserver\.observe\(document\.documentElement/);
+ assert.match(source, /\.wbs-account-note-footer \.primary:disabled\{background:rgba\(255,255,255,\.78\) !important[^}]*color:#34343c !important/);
+});
test('avatar presets retain legacy custom uploads and are safe before official conversion completes', () => {
const context = {};
vm.runInNewContext(section(' function resolveAvatarChoice(', ' function checkinHtml('), context);
diff --git a/test/quick-phrase-composer.test.js b/test/quick-phrase-composer.test.js
index 2607d4e..4950c09 100644
--- a/test/quick-phrase-composer.test.js
+++ b/test/quick-phrase-composer.test.js
@@ -36,7 +36,7 @@ test('AI busy detection ignores WorkDaddy controls but keeps official stop contr
assert.equal(evaluateBusy([officialStop]), true);
});
-function harness(hasContent, failSelect = false, postClickHasContent = false) {
+function harness(hasContent, failSelect = false, postClickHasContent = false, submitError = '') {
const calls = [];
let evaluations = 0;
let submitted = false;
@@ -58,7 +58,11 @@ function harness(hasContent, failSelect = false, postClickHasContent = false) {
if (failSelect && params.commands?.includes('selectAll')) throw new Error('selection failed');
return {};
},
- cdpMouseClick: async () => { submitted = true; calls.push({ method: 'submit' }); },
+ cdpMouseClick: async () => {
+ submitted = true;
+ calls.push({ method: 'submit' });
+ if (submitError) throw new Error(submitError);
+ },
};
vm.runInNewContext(source.slice(start, end), context);
return { calls, send: (text) => context.sendStashToComposer({ content: { text, items: [] } }) };
@@ -87,6 +91,12 @@ test('quick phrase replaces a draft using a renderer edit command without macOS
assert.equal(inputs.at(-1).method, 'submit');
});
+test('quick phrase treats a collected promise after the send click as an already submitted message', async () => {
+ const { calls, send } = harness(false, false, false, 'Promise was collected');
+ assert.equal((await send('replacement')).sent, true);
+ assert.equal(calls.filter(({ method }) => method === 'submit').length, 1);
+});
+
test('empty composer skips clearing and multiline phrases retain Shift+Enter', async () => {
const { calls, send } = harness(false);
await send('first\nsecond');
diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.js
index a276d67..c4a9566 100644
--- a/test/session-delete-confinement.test.js
+++ b/test/session-delete-confinement.test.js
@@ -242,7 +242,7 @@ test('delete route validates before SQL and deletes the matched set only', () =>
const selectAt = route.indexOf("SELECT id, user_id FROM sessions");
assert.ok(normalizeAt >= 0 && normalizeAt < validateAt, 'the raw batch must be bounded before path validation');
assert.ok(validateAt < selectAt, 'all IDs must be validated before SELECT or DELETE');
- assert.match(route, /SELECT id, user_id FROM sessions WHERE id IN \(' \+ placeholders \+ '\);', memberIds/);
+ assert.match(route, /SELECT id, user_id FROM sessions WHERE id IN \(' \+ placeholders \+ '\).*memberIds/);
assert.match(route, /collectLineageMembersForDelete\(DATA_DIR, ids\)/);
assert.match(route, /\.filter\(\(id\) => isValidSessionId\(id\)\)/);
assert.match(route, /DELETE FROM sessions WHERE id IN \(" \+ sqlPlaceholders\(matchedIds\) \+ "\);",\s+matchedIds/s);
@@ -253,13 +253,35 @@ test('delete route validates before SQL and deletes the matched set only', () =>
const deleteAt = route.indexOf('DELETE FROM sessions WHERE id IN');
assert.ok(filesAt >= 0 && filesAt < rulesAt && rulesAt < deleteAt,
'filesystem and rule cleanup must succeed before the retry anchor is removed from the database');
+ assert.match(route, /assertAccountSwitchIdle\(\)/,
+ 'deletion must exclude concurrent account-switch session copy writes');
+});
+
+test('delete route refuses while account switching or session copy holds the operation gate', async () => {
+ 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,
+ req: { method: 'POST' },
+ p: '/api/sessions/delete',
+ res: {},
+ normalizeSessionIdBatch: require('../scripts/session-db.js').normalizeSessionIdBatch,
+ readBody: async () => ({ ids: ['session'] }),
+ isValidSessionId: id => id === 'session',
+ assertAccountSwitchIdle: async () => { throw new Error('会话同步尚未完成,请稍后切换账号'); },
+ json: (_, status, body) => ({ status, body }),
+ });
+ const result = await vm.runInContext('(async function () {' + source.slice(start, end) + '\n})()', ctx);
+ assert.equal(result.status, 409);
+ assert.match(result.body.error, /会话同步尚未完成/);
});
test('delete route accepts more than 100 session IDs in one request', async (t) => {
const { createSessionDb, normalizeSessionIdBatch } = require('../scripts/session-db.js');
const root = tempDir(t);
const db = createSessionDb({ dbPath: path.join(root, 'sessions.db') });
- await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT)');
+ await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT, is_background_automation INTEGER)');
const ids = Array.from({ length: 101 }, (_, index) => `00000000-0000-0000-0000-${String(index).padStart(12, '0')}`);
for (const id of ids) await db.run('INSERT INTO sessions (id, user_id) VALUES (?, ?)', [id, 'owner']);
@@ -295,7 +317,7 @@ test('delete route removes recorded copies across accounts from both DB and file
const { createSessionDb, normalizeSessionIdBatch } = require('../scripts/session-db.js');
const root = tempDir(t);
const db = createSessionDb({ dbPath: path.join(root, 'sessions.db') });
- await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT)');
+ await db.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id TEXT, is_background_automation INTEGER)');
const rows = [['session-a', 'source'], ['copy-a', 'target'], ['copy-third', 'third'], ['unrelated', 'target']];
for (const [id, uid] of rows) {
await db.run('INSERT INTO sessions (id, user_id) VALUES (?, ?)', [id, uid]);
diff --git a/test/session-fork-integration.test.js b/test/session-fork-integration.test.js
index 2fca718..ba45859 100644
--- a/test/session-fork-integration.test.js
+++ b/test/session-fork-integration.test.js
@@ -143,5 +143,5 @@ test('fork route accepts a shared session row for the current account', () => {
const end = daemonSource.indexOf("p === '/api/sessions/copy'", start);
assert.ok(start >= 0 && end > start, 'fork route must remain isolated from copy route');
const route = daemonSource.slice(start, end);
- assert.match(route, /FROM sessions WHERE id = \? AND \(user_id = \? OR user_id = ''\) AND deleted_at IS NULL LIMIT 1;/);
+ assert.match(route, /FROM sessions WHERE id = \? AND \(user_id = \? OR user_id = ''\) AND deleted_at IS NULL AND COALESCE\(is_background_automation, 0\) = 0 LIMIT 1;/);
});
diff --git a/test/session-monitor.test.js b/test/session-monitor.test.js
index c004689..cc3808d 100644
--- a/test/session-monitor.test.js
+++ b/test/session-monitor.test.js
@@ -347,3 +347,66 @@ test('compat reads the sidebar conversation status snapshot from a narrow fiber
};
assert.deepEqual(compat.findConversationListRecords(doc), records);
});
+
+
+test('dirty monitor polls sidebar revisions when the resource stays empty, and disposes on reinjection', async t => {
+ const vm = require('node:vm');
+ let records = [{ id: 'old', title: 'fixture', status: 'completed', sortAt: 10 }];
+ const sent = [];
+ const intervals = new Map();
+ const disposers = [];
+ const trackers = [];
+ const ctx = {
+ document: {}, Promise, setTimeout, clearTimeout,
+ setInterval(fn) { intervals.set(fn, fn); return fn; },
+ clearInterval(id) { intervals.delete(id); },
+ registerDisposer(fn) { disposers.push(fn); },
+ api: async (route, options) => {
+ if (route === '/api/current') return { uid: 'fixture-account' };
+ sent.push(JSON.parse(options.body)); return { ok: true };
+ },
+ WBS_COMPAT: {
+ findSessionsResource: () => ({ list: () => ({ agents: [] }), on() {}, off() {} }),
+ findConversationListRecords: () => records,
+ },
+ subscribeSessionMonitorResource: inject.subscribeSessionMonitorResource,
+ createSessionDirtyTracker(send) {
+ const tracker = inject.createSessionDirtyTracker(send);
+ trackers.push(tracker); return tracker;
+ },
+ };
+ t.after(() => { disposers.forEach(fn => fn()); trackers.forEach(tracker => tracker.destroy()); });
+ const start = injectSource.indexOf(' var sessionDirtyResource = null;');
+ const end = injectSource.indexOf(' /** 状态机可视化日志', start);
+ vm.runInNewContext(injectSource.slice(start, end), ctx);
+ await new Promise(resolve => setImmediate(resolve));
+ const poll = () => { for (const fn of intervals.values()) fn(); trackers.forEach(tracker => tracker.flush()); };
+ poll();
+ assert.equal(sent.flatMap(body => body.events || []).length, 0, 'initial sidebar data is a clean baseline');
+ records = [{ ...records[0], sortAt: 11 }];
+ poll();
+ assert.deepEqual(sent.flatMap(body => body.events || []), [{ id: 'old', event: 'sessionUpdated' }]);
+ assert.equal(sent.at(-1).uid, 'fixture-account');
+ poll();
+ assert.equal(sent.flatMap(body => body.events || []).length, 1, 'unchanged polls do not repeat events');
+ records = [];
+ poll();
+ records = [{ id: 'old', title: 'fixture', status: 'completed', sortAt: 11 },
+ { id: 'new', title: 'new fixture', status: 'running', sortAt: 12 }];
+ poll();
+ assert.deepEqual(sent.flatMap(body => body.events || []).at(-1), { id: 'new', event: 'sessionCreated' });
+ assert.equal(sent.flatMap(body => body.events || []).length, 2, 'temporary missing sidebar does not reset the baseline');
+ disposers.forEach(fn => fn());
+ assert.equal(intervals.size, 0, 'reinjection removes the polling timer');
+});
+
+
+test('synced-member eligibility survives later renderer events and dirty-index reloads', () => {
+ let index = createDirtyIndex();
+ index.markBaseline('one');
+ index.mark('one', 'a', 'sessionSynced', 100);
+ index.mark('one', 'a', 'sessionUpdated', 101);
+ index = createDirtyIndex(JSON.parse(JSON.stringify(index.state)));
+ assert.deepEqual(index.get('one', 'a'), { at: 101, event: 'sessionSynced' });
+ assert.equal(index.clear('one', 'a', 100), false, 'older acknowledgements cannot erase a newer event');
+});
diff --git a/test/session-size-summary.test.js b/test/session-size-summary.test.js
index 4299d13..47c70a5 100644
--- a/test/session-size-summary.test.js
+++ b/test/session-size-summary.test.js
@@ -26,3 +26,29 @@ test('account total includes all sessions even when the time filter hides old se
test('an unreadable session cannot silently understate the account total', async () => {
assert.equal((await query('today', [['old', null], ['new', 2000]])).totalBytes, null);
});
+
+test('session listing excludes WorkBuddy background automation records', async () => {
+ const rows = [
+ { id: 'ordinary', user_id: 'owner', created_at: 200, is_background_automation: 0 },
+ { id: 'scheduled', user_id: 'owner', created_at: 100, is_background_automation: 1 },
+ ];
+ const ctx = vm.createContext({
+ req: { method: 'GET' }, p: '/api/sessions', url: new URL('http://localhost/api/sessions?range=all'), res: {}, DATA_DIR: '', PROFILE: { dataRoot: '' },
+ normalizeAutoCopyLineages() {}, currentAccount: () => ({ uid: 'owner' }), sessionRangeMs: () => 0,
+ sqliteQuery: async (sql, params) => {
+ assert.ok(params.includes('owner'));
+ assert.match(sql, /COALESCE\(is_background_automation, 0\) = 0/);
+ return rows.filter(row => Number(row.is_background_automation || 0) === 0);
+ },
+ getAutoCopyRules: () => ({ sessionIds: [], workspaces: [], allLineages: {} }), canonicalWorkspace: String,
+ dedupeAutoCopySessionRows: rows => rows,
+ sessionSync: { readSessionSizes: async () => new Map([['ordinary', 1]]) },
+ json: (_, status, body) => { assert.equal(status, 200, body && body.error); return body; },
+ });
+ const start = source.indexOf(" if (req.method === 'GET' && p === '/api/sessions')");
+ const result = await vm.runInContext('(async () => {' + source.slice(start, source.indexOf(' // 会话空间列表', start)) + '})()', ctx);
+ assert.deepEqual(result.sessions.map(session => session.id), ['ordinary']);
+ const plannerStart = source.indexOf('async function buildAutoCopyPlan(');
+ const plannerEnd = source.indexOf('let autoCopyTargetRevisionMigrationStarted', plannerStart);
+ assert.match(source.slice(plannerStart, plannerEnd), /COALESCE\(is_background_automation, 0\) = 0/);
+});
diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.js
index 205dc05..f2652b3 100644
--- a/test/session-sync-daemon.test.js
+++ b/test/session-sync-daemon.test.js
@@ -11,7 +11,7 @@ const sessionSync = require('../scripts/session-sync.js');
const { createDirtyIndex } = require('../scripts/session-dirty.js');
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) {
+function harness(t, withPlanner = false) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-pair-daemon-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const rows = new Map();
@@ -33,7 +33,11 @@ function harness(t) {
accountSwitchInProgress: false, SESSION_COPY_COLUMNS: ['id', 'user_id'], sessionCopyLocks: new Map(), yieldAutoCopyToRenderer: async () => {}, assertSessionSyncIdle: async () => {},
getSessionSyncCache: () => syncCacheMap, scheduleSessionSyncCacheSave: () => {},
getSessionDirtyIndex: () => dirtyIndex,
+ setTimeout, clearTimeout,
log: () => {}, sqliteQuery: async (_, params) => {
+ if (withPlanner && params.length === 1 && /FROM sessions WHERE deleted_at IS NULL.* user_id = \?/.test(_)) {
+ return [...rows.values()].filter(row => row.user_id === params[0]).map(row => ({ ...row }));
+ }
if (params.length >= 4) {
return [...rows.values()].filter((candidate) => String(candidate.user_id) === String(params[0]) &&
String(candidate.cwd || '') === String(params[1] || '') &&
@@ -42,14 +46,14 @@ function harness(t) {
}
const row = rows.get(params[0]); return row && (!params[1] || params[1] === row.user_id) ? [{ ...row }] : [];
},
- sqliteRun: async (_, params) => { const row = rows.get(params[5]); assert.ok(row); Object.assign(row, { title: params[0], updated_at: params[3] }); },
+ sqliteRun: async (_, params) => { const row = rows.get(params[5]); assert.ok(row); Object.assign(row, { title: params[0], custom_title: params[1], status: params[2], updated_at: params[3], last_activity_at: params[4] }); },
insertCopiedSession: async (src, uid, id) => {
const row = { ...src, user_id: uid, id, updated_at: Date.now(), last_activity_at: Number(src.last_activity_at || src.updated_at || Date.now()) };
rows.set(id, row);
return row;
},
};
- vm.runInNewContext(source.slice(source.indexOf('function sessionCopyContentRevision('), source.indexOf('async function buildAutoCopyPlan(')), ctx);
+ vm.runInNewContext(source.slice(source.indexOf('function sessionCopyContentRevision('), source.indexOf(withPlanner ? 'const autoCopyJobs' : 'async function buildAutoCopyPlan(')), ctx);
return { root, rows, file, write, ctx, lineage, copy: () => ctx.copySessionRecord(rows.get('a'), 'two', { auto: true, lineageId: lineage }) };
}
test('account two continuation updates account one and never account three', async t => {
@@ -915,3 +919,87 @@ test('native automatic first copy registers destination ownership before selecti
assert.ok(files.collect(result.targetId).every(f=>f.source.includes(path.join('two','CodeBuddyIDE','two'))));
assert.equal((await h.copy()).status,'skipped');
});
+
+
+async function multiAccountHarness(t) {
+ const h = harness(t, true);
+ lib.setAutoCopyAllSessions(h.root, true);
+ h.rows.set('d', { ...h.rows.get('a'), id: 'd', user_id: 'four' });
+ lib.addAutoCopySessionMember(h.root, h.lineage, 'four', 'd');
+ h.write('d', base);
+ for (const row of h.rows.values()) {
+ Object.assign(row, { status: 'completed', custom_title: '', last_activity_at: 1 });
+ h.ctx.markSessionDirtyBaseline(row.user_id);
+ }
+ for (const uid of ['two', 'three', 'four']) {
+ await h.ctx.copySessionRecord(h.rows.get('a'), uid, { auto: true, lineageId: h.lineage });
+ }
+ await h.ctx.copySessionRecord(h.rows.get('b'), 'one', { auto: true, lineageId: h.lineage });
+ // All four accounts already have stable mappings before the old session changes.
+ h.write('a', [...base, nextMessage('continued old session')]);
+ Object.assign(h.rows.get('a'), { updated_at: 2, last_activity_at: 2 });
+ h.ctx.markSessionDirty('one', 'a', 'sessionUpdated');
+ h.switchTo = async (from, to) => {
+ const plan = await h.ctx.buildAutoCopyPlan(from, to);
+ h.lastResults = [];
+ for (const row of plan) h.lastResults.push(await h.ctx.copySessionRecord(row, to, { auto: true, lineageId: row.lineageId }));
+ return plan;
+ };
+ return h;
+}
+
+test('one old-session edit reaches all four initialized accounts over successive switches', async t => {
+ const h = await multiAccountHarness(t);
+ for (const [from, to, id] of [['one', 'two', 'b'], ['two', 'three', 'c'], ['three', 'four', 'd']]) {
+ assert.equal((await h.switchTo(from, to)).length, 1, `${from} -> ${to} must retain the update signal`);
+ assert.deepEqual(fs.readFileSync(h.file(id)), fs.readFileSync(h.file('a')));
+ }
+ const circuit = [['four', 'one'], ['one', 'two'], ['two', 'three'], ['three', 'four']];
+ for (const [from, to] of circuit) {
+ await h.switchTo(from, to);
+ assert.ok(h.lastResults.every(result => result.status === 'skipped' && result.copiedBytes === 0),
+ 'returning to the edited source may refresh its mapping but must not rewrite files');
+ }
+ for (const [from, to] of circuit) {
+ assert.equal((await h.switchTo(from, to)).length, 0, 'a completed circuit does not schedule duplicate copies');
+ }
+});
+
+test('returning through an already synchronized account does not lose remaining targets', async t => {
+ const h = await multiAccountHarness(t);
+ assert.equal((await h.switchTo('one', 'two')).length, 1);
+ await h.switchTo('two', 'one');
+ assert.ok(h.lastResults.every(result => result.status === 'skipped' && result.copiedBytes === 0));
+ assert.equal((await h.switchTo('one', 'three')).length, 1);
+ assert.deepEqual(fs.readFileSync(h.file('c')), fs.readFileSync(h.file('a')));
+});
+
+
+test('existing and later lifecycle markers cannot consume an updated member before fanout', async t => {
+ const h = await multiAccountHarness(t);
+ h.ctx.markSessionDirty('two', 'b', 'sessionUpdated');
+ await h.switchTo('one', 'two');
+ await h.switchTo('two', 'one');
+ h.ctx.markSessionDirty('two', 'b', 'sessionUpdated');
+ assert.equal((await h.switchTo('two', 'one')).length, 0);
+ assert.equal((await h.switchTo('two', 'three')).length, 1);
+ assert.deepEqual(fs.readFileSync(h.file('c')), fs.readFileSync(h.file('a')));
+});
+
+
+test('copy completion preserves timestamps of concurrent source and target dirty events', async t => {
+ const h = await multiAccountHarness(t);
+ const at = h.ctx.getSessionDirtyIndex().get('one', 'a').at + 100;
+ let yields = 0;
+ h.ctx.yieldAutoCopyToRenderer = async () => {
+ if (++yields === 2) {
+ h.ctx.markSessionDirty('one', 'a', 'sessionUpdated', at);
+ h.ctx.markSessionDirty('two', 'b', 'sessionUpdated', at + 1);
+ }
+ };
+ await h.switchTo('one', 'two');
+ assert.ok(yields >= 2);
+ assert.equal(h.ctx.getSessionDirtyIndex().get('one', 'a').at, at);
+ assert.equal(h.ctx.getSessionDirtyIndex().get('two', 'b').at, at + 1);
+ assert.equal((await h.switchTo('two', 'three')).length, 1);
+});
diff --git a/test/theme-patches.test.js b/test/theme-patches.test.js
index 048c684..5fa5c92 100644
--- a/test/theme-patches.test.js
+++ b/test/theme-patches.test.js
@@ -90,6 +90,18 @@ test('nebula file links and code copy controls use transparent backgrounds in al
assert.doesNotMatch(patch.css, /:hover|:focus|:active/, 'unconditional important override covers native hover and active fills');
});
+test('nebula removes backgrounds from teams composer utility trigger wrappers', () => {
+ const patch = patches.find(p => p.id === 'patch-107');
+ assert.ok(patch);
+ assert.equal(patch.themeId, 'nebula');
+ for (const cls of ['cr-voice-trigger-tooltip', 'cr-context-usage-tooltip-trigger', 'cr-enhance-button-tooltip']) {
+ assert.ok(patch.css.includes('.' + cls));
+ }
+ assert.match(patch.css, /\.cr-input-toolbar__right>span:is\(/);
+ assert.match(patch.css, /background:transparent !important/);
+ assert.match(patch.css, /background-color:transparent !important/);
+});
+
test('generic dark popup text repair excludes the WorkDaddy status popover', () => {
const patch = patches.find(item => item.id === 'patch-44');
const selectors = patch.css.slice(0, patch.css.indexOf('{')).split(',');
diff --git a/test/theme-restore-stability.test.js b/test/theme-restore-stability.test.js
index 00f5e2e..d563a20 100644
--- a/test/theme-restore-stability.test.js
+++ b/test/theme-restore-stability.test.js
@@ -597,3 +597,31 @@ test('frosted takeover completes even when background renderer timers and animat
assert.equal(applies, 2, 'native dark precedes glass');
assert.deepEqual(delays, [120], 'the daemon owns the bounded settle delay');
});
+
+for (const uid of ['current', null]) test('stale URL account never owns a new native theme snapshot: ' + uid, async () => {
+ const { context } = renderer();
+ context.URL = URL;
+ context.location = { href: 'file:///app/index.html?accountSnapshot=' + encodeURIComponent(encodeURIComponent(JSON.stringify({ uid: 'old' }))) };
+ context.localStorage.setItem('workbuddy.appearance.lastApplied', '{"resourceKey":"light","appearance":"light"}');
+ vm.runInNewContext(await themeExpression('dark', true, uid), context);
+ assert.equal(context.localStorage.getItem('workdaddy.theme.native-snapshot::old'), null);
+ if (uid) assert.ok(context.localStorage.getItem('workdaddy.theme.native-snapshot::current'));
+});
+
+test('native theme restoration uses the current account even when the URL is stale', async () => {
+ const { context } = renderer();
+ context.URL = URL;
+ context.location = { href: 'file:///app/index.html?accountSnapshot=' + encodeURIComponent(encodeURIComponent(JSON.stringify({ uid: 'old' }))) };
+ for (const [uid, resource] of [['current', 'theme-current'], ['old', 'theme-old']]) {
+ context.localStorage.setItem('workdaddy.theme.native-snapshot::' + uid, JSON.stringify({ keys: [
+ ['workbuddy.appearance.lastApplied', JSON.stringify({ resourceKey: resource, appearance: 'light' })],
+ ] }));
+ }
+ const daemon = { cdp: { connected: true }, currentAccount: () => ({ uid: 'current' }),
+ cdpSend: async (_, params) => ({ result: { value: await vm.runInNewContext(params.expression, context) } }),
+ };
+ const start = source.indexOf('async function restoreNativeAppearanceByCdp()');
+ vm.runInNewContext(source.slice(start, source.indexOf('/** 恢复已保存的主题', start)), daemon);
+ await daemon.restoreNativeAppearanceByCdp();
+ assert.equal(JSON.parse(context.localStorage.getItem('workbuddy.appearance.lastApplied')).resourceKey, 'theme-current');
+});
diff --git a/test/token-stats-modal.test.js b/test/token-stats-modal.test.js
index c3cc256..43115c1 100644
--- a/test/token-stats-modal.test.js
+++ b/test/token-stats-modal.test.js
@@ -22,7 +22,7 @@ function harness() {
for (const kind of ['credit', 'token']) periods[kind] = [1, 7, 30, 90].map(days => {
const el = element({ 'aria-pressed': String(days === 7) }); el.dataset[kind + 'Days'] = days; return el;
});
- const overlay = element(), body = element(), mask = element();
+ const overlay = element(), body = element(), mask = element(), refresh = element();
mask.querySelectorAll = selector => selector === '[data-usage-tab]' ? tabs : selector === '[data-usage-pane]' ? panes
: selector === '[data-token-days]' ? periods.token : selector === '[data-credit-days]' ? periods.credit : [];
mask.querySelector = selector => {
@@ -30,13 +30,14 @@ function harness() {
for (const kind of ['token', 'credit']) if (selector === '[data-' + kind + '-days][aria-pressed="true"]') return periods[kind].find(b => b.attrs['aria-pressed'] === 'true');
if (selector === '.wbs-token-stats-overlay') return overlay;
if (selector === '.wbs-token-stats-body') return body;
+ if (selector === '[data-usage-refresh]') return refresh;
return element();
};
const calls = [], pending = [];
const context = {
document: { getElementById: () => null, createElement: () => mask }, root: { appendChild() {} },
registerDisposer() {}, usageTimeSegmentHtml: () => '', setTimeout, clearTimeout,
- esc: String, escAttr: String, formatTokenCount: String, toast() {},
+ esc: String, escAttr: String, formatTokenCount: String, toast() {}, USAGE_REFRESH_ICON: '<svg></svg>',
usageTrendChartHtml: () => '', usagePieHtml: () => '', wireUsagePies() {}, renderUsageBreakdown() {},
api: url => {
calls.push(url);
@@ -48,7 +49,7 @@ function harness() {
const start = source.indexOf(' function onTokenStats()');
vm.runInNewContext(source.slice(start, source.indexOf('\n // ===== Tab 切换', start)), context);
context.onTokenStats();
- return { calls, pending, tabs, periods, overlay, mask };
+ return { calls, pending, tabs, periods, overlay, mask, refresh };
}
const settle = () => new Promise(resolve => setImmediate(resolve));
test('opening Token starts the default seven-day query once and hides the spinner on completion', async () => {
@@ -69,3 +70,23 @@ test('opening Token starts the default seven-day query once and hides the spinne
h.pending.shift()({stats: {}, accounts: []}); await settle();
assert.equal(h.mask.isConnected, false);
});
+test('refresh re-runs the active tab query and stays disabled while it is in flight', async () => {
+ const h = harness(); await settle();
+ assert.equal(h.calls.filter(url => url === '/api/credit-stats').length, 1);
+ h.refresh.click(); await settle();
+ assert.equal(h.calls.filter(url => url === '/api/credit-stats').length, 2, 'credit tab refresh must re-query credits');
+ assert.equal(h.refresh.disabled, false);
+ h.tabs[1].click(); await settle();
+ const tokenReads = () => h.calls.filter(url => url === '/api/token-stats?days=7').length;
+ assert.equal(tokenReads(), 1);
+ assert.equal(h.refresh.disabled, true);
+ h.refresh.click(); await settle();
+ assert.equal(tokenReads(), 1, 'a second read must not start while the first is in flight');
+ h.pending.shift()({ stats: {}, accounts: [] }); await settle();
+ assert.equal(h.refresh.disabled, false);
+ h.refresh.click(); await settle();
+ // 刷新必须绕过 daemon 的历史树枚举缓存,否则刚结束的会话依旧缺失。
+ assert.equal(tokenReads(), 1);
+ assert.equal(h.calls.at(-1), '/api/token-stats?days=7&refresh=1');
+ h.mask.__wbsClose();
+});
diff --git a/test/token-stats.test.js b/test/token-stats.test.js
index a96b135..df6bf5e 100644
--- a/test/token-stats.test.js
+++ b/test/token-stats.test.js
@@ -133,6 +133,31 @@ test('cached history and live buckets do not double count calls', () => {
assert.equal(second.totals.calls, 1);
});
+test('an unchanged scan keeps the cached totals without rewriting the cache file', t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-token-nowrite-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const now = Date.parse('2026-09-11T10:00:00Z');
+ const file = path.join(root, 'session.jsonl');
+ fs.writeFileSync(file, JSON.stringify({ timestamp: '2026-09-10T10:00:00Z', usage: { input_tokens: 3 } }) + '\n');
+ const cache = path.join(root, '.workdaddy-token-stats-cache.json');
+ assert.equal(scanTokenStatsCached(root, { now, days: 7 }).cacheHit, false);
+ fs.utimesSync(cache, new Date(now - 60_000), new Date(now - 60_000));
+ const stamp = fs.statSync(cache).mtimeMs;
+ const reused = scanTokenStatsCached(root, { now: now + 1000, days: 7 });
+ assert.equal(reused.totals.calls, 1);
+ assert.equal(reused.cacheHit, true);
+ assert.equal(reused.cacheReady, true);
+ assert.equal(fs.statSync(cache).mtimeMs, stamp, 'no change must not rewrite the cache');
+ fs.appendFileSync(file, JSON.stringify({ timestamp: '2026-09-11T09:00:00Z', usage: { input_tokens: 4 } }) + '\n');
+ const appended = scanTokenStatsCached(root, { now: now + 2000, days: 7 });
+ assert.equal(appended.totals.calls, 2);
+ assert.notEqual(fs.statSync(cache).mtimeMs, stamp, 'new usage must be persisted');
+ fs.unlinkSync(file);
+ const removed = scanTokenStatsCached(root, { now: now + 3000, days: 7 });
+ assert.equal(removed.totals.calls, 0);
+ assert.equal(JSON.parse(fs.readFileSync(cache, 'utf8')).todayFiles['session.jsonl'], undefined, 'deleted files must be dropped from the cache');
+});
+
test('token statistics UI keeps results under an overlay and exposes presets through 90 days only', () => {
const source = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');
assert.match(source, /class="wbs-token-stats-content"/);
@@ -197,10 +222,26 @@ test('usage charts derive all series from WorkBuddy theme tokens', () => {
const palette = source.match(/\.wbs-trend-panel,\.wbs-usage-pie-section\{([^}]+)\}/)[1];
assert.doesNotMatch(palette, /#[0-9a-f]|rgba?\(/i);
assert.match(palette, /--wbs-chart-base:var\(--wbs-credit-theme-color,var\(--wbs-primary\)\)/);
+ // 总览沿用主题色;按账号/按模型的分组序列必须换成互不相同的色相,
+ // 否则同一色相的明度梯变在多序列折线与饼图中难以区分。
assert.match(palette, /--wbs-trend-series-1:var\(--wbs-chart-base\)/);
- assert.match(palette, /--wbs-trend-series-2:color-mix\(in srgb,var\(--wbs-chart-base\)/);
- assert.match(palette, /--wbs-trend-series-12:color-mix\(in srgb,var\(--wbs-chart-base\)/);
- assert.doesNotMatch(palette, /--wb-palette-(blue|purple|green|cyan|red|orange)-5/);
+ assert.doesNotMatch(palette, /color-mix/, 'series colors must be distinct hues, not tints of the base color');
+ const mapped = Array.from(palette.matchAll(/--wbs-trend-series-(\d+):var\((--wbs-series-\d+)\)/g));
+ assert.deepEqual(mapped.map(match => Number(match[1])), [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
+ const tokens = mapped.map(match => match[2]);
+ assert.equal(new Set(tokens).size, tokens.length, 'split series must not reuse one hue token');
+ // 每个色相都要在浅色与深色主题下各自定义,且深浅两套颜色本身互不相同。
+ const lit = (block, token) => (new RegExp(token + ':(#[0-9a-f]{6})').exec(block) || [])[1];
+ const lightBlock = source.match(/\.wbs-root,\.wbs-status-popover,\.wbs-credit-summary-popover,#wbs-token-stats-modal\{([^}]+)\}/)[1];
+ const darkBlock = source.match(/html\[data-wbs-theme-id="dark"\][\s\S]*?#wbs-token-stats-modal\{([^}]+)\}/)[1];
+ for (const token of tokens) {
+ assert.ok(lit(lightBlock, token), `${token} missing from the light palette`);
+ assert.ok(lit(darkBlock, token), `${token} missing from the dark palette`);
+ }
+ const lightValues = tokens.map(token => lit(lightBlock, token));
+ assert.equal(new Set(lightValues).size, lightValues.length, 'light palette hues must differ');
+ const darkValues = tokens.map(token => lit(darkBlock, token));
+ assert.equal(new Set(darkValues).size, darkValues.length, 'dark palette hues must differ');
assert.match(source, /html\[data-theme="dark"\][\s\S]*--wbs-primary:#7f77dd/);
assert.match(source, /--wbs-credit-theme-color:var\(--wb-button-primary-bg\)/);
assert.equal((palette.match(/--wbs-trend-series-\d+:/g) || []).length, 12);
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index 82b98e4..2cc1c09 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -161,7 +161,7 @@ test('account switching refreshes WorkBuddy after replacing auth without restart
const route = script.slice(routeStart, routeStart + 5200);
const copy = route.indexOf('await switchAccountForProfile(uid)');
assert.notEqual(copy, -1);
- assert.match(route, /await reloadWorkBuddyPage\(\{ waitForInjection: false \}\)/);
+ assert.match(route, /await reloadWorkBuddyPage\(\{ waitForInjection: false, account: acct \}\)/);
assert.doesNotMatch(route, /await quitWorkBuddy\(\)/);
assert.doesNotMatch(route, /await relaunchWorkBuddy\(\)/);
assert.match(lib, /function retireLogoutMarker/);
@@ -187,8 +187,16 @@ test('account switching carries the active conversation and opens its copied tar
assert.match(inject, /function acSwitchConversationId()/);
assert.match(inject, /openCopiedSession/);
assert.match(compat, /function findConversationActivationApi\(doc, options\)/);
- assert.match(compat, /setCurrentConversation/);
- assert.match(compat, /sdkNavigateKind/);
+ // Only real navigation sources may drive activation: the conversation-list
+ // React handler (both the WorkBuddy >= 5.7 and the <= 5.6 marker groups) or
+ // the session-navigation SDK. conversations.setCurrentConversation merely
+ // reports the active session to the main process, so it must never be used as
+ // an activation path.
+ assert.doesNotMatch(compat, /conversations\.setCurrentConversation/);
+ assert.match(compat, /CONVERSATION_NAVIGATION_MARKER_GROUPS/);
+ assert.match(compat, /\['preserveListView', 'conversationEngineRouteTarget', 'loadSession'\]/);
+ assert.match(compat, /\['dismissHoverPeek', 'syncTaskRouteFromClick'\]/);
+ assert.match(compat, /conversations\.navigateToSession/);
assert.match(compat, /adapter\.emit\('jump-to-conversation'/);
assert.match(inject, /activationApi\.hasSession\(id\)/);
assert.match(inject, /job\.openSessionId\) setBuildTimeout\(function \(\) \{ openCopiedSession\(job\.openSessionId\); \}, 1000\)/);
@@ -585,6 +593,24 @@ test('release scripts package all four independently branded profiles', () => {
assert.match(installer, /\$lnkPath\s*=\s*Join-Path\s+\$desktopDir\s+\(\$productName\s+\+\s+'\.lnk'\)/);
});
+test('macOS DMG fallback layouts pin every branded app beside Applications', () => {
+ const mac = read('build-mac-dmg.sh');
+ assert.match(mac, /codebuddy-cn\) DSSTORE_FALLBACK=.*codedaddy-cn\.DS_Store/);
+ assert.match(mac, /codebuddy-intl\) DSSTORE_FALLBACK=.*codedaddy\.DS_Store/);
+ const layouts = [
+ ['workdaddy.DS_Store', 'WorkDaddy.app'],
+ ['workdaddy-ai.DS_Store', 'WorkDaddy AI.app'],
+ ['codedaddy-cn.DS_Store', 'CodeDaddy CN.app'],
+ ['codedaddy.DS_Store', 'CodeDaddy.app'],
+ ];
+ for (const [name, app] of layouts) {
+ const bytes = fs.readFileSync(path.join(repoRoot, 'scripts', 'assets', 'dmg-layout', name));
+ const utf16be = value => Buffer.from(value, 'utf16le').swap16();
+ assert.ok(bytes.includes(utf16be(app)), `${name} must contain its app item`);
+ assert.ok(bytes.includes(utf16be('Applications')), `${name} must contain Applications`);
+ }
+});
+
test('Windows installer writes through the console API for PowerShell 5.1 compatibility', () => {
const installer = read('install-win.ps1');
const entry = read('install-win.cmd');
@@ -1065,17 +1091,26 @@ test('robot button decorations remain visible alongside the eye states', () => {
assert.match(script, /\.wbs-fab \.click \.button \.speak~\.speak\{display:none\}/);
});
-test('robot button defaults to the window bottom-right and snaps right after free dragging', () => {
+test('robot button anchors to the conversation area bottom-right and snaps right after free dragging', () => {
const script = read('inject.js');
- assert.match(script, /FAB_POSITION_KEY = 'wbs-fab-bottom-v2-' \+ PROFILE_ID/);
- assert.match(script, /FAB_LEGACY_POSITION_KEY = 'wbs-fab-bottom-' \+ PROFILE_ID/);
+ assert.match(script, /FAB_POSITION_KEY = 'wbs-fab-bottom-v3-' \+ PROFILE_ID/);
+ assert.match(script, /'wbs-fab-bottom-v2-' \+ PROFILE_ID/);
+ assert.match(script, /'wbs-fab-bottom-' \+ PROFILE_ID/);
assert.match(script, /raw !== null && raw !== '' && isFinite\(value\)/);
- assert.match(script, /localStorage\.removeItem\(FAB_LEGACY_POSITION_KEY\)/);
+ assert.match(script, /localStorage\.removeItem\(FAB_RETIRED_POSITION_KEYS\[i\]\)/);
+ // The anchor is the conversation area, not the window.
+ assert.match(script, /'\.teams-container\.is-mac \.conversation-shell'/);
+ assert.match(script, /function readFabAnchorNode\(\)/);
+ assert.match(script, /function fabAnchorOffsets\(\)/);
+ assert.match(script, /window\.innerWidth - rect\.right\) \+ FAB_EDGE_GAP/);
+ assert.match(script, /window\.innerHeight - rect\.bottom\) \+ FAB_EDGE_GAP/);
+ assert.match(script, /new ResizeObserver\(function \(\) \{ scheduleFabPos\(\); \}\)/);
+ assert.match(script, /ensureFabAnchorObserver\(\)/);
assert.match(script, /setPointerCapture\(e\.pointerId\)/);
assert.match(script, /FAB_DRAG_THRESHOLD = 6/);
assert.match(script, /fabDrag\.startRight - deltaX/);
assert.match(script, /fabDrag\.startBottom - deltaY/);
- assert.match(script, /applyFabPosition\(fab, FAB_EDGE_GAP, bottom\)/);
+ assert.match(script, /applyFabPosition\(fab, fabAnchorOffsets\(\)\.right, bottom\)/);
assert.match(script, /localStorage\.setItem\(FAB_POSITION_KEY/);
assert.match(script, /touchAction = 'none'/);
assert.match(script, /is-snapping/);
@@ -1121,7 +1156,7 @@ test('Windows updater stops at the installer prompt after download', () => {
assert.doesNotMatch(script, /var WBS_PLATFORM = '__WBS_PLATFORM__'/);
const injectedWindows = script.replace(/__WBS_PLATFORM__/g, JSON.stringify('win32'));
assert.match(injectedWindows, /var WBS_PLATFORM = "win32";/);
- assert.match(script, /function showWindowsInstallerReady\(prog, btn, card, timer\)/);
+ assert.match(script, /function showWindowsInstallerReady\(prog, btn, card, timer(?:, keepDisabled)?\)/);
assert.match(script, /function openWindowsInstallerAfterDownload\(prog, btn, card, timer, resolve, reject\)/);
assert.match(script, /appendUpdateLog\(prog, '即将打开安装包…'\)/);
assert.match(script, /if \(WBS_PLATFORM === 'win32'\) \{[\s\S]*openWindowsInstallerAfterDownload\(prog, btn, card, timer, resolve, reject\);/);
@@ -1382,10 +1417,10 @@ test('automatic session copy filters clean sessions before target queries and sn
assert.match(daemon, /const dirtyIndex = (?:getSessionDirtyIndex\(\)|typeof getSessionDirtyIndex === 'function'[\s\S]*?getSessionDirtyIndex\(\))[\s\S]*const dirtyRows = selectedRows\.filter\(\(\) => false\);[\s\S]*for \(const row of selectedRows\)[\s\S]*dirtyIndex\.shouldSync\(source, row\.id\)[\s\S]*mappingSourceRevisionMatches/);
assert.match(daemon, /const SESSION_DIRTY_FILE = (?:path\.join\(DATA_DIR, 'session-dirty\.json'\)|typeof DATA_DIR !== 'undefined'[\s\S]*?session-dirty\.json)/);
assert.match(daemon, /POST' && p === '\/api\/sessions\/dirty'/);
- assert.match(daemon, /clearAutoDirty\(\);/);
+ assert.match(daemon, /finishAutoDirty\(targetId, changed\);/);
assert.match(inject, /function sessionCopyIsNoop\(job\)/);
assert.match(inject, /if \(sessionCopyIsNoop\(job\)\) \{[\s\S]*closeSessionCopyNotice\(\);/);
- assert.match(inject, /createSessionDirtyTracker\(function \(payload\)/);
+ assert.match(inject, /createSessionDirtyTracker\(sendSessionDirtyEvents\)/);
assert.match(inject, /sessionDirtyTracker\.baseline\(records\)/);
});
diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.js
index 6b489ec..2efed2c 100644
--- a/test/windows-native-flow.test.js
+++ b/test/windows-native-flow.test.js
@@ -198,6 +198,20 @@ test('Windows update opens the verified Setup visibly and keeps daemon alive', (
assert.match(inject, /WBS_PLATFORM === 'win32'[\s\S]*showWindowsInstallerReady/);
});
+test('Windows update deduplicates installer launches and keeps the opening button locked', () => {
+ const daemon = read('scripts/daemon.js');
+ const inject = read('scripts/inject.js');
+ const applyStart = daemon.indexOf('function applyUpdate()');
+ const applyEnd = daemon.indexOf('\n const scriptPath = path.join(__dirname, \'apply-update.sh\')', applyStart);
+ const applyBlock = daemon.slice(applyStart, applyEnd);
+ assert.match(applyBlock, /updateApplyPromise/);
+ assert.match(applyBlock, /status === 'installer-opened'/);
+ assert.match(applyBlock, /alreadyOpen: true/);
+ assert.match(inject, /windowsInstallerOpening/);
+ assert.match(inject, /showWindowsInstallerReady\(prog, btn, card, timer, true\)/);
+ assert.match(inject, /安装程序已打开,请到任务栏选择安装窗口/);
+});
+
test('Windows installer launch uses a visible detached process without shell arguments', async () => {
let call = null;
let unreferenced = false;
diff --git a/test/workbuddy-compat.test.js b/test/workbuddy-compat.test.js
index 95ec9af..580ae5a 100644
--- a/test/workbuddy-compat.test.js
+++ b/test/workbuddy-compat.test.js
@@ -82,11 +82,43 @@ test('conversation activation exposes the official session lookup and jump event
}]);
});
-test('conversation activation prefers the official React navigation handler', async () => {
+test('conversation activation prefers the WorkBuddy 5.7 conversation-list handler', async () => {
+ const calls = [];
+ const navigate = async function loadConversationFromList(id, cwd = '', skipLocalCheck = false, preserveListView = false, options = {}) {
+ // Markers mirror WorkBuddy >= 5.7. Its loader dedupes on loadSession, reads
+ // options.conversationEngineRouteTarget and honours preserveListView.
+ if (preserveListView) calls.push('preserve');
+ if (options.conversationEngineRouteTarget === 'localAssistant') return;
+ console.debug('[ConversationList] loadSession deduped:', id);
+ calls.push([id, cwd, skipLocalCheck, preserveListView, options]);
+ };
+ const adapter = {
+ enqueueConversationMessageQueueItem() {},
+ pauseConversationMessageQueue() {},
+ emit() { throw new Error('legacy activation must not be used'); },
+ };
+ const root = visibleElement();
+ root.__reactFiber$test = {
+ memoizedProps: {},
+ memoizedState: { memoizedState: { current: navigate }, next: null },
+ return: null,
+ };
+ const documentLike = {
+ querySelector(selector) { return selector === '.conversation-list' ? root : null; },
+ };
+ const activation = compat.findConversationActivationApi(documentLike);
+ assert.ok(activation);
+ assert.equal(activation.authoritative, true);
+ assert.equal(activation.activate('official-session'), true);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(calls, [['official-session', '', false, false, {}]]);
+});
+
+test('conversation activation still matches the pre-5.7 navigation handler', async () => {
const calls = [];
const navigate = async function handleConversationClick(id, cwd, skipLocalCheck, preserveListView, options) {
- // The markers mirror WorkBuddy's current handler without depending on its
- // minified component names.
+ // Markers mirror WorkBuddy <= 5.6, which used these private symbols. Both
+ // were removed in 5.7, so they must stay supported for older clients.
function dismissHoverPeek() {}
function syncTaskRouteFromClick() {}
dismissHoverPeek();
@@ -105,13 +137,59 @@ test('conversation activation prefers the official React navigation handler', as
return: null,
};
const documentLike = {
- querySelector(selector) { return selector === '#root > div' ? root : null; },
+ querySelector(selector) { return selector === '.conversation-list' ? root : null; },
};
const activation = compat.findConversationActivationApi(documentLike);
assert.ok(activation);
- assert.equal(activation.activate('official-session'), true);
+ assert.equal(activation.authoritative, true);
+ assert.equal(activation.activate('legacy-session'), true);
await new Promise((resolve) => setImmediate(resolve));
- assert.deepEqual(calls, [['official-session', '', false, false, {}]]);
+ assert.deepEqual(calls, [['legacy-session', '', false, false, {}]]);
+});
+
+test('conversation activation ignores the non-navigating setCurrentConversation SDK method', () => {
+ // setCurrentConversation only reports the active conversation to the main
+ // process. Treating it as an authoritative route transition produced
+ // "official-dispatched" without a page change, then retried until timeout.
+ const calls = [];
+ const previousWindow = global.window;
+ global.window = {
+ wb: { conversations: { setCurrentConversation(id) { calls.push(id); } } },
+ };
+ try {
+ const documentLike = { querySelector() { return null; } };
+ assert.equal(compat.findConversationActivationApi(documentLike), null);
+ assert.deepEqual(calls, []);
+ } finally {
+ if (previousWindow === undefined) delete global.window;
+ else global.window = previousWindow;
+ }
+});
+
+test('conversation activation uses the session navigation SDK when it is exposed', async () => {
+ const calls = [];
+ const previousWindow = global.window;
+ global.window = {
+ wb: {
+ conversations: {
+ navigateToSession(id, options) { calls.push([this && typeof this.navigateToSession, id, options]); return Promise.resolve(); },
+ },
+ },
+ };
+ try {
+ const documentLike = { querySelector() { return null; } };
+ const activation = compat.findConversationActivationApi(documentLike);
+ assert.ok(activation);
+ assert.equal(activation.authoritative, true);
+ assert.equal(activation.activate('sdk-session'), true);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0][1], 'sdk-session');
+ assert.deepEqual(calls[0][2], { ensureLoaded: true });
+ } finally {
+ if (previousWindow === undefined) delete global.window;
+ else global.window = previousWindow;
+ }
});
test('selected conversation lookup is capability based rather than profile based', () => {
@@ -179,6 +257,19 @@ test('Windows encrypted-field key lookup honors the configured WorkBuddy target
}
});
+test('Windows encrypted-field lookup keeps WorkBuddy key providers available for CodeBuddy imports', () => {
+ const candidates = lib.wdCompatWindowsExeCandidates({
+ localAppData: 'C:\\Users\\tester\\AppData\\Local',
+ profileId: 'codebuddy-cn',
+ configured: 'C:\\Users\\tester\\AppData\\Local\\Programs\\CodeBuddy CN\\CodeBuddy CN.exe',
+ });
+ assert.deepEqual(candidates.slice(0, 2), [
+ 'C:\\Users\\tester\\AppData\\Local\\Programs\\WorkBuddy\\WorkBuddy.exe',
+ 'C:\\Users\\tester\\AppData\\Local\\Programs\\WorkBuddyAI\\WorkBuddyAI.exe',
+ ]);
+ assert.equal(candidates.includes('C:\\Users\\tester\\AppData\\Local\\Programs\\CodeBuddy CN\\CodeBuddy CN.exe'), false);
+});
+
test('account backup keeps both legacy plaintext and encrypted source bytes unchanged', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-compat-'));
try {