WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
选择会话消息文本,引用文本到输入框;启动的时候触发一次签到;修复 windows 安装问题;
[email protected]bb6d44452f62
diff --git a/release/macos/WorkDaddy-1.1.3.dmg b/release/macos/WorkDaddy-1.1.4.dmgsimilarity index 77%rename from release/macos/WorkDaddy-1.1.3.dmgrename to release/macos/WorkDaddy-1.1.4.dmgindex f8a7902..643ec63 100644Binary files a/release/macos/WorkDaddy-1.1.3.dmg and b/release/macos/WorkDaddy-1.1.4.dmg differdiff --git a/release/macos/WorkDaddy-AI-1.1.3.dmg b/release/macos/WorkDaddy-AI-1.1.4.dmgsimilarity index 71%rename from release/macos/WorkDaddy-AI-1.1.3.dmgrename to release/macos/WorkDaddy-AI-1.1.4.dmgindex 3e5c406..0080cd2 100644Binary files a/release/macos/WorkDaddy-AI-1.1.3.dmg and b/release/macos/WorkDaddy-AI-1.1.4.dmg differdiff --git a/release/windows/WorkDaddy-Setup-1.1.3.exe b/release/windows/WorkDaddy-AI-Setup-1.1.4.exesimilarity index 74%rename from release/windows/WorkDaddy-Setup-1.1.3.exerename to release/windows/WorkDaddy-AI-Setup-1.1.4.exeindex 95f34d6..0e5b639 100644Binary files a/release/windows/WorkDaddy-Setup-1.1.3.exe and b/release/windows/WorkDaddy-AI-Setup-1.1.4.exe differdiff --git a/release/windows/WorkDaddy-AI-Setup-1.1.3.exe b/release/windows/WorkDaddy-Setup-1.1.4.exesimilarity index 74%rename from release/windows/WorkDaddy-AI-Setup-1.1.3.exerename to release/windows/WorkDaddy-Setup-1.1.4.exeindex a0cccc5..a02d81f 100644Binary files a/release/windows/WorkDaddy-AI-Setup-1.1.3.exe and b/release/windows/WorkDaddy-Setup-1.1.4.exe differdiff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex ed79211..bdcd2b3 100644--- a/scripts/build-mac-dmg.sh+++ b/scripts/build-mac-dmg.sh@@ -32,7 +32,6 @@ case "$PROFILE" inworkbuddy-ai) PACKAGE_APP_NAME="WorkDaddy AI"; OUT="release/macos/WorkDaddy-AI-${VERSION}.dmg" ;;*) PROFILE="workbuddy-cn"; PACKAGE_APP_NAME="WorkDaddy"; OUT="release/macos/WorkDaddy-${VERSION}.dmg" ;;esac-VERSION_CODE="$(printf '%s' "$VERSION" | tr -d '.')"echo "==> profile: ${PROFILE}"echo "==> 版本: ${VERSION}"@@ -139,7 +138,8 @@ source = source.replace(' echo "[$(date -u +%FT%TZ)] manual inject result: ${INwith open(path, 'w', encoding='utf-8', newline='') as f:f.write(source)PY-perl -0pi -e "s/<string>1\\.0\\.8<\\/string>/<string>${VERSION}<\\/string>/g; s/<string>108<\\/string>/<string>${VERSION_CODE}<\\/string>/g" "$PACKAGE_APP/Contents/Info.plist"+/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString ${VERSION}" "$PACKAGE_APP/Contents/Info.plist"+/usr/libexec/PlistBuddy -c "Set :CFBundleVersion ${VERSION}" "$PACKAGE_APP/Contents/Info.plist"# 无论源码壳当前版本如何,每次产物都必须让 daemon 版本与安装包版本一致。perl -0pi -e "s/(const DAEMON_VERSION = ')[^']+(';)/\${1}${VERSION}\${2}/" \"$PACKAGE_APP/Contents/Resources/scripts/daemon.js"diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 4e6224b..e66f90d 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -228,8 +228,10 @@ const DATA_DIR = defaultDataDir();// 1.1.16:元素检查器改为 WorkDaddy 插件内弹窗,支持 DOM 树、悬停高亮和重叠元素浏览,不再提供独立页面。// 1.1.24:6 号官方壁纸替换为新默认图;消息导航与机器人瞳孔改为悬浮毛玻璃。// 1.1.25:内置官方壁纸更新时刷新数据目录旧副本;新 profile 默认启用 WorkDaddy 壁纸主题。-const DAEMON_VERSION = '1.1.25';-const DAEMON_BUILD_ID = 'release-1.1.25-20260830-unread-dot-theme';+// 1.1.26:daemon 启动 30 秒后补签,并将全账号签到兜底周期缩短为 1 小时。+// 1.1.27:修复 Windows 原生启动路径发现、旧托管 Node 升级和首次会话播种失败;补充脱敏启动诊断与匿名安装 ID。+const DAEMON_VERSION = '1.1.27';+const DAEMON_BUILD_ID = 'release-1.1.27-20260831-windows-sentry-diagnostics';const HOST = '127.0.0.1';const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app@@ -2206,6 +2208,8 @@ const CHECKIN_ENDPOINTS = profileCheckinEndpoints();const CHECKIN_CACHE_FILE = path.join(DATA_DIR, 'checkin-cache.json');const CHECKIN_REQUEST_TIMEOUT_MS = 12000;const CHECKIN_QUEUE_DELAY_MS = 250;+const CHECKIN_STARTUP_DELAY_MS = 30 * 1000;+const CHECKIN_INTERVAL_MS = 60 * 60 * 1000;let claimInFlight = false;let checkinState = { running: false, total: 0, done: 0, startedAt: 0, finishedAt: 0 };@@ -3732,6 +3736,7 @@ const SESS_NS = 'session';const SESS_SWITCHES = ['stashEnabled', 'phraseEnabled'];// 首次使用时播种的默认快捷短语(仅一次;用户删除后不再补——seeded 标志已置位,删除即永久生效)const SESS_DEFAULT_PHRASES = ['继续执行'];+let sessionSeedPersistReported = false;function sessBuild(st, phrases) {return {@@ -3754,7 +3759,24 @@ function readSessionState() {}if (!s.wbs || typeof s.wbs !== 'object') s.wbs = {};s.wbs[SESS_NS] = { state: st, phrases, seeded: true };- writeWorkbuddySettings(s);+ try {+ writeWorkbuddySettings(s);+ } catch (error) {+ if (!sessionSeedPersistReported) {+ sessionSeedPersistReported = true;+ const reportError = new Error('首次会话播种持久化失败');+ captureException(reportError, {+ stage: 'session-seed-persist',+ extra: {+ platform: process.platform,+ settingsWrite: 'first-run-session-seed',+ errorName: String(error && error.name || 'Error').slice(0, 80),+ errorCode: String(error && error.code || 'unknown').slice(0, 80),+ syscall: String(error && error.syscall || 'unknown').slice(0, 80),+ },+ }).catch(() => {});+ }+ }}return sessBuild(st, phrases);}@@ -7208,8 +7230,15 @@ updateDebug('daemon-start', { authFile: AUTH_FILE, dataDir: DATA_DIR, appPath: IrestoreSleepMode();startServer();cdpLoop();-// 每天多次兜底自动签到(面板打开也会触发),带每日缓存不会重复领-setInterval(() => { claimDailyForAll().catch((e) => log('[checkin] 定时签到失败: ' + e.message)); }, 3 * 60 * 60 * 1000);+// 启动后给网络和本地存储留出就绪时间,再补一轮;之后每小时兜底。+const startupCheckinTimer = setTimeout(() => {+ claimDailyForAll().catch((e) => log('[checkin] 启动签到失败: ' + e.message));+}, CHECKIN_STARTUP_DELAY_MS);+startupCheckinTimer.unref && startupCheckinTimer.unref();+const periodicCheckinTimer = setInterval(() => {+ claimDailyForAll().catch((e) => log('[checkin] 定时签到失败: ' + e.message));+}, CHECKIN_INTERVAL_MS);+periodicCheckinTimer.unref && periodicCheckinTimer.unref();// 自动更新:启动时检查一次(延迟 8s 等网络就绪),之后每 6 小时一次setTimeout(() => { checkUpdate(true).catch(() => {}); }, 8000);updateTimer = setInterval(() => { checkUpdate(false).catch(() => {}); }, UPDATE_CHECK_INTERVAL);diff --git a/scripts/inject.js b/scripts/inject.jsindex e060659..99b9c91 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -203,7 +203,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {(function () {var n;if ((n = document.querySelector('.wbs-root'))) n.remove();- var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline');+ var st = document.querySelectorAll('.wbs-stash-inline, .wbs-stash-btn, .wbs-explore-inline, .wbs-selection-quote-btn');for (var i = 0; i < st.length; i++) st[i].remove();var nav = document.querySelectorAll('.wbs-message-nav-root');for (var ni = 0; ni < nav.length; ni++) nav[ni].remove();@@ -1086,19 +1086,27 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {exploreBtn.addEventListener('mouseleave', function () { exploreBtn.classList.remove('wbs-menu-closed'); });if (isWelcomePage()) exploreBtn.style.display = 'none'; // 欢迎页无操作栏,定位没意义;其余情况由 syncStash 常驻显示- /* ———— 会话模块(session):暂存提示词、会话消息索引 & 快捷短语 ————+ /* ———— 会话模块(session):暂存提示词、会话消息索引、选中文字引用 & 快捷短语 ————* 暂存提示词/快捷短语由 daemon 持久化;消息索引开关保存在渲染器 localStorage。* stash 按钮显隐受「暂存提示词」开关影响;explore 按钮与面板选项受「快捷短语」开关/列表影响。 */var MESSAGE_NAV_ENABLED_KEY = 'workdaddy.session.messageNavigationEnabled';+ var SELECTION_QUOTE_ENABLED_KEY = 'workdaddy.session.selectionQuoteEnabled';function readMessageNavigationEnabled() {try { return localStorage.getItem(MESSAGE_NAV_ENABLED_KEY) !== '0'; } catch (_) { return true; }}function writeMessageNavigationEnabled(enabled) {try { localStorage.setItem(MESSAGE_NAV_ENABLED_KEY, enabled ? '1' : '0'); } catch (_) {}}+ function readSelectionQuoteEnabled() {+ try { return localStorage.getItem(SELECTION_QUOTE_ENABLED_KEY) !== '0'; } catch (_) { return true; }+ }+ function writeSelectionQuoteEnabled(enabled) {+ try { localStorage.setItem(SELECTION_QUOTE_ENABLED_KEY, enabled ? '1' : '0'); } catch (_) {}+ }var sessState = {stash: true,messageNav: readMessageNavigationEnabled(),+ selectionQuote: readSelectionQuoteEnabled(),phrase: true,phrases: [],qpBatch: false,@@ -1111,14 +1119,16 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {sessState.stash = !!d.stashEnabled;sessState.phrase = !!d.phraseEnabled;sessState.phrases = Array.isArray(d.phrases) ? d.phrases : [];- // 同步 UI:三个开关 + 快捷短语列表区显隐+ // 同步 UI:会话开关 + 快捷短语列表区显隐var pane0 = enhancePane;var swS = pane0 && pane0.querySelector('#wbs-sess-stash');var swN = pane0 && pane0.querySelector('#wbs-sess-message-nav');+ var swQ = pane0 && pane0.querySelector('#wbs-sess-selection-quote');var swP = pane0 && pane0.querySelector('#wbs-sess-phrase');var area = pane0 && pane0.querySelector('#wbs-qp-area');if (swS) swS.checked = !!sessState.stash;if (swN) swN.checked = !!sessState.messageNav;+ if (swQ) swQ.checked = !!sessState.selectionQuote;if (swP) swP.checked = !!sessState.phrase;if (area) area.style.display = sessState.phrase ? '' : 'none';renderQpList();@@ -1145,6 +1155,139 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {syncSessionModule();});}++ // 轻量选区引用:只保存当前选中的文字,通过 WorkBuddy 官方 content-block 请求插入输入框。+ // 不复制 Codex 的 locator/回复标注协议,避免依赖脆弱的内部状态。+ var selectionQuoteButton = null;+ var selectionQuotePending = null;+ var selectionQuoteFrame = null;+ var SELECTION_QUOTE_MAX_LENGTH = 12000;+ /* WorkBuddy 的 selection-quote renderer 会通过 InputContextTag 自己渲染消息图标。 */++ function selectionQuoteElement(range) {+ if (!range || !range.commonAncestorContainer) return null;+ var node = range.commonAncestorContainer;+ var element = node.nodeType === 1 ? node : node.parentElement;+ if (!element || !element.closest) return null;+ if (element.closest('.wbs-root,.wbs-selection-quote-btn,textarea,input')) return null;+ var editable = element.closest('[contenteditable="true"]');+ var composer = findComposer();+ if (editable && composer && editable === composer) return null;+ return element.closest(+ '[data-message-id],[data-message-request-id],.cb-message,.cr-message,.cr-message-content,' ++ '[class*="message-content"],[class*="messageContent"],[class*="message-bubble"],[class*="messageBubble"]'+ ) || element.closest('.cr-document[data-root-id]');+ }++ function selectionQuoteBlock(text) {+ return {+ type: 'resource_link',+ name: '引用文本',+ uri: 'selection://document-selection',+ _meta: {+ displayAsPhrase: true,+ displayAsContext: false,+ displayText: '引用文本',+ selectionQuote: true,+ mentionType: 'selection',+ selectedText: text,+ title: '引用文本',+ },+ };+ }++ function hideSelectionQuoteButton() {+ if (selectionQuoteButton) selectionQuoteButton.style.display = 'none';+ selectionQuotePending = null;+ }++ function updateSelectionQuoteButton() {+ selectionQuoteFrame = null;+ if (!alive || !sessState.selectionQuote || !selectionQuoteButton) return;+ var sel = window.getSelection && window.getSelection();+ if (!sel || sel.rangeCount < 1 || sel.isCollapsed) return hideSelectionQuoteButton();+ var range = sel.getRangeAt(0);+ var message = selectionQuoteElement(range);+ var text = String(sel.toString() || '').trim();+ if (!message || !text || text.length > SELECTION_QUOTE_MAX_LENGTH) return hideSelectionQuoteButton();+ var rect = range.getBoundingClientRect();+ if (!rect || rect.width <= 0 || rect.height <= 0 || rect.bottom < 0 || rect.top > window.innerHeight) {+ return hideSelectionQuoteButton();+ }+ selectionQuotePending = { text: text, rect: rect };+ selectionQuoteButton.style.display = 'inline-flex';+ var buttonRect = selectionQuoteButton.getBoundingClientRect();+ var left = Math.max(8, Math.min(window.innerWidth - buttonRect.width - 8, rect.right - buttonRect.width));+ var top = rect.top - buttonRect.height - 8;+ if (top < 8) top = Math.min(window.innerHeight - buttonRect.height - 8, rect.bottom + 8);+ selectionQuoteButton.style.left = Math.round(left) + 'px';+ selectionQuoteButton.style.top = Math.round(Math.max(8, top)) + 'px';+ }++ function scheduleSelectionQuoteButton() {+ if (selectionQuoteFrame !== null) return;+ var request = window.requestAnimationFrame || function (callback) { return setTimeout(callback, 40); };+ selectionQuoteFrame = request(updateSelectionQuoteButton);+ }++ function insertSelectionQuote() {+ var pending = selectionQuotePending;+ if (!pending || !pending.text) return;+ hideSelectionQuoteButton();+ var adapter = null;+ try { adapter = window.__wbsAdapter || findWbsAdapter(); } catch (_) {}+ if (!adapter || typeof adapter.requestInsertContentBlocks !== 'function') {+ toast('当前输入框暂不支持引用插入', true, root);+ return;+ }+ var request = { contentBlocks: [selectionQuoteBlock(pending.text)] };+ try {+ Promise.resolve(adapter.requestInsertContentBlocks(request)).then(function () {+ toast('已引用选中文字', false, root);+ }).catch(function () {+ toast('引用插入失败,请重试', true, root);+ });+ } catch (_) {+ toast('引用插入失败,请重试', true, root);+ }+ }++ function setupSelectionQuote() {+ if (!document.body) return;+ if (!sessState.selectionQuote) hideSelectionQuoteButton();+ if (!selectionQuoteButton) {+ selectionQuoteButton = el('button', 'wbs-selection-quote-btn');+ selectionQuoteButton.type = 'button';+ selectionQuoteButton.setAttribute('aria-label', '引用文本');+ selectionQuoteButton.textContent = '引用文本';+ document.body.appendChild(selectionQuoteButton);+ listen(selectionQuoteButton, 'pointerdown', function (event) {+ if (event.preventDefault) event.preventDefault();+ if (event.stopPropagation) event.stopPropagation();+ });+ listen(selectionQuoteButton, 'click', function (event) {+ if (event.preventDefault) event.preventDefault();+ if (event.stopPropagation) event.stopPropagation();+ insertSelectionQuote();+ });+ }+ listen(document, 'selectionchange', scheduleSelectionQuoteButton);+ listen(document, 'mouseup', scheduleSelectionQuoteButton);+ listen(window, 'scroll', scheduleSelectionQuoteButton, true);+ listen(window, 'resize', scheduleSelectionQuoteButton);+ listen(document, 'keydown', function (event) {+ if (event.key === 'Escape') hideSelectionQuoteButton();+ });+ registerDisposer(function () {+ if (selectionQuoteFrame !== null) {+ var cancel = window.cancelAnimationFrame || clearTimeout;+ try { cancel(selectionQuoteFrame); } catch (_) {}+ selectionQuoteFrame = null;+ }+ if (selectionQuoteButton) { selectionQuoteButton.remove(); selectionQuoteButton = null; }+ selectionQuotePending = null;+ });+ }/** 增强页快捷短语列表渲染(含批量模式) */function renderQpList() {var pane1 = enhancePane;@@ -2396,6 +2539,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {};}});+ // Composer content-block requests are handled by WorkBuddy's Slate owner.+ // Keep the original receiver so prototype methods retain their context.+ ['requestInsertContentBlocks', 'requestSendPrompt', 'onInsertContentBlocksRequest'].forEach(function (m) {+ if (typeof target[m] === 'function') {+ shim[m] = function () {+ return target[m].apply(target, arguments);+ };+ }+ });Object.defineProperty(shim, 'currentActiveSessionId', {enumerable: true,configurable: true,@@ -4484,6 +4636,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<label class="wbs-switch" title="在会话左侧显示消息索引"><input type="checkbox" id="wbs-sess-message-nav"><span class="wbs-switch-slider"></span></label>' +'</div>' +'<div class="wbs-nd-row">' ++ '<span class="wbs-nd-title">引用消息文本</span>' ++ '<span class="wbs-nd-hint">选中会话消息文字后,一键插入输入框。</span>' ++ '<label class="wbs-switch" title="选中会话消息中的文字后显示引用按钮"><input type="checkbox" id="wbs-sess-selection-quote"><span class="wbs-switch-slider"></span></label>' ++ '</div>' ++ '<div class="wbs-nd-row">' +'<span class="wbs-nd-title">快捷短语</span>' +'<span class="wbs-nd-hint">发送后不会自动删除。</span>' +'<label class="wbs-switch"><input type="checkbox" id="wbs-sess-phrase"><span class="wbs-switch-slider"></span></label>' +@@ -7164,6 +7321,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {writeMessageNavigationEnabled(sessState.messageNav);if (messageNavigation) messageNavigation.setEnabled(sessState.messageNav);});+ var swQ = pane2.querySelector('#wbs-sess-selection-quote');+ if (swQ) swQ.addEventListener('change', function () {+ sessState.selectionQuote = !!this.checked;+ writeSelectionQuoteEnabled(sessState.selectionQuote);+ if (!sessState.selectionQuote) hideSelectionQuoteButton();+ else scheduleSelectionQuoteButton();+ });var swP = pane2.querySelector('#wbs-sess-phrase');if (swP) swP.addEventListener('change', function () { setSessionSwitchWire('phraseEnabled', this); });var batchBtn = pane2.querySelector('#wbs-qp-batch');@@ -8188,6 +8352,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {try { ensureAutoContinueMonitor(); } catch (e) {}// 注入完成即同步会话模块状态(暂存/快捷短语开关 + 短语列表)并应用到输入框按钮显隐try { syncSessionModule(); } catch (e) {}+ // 选区引用按钮默认开启;开关关闭时仅保留监听器,重新开启无需重注入。+ try { setupSelectionQuote(); } catch (e) {}// 打开面板时校验指令块是否丢失,丢失则自动关闭开关(不弹 toast)try { acCheckPromptOnOpen(); } catch (e) {}// 按钮主题色(浅色黑底白图 / 深色白底黑图)+ 监听主题切换@@ -8260,6 +8426,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-message-nav-response{-webkit-line-clamp:6;margin-top:7px;padding-top:7px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.12));font-size:11px;font-weight:400;line-height:1.55;color:var(--wb-color-text-secondary,#5f626a)}','.wbs-message-nav-highlight{animation:wbs-message-nav-highlight .7s ease-out}','@keyframes wbs-message-nav-highlight{0%{box-shadow:0 0 0 3px color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 48%,transparent)}100%{box-shadow:0 0 0 8px transparent}}',+ /* WorkBuddy 内置引用 tooltip 复用快捷短语的气泡风格,长文本在气泡内滚动 */+ '.sq-tooltip-wrapper{width:max-content!important;max-width:calc(100vw - 24px)!important;padding:0!important;border:1px solid color-mix(in srgb,var(--wb-border-subtle,#ececec) 65%,transparent)!important;border-radius:8px!important;background:var(--wb-bg-popover,#fff)!important;box-shadow:0 6px 20px rgba(0,0,0,.16)!important;color:var(--wb-color-text-primary,#1f1f1f)}',+ '.sq-tooltip-wrapper .sq-popover,.sq-tooltip-wrapper .sq-image-preview{width:max-content;max-width:min(240px,calc(100vw - 24px));max-height:min(48vh,240px);box-sizing:border-box;padding:5px 11px;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain}',+ '.sq-tooltip-wrapper .sq-popover__row--title,.sq-tooltip-wrapper .sq-image-preview__title-row{display:none!important}',+ '.sq-tooltip-wrapper .sq-popover__locate-btn,.sq-tooltip-wrapper .sq-image-preview__locate-fab{display:none!important}',+ '.sq-tooltip-wrapper .sq-popover__row--selection{align-items:flex-start}',+ '.sq-tooltip-wrapper .sq-popover__preview{display:block;max-height:min(44vh,220px);overflow-x:hidden;overflow-y:auto;overflow-wrap:anywhere;word-break:break-word;white-space:pre-wrap;text-overflow:clip;scrollbar-width:thin}',+ 'html.cb-dark .sq-tooltip-wrapper{background:var(--wb-bg-popover,#202126)!important;border-color:color-mix(in srgb,var(--wb-border-subtle,#ececec) 65%,transparent)!important;color:var(--wb-color-text-primary,#f2f3f5)}',+ /* 复用 WorkBuddy 官方 InputContextTag 的消息图标与关闭图标,仅修正 sceneTag 的 hover 覆盖规则。 */+ '.slate-selection-quote-sceneTag._hasCloseIcon:hover [class*="iconContainer"],.slate-selection-quote-sceneTag__readOnly._hasCloseIcon:hover [class*="iconContainer"]{visibility:hidden!important}',+ '.wbs-selection-quote-btn{position:fixed;z-index:1000;display:none;align-items:center;justify-content:center;min-width:64px;height:30px;box-sizing:border-box;padding:0 10px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.18));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 7px 18px rgba(20,24,32,.2),inset 0 1px 0 rgba(255,255,255,.45);backdrop-filter:blur(12px) saturate(1.2);-webkit-backdrop-filter:blur(12px) saturate(1.2);cursor:pointer;outline:none;font:inherit;font-size:12px;line-height:1;white-space:nowrap;transition:background .15s,border-color .15s,box-shadow .15s;color-scheme:light}',+ '.wbs-selection-quote-btn:hover,.wbs-selection-quote-btn:focus-visible{background:color-mix(in srgb,var(--wb-bg-hover,#f3f3f3) 86%,transparent);border-color:var(--wb-border-default,#d5d5d5);box-shadow:0 8px 20px rgba(20,24,32,.2),inset 0 1px 0 rgba(255,255,255,.35)}',+ 'html.cb-dark .wbs-selection-quote-btn,html[data-theme="dark"] .wbs-selection-quote-btn,body[data-vscode-theme-name*="dark" i] .wbs-selection-quote-btn{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 70%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.16));color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 8px 22px rgba(0,0,0,.4),inset 0 1px 0 rgba(255,255,255,.08);color-scheme:dark}',+ 'html.cb-dark .wbs-selection-quote-btn:hover,html.cb-dark .wbs-selection-quote-btn:focus-visible,html[data-theme="dark"] .wbs-selection-quote-btn:hover,html[data-theme="dark"] .wbs-selection-quote-btn:focus-visible,body[data-vscode-theme-name*="dark" i] .wbs-selection-quote-btn:hover,body[data-vscode-theme-name*="dark" i] .wbs-selection-quote-btn:focus-visible{background:color-mix(in srgb,var(--wb-bg-hover,#303238) 84%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.2));box-shadow:0 9px 24px rgba(0,0,0,.38),inset 0 1px 0 rgba(255,255,255,.08)}','html.cb-dark .wbs-message-nav-rail,html[data-theme="dark"] .wbs-message-nav-rail,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 14%,transparent);border-color:transparent;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}','html.cb-dark .wbs-message-nav-rail:hover,html.cb-dark .wbs-message-nav-rail:focus-within,html[data-theme="dark"] .wbs-message-nav-rail:hover,html[data-theme="dark"] .wbs-message-nav-rail:focus-within,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail:hover,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-rail:focus-within{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 44%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.12));box-shadow:0 6px 20px rgba(0,0,0,.28);backdrop-filter:blur(14px) saturate(1.12);-webkit-backdrop-filter:blur(14px) saturate(1.12)}','html.cb-dark .wbs-message-nav-tooltip,html[data-theme="dark"] .wbs-message-nav-tooltip,body[data-vscode-theme-name*="dark" i] .wbs-message-nav-tooltip{background:color-mix(in srgb,var(--wb-bg-popover,#202126) 70%,transparent);border-color:var(--wb-border-subtle,rgba(255,255,255,.14));color:var(--wb-color-text-primary,#f2f3f5);box-shadow:0 14px 38px rgba(0,0,0,.42),inset 0 1px 0 rgba(255,255,255,.08)}',diff --git a/scripts/sentry-report.js b/scripts/sentry-report.jsindex 3126729..e82caa9 100644--- a/scripts/sentry-report.js+++ b/scripts/sentry-report.js@@ -23,11 +23,12 @@ const CLIENT_VARIANT = PROFILE_ID === 'workbuddy-ai' ? 'workbuddy-ai'const CLIENT_NAME = CLIENT_VARIANT === 'workbuddy-ai' ? 'WorkBuddy AI': CLIENT_VARIANT === 'codebuddy-cn' ? 'CodeBuddy CN': CLIENT_VARIANT === 'codebuddy-intl' ? 'CodeBuddy' : 'WorkBuddy';-const SHARED_DATA_DIR = IS_WIN+const SHARED_DATA_DIR = process.env.WBSWITCH_SHARED_DATA_DIR || (IS_WIN? path.join(process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming'), 'WorkDaddy')- : path.join(HOME, 'Library', 'Application Support', 'WorkDaddy');+ : path.join(HOME, 'Library', 'Application Support', 'WorkDaddy'));const DATA_DIR = process.env.WBSWITCH_DATA_DIR || (PROFILE_ID === 'workbuddy-cn'? SHARED_DATA_DIR : path.join(SHARED_DATA_DIR, 'profiles', PROFILE_ID));+const INSTALLATION_ID_FILE = path.join(SHARED_DATA_DIR, 'installation-id');const OUTBOX_DIR = path.join(DATA_DIR, 'telemetry', 'outbox');const TELEMETRY_SETTINGS_FILE = path.join(DATA_DIR, 'telemetry-settings.json');const MAX_OUTBOX_FILES = 50;@@ -36,6 +37,47 @@ const REQUEST_TIMEOUT_MS = 3000;const MAX_TEXT = 6000;const FORCE_SEND_ATTEMPTS = 6;const FORCE_SEND_DELAYS_MS = [250, 500, 1000, 2000, 3000];+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;+let processInstallationId = null;++function installationId() {+ if (processInstallationId) return processInstallationId;+ const readPersisted = () => {+ const value = fs.readFileSync(INSTALLATION_ID_FILE, 'utf8').trim();+ if (!UUID_PATTERN.test(value)) throw new Error('invalid installation id');+ try { fs.chmodSync(INSTALLATION_ID_FILE, 0o600); } catch (_) {}+ return value.toLowerCase();+ };+ try {+ processInstallationId = readPersisted();+ return processInstallationId;+ } catch (_) {}++ const generated = crypto.randomUUID().toLowerCase();+ let temp = '';+ try {+ fs.mkdirSync(SHARED_DATA_DIR, { recursive: true, mode: 0o700 });+ try { fs.chmodSync(SHARED_DATA_DIR, 0o700); } catch (_) {}+ temp = `${INSTALLATION_ID_FILE}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;+ fs.writeFileSync(temp, generated + '\n', { flag: 'wx', mode: 0o600 });+ try {+ // Publish a fully-written inode atomically. Concurrent CN/AI starts either+ // create this link or read the winner; neither can observe a partial ID.+ fs.linkSync(temp, INSTALLATION_ID_FILE);+ try { fs.chmodSync(INSTALLATION_ID_FILE, 0o600); } catch (_) {}+ processInstallationId = generated;+ } catch (error) {+ if (!error || error.code !== 'EEXIST') throw error;+ processInstallationId = readPersisted();+ }+ } catch (_) {+ // Identity is diagnostic only. Never make startup depend on persistence.+ processInstallationId = generated;+ } finally {+ if (temp) try { fs.unlinkSync(temp); } catch (_) {}+ }+ return processInstallationId;+}function telemetrySettingsPath(env = process.env) {const dataDir = String(env.WBSWITCH_DATA_DIR || DATA_DIR);@@ -218,6 +260,7 @@ function makeEvent({ stage, message, level = 'error', tags = {}, extra = {}, excmessage: redactText(message || 'WorkDaddy telemetry event'),logger: 'workdaddy',release: `workdaddy@${version}`,+ user: { id: installationId() },tags: sanitize({source: 'workdaddy',stage: stage || 'unknown',diff --git a/scripts/win-launcher.js b/scripts/win-launcher.jsindex d70d378..1dd876e 100644--- a/scripts/win-launcher.js+++ b/scripts/win-launcher.js@@ -357,7 +357,8 @@ async function configureCdpPort() {}function strictPowerShellLines(cmd) {- const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', cmd], {+ const utf8Command = '$OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); ' + cmd;+ const result = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', utf8Command], {encoding: 'utf8', timeout: 10000, windowsHide: true,});if (result.error) throw result.error;@@ -1112,9 +1113,17 @@ function launchWorkBuddy(wb) {const child = spawn(wb, [args], {cwd: path.dirname(wb), detached: true, stdio: 'ignore', windowsHide: true,});- child.on('error', (e) => { log('启动 WorkBuddy 失败: ' + e.message); });+ const state = { method: 'node-spawn', pid: Number.isSafeInteger(child.pid) ? child.pid : null, errorCode: null, exitCode: null, signal: null };+ child.on('error', (e) => {+ state.errorCode = String(e && e.code || 'spawn-error').slice(0, 80);+ log('启动 WorkBuddy 失败: ' + e.message);+ });+ child.on('exit', (code, signal) => {+ state.exitCode = Number.isInteger(code) ? code : null;+ state.signal = signal ? String(signal).slice(0, 32) : null;+ });child.unref();- return { method: 'node-spawn', pid: child.pid };+ return state;}async function waitForWorkBuddyCdp(binary) {@@ -1249,6 +1258,37 @@ function runNativeHelper(args, options = {}) {return result;}+let nativeDiscoveryState = null;+let nativeWatchdogAttempts = [];+let nativeLaunchState = null;++function nativeWorkBuddyProcessSummary() {+ const summary = { queryStatus: null, count: 0, withPath: 0, uniquePathCount: 0 };+ try {+ const result = runNativeHelper(['--list-workbuddy', '--profile', PROFILE.id]);+ summary.queryStatus = result.status;+ if (result.status !== 0) return summary;+ const rows = JSON.parse(String(result.stdout || '[]'));+ if (!Array.isArray(rows)) return summary;+ const paths = [];+ summary.count = rows.length;+ for (const row of rows) {+ const value = String(row && row.path || '').trim();+ if (!value) continue;+ summary.withPath += 1;+ if (!paths.some((item) => sameWindowsPath(item, value))) paths.push(value);+ }+ summary.uniquePathCount = paths.length;+ } catch (error) {+ summary.errorCode = String(error && error.code || 'query-failed').slice(0, 80);+ }+ return summary;+}++function nativeWorkBuddyDiscoverySummary() {+ return nativeDiscoveryState ? { ...nativeDiscoveryState } : { completed: false };+}+function nativeWorkBuddyRunning() {const result = runNativeHelper(['--check-workbuddy', '--profile', PROFILE.id]);if (result.status === 10) return true;@@ -1258,37 +1298,169 @@ function nativeWorkBuddyRunning() {function findWorkBuddyNative() {const candidates = [];- const add = (value) => {+ const summary = {+ completed: false,+ nativeProcessCount: 0,+ explicitCandidateCount: 0,+ registeredCandidateCount: 0,+ portableCandidateCount: 0,+ scannedCandidateCount: 0,+ validCandidateCount: 0,+ };+ nativeDiscoveryState = summary;+ const add = (value, source) => {const candidate = String(value || '').trim().replace(/^"(.*)"(?:,\d+)?$/, '$1').replace(/,\d+$/, '');- if (candidate && !candidates.some((item) => sameWindowsPath(item, candidate))) candidates.push(candidate);+ if (!candidate || candidates.some((item) => sameWindowsPath(item.path, candidate))) return;+ candidates.push({ path: candidate, source });+ const key = source + 'CandidateCount';+ if (Object.hasOwn(summary, key)) summary[key] += 1;};- add(process.env.WBSWITCH_WORKBUDDY_BIN);- add(PROFILE.appPath);+ try {+ const result = runNativeHelper(['--list-workbuddy', '--profile', PROFILE.id]);+ summary.nativeProcessQueryStatus = result.status;+ if (result.status === 0) {+ const rows = JSON.parse(String(result.stdout || '[]'));+ if (Array.isArray(rows)) {+ summary.nativeProcessCount = rows.length;+ for (const row of rows) add(row && row.path, 'explicit');+ }+ }+ } catch (error) {+ summary.nativeProcessQueryError = String(error && error.code || 'query-failed').slice(0, 80);+ }+ add(process.env.WBSWITCH_WORKBUDDY_BIN, 'explicit');+ add(PROFILE.appPath, 'explicit');const local = process.env.LOCALAPPDATA || '';const programFiles = process.env.ProgramFiles || '';const programFilesX86 = process.env['ProgramFiles(x86)'] || '';+ const expectedName = PROFILE.id === 'workbuddy-ai' ? 'WorkBuddyAI.exe' : 'WorkBuddy.exe';+ if (process.env.WBSWITCH_WORKBUDDY_DIR) {+ add(path.join(process.env.WBSWITCH_WORKBUDDY_DIR, expectedName), 'explicit');+ }+ const appPathNames = PROFILE.id === 'workbuddy-ai' ? ['WorkBuddyAI.exe'] : ['WorkBuddy.exe'];+ const appPathKeys = [];+ for (const name of appPathNames) {+ appPathKeys.push(`HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${name}`);+ appPathKeys.push(`HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${name}`);+ }+ const appPathCommand = "$k=@(" + appPathKeys.map(powershellLiteral).join(',') + "); Get-ItemProperty $k -ErrorAction SilentlyContinue | ForEach-Object { if ($_.'(default)') { $_.'(default)' } elseif ($_.Path) { Join-Path $_.Path " + powershellLiteral(expectedName) + " } }";+ for (const candidate of bestEffortPowerShellLines(appPathCommand, 'App Paths')) add(candidate, 'registered');+ const uninstallCommand = "$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy' } | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation " + powershellLiteral(expectedName) + " } }";+ for (const candidate of bestEffortPowerShellLines(uninstallCommand, '卸载注册表')) add(candidate, 'registered');if (PROFILE.id === 'workbuddy-ai') {- add(path.join(local, 'Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'));- add(path.join(local, 'Programs', 'WorkBuddy AI', 'WorkBuddyAI.exe'));- add(path.join(programFiles, 'WorkBuddyAI', 'WorkBuddyAI.exe'));- add(path.join(programFiles, 'WorkBuddy AI', 'WorkBuddyAI.exe'));- add(path.join(programFilesX86, 'WorkBuddyAI', 'WorkBuddyAI.exe'));- add(path.join(programFilesX86, 'WorkBuddy AI', 'WorkBuddyAI.exe'));+ add(path.join(local, 'Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'), 'portable');+ add(path.join(local, 'Programs', 'WorkBuddy AI', 'WorkBuddyAI.exe'), 'portable');+ add(path.join(programFiles, 'WorkBuddyAI', 'WorkBuddyAI.exe'), 'portable');+ add(path.join(programFiles, 'WorkBuddy AI', 'WorkBuddyAI.exe'), 'portable');+ add(path.join(programFilesX86, 'WorkBuddyAI', 'WorkBuddyAI.exe'), 'portable');+ add(path.join(programFilesX86, 'WorkBuddy AI', 'WorkBuddyAI.exe'), 'portable');} else {- add(path.join(local, 'Programs', 'WorkBuddy', 'WorkBuddy.exe'));- add(path.join(programFiles, 'WorkBuddy', 'WorkBuddy.exe'));- add(path.join(programFilesX86, 'WorkBuddy', 'WorkBuddy.exe'));+ add(path.join(local, 'Programs', 'WorkBuddy', 'WorkBuddy.exe'), 'portable');+ add(path.join(programFiles, 'WorkBuddy', 'WorkBuddy.exe'), 'portable');+ add(path.join(programFilesX86, 'WorkBuddy', 'WorkBuddy.exe'), 'portable');}- for (const candidate of candidates) {+ const driveRoots = bestEffortPowerShellLines('(Get-PSDrive -PSProvider FileSystem).Root', '磁盘根目录');+ for (const root of driveRoots) {+ add(path.join(root, 'Software', PROFILE.id === 'workbuddy-ai' ? 'workbuddy-ai' : 'workbuddy', expectedName), 'portable');+ add(path.join(root, PROFILE.id === 'workbuddy-ai' ? 'WorkBuddyAI' : 'WorkBuddy', expectedName), 'portable');+ }+ const scanDirs = PROFILE.id === 'workbuddy-ai'+ ? [path.join(local, 'Programs', 'WorkBuddyAI'), path.join(local, 'Programs', 'WorkBuddy AI'), path.join(local, 'WorkBuddyAI')]+ : [path.join(local, 'Programs', 'WorkBuddy'), path.join(local, 'WorkBuddy'), path.join(process.env.APPDATA || '', 'WorkBuddy')];+ const scanCommand = [+ '$roots=@(' + scanDirs.map(powershellLiteral).join(',') + ')',+ 'foreach($root in $roots){',+ 'if(-not (Test-Path -LiteralPath $root -PathType Container)){continue}',+ 'Get-ChildItem -LiteralPath $root -File -Recurse -Depth 5 -ErrorAction SilentlyContinue | Where-Object { $_.Name -ieq ' + powershellLiteral(expectedName) + ' } | Select-Object -ExpandProperty FullName',+ '}',+ ].join('; ');+ for (const candidate of bestEffortPowerShellLines(scanCommand, '安装目录扫描')) add(candidate, 'scanned');+ for (const item of candidates) {try {- if (!fs.statSync(candidate).isFile()) continue;- const expectedName = PROFILE.id === 'workbuddy-ai' ? 'workbuddyai.exe' : 'workbuddy.exe';- if (path.win32.basename(candidate).toLowerCase() === expectedName) return fs.realpathSync.native(candidate);+ if (!fs.statSync(item.path).isFile()) continue;+ if (path.win32.basename(item.path).toLowerCase() !== expectedName.toLowerCase()) continue;+ summary.validCandidateCount += 1;+ summary.selectedSource = item.source;+ summary.completed = true;+ return fs.realpathSync.native(item.path);} catch (_) {}}+ summary.completed = true;return null;}+async function stopVerifiedLegacyManagedLifecycle(bundledNode) {+ const legacyNode = findNode();+ if (!legacyNode || sameWindowsPath(legacyNode, bundledNode)) return false;+ await stopDaemonByPort(legacyNode);+ log('已通过验证边界停止旧托管 Node 的当前 profile 生命周期');+ return true;+}++async function nativeDaemonDiagnostics() {+ const result = {+ uiPort: UI_PORT,+ watchdogAttempts: nativeWatchdogAttempts.map((item) => ({ ...item })),+ watchdogPidFile: { present: false, valid: false, pid: null },+ daemonLockFile: { present: false },+ };+ try {+ result.listeners = listenerPids(UI_PORT);+ } catch (error) {+ result.listenerErrorCode = String(error && error.code || 'query-failed').slice(0, 80);+ }+ try {+ const pid = readWatchdogPid();+ result.watchdogPidFile = { present: pid !== null, valid: pid !== null, pid };+ } catch (_) {+ result.watchdogPidFile = { present: true, valid: false, pid: null };+ }+ try { result.daemonLockFile.present = fs.existsSync(path.join(DATA_DIR, '.daemon.lock')); } catch (_) {}+ try {+ const status = await readStatus();+ const identity = readDaemonIdentity();+ result.status = status ? {+ reachable: true,+ ok: status.ok === true,+ pid: Number.isSafeInteger(status.pid) ? status.pid : null,+ profileMatches: Boolean(status.profile && status.profile.id === PROFILE.id),+ dataDirMatches: Boolean(status.dataDir && sameWindowsPath(status.dataDir, DATA_DIR)),+ versionMatches: status.version === identity.version,+ buildMatches: status.buildId === identity.buildId,+ privilege: String(status.privilege || 'unknown').slice(0, 32),+ } : { reachable: false };+ result.statusPidMatchesListener = Boolean(status && Array.isArray(result.listeners) && result.listeners.length === 1 && status.pid === result.listeners[0]);+ } catch (error) {+ result.status = { reachable: false, errorCode: String(error && error.code || 'invalid-response').slice(0, 80) };+ }+ return result;+}++async function nativeCdpDiagnostics() {+ const ports = await Promise.all(cdpPortCandidates().map(async (port) => {+ const [version, targets] = await Promise.all([httpGet(port, '/json/version'), httpGet(port, '/json/list')]);+ let targetCount = null;+ let profileTarget = false;+ if (targets && targets.status === 200) {+ try {+ const rows = JSON.parse(targets.body || '[]');+ if (Array.isArray(rows)) {+ targetCount = rows.length;+ profileTarget = rows.some((target) => isTargetForProfile(target, PROFILE));+ }+ } catch (_) {}+ }+ return {+ port,+ versionStatus: version ? version.status : null,+ targetsStatus: targets ? targets.status : null,+ targetCount,+ profileTarget,+ };+ }));+ return { ports, launch: nativeLaunchState ? { ...nativeLaunchState } : null };+}+function nativeDaemonStatusMatches(status) {const identity = readDaemonIdentity();return Boolean(@@ -1328,14 +1500,23 @@ async function ensureDaemonNative(nodeBin) {return true;}if (status) {- log('daemon 身份或版本不匹配,使用原生 helper 停止当前 profile 生命周期');+ log('daemon 身份或版本不匹配,先检查旧托管 Node 生命周期');+ await stopVerifiedLegacyManagedLifecycle(nodeBin);stopNativeLifecycle();await sleep(800);}const startWatchdog = () => {log('通过内置 Node 启动无 CIM watchdog: ' + nodeBin);+ const attempt = { attempt: nativeWatchdogAttempts.length + 1, pid: null, errorCode: null, exitCode: null, signal: null };+ nativeWatchdogAttempts.push(attempt);const child = spawn(nodeBin, [WATCHDOG_SCRIPT], { detached: true, stdio: 'ignore', windowsHide: true, env: process.env });+ attempt.pid = Number.isSafeInteger(child.pid) ? child.pid : null;+ child.once('error', (error) => { attempt.errorCode = String(error && error.code || 'spawn-error').slice(0, 80); });+ child.once('exit', (code, signal) => {+ attempt.exitCode = Number.isInteger(code) ? code : null;+ attempt.signal = signal ? String(signal).slice(0, 32) : null;+ });child.unref();};startWatchdog();@@ -1345,16 +1526,21 @@ async function ensureDaemonNative(nodeBin) {// A previous watchdog may own the OS lock while its daemon is unhealthy.// Stop only the PID whose executable path is the bundled node, then retry once.log('首次等待 daemon 超时,原生 helper 清理精确 lifecycle 后重试');+ await stopVerifiedLegacyManagedLifecycle(nodeBin);stopNativeLifecycle();await sleep(800);startWatchdog();status = await waitForNativeDaemon();if (status) return true;- throw new Error('等待 WorkDaddy 后台服务启动超时');+ const error = new Error('等待 WorkDaddy 后台服务启动超时');+ error.sentryStage = 'windows-native-launcher-daemon-timeout';+ error.sentryExtra = { daemon: await nativeDaemonDiagnostics() };+ throw error;}async function waitForWorkBuddyCdpNative(binary) {const launched = launchWorkBuddy(binary);+ nativeLaunchState = launched;log('WorkBuddy 启动请求已派发 method=' + launched.method + ' expectedPort=' + CDP_PORT +(launched.pid ? ' pid=' + launched.pid : ''));const deadline = Date.now() + CDP_STARTUP_TIMEOUT_MS;@@ -1390,8 +1576,13 @@ async function nativeStartupMain() {const wb = findWorkBuddyNative();if (!wb) {- await captureMessage('未找到 WorkBuddy.exe', { stage: 'windows-native-launcher-workbuddy-path' }).catch(() => {});- throw new Error('未找到 WorkBuddy,请先安装对应客户端');+ const error = new Error('未找到 WorkBuddy,请先安装对应客户端');+ error.sentryStage = 'windows-native-launcher-workbuddy-path';+ error.sentryExtra = {+ discovery: nativeWorkBuddyDiscoverySummary(),+ processes: nativeWorkBuddyProcessSummary(),+ };+ throw error;}if (nativeWorkBuddyRunning()) {log('WorkBuddy 已运行但没有 CDP,交给原生启动器提示用户手动退出');@@ -1401,7 +1592,14 @@ async function nativeStartupMain() {const ok = await waitForWorkBuddyCdpNative(wb);if (!ok) {await captureMessage('等待 WorkBuddy CDP 端口超时', {- stage: 'windows-native-launcher-cdp-timeout', extra: { cdpPort: CDP_PORT, timeoutMs: CDP_STARTUP_TIMEOUT_MS },+ stage: 'windows-native-launcher-cdp-timeout',+ extra: {+ cdpPort: CDP_PORT,+ timeoutMs: CDP_STARTUP_TIMEOUT_MS,+ cdp: await nativeCdpDiagnostics(),+ processes: nativeWorkBuddyProcessSummary(),+ discovery: nativeWorkBuddyDiscoverySummary(),+ },}).catch(() => {});return 3;}@@ -1418,7 +1616,10 @@ if (require.main === module && process.env.WBSWITCH_NATIVE_LAUNCHER === '1') {nativeStartupMain().then((code) => process.exit(code)).catch((error) => {log('原生启动路径异常: ' + (error && error.stack || error));console.error(error && error.message || error);- captureException(error, { stage: 'windows-native-launcher-uncaught' })+ captureException(error, {+ stage: error && error.sentryStage || 'windows-native-launcher-uncaught',+ extra: error && error.sentryExtra || {},+ }).catch(() => {}).finally(() => process.exit(4));});} else if (require.main === module) (async () => {@@ -1496,6 +1697,7 @@ if (require.main === module && process.env.WBSWITCH_NATIVE_LAUNCHER === '1') {});module.exports = {+ strictPowerShellLines,getWorkBuddyProcesses,workBuddyProcesses,requireWorkBuddyClosedBeforeLaunch,diff --git a/scripts/windows-native/main.go b/scripts/windows-native/main.goindex 87fc31f..0a988f2 100644--- a/scripts/windows-native/main.go+++ b/scripts/windows-native/main.go@@ -345,6 +345,34 @@ func terminateExactNode(pid int, expectedNode string) (bool, int, error) {return terminateExactProcess(pid, expectedNode, "node")}+func stopInstalledLauncher(appDir string) int {+ expectedLauncher := filepath.Join(appDir, "WorkDaddyLauncher.exe")+ records, err := enumerateProcesses()+ if err != nil {+ fmt.Fprintln(os.Stderr, err)+ return exitFailure+ }+ matches := make([]processRecord, 0, 1)+ for _, record := range records {+ if strings.EqualFold(record.Name, "WorkDaddyLauncher.exe") && samePath(record.Path, expectedLauncher) {+ matches = append(matches, record)+ }+ }+ if len(matches) > 1 {+ fmt.Fprintln(os.Stderr, "发现多个当前安装目录的 WorkDaddyLauncher 进程,已拒绝批量结束")+ return exitIdentityMismatch+ }+ if len(matches) == 0 {+ return 0+ }+ _, code, stopErr := terminateExactProcess(int(matches[0].PID), expectedLauncher, "launcher")+ if stopErr != nil {+ fmt.Fprintln(os.Stderr, stopErr)+ return code+ }+ return 0+}+func uniqueRunningWorkBuddyPath(profile string, matches []processRecord) (string, error) {paths := make([]string, 0, len(matches))for _, match := range matches {@@ -434,6 +462,9 @@ func stopLifecycle(profile, appDir string) int {_ = os.Remove(candidate.path)}}+ if code := stopInstalledLauncher(appDir); code != 0 {+ return code+ }return 0}diff --git a/test/checkin-schedule.test.js b/test/checkin-schedule.test.jsnew file mode 100644index 0000000..3f1d778--- /dev/null+++ b/test/checkin-schedule.test.js@@ -0,0 +1,21 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');++const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');++test('daemon checks in shortly after startup and hourly thereafter', () => {+ assert.match(daemon, /const CHECKIN_STARTUP_DELAY_MS = 30 \* 1000;/);+ assert.match(daemon, /const CHECKIN_INTERVAL_MS = 60 \* 60 \* 1000;/);+ assert.match(daemon, /startupCheckinTimer = setTimeout\([\s\S]*?CHECKIN_STARTUP_DELAY_MS\);/);+ assert.match(daemon, /periodicCheckinTimer = setInterval\([\s\S]*?CHECKIN_INTERVAL_MS\);/);+ assert.doesNotMatch(daemon, /claimDailyForAll[\s\S]{0,180}3 \* 60 \* 60 \* 1000/);+});++test('check-in timers do not keep the daemon alive', () => {+ assert.match(daemon, /startupCheckinTimer\.unref && startupCheckinTimer\.unref\(\);/);+ assert.match(daemon, /periodicCheckinTimer\.unref && periodicCheckinTimer\.unref\(\);/);+});diff --git a/test/element-inspector.test.js b/test/element-inspector.test.jsindex 9d0158a..72df40c 100644--- a/test/element-inspector.test.js+++ b/test/element-inspector.test.js@@ -12,18 +12,21 @@ const pickerSource = fs.existsSync(pickerPath) ? fs.readFileSync(pickerPath, 'utconst daemonSource = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');const macBuildSource = fs.readFileSync(path.join(__dirname, '../scripts/build-mac-dmg.sh'), 'utf8');-const test = require('node:test');-const assert = require('node:assert/strict');-if (!pickerSource) {test('picker-internal.js 未就绪(内部模块不入库)', (t) => t.skip());} else {+ function functionSource(name, nextName) {+ const start = pickerSource.indexOf('function ' + name + '(');+ const end = pickerSource.indexOf('function ' + nextName + '(', start + 1);+ assert.ok(start >= 0 && end > start, `missing picker function ${name}`);+ return pickerSource.slice(start, end);+ }+test('拾取点击直接打开插件内 DOM 检查器', () => {- const handler = functionSource('showInspector', 'stopInspect');- const handler = functionSource('onInspectClick', 'onInspectKey');- assert.match(handler, /showInspector\(stack, el\)/);- assert.doesNotMatch(handler, /window\.open|api\(|element-inspector-url|open-url/);-});+ const handler = functionSource('onInspectClick', 'onInspectKey');+ assert.match(handler, /showInspector\(stack, el\)/);+ assert.doesNotMatch(handler, /window\.open|api\(|element-inspector-url|open-url/);+ });test('插件内检查器包含 DOM 树、重叠元素栈、节点详情和 HTML', () => {const handler = functionSource('showInspector', 'stopInspect');@@ -102,3 +105,4 @@ test('daemon 不再暴露 localhost 元素检查器页面与 bridge', () => {test('macOS 打包不再携带外部元素检查器文件', () => {assert.doesNotMatch(macBuildSource, /element-inspector\.js|element-inspector\.html/);});+}diff --git a/test/selection-quote.test.js b/test/selection-quote.test.jsnew file mode 100644index 0000000..79ad380--- /dev/null+++ b/test/selection-quote.test.js@@ -0,0 +1,45 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');++test('selection quote is a local session setting enabled by default and ordered after message navigation', () => {+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ const navigationSwitch = inject.indexOf('id="wbs-sess-message-nav"');+ const quoteSwitch = inject.indexOf('id="wbs-sess-selection-quote"');+ const phraseSwitch = inject.indexOf('id="wbs-sess-phrase"');++ assert.ok(navigationSwitch >= 0 && quoteSwitch > navigationSwitch && phraseSwitch > quoteSwitch);+ assert.match(inject, /workdaddy\.session\.selectionQuoteEnabled/);+ assert.match(inject, /<span class="wbs-nd-title">引用消息文本<\/span>/);+ assert.doesNotMatch(inject, /<span class="wbs-nd-title">选中文字引用<\/span>/);+ assert.match(inject, /localStorage\.getItem\(SELECTION_QUOTE_ENABLED_KEY\) !== '0'/);+ assert.match(inject, /localStorage\.setItem\(SELECTION_QUOTE_ENABLED_KEY, enabled \? '1' : '0'\)/);+});++test('selection quote uses the official content-block insertion request and avoids direct Slate DOM edits', () => {+ const inject = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'inject.js'), 'utf8');+ assert.match(inject, /requestInsertContentBlocks/);+ assert.match(inject, /contentBlocks: \[selectionQuoteBlock\(pending\.text\)\]/);+ assert.match(inject, /type: 'resource_link'/);+ assert.match(inject, /name: '引用文本'/);+ assert.match(inject, /displayText: '引用文本'/);+ assert.match(inject, /selectionQuote: true/);+ assert.match(inject, /selection:\/\/document-selection/);+ assert.match(inject, /selectionQuoteButton\.textContent = '引用文本'/);+ assert.doesNotMatch(inject, /selectionQuoteButton\.title/);+ assert.match(inject, /sq-tooltip-wrapper \.sq-popover__locate-btn[^']*display:none!important/);+ assert.match(inject, /sq-tooltip-wrapper \.sq-popover[^']*max-height:min\(48vh,240px\)/);+ assert.doesNotMatch(inject, /function syncSelectionQuoteIcons\(\)/);+ assert.doesNotMatch(inject, /container\.innerHTML = SELECTION_QUOTE_MESSAGE_ICON/);+ assert.match(inject, /InputContextTag/);+ assert.match(inject, /slate-selection-quote-sceneTag\._hasCloseIcon:hover[^']*visibility:hidden!important/);+ assert.match(inject, /wbs-selection-quote-btn\{position:fixed;z-index:1000;/);+ assert.doesNotMatch(inject, /wbs-selection-quote-btn\{position:fixed;z-index:2147483647;/);+ assert.match(inject, /background:color-mix\(in srgb,var\(--wb-bg-hover/);+ assert.doesNotMatch(inject, /wbs-selection-quote-btn:hover[^']*border-color:var\(--wb-accent-blue/);+ assert.match(inject, /backdrop-filter:blur\(12px\) saturate\(1\.2\)/);+ assert.match(inject, /html\.cb-dark \.wbs-selection-quote-btn/);+});diff --git a/test/sentry.test.js b/test/sentry.test.jsindex e0bedcc..d1e11bc 100644--- a/test/sentry.test.js+++ b/test/sentry.test.js@@ -14,29 +14,87 @@ const reporterSource = fs.readFileSync(reporter, 'utf8');const daemonSource = fs.readFileSync(path.join(repoRoot, 'scripts', 'daemon.js'), 'utf8');const injectSource = fs.readFileSync(path.join(repoRoot, 'scripts', 'inject.js'), 'utf8');-function dryRun(profile) {+function dryRun(profile, sharedDataDir) {const result = childProcess.spawnSync(process.execPath, [reporter, '--dry-run', '--stage', 'test', '--message', 'profile test'], {cwd: repoRoot,- env: { ...process.env, WBSWITCH_PROFILE: profile, WORKDADDY_TELEMETRY: '0' },+ env: {+ ...process.env,+ WBSWITCH_PROFILE: profile,+ WBSWITCH_SHARED_DATA_DIR: sharedDataDir,+ WORKDADDY_TELEMETRY: '0',+ },encoding: 'utf8',});assert.equal(result.status, 0, result.stderr);return JSON.parse(result.stdout);}+function dryRunAsync(profile, sharedDataDir) {+ return new Promise((resolve, reject) => {+ const child = childProcess.spawn(process.execPath, [reporter, '--dry-run', '--stage', 'test', '--message', 'profile test'], {+ cwd: repoRoot,+ env: {+ ...process.env,+ WBSWITCH_PROFILE: profile,+ WBSWITCH_SHARED_DATA_DIR: sharedDataDir,+ WORKDADDY_TELEMETRY: '0',+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', (chunk) => { stdout += chunk; });+ child.stderr.on('data', (chunk) => { stderr += chunk; });+ child.on('error', reject);+ child.on('exit', (code) => {+ if (code !== 0) reject(new Error(stderr || `Sentry dry run exited ${code}`));+ else {+ try { resolve(JSON.parse(stdout)); } catch (error) { reject(error); }+ }+ });+ });+}+test('Sentry events identify WorkBuddy CN and WorkBuddy AI without account data', () => {- const cn = dryRun('workbuddy-cn');- assert.equal(cn.tags.client, 'workbuddy');- assert.equal(cn.tags.client_name, 'WorkBuddy');- assert.equal(cn.tags.workbuddy_variant, 'workbuddy');- assert.deepEqual(cn.contexts.client, { name: 'WorkBuddy', profile: 'workbuddy-cn', variant: 'workbuddy' });-- const ai = dryRun('workbuddy-ai');- assert.equal(ai.tags.client, 'workbuddy-ai');- assert.equal(ai.tags.client_name, 'WorkBuddy AI');- assert.equal(ai.tags.workbuddy_variant, 'workbuddy-ai');- assert.deepEqual(ai.contexts.client, { name: 'WorkBuddy AI', profile: 'workbuddy-ai', variant: 'workbuddy-ai' });- assert.doesNotMatch(JSON.stringify(ai), /accessToken|refreshToken|cookie|password/i);+ const sharedDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-sentry-identity-'));+ try {+ const cn = dryRun('workbuddy-cn', sharedDataDir);+ assert.equal(cn.tags.client, 'workbuddy');+ assert.equal(cn.tags.client_name, 'WorkBuddy');+ assert.equal(cn.tags.workbuddy_variant, 'workbuddy');+ assert.deepEqual(cn.contexts.client, { name: 'WorkBuddy', profile: 'workbuddy-cn', variant: 'workbuddy' });++ const ai = dryRun('workbuddy-ai', sharedDataDir);+ assert.equal(ai.tags.client, 'workbuddy-ai');+ assert.equal(ai.tags.client_name, 'WorkBuddy AI');+ assert.equal(ai.tags.workbuddy_variant, 'workbuddy-ai');+ assert.deepEqual(ai.contexts.client, { name: 'WorkBuddy AI', profile: 'workbuddy-ai', variant: 'workbuddy-ai' });+ assert.match(cn.user.id, /^[0-9a-f]{8}-[0-9a-f-]{27}$/);+ assert.equal(ai.user.id, cn.user.id, 'CN and AI profiles must share one anonymous installation id');+ assert.equal(fs.readFileSync(path.join(sharedDataDir, 'installation-id'), 'utf8').trim(), cn.user.id);+ assert.doesNotMatch(JSON.stringify(ai), /accessToken|refreshToken|cookie|password/i);+ } finally {+ fs.rmSync(sharedDataDir, { recursive: true, force: true });+ }+});++test('concurrent first-run reporters publish one complete installation id', async () => {+ const sharedDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-sentry-concurrent-'));+ try {+ const events = await Promise.all(Array.from({ length: 12 }, (_, index) =>+ dryRunAsync(index % 2 ? 'workbuddy-ai' : 'workbuddy-cn', sharedDataDir)));+ const ids = new Set(events.map((event) => event.user && event.user.id));+ assert.equal(ids.size, 1);+ const [id] = ids;+ assert.match(id, /^[0-9a-f]{8}-[0-9a-f-]{27}$/);+ assert.equal(fs.readFileSync(path.join(sharedDataDir, 'installation-id'), 'utf8').trim(), id);+ if (process.platform !== 'win32') {+ assert.equal(fs.statSync(path.join(sharedDataDir, 'installation-id')).mode & 0o777, 0o600);+ assert.equal(fs.statSync(sharedDataDir).mode & 0o777, 0o700);+ }+ } finally {+ fs.rmSync(sharedDataDir, { recursive: true, force: true });+ }});test('diagnostic telemetry defaults on and respects explicit overrides', () => {diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex f1f56b4..a3e3da7 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -325,6 +325,18 @@ test('Windows launcher gives cold-start instances time before changing CDP portsassert.doesNotMatch(launcher, /diagnostics\.every\(\(p\) => p\.hasCommandLine\)/);});+test('session module read remains usable when first-run seed persistence fails', () => {+ const daemon = fs.readFileSync(path.join(repoRoot, 'scripts', 'daemon.js'), 'utf8');+ const start = daemon.indexOf('function readSessionState()');+ const end = daemon.indexOf('\nfunction writeSessionState', start);+ assert.ok(start >= 0 && end > start);+ const reader = daemon.slice(start, end);+ assert.match(reader, /try\s*\{[\s\S]*writeWorkbuddySettings\(s\)/);+ assert.match(reader, /catch \(error\)/);+ assert.match(reader, /session-seed-persist/);+ assert.match(reader, /return sessBuild\(st, phrases\)/);+});+test('macOS updater validates a cached/downloaded DMG before mounting it', () => {const daemon = read('daemon.js');assert.match(daemon, /hdiutil['"],\s*\['imageinfo'/);@@ -383,6 +395,9 @@ test('release scripts synchronize daemon version and build id', () => {assert.match(win, /staged daemon\.js DAEMON_BUILD_ID/);assert.match(mac, /const DAEMON_BUILD_ID = 'release-/);assert.match(mac, /产物 daemon\.js 的版本或 Build ID/);+ assert.match(mac, /PlistBuddy[^\n]+Set :CFBundleShortVersionString \$\{VERSION\}/);+ assert.match(mac, /PlistBuddy[^\n]+Set :CFBundleVersion \$\{VERSION\}/);+ assert.doesNotMatch(mac, /VERSION_CODE/);});test('daemon settings writes tolerate transient Windows file locks', () => {diff --git a/test/verify-win-exit.test.js b/test/verify-win-exit.test.jsindex 1346bae..c32ab09 100644--- a/test/verify-win-exit.test.js+++ b/test/verify-win-exit.test.js@@ -58,7 +58,8 @@ test('Windows verifier returns success for a complete source package', { skip: pconst scriptsDir = path.join(dir, 'scripts');const required = ['daemon.js', 'session-db.js', 'secure-transfer.js', 'lib.js', 'watchdog.js', 'win-launcher.js',- 'windows-process-boundary.js', 'windows-process-boundary.ps1', 'windows-relaunch-standard.ps1', 'inject.js',+ 'windows-process-boundary.js', 'windows-process-boundary.ps1', 'windows-relaunch-standard.ps1',+ 'workbuddy-compat.js', 'inject.js','theme-patches.js', 'launcher.cmd', 'launcher-hidden.vbs', 'install-win.cmd','install-win.ps1', 'prepare-win-install.ps1', 'uninstall-win.ps1', 'apply-update.ps1',path.join('win', 'setup.sed'), 'verify-win.cmd',diff --git a/test/windows-native-flow.test.js b/test/windows-native-flow.test.jsindex c3880b6..6f7a6a1 100644--- a/test/windows-native-flow.test.js+++ b/test/windows-native-flow.test.js@@ -6,6 +6,7 @@ const { EventEmitter } = require('node:events');const path = require('node:path');const test = require('node:test');const { launchWindowsInstaller } = require('../scripts/windows-installer-launch.js');+const { strictPowerShellLines } = require('../scripts/win-launcher.js');const root = path.join(__dirname, '..');const read = (relative) => fs.readFileSync(path.join(root, relative), 'utf8');@@ -129,3 +130,67 @@ test('native lifecycle cleanup accepts a PID that exits during exact inspection'assert.ok(missingPath >= 0 && exitedCheck > missingPath && mismatch > exitedCheck);assert.match(source.slice(exitedCheck, mismatch), /waitResult == waitObject0[\s\S]*return false, 0, nil/);});++test('installer lifecycle cleanup releases only the exact installed native launcher', () => {+ const source = read('scripts/windows-native/main.go');+ const stopStart = source.indexOf('func stopInstalledLauncher(appDir string) int');+ const stopEnd = source.indexOf('\nfunc uniqueRunningWorkBuddyPath(', stopStart);+ assert.ok(stopStart >= 0 && stopEnd > stopStart);+ const stop = source.slice(stopStart, stopEnd);+ assert.match(stop, /filepath\.Join\(appDir, "WorkDaddyLauncher\.exe"\)/);+ assert.match(stop, /enumerateProcesses\(\)/);+ assert.match(stop, /samePath\(record\.Path, expectedLauncher\)/);+ assert.match(stop, /len\(matches\) > 1[\s\S]*exitIdentityMismatch/);+ assert.match(stop, /terminateExactProcess\(int\(matches\[0\]\.PID\), expectedLauncher, "launcher"\)/);+});++test('native startup retains portable and registered WorkBuddy discovery without CIM', () => {+ const launcher = read('scripts/win-launcher.js');+ const nativeFinderStart = launcher.indexOf('function findWorkBuddyNative()');+ const nativeFinderEnd = launcher.indexOf('\nfunction nativeDaemonStatusMatches', nativeFinderStart);+ assert.ok(nativeFinderStart >= 0 && nativeFinderEnd > nativeFinderStart);+ const nativeFinder = launcher.slice(nativeFinderStart, nativeFinderEnd);+ assert.match(nativeFinder, /--list-workbuddy/);+ assert.match(nativeFinder, /WBSWITCH_WORKBUDDY_DIR/);+ assert.match(nativeFinder, /App Paths/);+ assert.match(nativeFinder, /CurrentVersion\\\\Uninstall/);+ assert.match(nativeFinder, /Get-ChildItem[\s\S]*-Depth 5/);+ assert.doesNotMatch(nativeFinder, /Get-CimInstance/);+});++test('PowerShell discovery preserves non-ASCII installation paths', { skip: process.platform !== 'win32' }, () => {+ const expected = 'D:\\沃克巴迪\\WorkBuddyAI\\WorkBuddyAI.exe';+ assert.deepEqual(strictPowerShellLines(`Write-Output '${expected}'`), [expected]);+});++test('native upgrade stops a managed-Node lifecycle only through the verified JS boundary', () => {+ const launcher = read('scripts/win-launcher.js');+ assert.match(launcher, /async function stopVerifiedLegacyManagedLifecycle\(bundledNode\)/);+ const cleanupStart = launcher.indexOf('async function stopVerifiedLegacyManagedLifecycle(bundledNode)');+ const cleanupEnd = launcher.indexOf('\nfunction nativeDaemonStatusMatches', cleanupStart);+ const cleanup = launcher.slice(cleanupStart, cleanupEnd);+ assert.match(cleanup, /findNode\(\)/);+ assert.match(cleanup, /sameWindowsPath\(legacyNode, bundledNode\)/);+ assert.match(cleanup, /await stopDaemonByPort\(legacyNode\)/);+ assert.doesNotMatch(cleanup, /taskkill|terminateExactNode/);+ const ensureStart = launcher.indexOf('async function ensureDaemonNative(nodeBin)');+ const ensureEnd = launcher.indexOf('\nasync function waitForWorkBuddyCdpNative', ensureStart);+ const ensure = launcher.slice(ensureStart, ensureEnd);+ assert.ok(+ ensure.indexOf('stopVerifiedLegacyManagedLifecycle(nodeBin)') < ensure.indexOf('stopNativeLifecycle()'),+ 'verified legacy cleanup must run before the bundled-node-only native helper'+ );+});++test('native startup failures report one structured diagnostic event', () => {+ const launcher = read('scripts/win-launcher.js');+ const nativeMainStart = launcher.indexOf('async function nativeStartupMain()');+ const nativeMainEnd = launcher.indexOf('\n// ---------- legacy script entry', nativeMainStart);+ const nativeMain = launcher.slice(nativeMainStart, nativeMainEnd);+ assert.match(nativeMain, /nativeWorkBuddyDiscoverySummary\(\)/);+ assert.match(nativeMain, /nativeCdpDiagnostics/);+ assert.doesNotMatch(nativeMain, /captureMessage\('未找到 WorkBuddy\.exe'/);+ assert.match(launcher, /error\.sentryStage/);+ assert.match(launcher, /error\.sentryExtra/);+ assert.match(launcher, /nativeDaemonDiagnostics/);+});