Skip to content

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

feat: consolidate WorkDaddy 1.2.10

[email protected]7848b2cc1414
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index c242499..7bc170b 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 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-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.
@@ -362,12 +362,12 @@ if [ "$TARGET_APP_BUNDLE" = "$APP_BIN" ] || [ ! -d "$TARGET_APP_BUNDLE" ]; then
notify "WorkDaddy" "WorkBuddy 应用路径无效,启动失败"
exit 1
fi
-NATIVE_ARGS=()
+OPEN_ARGS=(--args "--remote-debugging-port=$PORT")
case "$PROFILE" in
- codebuddy-cn) NATIVE_ARGS=(--inspect=127.0.0.1:9244) ;;
- codebuddy-intl) NATIVE_ARGS=(--inspect=127.0.0.1:9245) ;;
+ codebuddy-cn) OPEN_ARGS+=(--inspect=127.0.0.1:9244) ;;
+ codebuddy-intl) OPEN_ARGS+=(--inspect=127.0.0.1:9245) ;;
esac
-if ! /usr/bin/open -a "$TARGET_APP_BUNDLE" --args "--remote-debugging-port=$PORT" "${NATIVE_ARGS[@]}"; then
+if ! /usr/bin/open -a "$TARGET_APP_BUNDLE" "${OPEN_ARGS[@]}"; then
notify "WorkDaddy" "无法启动 WorkBuddy,请重试"
exit 1
fi'''
diff --git a/scripts/cdp-targets.js b/scripts/cdp-targets.js
index 332b746..c2806ec 100644
--- a/scripts/cdp-targets.js
+++ b/scripts/cdp-targets.js
@@ -131,7 +131,12 @@ function selectPageTarget(targets, profile) {
if (!isTargetForProfile(target, profile)) return false;
// CodeBuddy's standalone Agents window is distinct from the IDE and its
// extension webviews. Wait for that window instead of attaching to the IDE.
- return profile.kind !== 'codebuddy' || /\/agentManager\.html(?:[?#]|$)/i.test(String(target.url || ''));
+ // [CodeBuddy IDE 状态栏] 主连接保持 1.2.9 原行为:只认 agentManager.html。
+ // IDE 主窗口(workbench.html)不走主连接——daemon 会先选到先出现的 workbench
+ // 且不再重选,导致后打开的 agents 窗口永远等不到完整面板注入;因此 workbench
+ // 由 selectIdeTargets 交给 daemon 内独立的 IDE 浮层管理器并行注入。
+ if (profile.kind !== 'codebuddy') return true;
+ return /\/agentManager\.html(?:[?#]|$)/i.test(String(target.url || ''));
});
const score = (target) => {
const url = String(target && target.url || '');
@@ -142,4 +147,17 @@ function selectPageTarget(targets, profile) {
return candidates.sort((a, b) => score(a) - score(b))[0] || null;
}
-module.exports = { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget };
+/**
+ * [CodeBuddy IDE 状态栏] 选出需要注入轻量浮层的 IDE 工作台页面。
+ * codebuddy profile 专属:返回全部 workbench.html 页面(每个 IDE 窗口一条独立连接,
+ * 由 daemon 的 IDE 浮层管理器维护);非 codebuddy profile 返回空数组。
+ * inject.js 运行时通过 location.href 自判 IDE 模式,无需 target 侧附加标记。
+ */
+function selectIdeTargets(targets, profile) {
+ if (!profile || profile.kind !== 'codebuddy') return [];
+ return (Array.isArray(targets) ? targets : []).filter((target) =>
+ isTargetForProfile(target, profile)
+ && /\/workbench\.html(?:[?#]|$)/i.test(String(target.url || '')));
+}
+
+module.exports = { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget, selectIdeTargets };
diff --git a/scripts/credit-segments.js b/scripts/credit-segments.js
index dac831e..102b812 100644
--- a/scripts/credit-segments.js
+++ b/scripts/credit-segments.js
@@ -81,6 +81,23 @@ function firstTimestamp(value, fields) {
return null;
}
+// [积分段到期修正] 月度套餐基础包(如套餐基础500)同时携带两类时间:
+// DeductionEndTime = 长期扣费有效期(如 2034,真正的权益期)
+// CycleEndTime = 本计费周期结束(月底 23:59:59,额度每月重发)
+// firstTimestamp 按字段优先级取值会把这类包判成 2034 年才过期,导致
+// 「即将过期」统计漏掉月底清零的额度。积分只在「扣费窗口 ∩ 计费周期」内可用,
+// 因此到期点应取候选字段中最早的非空值:月度包取到本周期 CycleEndTime,
+// 裂变包/一次性包两类字段相等(取最早无影响)。
+function earliestTimestamp(value, fields) {
+ let earliest = null;
+ for (const field of fields) {
+ const parsed = parseTimestamp(value && value[field]);
+ if (parsed === null) continue;
+ if (earliest === null || parsed < earliest) earliest = parsed;
+ }
+ return earliest;
+}
+
function firstText(value, fields) {
for (const field of fields) {
const text = value && value[field];
@@ -102,7 +119,7 @@ function extractCreditSegments(accounts, source) {
return {
remaining: Number(remaining.toFixed(2)),
total: Number((total === null ? remaining : Math.max(total, remaining)).toFixed(2)),
- expiresAt: firstTimestamp(item, EXPIRY_FIELDS),
+ expiresAt: earliestTimestamp(item, EXPIRY_FIELDS),
source: firstText(item, LABEL_FIELDS) || source || '积分',
packageCode: item && item.PackageCode ? String(item.PackageCode) : '',
};
diff --git a/scripts/daemon.js b/scripts/daemon.js
index aebd9c5..848088e 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -163,7 +163,7 @@ const { readWorkBuddyTarget } = require('./workbuddy-target.js');
const { BINDING, createRendererApiBridge, rendererBridgeSource } = require('./renderer-api-bridge.js');
const { createCodeBuddyNative } = require('./codebuddy-native.js');
const { createCodeBuddySessionStore } = require('./codebuddy-session-store.js');
-const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget } = require('./cdp-targets.js');
+const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget, selectIdeTargets } = require('./cdp-targets.js');
const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');
const { createDirtyIndex } = require('./session-dirty.js');
const {
@@ -432,8 +432,9 @@ const primaryAccountStore = createPrimaryAccountStore(DATA_DIR, (uid) => fs.exis
// 1.2.188:关闭主题接管时跟随 WorkBuddy AI 的原生 agent-ui-theme,避免旧快照覆盖官方浅色/深色选择。
// 1.2.189:毛玻璃底色等待移至 daemon,避免后台页面定时器节流拖延开关和壁纸加载。
// 1.2.191:CodeDaddy 共用完整面板,通过本机 CDP 适配通信、原生登录态和会话缓存。
-const DAEMON_VERSION = '1.2.205';
-const DAEMON_BUILD_ID = 'release-1.2.205-20260929-codebuddy-cn-executable';
+// 1.2.10:合并会话、用量、启动器及 CodeBuddy IDE 注入重试与积分刷新修复。
+const DAEMON_VERSION = '1.2.10';
+const DAEMON_BUILD_ID = 'release-1.2.10-20260930-markdown-preview';
const usageReporter = createUsageReporter({ profile: PROFILE.id, version: DAEMON_VERSION });
configureAutomationRuntime({version: DAEMON_VERSION, profileId: PROFILE.id, platform: process.platform});
const automationDiscovery = createAutomationDiscovery({
@@ -2305,6 +2306,165 @@ function onCdpEvent(method, params) {
}
}
+// ===== [CodeBuddy IDE 状态栏] IDE 主窗口轻量浮层管理器 =====
+// 主连接(connectCdp)保持 1.2.9 原行为:只绑定 agentManager.html(完整面板)。
+// IDE 主窗口(workbench.html)由本管理器并行维护:每个 IDE 窗口一条独立 ws,
+// 只注入轻量 FAB(inject.js 运行时通过 location.href 自判 IDE 分支)。
+// 主连接单 target 且不重选:若让 workbench 走主连接,先出现的 workbench 会被
+// 绑定,后打开的 agents 窗口将永远等不到注入(实测回归),故必须双路。
+const idePages = new Map(); // Per-target connection, navigation and injection retry state.
+const IDE_INJECT_MAX_ATTEMPTS = 3;
+const IDE_COMMAND_TIMEOUT_MS = 10000;
+
+function ideSend(entry, method, params = {}) {
+ return new Promise((resolve, reject) => {
+ if (!entry.ws || entry.ws.readyState !== 1) return reject(new Error('IDE ws 未连接'));
+ const id = ++entry.msgId;
+ const timer = setTimeout(() => {
+ entry.pending.delete(id);
+ reject(new Error('IDE CDP request timed out'));
+ }, IDE_COMMAND_TIMEOUT_MS);
+ entry.pending.set(id, { resolve, reject, timer });
+ try {
+ entry.ws.send(JSON.stringify({ id, method, params }));
+ } catch (e) {
+ entry.pending.delete(id);
+ clearTimeout(timer);
+ reject(e);
+ }
+ });
+}
+
+function ideInjectPage(entry, reason) {
+ if (entry.injecting) return entry.injecting;
+ if (entry.closed || entry.mounted || entry.attempts >= IDE_INJECT_MAX_ATTEMPTS || Date.now() < entry.retryAt) return Promise.resolve();
+ const navigation = entry.navigation;
+ entry.attempts++;
+ entry.injecting = (async () => {
+ try {
+ const script = buildInjectScript();
+ // 与主连接注入管线一致:先注册 binding(rendererBridgeSource 的 __wbsApiFetch 依赖它)
+ await ideSend(entry, 'Runtime.addBinding', { name: BINDING });
+ if (entry.closed || entry.navigation !== navigation) return;
+ // 脚本顶部 cleanup IIFE 已移除 #wbs-ide-statusbar-root,这里不重复清理
+ const result = await ideSend(entry, 'Runtime.evaluate', { expression: script, returnByValue: false });
+ if (result && result.exceptionDetails) {
+ const ex = result.exceptionDetails.exception;
+ log(`[cdp-ide] IDE 浮层注入抛错(${reason}): ${redactDiagnosticText((ex && (ex.description || ex.value)) || result.exceptionDetails.text || '', 300)}`);
+ return;
+ }
+ // IDE 分支不挂 .wbs-root/__wbsWidget,只认 FAB 根节点
+ let mounted = false;
+ for (let attempt = 0; attempt < 3 && !mounted && !entry.closed && entry.navigation === navigation; attempt++) {
+ await new Promise((resolve) => setTimeout(resolve, attempt === 0 ? 200 : 600));
+ if (entry.closed || entry.navigation !== navigation) return;
+ const check = await ideSend(entry, 'Runtime.evaluate', {
+ expression: 'JSON.stringify({ fab: !!document.getElementById("wbs-ide-statusbar-root"), ready: document.readyState })',
+ returnByValue: true,
+ }).catch(() => null);
+ const state = check && check.result && check.result.value ? JSON.parse(check.result.value) : {};
+ mounted = !!state.fab;
+ if (attempt === 2) log(`[cdp-ide] IDE 浮层注入${mounted ? '确认' : '未确认'}(${reason}): ${JSON.stringify(state)}`);
+ }
+ if (entry.closed || entry.navigation !== navigation) return;
+ entry.mounted = mounted;
+ if (mounted) log(`[cdp-ide] IDE 浮层已注入(${reason}) target=${String(entry.url || '').slice(-64)}`);
+ } catch (e) {
+ log(`[cdp-ide] IDE 浮层注入失败(${reason}): ${e.message}`);
+ }
+ })().finally(() => {
+ entry.injecting = null;
+ if (!entry.closed && entry.navigation === navigation && !entry.mounted) {
+ entry.retryAt = Date.now() + 1000 * (2 ** (entry.attempts - 1));
+ }
+ });
+ return entry.injecting;
+}
+
+function ideConnectPage(target) {
+ const entry = { ws: null, url: target.url, msgId: 0, pending: new Map(), reloadTimer: null,
+ injecting: null, mounted: false, attempts: 0, retryAt: 0, navigation: 0, closed: false };
+ idePages.set(target.id, entry);
+ // [CodeBuddy IDE 状态栏] workbench 页面 CSP 禁止直接 fetch http://,api() 走
+ // __wbsApiFetch(Runtime.bindingCalled 通道)。主连接的 bridge 把 send 绑死在
+ // cdpSend 上,因此每个 IDE 页面必须建自己的 bridge 实例,回复才能回到同一页面。
+ entry.bridge = createRendererApiBridge({ token: API_TOKEN, port: () => ACTUAL_PORT, send: (method, params) => ideSend(entry, method, params) });
+ const ws = new WebSocketCtor(target.webSocketDebuggerUrl);
+ entry.ws = ws;
+ ws.onopen = () => {
+ ideSend(entry, 'Page.enable').catch(() => {}); // 监听 loadEventFired 以便刷新后补注入
+ ideInjectPage(entry, 'connect');
+ };
+ ws.onmessage = (ev) => {
+ let msg;
+ try { msg = JSON.parse(ev.data); } catch (_) { return; }
+ if (msg.id !== undefined) {
+ const p = entry.pending.get(msg.id);
+ if (p) {
+ entry.pending.delete(msg.id);
+ clearTimeout(p.timer);
+ msg.error ? p.reject(new Error(msg.error.message)) : p.resolve(msg.result);
+ }
+ return;
+ }
+ // IDE 浮层 FAB 的账号列表/切换请求经 binding 通道进来,用本页 bridge 应答
+ if (msg.method === 'Runtime.bindingCalled') {
+ entry.bridge(msg.params || {}).catch(() => {});
+ return;
+ }
+ // workbench 刷新会重建 DOM,加载完成后补一次注入(脚本幂等)
+ if (msg.method === 'Page.loadEventFired') {
+ entry.navigation++;
+ entry.mounted = false;
+ entry.attempts = 0;
+ entry.retryAt = Date.now() + 400;
+ if (entry.reloadTimer) clearTimeout(entry.reloadTimer);
+ entry.reloadTimer = setTimeout(() => {
+ entry.reloadTimer = null;
+ if (entry.ws && entry.ws.readyState === 1) ideInjectPage(entry, 'reload');
+ }, 400);
+ }
+ };
+ ws.onclose = () => {
+ entry.closed = true;
+ for (const pending of entry.pending.values()) {
+ clearTimeout(pending.timer);
+ pending.reject(new Error('IDE CDP connection closed'));
+ }
+ entry.pending.clear();
+ if (entry.reloadTimer) clearTimeout(entry.reloadTimer);
+ if (idePages.get(target.id) === entry) idePages.delete(target.id);
+ log(`[cdp-ide] IDE 页面连接关闭 target=${String(target.url || '').slice(-64)}`);
+ };
+ ws.onerror = () => {};
+}
+
+async function ideSyncScan() {
+ if (PROFILE.kind !== 'codebuddy' || !WebSocketCtor) return;
+ let port = cdp.port;
+ if (!port) port = await findCdpEndpoint();
+ if (!port) return;
+ let list;
+ try {
+ const r = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(1500) });
+ list = await r.json();
+ } catch (_) {
+ return; // 端口不可达,跳过本轮
+ }
+ const targets = selectIdeTargets(list, PROFILE);
+ for (const target of targets) {
+ if (!target.webSocketDebuggerUrl) continue;
+ const entry = idePages.get(target.id);
+ if (!entry) ideConnectPage(target);
+ else if (entry.ws && entry.ws.readyState === 1) ideInjectPage(entry, 'retry');
+ }
+ // 兜底清理:target 已消失但 ws 尚未触发 close 的陈旧条目
+ const alive = new Set(targets.map((t) => t.id));
+ for (const [id, entry] of idePages) {
+ if (!alive.has(id) && (!entry.ws || entry.ws.readyState !== 1)) idePages.delete(id);
+ }
+}
+
async function cdpLoop() {
for (;;) {
if (!cdp.connected) {
@@ -2314,6 +2474,8 @@ async function cdpLoop() {
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));
}
}
@@ -2349,9 +2511,21 @@ async function reloadWorkBuddyPage(options = {}) {
const pending = armPendingReloadInjection(frameId);
try {
await withTimeout(cdpSend('Page.reload', { ignoreCache: false }), 10000, '刷新 WorkBuddy 页面');
- if (options.waitForInjection === false) return true;
+ // WorkBuddy's SQLite replacement and renderer reload do not publish the
+ // local collection change. Refresh after WorkDaddy has mounted so the
+ // official controller sees migrated/history rows before user interaction.
+ const refreshAfterMount = pending.ready.then((mounted) => {
+ if (!mounted) return false;
+ const uid = String((currentAccount() || {}).uid || '').trim();
+ return refreshWorkBuddySessionList(uid, 'account-reload');
+ }).catch(() => false);
+ if (options.waitForInjection === false) {
+ refreshAfterMount.catch(() => {});
+ return true;
+ }
const mounted = await pending.ready;
if (!mounted) log('[cdp] 页面重载后组件未在 5 秒内确认挂载,继续后台流程');
+ if (mounted) await refreshAfterMount;
return mounted;
} catch (error) {
settlePendingReloadInjection(pending, false);
@@ -3905,6 +4079,7 @@ async function injectWidget(reason, executionContextId) {
}
function buildInjectScript() {
+ const markdownScript = fs.readFileSync(path.join(__dirname, 'markdown-preview.js'), 'utf8');
const toastScript = fs.readFileSync(path.join(__dirname, 'toast-runtime.js'), 'utf8');
const compatScript = fs.readFileSync(path.join(__dirname, 'workbuddy-compat.js'), 'utf8');
let injectScript = fs.readFileSync(path.join(__dirname, 'inject.js'), 'utf8');
@@ -3948,7 +4123,8 @@ function buildInjectScript() {
})();\n` : '';
let source = (PROFILE.kind === 'codebuddy' ? rendererBridgeSource() : '') + toastScript + '\n' + compatScript + '\n' + injectScript;
if (PROFILE.kind === 'codebuddy') source = source.replace(/\.innerHTML\b/g, '.__wbsHTML').replace(/\binnerHTML\s*:/g, '__wbsHTML:').replace(/\.outerHTML\b/g, '.__wbsOuterHTML').replace(/\.insertAdjacentHTML\b/g, '.__wbsInsertAdjacentHTML');
- return (trustedTypesBootstrap + source)
+ // Keep the sanitizer outside the legacy innerHTML sink rewrite.
+ return (trustedTypesBootstrap + markdownScript + '\n' + source)
.replace(/__WBS_API__/g, `http://${HOST}:${ACTUAL_PORT}`)
.replace(/__WBS_VERSION__/g, DAEMON_VERSION)
// 注入本地 API 能力凭证;旧版面板不会携带该 header,但新版 daemon 会在启动时重新注入新版面板。
@@ -4634,6 +4810,110 @@ function sessionCopyContentRevision(row) {
]);
}
+// WorkBuddy stores the context-window denominator on the session row and the
+// usage ring data in session_usage. Both are optional across client versions;
+// a missing column/table must not break account switching for older clients.
+let sessionContextWindowState = typeof PROFILE !== 'undefined' && PROFILE.kind === 'workbuddy' ? 'unknown' : 'unsupported';
+let sessionUsageState = typeof PROFILE !== 'undefined' && PROFILE.kind === 'workbuddy' ? 'unknown' : 'unsupported';
+
+function isMissingSessionStorageError(error) {
+ return /no such (table|column)/i.test(String(error && error.message || error || ''));
+}
+
+async function readSessionContextWindow(id) {
+ if (sessionContextWindowState === 'unsupported') return null;
+ try {
+ const rows = await sqliteQuery('SELECT context_window FROM sessions WHERE id = ? LIMIT 1;', [id]);
+ sessionContextWindowState = 'supported';
+ const value = rows && rows[0] && rows[0].context_window;
+ if (value === '' || value === null || value === undefined) return null;
+ const numeric = Number(value);
+ return Number.isFinite(numeric) && numeric >= 0 ? numeric : null;
+ } catch (error) {
+ if (isMissingSessionStorageError(error)) {
+ sessionContextWindowState = 'unsupported';
+ return null;
+ }
+ throw error;
+ }
+}
+
+async function writeSessionContextWindow(id, value) {
+ if (sessionContextWindowState === 'unsupported' || value === null || value === undefined) return;
+ try {
+ await sqliteRun(
+ 'UPDATE sessions SET context_window = ? WHERE id = ? AND deleted_at IS NULL;',
+ [value, id]
+ );
+ sessionContextWindowState = 'supported';
+ } catch (error) {
+ if (isMissingSessionStorageError(error)) {
+ sessionContextWindowState = 'unsupported';
+ return;
+ }
+ throw error;
+ }
+}
+
+async function copySessionUsage(sourceId, targetId) {
+ if (sessionUsageState === 'unsupported') return;
+ let sourceRows;
+ try {
+ sourceRows = await sqliteQuery(
+ 'SELECT used, size, updated_at, credit_json FROM session_usage WHERE session_id = ? LIMIT 1;',
+ [sourceId]
+ );
+ sessionUsageState = 'supported';
+ } catch (error) {
+ if (isMissingSessionStorageError(error)) {
+ sessionUsageState = 'unsupported';
+ return;
+ }
+ throw error;
+ }
+ if (!sourceRows || !sourceRows.length) return;
+ const source = sourceRows[0];
+ const used = source.used === '' ? null : Number(source.used);
+ const size = source.size === '' ? null : Number(source.size);
+ if (![used, size].every(value => value === null || Number.isFinite(value))) return;
+ let targetRows;
+ try {
+ targetRows = await sqliteQuery(
+ 'SELECT used, size, updated_at, credit_json FROM session_usage WHERE session_id = ? LIMIT 1;',
+ [targetId]
+ );
+ } catch (error) {
+ if (isMissingSessionStorageError(error)) {
+ sessionUsageState = 'unsupported';
+ return;
+ }
+ throw error;
+ }
+ const target = targetRows && targetRows[0];
+ if (target && String(target.used || '') === String(source.used || '') &&
+ String(target.size || '') === String(source.size || '') &&
+ String(target.updated_at || '') === String(source.updated_at || '') &&
+ String(target.credit_json || '') === String(source.credit_json || '')) return;
+ try {
+ await sqliteRun(
+ 'INSERT OR REPLACE INTO session_usage (session_id, used, size, updated_at, credit_json) VALUES (?, ?, ?, ?, ?);',
+ [
+ targetId,
+ used,
+ size,
+ source.updated_at === '' ? null : Number(source.updated_at),
+ source.credit_json === '' ? null : String(source.credit_json),
+ ]
+ );
+ } catch (error) {
+ if (isMissingSessionStorageError(error)) {
+ sessionUsageState = 'unsupported';
+ return;
+ }
+ throw error;
+ }
+}
+
// This revision is the cheap fallback used when the renderer event was
// missed. WorkBuddy advances updated_at for edits that do not necessarily
// change the sidebar lifecycle payload, so it is part of the observable
@@ -4818,6 +5098,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
))[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 = () => {
@@ -4866,7 +5147,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
// Fast path is opt-in by fingerprintVersion so mappings written before
// revision persistence are revalidated once through the normal snapshot
// comparison path.
- if (options.auto && existingMappingTarget && mapping.fingerprintVersion === 2 &&
+ if (options.auto && existingMappingTarget && mapping.fingerprintVersion === 3 &&
mappingSourceRevisionMatches(mapping, sourceUid, sourceRow) &&
mappingTargetRevisionMatches(mapping, existingMappingTarget)) {
const sourceBytes = Number(mapping.sourceBytes);
@@ -4882,10 +5163,31 @@ async function copySessionRecord(src, targetUid, options = {}) {
copiedBytes: 0,
};
}
- let left = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, sourceRow.id, aliases, syncCache);
+ // Version 3 proves transcript runtime IDs were rebound, not merely that
+ // two accounts have equal messages. Revalidate legacy mappings once.
+ let runtimeRepairBytes = 0;
+ const readAndRepairSnapshot = async id => {
+ let snapshot = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, id, aliases, syncCache);
+ if (PROFILE.kind !== 'workbuddy') return snapshot;
+ const row = id === sourceRow.id ? sourceRow : candidates.find(candidate => candidate.id === id);
+ const guard = async () => {
+ await assertSessionSyncIdle([id]);
+ if (row && JSON.stringify(await readRow(id, row.user_id)) !== JSON.stringify(row)) {
+ throw new Error('会话记录正在变化,请稍后重试');
+ }
+ };
+ const repaired = await sessionSync.repairRuntimeIdentity(snapshot, {
+ backupRoot: path.join(DATA_DIR, 'session-sync-backups'), guard,
+ commit: async verify => { await guard(); await verify(); },
+ });
+ runtimeRepairBytes += repaired.copiedBytes;
+ if (repaired.copied) snapshot = await sessionSync.readSnapshotAsync(PROFILE.dataRoot, id, aliases, syncCache);
+ return snapshot;
+ };
+ let left = await readAndRepairSnapshot(sourceRow.id);
const selection = await sessionSync.selectTargetSnapshot(left, targetIds, async id => {
await yieldAutoCopyToRenderer();
- return sessionSync.readSnapshotAsync(PROFILE.dataRoot, id, aliases, syncCache);
+ return readAndRepairSnapshot(id);
}, mapping && mapping.targetId);
// A divergent source still needs to reach the destination. Publish it as
// a new physical session in the same lineage, so later scans find it by
@@ -4904,7 +5206,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
await withAutoCopyMetaWrite(() => {
if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);
setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
- targetId, status: 'copied', failedFiles: 0, fingerprintVersion: 2,
+ targetId, status: 'copied', failedFiles: 0, fingerprintVersion: 3,
...mappingWithSourceRevision(mapping, sourceUid, sourceRow),
targetRevision: sessionCopyRowRevision(existing || { ...sourceRow, id: targetId, user_id: targetUid }),
targetStateRevision: sessionCopyStableStateRevision(existing || { ...sourceRow, id: targetId, user_id: targetUid }),
@@ -4913,7 +5215,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
});
const warning = left.totalBytes > 100 * 1024 * 1024 ? '会话超过 100 MB,同步可能较慢' : '';
clearAutoDirty();
- return { status: 'skipped', sourceId: src.id, targetId, branched: false, failedFiles: 0, warning, sourceBytes: left.totalBytes, totalBytes: left.totalBytes, copiedBytes: 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);
// Size is advisory only; both manual and automatic sync keep all files.
@@ -4926,9 +5228,9 @@ async function copySessionRecord(src, targetUid, options = {}) {
}
const comparison = sessionSync.compareSnapshots(left, right);
if (comparison.kind === 'conflict') throw new Error('会话记录正在变化,请稍后重试');
- let changed = false;
+ let changed = runtimeRepairBytes > 0;
let totalBytes = left.totalBytes;
- let copiedBytes = 0;
+ let copiedBytes = runtimeRepairBytes;
let persistedTargetRow = existing || null;
const update = async (from, to, fromRow, toRow, missingOnly = false) => {
await yieldAutoCopyToRenderer();
@@ -4948,6 +5250,8 @@ async function copySessionRecord(src, targetUid, options = {}) {
// after insertion cannot create an untracked duplicate on retry.
await withAutoCopyMetaWrite(() => addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId, { branchCopy: branched }));
persistedTargetRow = await insertCopiedSession(fromRow, targetUid, targetId);
+ await writeSessionContextWindow(targetId, sourceContextWindow);
+ await copySessionUsage(fromRow.id, targetId);
}
else if (!missingOnly) {
const updatedAt = Number(fromRow.updated_at || 0);
@@ -4957,6 +5261,8 @@ async function copySessionRecord(src, targetUid, options = {}) {
[fromRow.title || '', fromRow.custom_title || '', fromRow.status || 'Pending',
updatedAt, lastActivityAt, toRow.id, toRow.user_id]
);
+ await writeSessionContextWindow(toRow.id, sourceContextWindow);
+ await copySessionUsage(fromRow.id, toRow.id);
persistedTargetRow = Object.assign({}, toRow, {
title: fromRow.title || '', custom_title: fromRow.custom_title || '', status: fromRow.status || 'Pending',
updated_at: updatedAt, last_activity_at: lastActivityAt,
@@ -4988,7 +5294,7 @@ async function copySessionRecord(src, targetUid, options = {}) {
await withAutoCopyMetaWrite(() => {
if (!getAutoCopySessionMembers(DATA_DIR, lineageId, targetUid).includes(targetId)) addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, targetId);
return setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
- targetId, status: 'copied', failedFiles: 0, fingerprintVersion: 2,
+ targetId, status: 'copied', failedFiles: 0, fingerprintVersion: 3,
...mappingWithSourceRevision(mapping, sourceUid, sourceRow),
targetRevision: sessionCopyRowRevision(mappingTarget),
targetStateRevision: sessionCopyStableStateRevision(mappingTarget),
@@ -5042,7 +5348,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
? getSessionDirtyIndex()
: { shouldSync: () => true };
const clearStableDirtyMarker = (row, mapping, provenEqual = false) => {
- if (!mapping || mapping.fingerprintVersion !== 2 || !mapping.targetId ||
+ if (!mapping || mapping.fingerprintVersion !== 3 || !mapping.targetId ||
(!provenEqual && !mappingSourceRevisionMatches(mapping, source, row))) return false;
if (typeof dirtyIndex.get !== 'function' || typeof clearSessionDirty !== 'function') return false;
const marker = dirtyIndex.get(source, row.id);
@@ -5111,7 +5417,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
if (!initializedClean(row)) return false;
const lineageId = rules.allLineages && rules.allLineages[String(row.id)];
const mapping = lineageId ? mappings.get(String(lineageId)) : null;
- return mapping && mapping.fingerprintVersion === 2 && mapping.targetId &&
+ return mapping && mapping.fingerprintVersion === 3 && mapping.targetId &&
!mappingSourceRevisionMatches(mapping, source, row);
});
if (hasRevisionDrift) await loadTargetRows();
@@ -5143,7 +5449,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
// The target mapping is enough to restore the active view. Only enter
// the worker when it is missing, its row disappeared, or the renderer
// explicitly marked the source session dirty.
- if (!mapping || mapping.fingerprintVersion !== 2 || !mapping.targetId ||
+ if (!mapping || mapping.fingerprintVersion !== 3 || !mapping.targetId ||
!targetById || !targetById.has(String(mapping.targetId))) {
dirtyRows.push(row);
continue;
@@ -5171,6 +5477,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
}
const lineageId = rules.allLineages && rules.allLineages[String(row.id)];
const mapping = lineageId ? mappings.get(String(lineageId)) : null;
+ if (mapping && mapping.fingerprintVersion !== 3) { dirtyRows.push(row); continue; }
if (dirtyIndex.shouldSync(source, row.id)) {
if (clearStableDirtyMarker(row, mapping)) continue;
if (mappingSourceLifecycleRevisionMatches(mapping, row) && targetById && stableTargetExists(mapping)) {
@@ -5180,7 +5487,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
dirtyRows.push(row);
continue;
}
- if (!mapping || mapping.fingerprintVersion !== 2 || !mapping.targetId) { dirtyRows.push(row); continue; }
+ if (!mapping || mapping.fingerprintVersion !== 3 || !mapping.targetId) { dirtyRows.push(row); continue; }
if (mappingSourceRevisionMatches(mapping, source, row)) continue;
// Once the renderer has supplied a baseline, a persisted revision drift
// without a dirty event is historical lineage churn, not a content edit.
@@ -5217,7 +5524,7 @@ async function buildAutoCopyPlan(sourceUid, targetUid, requestedSessionIds = [])
// unchanged sessions do not need to enter the worker pool at all.
return lineageRows.filter((row) => {
const mapping = row.lineageId ? mappings.get(String(row.lineageId)) : null;
- if (!mapping || mapping.fingerprintVersion !== 2 || !mapping.targetId) return true;
+ if (!mapping || mapping.fingerprintVersion !== 3 || !mapping.targetId) return true;
const targetRow = targetById.get(String(mapping.targetId));
return !targetRow || !mappingSourceRevisionMatches(mapping, source, row) ||
(!mappingTargetRevisionMatches(mapping, targetRow) &&
@@ -5515,14 +5822,15 @@ function startAutoCopyJob(sourceUid, targetUid, plan, labels) {
return job;
}
-async function refreshCopiedSessionList(job) {
- // WorkBuddy copies commit SQLite directly, bypassing its list-change bus.
- // Its first post-switch snapshot can therefore predate this batch. Use the
- // official collection refresh (including grouped folders), never navigation
- // or a second renderer reload. CodeBuddy already publishes native upserts;
- // it has a different store and must not enter this SDK path.
- if (PROFILE.kind !== 'workbuddy' || !(job.copied || job.partial || job.conflicts)) return;
- if (!cdp.connected || String((currentAccount() || {}).uid || '') !== String(job.targetUid)) return;
+async function refreshWorkBuddySessionList(targetUid, reason = 'sessions') {
+ // WorkBuddy writes session SQLite directly, bypassing its list-change bus.
+ // Its first snapshot can therefore predate a migration, account switch, or
+ // copy batch. Use the official collection refresh (including grouped
+ // folders), never navigation or a second renderer reload. CodeBuddy already
+ // publishes native upserts; it has a different store and must not enter this
+ // SDK path.
+ if (PROFILE.kind !== 'workbuddy') return false;
+ if (!cdp.connected || String((currentAccount() || {}).uid || '') !== String(targetUid || '')) return false;
let timer;
try {
const response = await Promise.race([
@@ -5541,15 +5849,23 @@ async function refreshCopiedSessionList(job) {
// delay restoring the selected conversation indefinitely.
new Promise(resolve => { timer = setTimeout(() => resolve(null), 2000); }),
]);
- log('[sessions-auto-copy] 列表刷新' + (response && response.result && response.result.value === true ? '已完成' : '未确认;复制结果已保留'));
+ const confirmed = response && response.result && response.result.value === true;
+ log('[' + reason + '] 列表刷新' + (confirmed ? '已完成' : '未确认;已保留本地会话数据'));
+ return confirmed;
} catch (_) {
// A disconnected renderer cannot invalidate already committed files/rows.
- log('[sessions-auto-copy] 列表刷新暂不可用;复制结果已保留');
+ log('[' + reason + '] 列表刷新暂不可用;已保留本地会话数据');
+ return false;
} finally {
clearTimeout(timer);
}
}
+async function refreshCopiedSessionList(job) {
+ if (!job || !(job.copied || job.partial || job.conflicts || job.openSessionId)) return false;
+ return refreshWorkBuddySessionList(job.targetUid, 'sessions-auto-copy');
+}
+
function publicAutoCopyJob(job) {
if (!job) return null;
const copiedBytes = typeof job.copiedBytes === 'number' && Number.isFinite(job.copiedBytes) ? Math.max(0, job.copiedBytes) : null;
@@ -10461,7 +10777,7 @@ function handleApi(req, res) {
try {
const rows = await sqliteQuery(
'SELECT ' + SESSION_COPY_COLUMNS.join(',') +
- ' FROM sessions WHERE id = ? AND user_id = ? AND deleted_at IS NULL LIMIT 1;',
+ " FROM sessions WHERE id = ? AND (user_id = ? OR user_id = '') AND deleted_at IS NULL LIMIT 1;",
[id, uid]
);
if (!rows.length) return json(res, 404, { ok: false, error: '当前账号下没有该会话' });
@@ -10535,6 +10851,10 @@ function handleApi(req, res) {
log(`[sessions-auto-copy] 迁移规则 ${row.id} 失败: ${e.message}`);
}
}
+ // The migration changes ownership in SQLite without going through
+ // WorkBuddy's collection store. Refresh the visible account's list so
+ // a migrated history row is hydrated by the official controller.
+ await refreshWorkBuddySessionList(String((currentAccount() || {}).uid || '').trim(), 'sessions-migrate');
return json(res, 200, { ok: true, moved: before.length, requested: ids.length, targetUid, rulesMoved });
} catch (e) {
return json(res, 500, { ok: false, error: e.message });
diff --git a/scripts/inject.js b/scripts/inject.js
index 5c58279..2e60631 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -1092,6 +1092,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
for (var j = 0; j < ss.length; j++) ss[j].remove();
var dbg = document.querySelectorAll('#wbs-diag-badge, #wbs-debug-panel');
for (var k = 0; k < dbg.length; k++) dbg[k].remove();
+ // [CodeBuddy IDE 状态栏] 清理 IDE 模式注入的浮层 root 与原生菜单去重样式,确保 reinjection 幂等
+ var ideRoot = document.getElementById('wbs-ide-statusbar-root');
+ if (ideRoot) ideRoot.remove();
+ var ideDedupe = document.getElementById('wbs-ide-menu-dedupe-style');
+ if (ideDedupe) ideDedupe.remove();
var usageSummaryNodes = document.querySelectorAll('#wbs-session-usage-summary, #wbs-session-usage-popover');
for (var us = 0; us < usageSummaryNodes.length; us++) usageSummaryNodes[us].remove();
// 销毁所有历史 build:置 alive=false、断开全部 observer/事件监听。
@@ -1129,6 +1134,288 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var WBS_BRAND = CAPS.appName || (WBS_PROFILE_IS_AI ? 'WorkDaddy AI' : 'WorkDaddy');
var WBS_PANEL_TITLE = CAPS.apiTransport === 'cdp' ? 'WorkDaddy' : WBS_BRAND;
+ // IDE 与 Agents 共用下方的 WorkDaddy 面板;旧浮层不再调用。
+ function injectCodeBuddyIdeMode() {
+ var rootId = 'wbs-ide-statusbar-root';
+ var panelAppearance = CAPS.panelAppearance || 'light';
+ var robotStyle = CAPS.robotStyle || 'black';
+ var brand = WBS_BRAND || 'WorkDaddy';
+ var accountLoadSerial = 0;
+ var modalOpen = false;
+ // 复用主面板翻译管线(i18n-coverage.test.js 要求全部 UI 文案可翻译)
+ function t(s) { return wbsTranslateString(s, WBS_LANGUAGE); }
+
+ // 幂等:reinjection 时移除旧 root 与旧去重样式(cleanup 已移除一次,双保险)
+ var existing = document.getElementById(rootId);
+ if (existing) existing.remove();
+ var existingDedupe = document.getElementById('wbs-ide-menu-dedupe-style');
+ if (existingDedupe) existingDedupe.remove();
+
+ var root = document.createElement('div');
+ root.id = rootId;
+ root.setAttribute('data-wbs-profile', PROFILE_ID);
+ root.className = 'wbs-ide-root wbs-ide-' + panelAppearance + ' wbs-ide-robot-' + robotStyle;
+ root.appendChild(buildIdeStyleNode());
+ root.appendChild(buildIdeFabNode());
+ root.appendChild(buildIdeModalNode());
+
+ // [CodeBuddy IDE 状态栏] CodeBuddy 官方帐户菜单的账号行按"认证会话"累积渲染:genie 扩展
+ // 替换会话时只发 added 不发 removed(官方 logout 才清理),而菜单把每行都显示成当前
+ // 账号昵称 → WorkDaddy 原生切换后残留的旧账号条目看起来就是多个一模一样的"当前账号"。
+ // 缓解:隐藏第一个之外的所有账号行(被隐藏行点击行为本就为空,无功能损失)。
+ // ⚠️ 若官方将来支持真正的多账号展示(各行显示各自昵称),删除本规则即可。
+ var dedupeStyle = document.createElement('style');
+ dedupeStyle.id = 'wbs-ide-menu-dedupe-style';
+ dedupeStyle.textContent = 'li.genie-account-menu-item ~ li.genie-account-menu-item{display:none !important;}';
+
+ function appendRoot() {
+ document.body.appendChild(root);
+ document.head.appendChild(dedupeStyle);
+ }
+ if (document.body) appendRoot();
+ else document.addEventListener('DOMContentLoaded', appendRoot);
+
+ function openModal() {
+ modalOpen = true;
+ var modal = root.querySelector('.wbs-ide-modal');
+ if (modal) modal.style.display = 'flex';
+ loadAccounts();
+ }
+ function closeModal() {
+ modalOpen = false;
+ accountLoadSerial++;
+ var modal = root.querySelector('.wbs-ide-modal');
+ if (modal) modal.style.display = 'none';
+ }
+
+ function isCurrentAccountLoad(serial) {
+ return modalOpen && root.isConnected && serial === accountLoadSerial;
+ }
+
+ function loadAccounts() {
+ var body = root.querySelector('.wbs-ide-modal-body');
+ if (!body) return;
+ var serial = ++accountLoadSerial;
+ var refresh = root.querySelector('.wbs-ide-credit-refresh');
+ refresh.disabled = true;
+ body.innerHTML = '<div class="wbs-ide-hint">' + t('读取账号中…') + '</div>';
+ api('/api/accounts').then(function (data) {
+ if (!isCurrentAccountLoad(serial)) return;
+ var accounts = (data && data.accounts) || [];
+ accounts.forEach(function (account) { account.ideCreditState = 'loading'; });
+ renderAccounts(body, accounts, data && data.current && data.current.uid);
+ // Only two queries at a time; closing/reopening the modal invalidates the
+ // remaining queue and late responses from the previous account list.
+ var next = 0;
+ function worker() {
+ if (!isCurrentAccountLoad(serial) || next >= accounts.length) return Promise.resolve();
+ var account = accounts[next++];
+ return api('/api/credits', {
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ uid: account.uid })
+ }).then(function (result) {
+ if (!isCurrentAccountLoad(serial)) return;
+ account.credits = typeof result.credits === 'number' && isFinite(result.credits) ? result.credits : null;
+ account.creditUnlimited = !!result.unlimited;
+ account.creditSegments = Array.isArray(result.segments) ? result.segments : [];
+ account.ideCreditState = 'fresh';
+ }).catch(function () {
+ if (isCurrentAccountLoad(serial)) account.ideCreditState = 'failed';
+ }).then(function () {
+ if (!isCurrentAccountLoad(serial)) return;
+ account.ideCreditNode.textContent = formatIdeCredits(account);
+ return worker();
+ });
+ }
+ return Promise.all([worker(), worker()]);
+ }).catch(function (err) {
+ if (isCurrentAccountLoad(serial)) body.innerHTML = '<div class="wbs-ide-error">' + t('读取失败:') + escapeText(err && err.message || err) + '</div>';
+ }).finally(function () {
+ if (isCurrentAccountLoad(serial)) refresh.disabled = false;
+ });
+ }
+
+ function renderAccounts(container, accounts, currentUid) {
+ if (!accounts.length) {
+ container.innerHTML = '<div class="wbs-ide-hint">' + t('暂无已备份账号') + '</div>';
+ return;
+ }
+ container.innerHTML = '';
+ var list = document.createElement('div');
+ list.className = 'wbs-ide-account-list';
+ for (var i = 0; i < accounts.length; i++) list.appendChild(renderAccountRow(accounts[i], currentUid));
+ container.appendChild(list);
+ }
+
+ function renderAccountRow(account, currentUid) {
+ var row = document.createElement('div');
+ row.className = 'wbs-ide-account-row';
+ // [CodeBuddy IDE 状态栏] 两行结构:昵称/手机号 + 积分摘要(来自 daemon /api/accounts
+ // 的 credits/creditUnlimited/creditSegments 缓存,与智能体面板同源数据)
+ var text = document.createElement('div');
+ text.className = 'wbs-ide-account-text';
+ var label = document.createElement('div');
+ label.className = 'wbs-ide-account-label';
+ var nick = escapeText(account.nickname || account.uid || t('未命名账号'));
+ var meta = account.phone ? ' · ' + escapeText(account.phone) : '';
+ label.innerHTML = '<span class="wbs-ide-account-nick">' + nick + '</span><span class="wbs-ide-account-meta">' + meta + '</span>';
+ var credits = document.createElement('div');
+ credits.className = 'wbs-ide-account-credits';
+ credits.textContent = formatIdeCredits(account);
+ account.ideCreditNode = credits;
+ text.appendChild(label);
+ text.appendChild(credits);
+ row.appendChild(text);
+ if (currentUid && account.uid === currentUid) {
+ // [CodeBuddy IDE 状态栏] 当前登录账号:显示「当前」徽章,不提供切换按钮
+ var badge = document.createElement('span');
+ badge.className = 'wbs-ide-current-badge';
+ badge.textContent = t('当前');
+ row.appendChild(badge);
+ } else {
+ var btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'wbs-ide-account-switch';
+ btn.textContent = t('切换');
+ btn.addEventListener('click', function () { switchAccount(account); });
+ row.appendChild(btn);
+ }
+ return row;
+ }
+
+ // 积分摘要:总额 + 即将过期提醒。过期统计按段到期时间分桶:
+ // 「24小时过期」= now+24h 内到期的段合计;「近7天过期」= now+7d 内到期的段合计(含 24h 桶)。
+ // creditSegments 明细留给智能体窗口的完整面板(浮层保持轻量)。
+ function formatIdeCredits(account) {
+ var known = account.creditUnlimited || (typeof account.credits === 'number' && isFinite(account.credits));
+ var summary = t('积分未查询');
+ if (account.creditUnlimited) summary = t('积分:无限');
+ else if (known) {
+ var segs = Array.isArray(account.creditSegments) ? account.creditSegments : [];
+ var now = Date.now();
+ var day = 0, week = 0;
+ for (var i = 0; i < segs.length; i++) {
+ if (!segs[i] || !(segs[i].remaining > 0) || typeof segs[i].expiresAt !== 'number') continue;
+ var left = segs[i].expiresAt - now;
+ if (left < 0) continue;
+ if (left <= 86400000) day += Number(segs[i].remaining);
+ if (left <= 604800000) week += Number(segs[i].remaining);
+ }
+ summary = t('积分') + ' ' + ideRound2(account.credits) + ' · ' + t('24小时过期:') + ideRound2(day)
+ + ' · ' + t('近7天过期:') + ideRound2(week);
+ }
+ if (known && account.ideCreditState !== 'fresh') summary = t('上次查询:') + summary;
+ if (account.ideCreditState === 'loading') summary += ' · ' + t('刷新中…');
+ if (account.ideCreditState === 'failed') summary += ' · ' + t('刷新失败');
+ return summary;
+ }
+
+ function ideRound2(v) { return Math.round((Number(v) || 0) * 100) / 100; }
+
+ function switchAccount(account) {
+ accountLoadSerial++;
+ var refresh = root.querySelector('.wbs-ide-credit-refresh');
+ refresh.disabled = true;
+ var body = root.querySelector('.wbs-ide-modal-body');
+ if (body) body.innerHTML = '<div class="wbs-ide-hint">' + t('正在切换到') + ' ' + escapeText(account.nickname || account.uid) + '…</div>';
+ api('/api/switch', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ uid: account.uid, reload: true })
+ }).then(function () {
+ // daemon 通过 CDP 触发 CodeBuddy 自动 reload,浮层会被 cleanup 重建
+ closeModal();
+ }).catch(function (err) {
+ if (body) body.innerHTML = '<div class="wbs-ide-error">' + t('切换失败:') + escapeText(err && err.message || err) + '</div>';
+ refresh.disabled = false;
+ });
+ }
+
+ function buildIdeStyleNode() {
+ var style = document.createElement('style');
+ style.id = 'wbs-ide-style';
+ // 仅使用 --wb-* CSS 变量 + panelAppearance/robotStyle 衍生色;不引入新字面色
+ style.textContent = [
+ '#' + rootId + ' *{box-sizing:border-box;}',
+ '#' + rootId + '{position:fixed;bottom:16px;right:16px;z-index:2147483647;font-family:-apple-system,"Segoe UI","Microsoft YaHei",sans-serif;}',
+ '#' + rootId + ' .wbs-ide-fab{width:36px;height:36px;border-radius:50%;border:1px solid var(--wb-border,#d0d4da);background:var(--wb-bg-elevated,#fff);box-shadow:0 4px 12px rgba(0,0,0,.15);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:transform .15s,box-shadow .15s;padding:0;}',
+ '#' + rootId + ' .wbs-ide-fab:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(0,0,0,.2);}',
+ '#' + rootId + ' .wbs-ide-fab svg{width:20px;height:20px;display:block;}',
+ '#' + rootId + ' .wbs-ide-modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.35);align-items:center;justify-content:center;z-index:1;}',
+ '#' + rootId + ' .wbs-ide-modal-card{width:400px;max-width:calc(100vw - 24px);max-height:60vh;display:flex;flex-direction:column;background:var(--wb-bg-elevated,#fff);border:1px solid var(--wb-border,#d0d4da);border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.2);overflow:hidden;}',
+ '#' + rootId + ' .wbs-ide-modal-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 14px;border-bottom:1px solid var(--wb-border,#e6e8eb);font-size:13px;color:var(--wb-color-text,#1f2329);background:var(--wb-bg-elevated,#fff);}',
+ '#' + rootId + ' .wbs-ide-modal-body{flex:1;overflow:auto;padding:6px;}',
+ '#' + rootId + ' .wbs-ide-credit-refresh{flex:0 0 24px;width:24px;height:24px;padding:0;border:1px solid var(--wb-border,#d0d4da);border-radius:6px;background:var(--wb-button-bg,#fff);color:var(--wb-color-text,#1f2329);font-size:16px;cursor:pointer;}',
+ '#' + rootId + ' .wbs-ide-credit-refresh:hover{background:var(--wb-button-hover,#f0f1f2);}',
+ '#' + rootId + ' .wbs-ide-credit-refresh:disabled{opacity:.5;cursor:default;}',
+ '#' + rootId + ' .wbs-ide-credit-refresh:focus-visible{outline:2px solid currentColor;outline-offset:2px;}',
+ '#' + rootId + ' .wbs-ide-account-row{display:flex;align-items:center;gap:8px;padding:8px 10px;border-radius:8px;}',
+ '#' + rootId + ' .wbs-ide-account-row:hover{background:var(--wb-bg-hover,#f5f6f7);}',
+ '#' + rootId + ' .wbs-ide-account-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px;}',
+ '#' + rootId + ' .wbs-ide-account-label{min-width:0;font-size:12px;color:var(--wb-color-text,#1f2329);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
+ '#' + rootId + ' .wbs-ide-account-nick{font-weight:500;}',
+ '#' + rootId + ' .wbs-ide-account-meta{color:var(--wb-color-text-secondary,#8a8f99);font-size:11px;margin-left:6px;}',
+ '#' + rootId + ' .wbs-ide-account-credits{font-size:11px;color:var(--wb-color-text-secondary,#8a8f99);white-space:normal;overflow-wrap:anywhere;}',
+ '#' + rootId + ' .wbs-ide-account-switch{flex:0 0 auto;border:1px solid var(--wb-border,#d0d4da);background:var(--wb-button-bg,#fff);color:var(--wb-color-text,#1f2329);border-radius:6px;padding:4px 10px;font-size:12px;cursor:pointer;}',
+ '#' + rootId + ' .wbs-ide-account-switch:hover{background:var(--wb-button-hover,#f0f1f2);}',
+ '#' + rootId + ' .wbs-ide-current-badge{flex:0 0 auto;font-size:11px;line-height:1;color:var(--wb-color-text-secondary,#8a8f99);border:1px solid var(--wb-border,#d0d4da);border-radius:999px;padding:3px 9px;background:var(--wb-bg-hover,#f5f6f7);}',
+ '#' + rootId + ' .wbs-ide-hint{padding:12px;text-align:center;font-size:12px;color:var(--wb-color-text-secondary,#8a8f99);}',
+ '#' + rootId + ' .wbs-ide-error{padding:12px;text-align:center;font-size:12px;color:var(--wb-color-danger,#d4380d);}',
+ ].join('\n');
+ return style;
+ }
+
+ function buildIdeFabNode() {
+ var btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'wbs-ide-fab';
+ btn.title = brand + ' ' + t('账号切换');
+ btn.setAttribute('aria-label', brand + ' ' + t('账号切换'));
+ // robotStyle=black → 黑色机器人;其他走 currentColor(继承 --wb-color-text)
+ var fillColor = robotStyle === 'black' ? '#1f1f1f' : 'currentColor';
+ btn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">'
+ + '<path d="M12 2a3 3 0 0 1 3 3v.5a4 4 0 0 1 4 4v.5a2 2 0 0 1 0 4v.5a4 4 0 0 1-4 4H9a4 4 0 0 1-4-4V14a2 2 0 0 1 0-4V9.5a4 4 0 0 1 4-4V5a3 3 0 0 1 3-3Z" fill="' + fillColor + '"/>'
+ + '<circle cx="9" cy="11" r="1" fill="#fff"/><circle cx="15" cy="11" r="1" fill="#fff"/>'
+ + '</svg>';
+ btn.addEventListener('click', function (e) { e.preventDefault(); openModal(); });
+ return btn;
+ }
+
+ function buildIdeModalNode() {
+ var modal = document.createElement('div');
+ modal.className = 'wbs-ide-modal';
+ var card = document.createElement('div');
+ card.className = 'wbs-ide-modal-card';
+ var head = document.createElement('div');
+ head.className = 'wbs-ide-modal-head';
+ var title = document.createElement('span');
+ title.textContent = brand + ' · ' + t('切换账号');
+ head.appendChild(title);
+ var refresh = document.createElement('button');
+ refresh.type = 'button';
+ refresh.className = 'wbs-ide-credit-refresh';
+ refresh.title = t('刷新积分');
+ refresh.setAttribute('aria-label', t('刷新积分'));
+ refresh.textContent = '↻';
+ refresh.addEventListener('click', loadAccounts);
+ head.appendChild(refresh);
+ var body = document.createElement('div');
+ body.className = 'wbs-ide-modal-body';
+ body.innerHTML = '<div class="wbs-ide-hint">' + t('读取账号中…') + '</div>';
+ card.appendChild(head);
+ card.appendChild(body);
+ modal.appendChild(card);
+ modal.addEventListener('click', function (e) { if (e.target === modal) closeModal(); });
+ return modal;
+ }
+
+ function escapeText(text) {
+ var div = document.createElement('div');
+ div.textContent = String(text == null ? '' : text);
+ return div.innerHTML;
+ }
+ }
+
// User-facing strings are translated at the injected root so dynamically-built
// panes and toasts follow the same language without touching WorkBuddy's DOM.
var WBS_LANGUAGE_KEY = 'workdaddy.ui.language';
@@ -1149,7 +1436,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'正在取消导出…': 'Cancelling export…', '会话导出已取消': 'Session export cancelled',
'正在导出会话,请等待完成或取消': 'An export is already running. Wait or cancel it.',
'下载目录空间不足,请释放空间后重试': 'Downloads is out of space. Free up space and retry.',
- '会话导出完成': 'Session export complete', '会话导出失败': 'Session export failed',
+ '后台运行': 'Run in background', '会话导出完成': 'Session export complete', '会话导出失败': 'Session export failed',
+ 'WorkBuddy 登录桥接不可用': 'WorkBuddy login bridge unavailable',
'导出进度暂时无法读取,正在重试…': 'Could not read export progress. Retrying…',
'取消导出': 'Cancel export', '打开导出目录': 'Open export folder',
'导出进度': 'Export progress', '导出任务不存在': 'Export job not found', '导出尚未完成': 'Export is not finished',
@@ -1217,7 +1505,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'查询已中断,请重新选择时间重试': 'Query interrupted. Select a time range to retry.',
'无法读取查询进度,请重新选择时间重试': 'Could not read progress. Select a time range to retry.',
'趋势分组': 'Trend grouping', '筛选折线': 'Filter lines', '统计时间': 'Statistics period',
- '总览': 'Overview', '按账号': 'By account', '按模型': 'By model', '总量': 'Total', '模型用量': 'Model usage', '其他': 'Other', 'Token(输入 + 输出)': 'Tokens (input + output)', '输入 + 输出': 'Input + output',
+ '总览': 'Overview', '按账号': 'By account', '按模型': 'By model', '总量': 'Total', '模型用量': 'Model usage', '其他': 'Other', 'Token(输入 + 输出)': 'Tokens (input + output)', 'Token(总量)': 'Total tokens', '输入 + 输出': 'Input + output',
'未识别模型': 'Unknown model', '未关联账号': 'Unassigned account', '暂无分组数据': 'No breakdown data',
'解锁后未读取到最新状态': 'Could not load the latest status after unlocking',
'Buddy 已解锁': 'Buddy unlocked', 'Buddy 解锁成功': 'Buddy unlocked', '解锁 Buddy 失败': 'Could not unlock Buddy',
@@ -1381,6 +1669,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'元素检查': 'Inspect element', '元素检查不可用:内部模块未加载': 'Element inspector unavailable: internal module not loaded', '元素拾取器尚未加载': 'Element picker is not loaded',
'DOM 元素检查器': 'DOM element inspector', '复制元素': 'Copy element', '关闭元素检查器': 'Close element inspector', '已复制元素': 'Element copied', '未找到可检查元素': 'No inspectable element found', '检查失败:': 'Inspection failed: ', '拾取模式:移动鼠标高亮元素,点击选中(Esc 退出)': 'Pick mode: move to highlight an element, click to select (Esc to exit)',
'到期时间': 'Expiry', '剩余': 'Remaining', '剩余时间计算中': 'Calculating remaining time', '积分': 'Credits', '积分节点': 'Credit node', '积分查询超时': 'Credit query timed out', '个人版': 'Personal', '企业': 'Enterprise', '基础用量': 'Base usage', '赠送与加量包': 'Gift & bonus packs', '其他积分': 'Other credits', '即将过期': 'Expiring soon', '已过期': 'Expired',
+ '积分未查询': 'Credits not queried', '上次查询:': 'Last checked: ', '刷新积分': 'Refresh credits', '刷新失败': 'Refresh failed',
+ '账号切换': 'Account switch', '切换账号': 'Switch account', '读取账号中…': 'Loading accounts…', '暂无已备份账号': 'No backed-up accounts yet',
+ '正在切换到': 'Switching to', '切换失败:': 'Switch failed: ', '读取失败:': 'Load failed: ', '24小时过期:': 'Expires in 24h: ', '近7天过期:': 'Expires in 7 days: ', '积分:无限': 'Credits: unlimited',
'昨天': 'Yesterday', '分钟': ' min', '小时': ' h', '定位到第': 'Jump to message ', '条用户消息': ' user message', '发送中': 'Sending', '附件': 'Attachment', '疑似未完成': 'Possibly incomplete',
'已开启': 'Enabled', '已关闭': 'Disabled', '已领取': 'Claimed', '立即领取,今日可领': 'Claim now, available today', '继续执行': 'Continue',
'下载': 'Download', '安装': 'Install', '校验': 'Verify', '检查': 'Check', '重启': 'Restart', '即将打开安装包…': 'Opening installer…', '安装包已打开': 'Installer opened', '安装失败': 'Install failed', '更新出错': 'Update error', '更新失败': 'Update failed', '检查更新失败': 'Update check failed', '已是最新版本': 'Already up to date',
@@ -1428,7 +1719,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'开启后批量删除不再弹确认;为防误删,所有删除强制先进废纸篓/回收站': 'Bulk delete skips dialogs; to prevent mistakes, all deletes go to Trash first',
'开启后 wsl、reg、sc、schtasks 等系统管理工具直接运行,不再确认': 'System admin tools like wsl, reg, sc, schtasks run directly without confirmation',
'开启后仍有确认弹窗时自动替你点「允许」,所有自动批准记录在审计日志': 'Auto-clicks “Allow” on remaining dialogs; all auto-approvals are logged',
- '在会话左侧显示消息索引': 'Show the message index on the left side of sessions', '选中会话消息中的文字后显示引用按钮': 'Show the quote button after selecting session message text',
+ '在会话左侧显示消息索引': 'Show the message index on the left side of sessions', '用户提示词列表': 'User prompt list', '选中会话消息中的文字后显示引用按钮': 'Show the quote button after selecting session message text',
'状态机日志': 'state machine log', '监控激活会话中': 'Monitoring active sessions',
'更换头像': 'Change avatar', '黑色半透明遮罩,压暗背景图': 'Black translucent overlay that dims the wallpaper',
'机器人自动停靠': 'Auto-dock robot', '闲置 5 秒后收起到窗口右侧,鼠标靠近边缘展开': 'Tuck into the right edge after 5 idle seconds; move near the edge to reveal',
@@ -2087,11 +2378,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function checkinHtml(a) {
if (WBS_PROFILE_IS_AI || CAPS.checkin === false) return '';
- var c = a && a.checkin;
- var checked = !!(c && c.ok && !c.inactive);
+ var checked = isCheckedInToday(a);
return '<span class="wbs-ck wbs-checkin-tag ' + (checked ? 'ok' : 'pending') + '" title="' + (checked ? '今日已签到' : '今日未签到') + '">' + (checked ? '今日已签到' : '今日未签到') + '</span>';
}
+ function isCheckedInToday(a) {
+ var c = a && a.checkin;
+ return !!(c && c.ok && !c.inactive);
+ }
+
+ function isGrowthActiveToday(a) {
+ var today = a && a.growthTodayActive;
+ // The CN growth calendar uses Beijing time, independently of the OS timezone.
+ var date = new Date(Date.now() + 8 * 3600000).toISOString().slice(0, 10);
+ return !!(today && today.ok === true && today.is_active === true && today.date === date);
+ }
+
function activityStreakHtml(a) {
if (WBS_PROFILE_IS_AI) return '';
var value = a && a.activityStreak;
@@ -4107,6 +4409,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var root = null;
var rail = null;
var tooltip = null;
+ var detail = null;
+ var previewRow = null;
+ var anchorButton = null;
+ var promptRows = Object.create(null);
var turns = [];
var buttons = Object.create(null);
var activeId = null;
@@ -4114,6 +4420,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var scrollElement = null;
var syncTimer = null;
var tooltipTimer = null;
+ var scrollbarTimers = new Map();
+ var centeredScrollTop = null;
var activeFrame = null;
var dragPointerId = null;
var dragLastIndex = -1;
@@ -4125,7 +4433,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var hidden = true;
var disposed = false;
- function messageText(message, limit) {
+ function messageText(message, limit, preserveMarkdown) {
var content = message && message.content;
var blocks = Array.isArray(content) ? content : [];
var parts = [];
@@ -4141,7 +4449,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (messageType === 'assistant') {
value = value.replace(/(?:^|\n)\s*\[wbs-reply-done\]:[^\n]*(?:\n\s*)*$/i, '');
}
- value = value.replace(/\s+/g, ' ').trim();
+ value = preserveMarkdown ? value.trim() : value.replace(/\s+/g, ' ').trim();
if (limit && value.length > limit) return value.slice(0, limit - 1) + '…';
return value;
}
@@ -4167,10 +4475,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
tooltip = document.createElement('div');
tooltip.className = 'wbs-message-nav-tooltip';
tooltip.id = 'wbs-message-nav-tooltip';
- tooltip.setAttribute('role', 'tooltip');
+ tooltip.classList.add('wbs-message-nav-list');
+ tooltip.setAttribute('role', 'navigation');
+ tooltip.setAttribute('aria-label', '用户提示词列表');
tooltip.hidden = true;
+ detail = el('div', 'wbs-message-nav-tooltip wbs-message-nav-detail');
+ detail.id = 'wbs-message-nav-detail';
+ detail.setAttribute('role', 'tooltip');
+ detail.hidden = true;
root.appendChild(rail);
root.appendChild(tooltip);
+ root.appendChild(detail);
// 挂 document.body:view 容器祖先里的 transform(_gridViewItem_* 恒等矩阵)
// 会劫持 position:fixed 的 containing block,使视口坐标偏移。
var mount = document.body;
@@ -4188,6 +4503,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
listen(root, 'pointerup', onNavPointerUp);
listen(root, 'pointercancel', onNavPointerCancel);
listen(root, 'lostpointercapture', onNavPointerCancel);
+ listen(tooltip, 'scroll', onFlyoutScroll, { passive: true });
+ listen(detail, 'scroll', onFlyoutScroll, { passive: true });
+ ['pointerdown', 'pointerup', 'click', 'keydown', 'wheel'].forEach(function (type) {
+ listen(root, type, function (event) { event.stopPropagation(); });
+ });
}
function position() {
@@ -4199,16 +4519,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
root.style.display = 'block';
var railChrome = 14;
- var desiredRailHeight = Math.max(36, turns.length * 12 + railChrome);
+ var markerCount = Math.min(20, turns.length);
+ var desiredRailHeight = Math.max(36, markerCount * 12 + railChrome);
var railHeight = Math.min(desiredRailHeight, rect.height);
var markerHeight = Math.max(1, Math.min(12,
- (railHeight - Math.min(railChrome, railHeight)) / Math.max(1, turns.length)));
+ (railHeight - Math.min(railChrome, railHeight)) / Math.max(1, markerCount)));
root.style.height = railHeight + 'px';
root.style.top = (rect.top + (rect.height - railHeight) / 2) + 'px';
var left = rect.left + 12;
root.style.left = Math.max(8, Math.min(window.innerWidth - 28, left)) + 'px';
root.style.setProperty('--wbs-message-nav-marker-height', markerHeight + 'px');
- root.style.setProperty('--wbs-message-nav-tooltip-max', Math.max(160, Math.min(320, window.innerWidth * 0.32)) + 'px');
+ positionFlyouts();
}
function setActive(id) {
@@ -4216,9 +4537,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
Object.keys(buttons).forEach(function (key) {
var button = buttons[key];
if (!button) return;
- if (key === activeId) button.setAttribute('aria-current', 'true');
+ var selected = button === buttons[activeId];
+ if (selected) button.setAttribute('aria-current', 'true');
else button.removeAttribute('aria-current');
- button.classList.toggle('is-active', key === activeId);
+ button.classList.toggle('is-active', selected);
+ var row = promptRows[key];
+ if (row && key === activeId) row.setAttribute('aria-current', 'true');
+ else if (row) row.removeAttribute('aria-current');
});
}
@@ -4228,51 +4553,152 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!tooltip) return;
tooltip.hidden = true;
tooltip.classList.remove('is-visible');
+ if (anchorButton) anchorButton.setAttribute('aria-expanded', 'false');
+ anchorButton = null;
+ hideDetail();
+ clearScrolling(tooltip);
+ centeredScrollTop = null;
};
if (immediate) close();
- else tooltipTimer = setBuildTimeout(close, 90);
+ else tooltipTimer = setBuildTimeout(close, 220);
}
function showTooltip(turn, button) {
if (!tooltip || !turn || !button) return;
if (tooltipTimer) { clearTimeout(tooltipTimer); tooltipTimer = null; }
- tooltip.textContent = '';
- var prompt = el('div', 'wbs-message-nav-prompt', messageText(turn.userMessage, 240) || '用户消息');
- tooltip.appendChild(prompt);
- var response = messageText(turn.assistantMessage, 320);
- if (response) tooltip.appendChild(el('div', 'wbs-message-nav-response', response));
+ if (!tooltip.hidden && anchorButton === button) return;
+ if (anchorButton) anchorButton.setAttribute('aria-expanded', 'false');
+ anchorButton = button;
+ button.setAttribute('aria-expanded', 'true');
+ hideDetail();
tooltip.hidden = false;
tooltip.classList.add('is-visible');
- var buttonRect = button.getBoundingClientRect();
+ positionFlyouts();
+ var row = promptRows[turn.id];
+ if (row) {
+ var previousTop = tooltip.scrollTop;
+ tooltip.scrollTop = row.offsetTop - tooltip.clientHeight / 2 + row.offsetHeight / 2;
+ centeredScrollTop = tooltip.scrollTop !== previousTop ? tooltip.scrollTop : null;
+ }
+ }
+
+ function clearScrolling(flyout) {
+ if (!flyout) return;
+ if (scrollbarTimers.has(flyout)) clearTimeout(scrollbarTimers.get(flyout));
+ scrollbarTimers.delete(flyout);
+ flyout.classList.remove('is-scrolling');
+ }
+
+ function onFlyoutScroll(event) {
+ var flyout = event.currentTarget;
+ if (!flyout || flyout.hidden) return;
+ // 打开列表时自动居中不算用户滚动,避免刚悬停就闪现滚动条。
+ if (flyout === tooltip && centeredScrollTop !== null) {
+ var centered = flyout.scrollTop === centeredScrollTop;
+ centeredScrollTop = null;
+ if (centered) return;
+ }
+ clearScrolling(flyout);
+ flyout.classList.add('is-scrolling');
+ scrollbarTimers.set(flyout, setBuildTimeout(function () { clearScrolling(flyout); }, 700));
+ }
+
+ function hideDetail() {
+ if (previewRow) previewRow.classList.remove('is-preview');
+ previewRow = null;
+ if (detail) { detail.hidden = true; detail.classList.remove('is-visible'); }
+ clearScrolling(detail);
+ }
+
+ function showDetail(turn, row) {
+ if (!detail || !turn || !row) return;
+ hideDetail();
+ previewRow = row;
+ row.classList.add('is-preview');
+ detail.textContent = '';
+ detail.appendChild(el('span', 'wbs-message-nav-role', '用户'));
+ var prompt = el('div', 'wbs-message-nav-prompt', messageText(turn.userMessage, 240) || '用户消息');
+ detail.appendChild(prompt);
+ var response = messageText(turn.assistantMessage, 20000, true);
+ if (response) {
+ var responseNode = el('div', 'wbs-message-nav-response');
+ try {
+ responseNode.appendChild(window.__wbsMarkdownPreview.render(response));
+ } catch (_) {
+ responseNode.textContent = response;
+ }
+ var answer = el('div', 'wbs-message-nav-answer');
+ answer.appendChild(el('span', 'wbs-message-nav-role', '助手'));
+ answer.appendChild(responseNode);
+ detail.appendChild(answer);
+ }
+ detail.hidden = false;
+ detail.classList.add('is-visible');
+ positionFlyouts();
+ }
+
+ function positionFlyouts() {
+ if (!tooltip || tooltip.hidden || !anchorButton) return;
+ var margin = 8, gap = 8;
+ // 为右侧详情预留空间;窄窗口同时缩小两列,避免详情覆盖列表或超出视口。
var rootRect = root.getBoundingClientRect();
- var leftSpace = Math.max(0, rootRect.left - 12);
- var rightSpace = Math.max(0, window.innerWidth - rootRect.right - 12);
- var side = rightSpace >= leftSpace ? 'right' : 'left';
- var available = side === 'right' ? rightSpace : leftSpace;
- var preferred = Math.max(160, Math.min(320, window.innerWidth * 0.32));
- tooltip.style.width = Math.max(120, Math.min(preferred, available)) + 'px';
- var top = buttonRect.top - rootRect.top + buttonRect.height / 2;
- var tooltipHeight = tooltip.getBoundingClientRect().height || 80;
- tooltip.style.top = Math.max(tooltipHeight / 2, Math.min(rootRect.height - tooltipHeight / 2, top)) + 'px';
- tooltip.classList.toggle('is-left', side === 'left');
- tooltip.classList.toggle('is-right', side === 'right');
+ var left = Math.max(margin, Math.min(rootRect.right + gap, window.innerWidth - margin - 160));
+ var available = Math.max(0, window.innerWidth - left - margin - gap);
+ var listWidth = Math.min(380, available * 0.46);
+ var detailWidth = Math.min(440, available - listWidth);
+ tooltip.style.width = listWidth + 'px';
+ tooltip.style.left = left + 'px';
+ var buttonRect = anchorButton.getBoundingClientRect();
+ var height = tooltip.getBoundingClientRect().height;
+ tooltip.style.top = Math.max(margin, Math.min(window.innerHeight - height - margin,
+ buttonRect.top + buttonRect.height / 2 - height / 2)) + 'px';
+ if (!detail || detail.hidden || !previewRow) return;
+ var rowRect = previewRow.getBoundingClientRect();
+ var listRect = tooltip.getBoundingClientRect();
+ if (rowRect.bottom <= listRect.top || rowRect.top >= listRect.bottom) { hideDetail(); return; }
+ detail.style.width = detailWidth + 'px';
+ detail.style.left = (left + listWidth + gap) + 'px';
+ detail.style.top = Math.max(margin, Math.min(window.innerHeight - detail.getBoundingClientRect().height - margin,
+ rowRect.top)) + 'px';
+ }
+
+ function markerTurnIndices(count) {
+ var size = Math.min(20, count), indices = [];
+ for (var i = 0; i < size; i++) indices.push(size === 1 ? 0 : Math.round(i * (count - 1) / (size - 1)));
+ return indices;
}
function render() {
if (!rail) return;
+ hideTooltip(true);
rail.textContent = '';
+ tooltip.textContent = '';
buttons = Object.create(null);
- for (var i = 0; i < turns.length; i++) {
- var turn = turns[i];
+ promptRows = Object.create(null);
+ var indices = markerTurnIndices(turns.length);
+ for (var i = 0; i < indices.length; i++) {
+ var turn = turns[indices[i]];
var button = el('button', 'wbs-message-nav-marker');
button.type = 'button';
button.setAttribute('data-wbs-message-nav-id', turn.id);
- button.setAttribute('aria-label', '定位到第 ' + (i + 1) + ' 条用户消息');
- button.setAttribute('aria-describedby', tooltip.id);
+ button.setAttribute('aria-label', '定位到第 ' + (indices[i] + 1) + ' 条用户消息');
+ button.setAttribute('aria-controls', tooltip.id);
+ button.setAttribute('aria-expanded', 'false');
button.appendChild(el('span', 'wbs-message-nav-dot'));
rail.appendChild(button);
buttons[turn.id] = button;
}
+ for (var ti = 0, nearest = 0; ti < turns.length; ti++) {
+ if (nearest + 1 < indices.length && ti - indices[nearest] > indices[nearest + 1] - ti) nearest++;
+ buttons[turns[ti].id] = rail.children[nearest];
+ // 长提示词可达数万字;CSS ellipsis 仍会排版全文,必须先限制单行预览的 DOM 文本量。
+ var row = el('button', 'wbs-message-nav-row', messageText(turns[ti].userMessage, 240) || '用户消息');
+ row.type = 'button';
+ row.setAttribute('data-wbs-message-nav-id', turns[ti].id);
+ row.setAttribute('aria-describedby', detail.id);
+ tooltip.appendChild(row);
+ promptRows[turns[ti].id] = row;
+ }
setActive(activeId || (turns[0] && turns[0].id));
}
@@ -4334,11 +4760,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
renderedSignature = signature;
render();
}
+ if (previewRow) showDetail(turnForButton(previewRow), previewRow);
position();
scheduleActive();
}
function unbindStore() {
+ hideTooltip(true);
if (unsubscribeStore) {
try { unsubscribeStore(); } catch (_) {}
}
@@ -4466,7 +4894,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var turn = turnForButton(button);
if (!button || !turn) return;
dragPointerId = event.pointerId;
- dragLastIndex = Array.prototype.indexOf.call(rail.children, button);
+ dragLastIndex = turns.indexOf(turn);
root.classList.add('is-dragging');
try { rail.setPointerCapture(event.pointerId); } catch (_) {}
navigateToTurn(turn, true);
@@ -4506,18 +4934,29 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function onNavPointerCancel(event) { finishNavDrag(event, true); }
function onPointerOver(event) {
if (dragPointerId != null) return;
+ if (tooltipTimer) { clearTimeout(tooltipTimer); tooltipTimer = null; }
+ var row = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-row') : null;
+ if (row) { showDetail(turnForButton(row), row); return; }
var button = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
+ if (!button && rail && rail.contains(event.target)) {
+ var nearestTurn = turns[dragIndexAt(event.clientY)];
+ button = nearestTurn && buttons[nearestTurn.id];
+ }
if (button) showTooltip(turnForButton(button), button);
}
function onPointerOut(event) {
if (dragPointerId != null) return;
- var from = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
- var to = event.relatedTarget && event.relatedTarget.closest ? event.relatedTarget.closest('.wbs-message-nav-marker') : null;
- if (from && from !== to) hideTooltip(false);
+ if (!event.relatedTarget || !root.contains(event.relatedTarget)) hideTooltip(false);
}
function onFocusIn(event) {
- var button = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
- if (button) showTooltip(turnForButton(button), button);
+ var row = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-row') : null;
+ if (row && tooltip) {
+ if (row.offsetTop < tooltip.scrollTop) tooltip.scrollTop = row.offsetTop;
+ else if (row.offsetTop + row.offsetHeight > tooltip.scrollTop + tooltip.clientHeight) {
+ tooltip.scrollTop = row.offsetTop + row.offsetHeight - tooltip.clientHeight;
+ }
+ }
+ onPointerOver(event);
}
function onFocusOut(event) {
if (dragPointerId != null) return;
@@ -4530,13 +4969,25 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
event.preventDefault();
return;
}
- var button = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
+ var button = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker, .wbs-message-nav-row') : null;
var turn = turnForButton(button);
if (!button || !turn) return;
navigateToTurn(turn, false);
}
function onKeyDown(event) {
if (event.key === 'Escape') { hideTooltip(true); return; }
+ var row = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-row') : null;
+ if (row && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
+ var sibling = event.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling;
+ event.preventDefault();
+ if (sibling) sibling.focus();
+ return;
+ }
+ if (event.key === 'ArrowRight') {
+ var turn = turnForButton(event.target);
+ if (turn && promptRows[turn.id] && !tooltip.hidden) { event.preventDefault(); promptRows[turn.id].focus(); }
+ return;
+ }
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
var current = event.target && event.target.closest ? event.target.closest('.wbs-message-nav-marker') : null;
if (!current) return;
@@ -4544,7 +4995,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var next = event.key === 'ArrowDown' ? index + 1 : index - 1;
if (next >= 0 && next < rail.children.length) { event.preventDefault(); rail.children[next].focus(); }
}
- function onWindowChange() { position(); scheduleActive(); }
+ function onWindowChange(event) {
+ if (event && root && root.contains(event.target)) { positionFlyouts(); return; }
+ position(); scheduleActive();
+ }
listen(window, 'resize', onWindowChange);
listen(window, 'scroll', onWindowChange, true);
@@ -5036,6 +5490,17 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
};
}
});
+ // The official growth-center flow uses the adapter event bus to mint a
+ // one-time device code, then opens the client-login bridge. Keep these
+ // methods on the compatibility shim so injected features can use the
+ // same authenticated navigation as WorkBuddy itself.
+ ['on', 'emit', 'openExternal'].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,
@@ -6211,7 +6676,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
button.setAttribute('aria-controls', popup.id);
mountPersistentOverlay(popup);
var hideTimer;
- function hide() { clearTimeout(hideTimer); popup.hidden = true; button.setAttribute('aria-expanded', 'false'); }
+ var scrollIdleTimer, scrollingNode;
+ function clearSummaryScrolling() {
+ clearTimeout(scrollIdleTimer);
+ scrollIdleTimer = null;
+ if (scrollingNode) scrollingNode.classList.remove('is-scrolling');
+ scrollingNode = null;
+ }
+ function hide() { clearTimeout(hideTimer); clearSummaryScrolling(); popup.hidden = true; button.setAttribute('aria-expanded', 'false'); }
function deferHide() { clearTimeout(hideTimer); hideTimer = setBuildTimeout(hide, 160); }
function show() {
clearTimeout(hideTimer);
@@ -6259,7 +6731,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
listen(popup, 'mouseenter', function () { clearTimeout(hideTimer); });
listen(popup, 'mouseleave', deferHide);
listen(popup, 'wheel', function (event) { event.stopPropagation(); });
- listen(popup, 'scroll', hideCreditTooltip, true);
+ listen(popup, 'scroll', function (event) {
+ hideCreditTooltip();
+ clearSummaryScrolling();
+ scrollingNode = event.target;
+ scrollingNode.classList.add('is-scrolling');
+ scrollIdleTimer = setBuildTimeout(clearSummaryScrolling, 700);
+ }, true);
listen(popup, 'pointerdown', function (event) { event.stopPropagation(); });
listen(window, 'resize', hide);
listen(accountsPane, 'scroll', hide, true);
@@ -6268,12 +6746,94 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
registerDisposer(function () { hide(); popup.remove(); });
}
- function openOfficialGrowthCenter() {
- api('/api/open-url', { method: 'POST', headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ url: 'https://www.workbuddy.cn/profile/growth-center' })
+ var OFFICIAL_GROWTH_TARGET = '/profile/growth-center?fromSource=gwzcw.15291246.15291246.15291246&utm_medium=cpc&utm_id=gwzcw.15291246.15291246.15291246';
+
+ function officialWebsiteOrigin() {
+ if (PROFILE_ID === 'workbuddy-ai') return 'https://www.workbuddy.ai';
+ if (PROFILE_ID === 'codebuddy-intl') return 'https://www.codebuddy.ai';
+ if (PROFILE_ID === 'codebuddy-cn') return 'https://www.codebuddy.cn';
+ return 'https://www.workbuddy.cn';
+ }
+
+ function requestGrowthDeviceCode(adapter, timeout) {
+ return new Promise(function (resolve, reject) {
+ if (!adapter || typeof adapter.on !== 'function' || typeof adapter.emit !== 'function') {
+ reject(new Error('WorkBuddy 登录桥接不可用'));
+ return;
+ }
+ var settled = false;
+ var timer = null;
+ var unsubscribe = null;
+ function cleanup() {
+ if (timer) clearTimeout(timer);
+ timer = null;
+ if (typeof unsubscribe === 'function') {
+ try { unsubscribe(); } catch (_) {}
+ } else if (typeof adapter.off === 'function') {
+ try { adapter.off('request-device-auth-code-result', onResult); } catch (_) {}
+ }
+ }
+ function finish(error, value) {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ if (error) reject(error); else resolve(value);
+ }
+ function onResult(data) {
+ var result = data || {};
+ var code = result.deviceCode || result.code;
+ if (result.success === false || !code) {
+ finish(new Error(result.message || 'deviceCode is empty'));
+ return;
+ }
+ finish(null, String(code));
+ }
+ try {
+ unsubscribe = adapter.on('request-device-auth-code-result', onResult);
+ timer = setTimeout(function () { finish(new Error('request-device-auth-code timeout')); }, Number(timeout) > 0 ? Number(timeout) : 10000);
+ adapter.emit('request-device-auth-code');
+ } catch (error) {
+ finish(error);
+ }
+ });
+ }
+
+ function growthClientLoginUrl(origin, target, deviceCode) {
+ return origin + '/console/client-login?code=' + encodeURIComponent(deviceCode) + '&target=' + encodeURIComponent(target);
+ }
+
+ function openGrowthExternal(url, adapter) {
+ if (adapter && typeof adapter.openExternal === 'function') {
+ try {
+ return Promise.resolve(adapter.openExternal(url)).catch(function () { return openGrowthViaApi(url); });
+ } catch (_) {}
+ }
+ return openGrowthViaApi(url);
+ }
+
+ function openGrowthViaApi(url) {
+ return api('/api/open-url', { method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ url: url })
}).catch(function (error) { toast(error.message || '无法打开官方成长中心', true, root); });
}
+ function openOfficialGrowthCenter() {
+ var origin = officialWebsiteOrigin();
+ var directUrl = origin + OFFICIAL_GROWTH_TARGET;
+ var adapter = null;
+ try { adapter = window.__wbsAdapter || findWbsAdapter(); } catch (_) {}
+ if (!adapter || typeof adapter.on !== 'function' || typeof adapter.emit !== 'function') {
+ return openGrowthViaApi(directUrl);
+ }
+ return requestGrowthDeviceCode(adapter, 10000).then(function (deviceCode) {
+ return openGrowthExternal(growthClientLoginUrl(origin, OFFICIAL_GROWTH_TARGET, deviceCode), adapter);
+ }).catch(function () {
+ // Keep the action usable on older/private builds without the official
+ // device-code bridge; the direct page may ask the browser to sign in.
+ return openGrowthViaApi(directUrl);
+ });
+ }
+
function confirmCurrentGrowthAccount(uid) {
return api('/api/accounts').then(function (data) {
if (data && data.current && String(data.current.uid) === String(uid)) return true;
@@ -7566,10 +8126,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
for (var dayIndex = 0; dayIndex < usageDays('token'); dayIndex++) {
var dayKey = tokenDate.getFullYear() + '-' + String(tokenDate.getMonth() + 1).padStart(2, '0') + '-' + String(tokenDate.getDate()).padStart(2, '0');
var dayRow = dailyByDate[dayKey] || { input: 0, output: 0 };
- tokenDays.push({ title: dayKey, label: dayKey.slice(5), value: (dayRow.input || 0) + (dayRow.output || 0) });
+ tokenDays.push({ title: dayKey, label: dayKey.slice(5), value: dayRow.total == null ? (dayRow.input || 0) + (dayRow.output || 0) + (dayRow.cacheWrite || 0) : dayRow.total });
tokenDate.setDate(tokenDate.getDate() + 1);
}
- var accountRows = (stats.accounts || []).filter(function (item) { return (item.input || 0) + (item.output || 0) + (item.cacheRead || 0) + (item.cacheWrite || 0) > 0; });
+ var accountRows = (stats.accounts || []).filter(function (item) { return (item.total == null ? (item.input || 0) + (item.output || 0) + (item.cacheWrite || 0) : item.total) > 0; });
body.innerHTML = '<div class="wbs-token-stats-grid">' +
'<div><span>调用</span><strong>' + esc(formatTokenCount(totals.calls)) + '</strong></div>' +
'<div><span>输入</span><strong>' + esc(formatTokenCount(totals.input)) + '</strong></div>' +
@@ -7578,13 +8138,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div><span>缓存写入</span><strong>' + esc(formatTokenCount(totals.cacheWrite)) + '</strong></div>' +
'</div><div class="wbs-token-stats-section"><div class="wbs-token-stats-section-title">每日趋势</div>' + usageTrendChartHtml('每日 Token 趋势', true) + '</div>' +
'<div class="wbs-usage-columns">' +
- usagePieHtml((stats.models || []).map(function (item) { return { label: item.model, value: (item.input || 0) + (item.output || 0), calls: item.calls }; }), '模型用量', 'Token(输入 + 输出)', formatTokenCount, '暂无模型数据') +
- usagePieHtml(accountRows.map(function (item) { return { label: item.nickname || item.account, value: (item.input || 0) + (item.output || 0), calls: item.calls }; }), '账号用量', 'Token(输入 + 输出)', formatTokenCount, '暂无账号数据') + '</div>';
+ usagePieHtml((stats.models || []).map(function (item) { return { label: item.model, value: item.total == null ? (item.input || 0) + (item.output || 0) + (item.cacheWrite || 0) : item.total, calls: item.calls }; }), '模型用量', 'Token(总量)', formatTokenCount, '暂无模型数据') +
+ usagePieHtml(accountRows.map(function (item) { return { label: item.nickname || item.account, value: item.total == null ? (item.input || 0) + (item.output || 0) + (item.cacheWrite || 0) : item.total, calls: item.calls }; }), '账号用量', 'Token(总量)', formatTokenCount, '暂无账号数据') + '</div>';
wireUsagePies(body);
var tokenNames = Object.create(null);
((result && result.accounts) || []).forEach(function (item) { tokenNames[item.uid] = item.nickname || item.uid; });
renderUsageBreakdown(body.querySelector('.wbs-trend-panel'), tokenDays, (stats.dailyBreakdown || []).map(function (row) {
- return { day: row.day, account: row.account, model: row.model, value: (row.input || 0) + (row.output || 0) };
+ return { day: row.day, account: row.account, model: row.model, value: row.total == null ? (row.input || 0) + (row.output || 0) + (row.cacheWrite || 0) : row.total };
}), { account: tokenNames, model: Object.create(null) }, tokenTrendState, formatTokenCount);
hasStats = true;
@@ -8367,9 +8927,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-sess-bbtn wbs-sess-done" type="button" id="wbs-sess-done">取消</button>' +
'</div>' +
'</div>' +
- '<div class="wbs-sess-export-progress" id="wbs-sess-export-progress" role="status" aria-live="polite" hidden>' +
- '<div class="wbs-sess-export-head"><strong data-export-title></strong><button type="button" class="wbs-sess-bbtn" data-export-cancel>取消导出</button><button type="button" class="wbs-sess-bbtn" data-export-open hidden>打开导出目录</button></div>' +
- '<progress data-export-progress max="100" aria-label="导出进度"></progress><div data-export-detail></div></div>' +
+ '<div class="wbs-modal-mask wbs-modal-mask-panel wbs-sess-export-progress" id="wbs-sess-export-progress" hidden>' +
+ '<div class="wbs-modal wbs-sess-export-dialog" role="dialog" aria-modal="true" aria-labelledby="wbs-export-title" aria-describedby="wbs-export-detail">' +
+ '<div class="wbs-modal-title" id="wbs-export-title" data-export-title></div>' +
+ '<div class="wbs-modal-body" aria-live="polite"><progress data-export-progress max="100" aria-label="导出进度"></progress><div id="wbs-export-detail" data-export-detail></div></div>' +
+ '<div class="wbs-modal-actions"><button type="button" class="wbs-modal-btn" data-export-cancel>取消导出</button><button type="button" class="wbs-modal-btn" data-export-close>关闭</button><button type="button" class="wbs-modal-btn wbs-modal-ok" data-export-open hidden>打开导出目录</button></div></div></div>' +
'<div class="wbs-sess-copy-progress" id="wbs-sess-copy-progress" role="status" aria-live="polite" hidden>' +
'<div class="wbs-sess-copy-head"><span class="wbs-sess-copy-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></span><strong class="wbs-sess-copy-title">正在同步会话</strong></div>' +
'<div class="wbs-sess-copy-detail"></div><div class="wbs-sess-copy-track" role="progressbar" aria-label="会话同步进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><span class="wbs-sess-copy-fill"></span></div>' +
@@ -8397,10 +8959,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
function renderSessionExport(job) {
- var card = sessionsPane && sessionsPane.querySelector('#wbs-sess-export-progress');
+ var card = sessionsState.exportModal || (sessionsPane && sessionsPane.querySelector('#wbs-sess-export-progress'));
if (!card) return;
sessionsState.exportJob = job;
- card.hidden = !job;
+ var wasHidden = card.hidden;
+ card.hidden = !job || sessionsState.exportDismissed === job.id + ':' + (job.running ? 'running' : job.status);
var button = sessionsPane.querySelector('#wbs-sess-export');
if (button) button.disabled = !!(job && job.running);
if (!job) return;
@@ -8413,6 +8976,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
card.querySelector('[data-export-cancel]').hidden = !job.running;
card.querySelector('[data-export-cancel]').disabled = job.status === 'cancelling';
card.querySelector('[data-export-open]').hidden = job.status !== 'completed';
+ card.querySelector('[data-export-close]').textContent = job.running ? wbsTranslateString('后台运行', WBS_LANGUAGE) : wbsTranslateString('关闭', WBS_LANGUAGE);
+ if (wasHidden && !card.hidden) setBuildTimeout(function () {
+ if (alive && !card.hidden) card.querySelector('[data-export-close]').focus();
+ }, 0);
+ }
+
+ function dismissSessionExport() {
+ var job = sessionsState.exportJob;
+ if (!job) return;
+ sessionsState.exportDismissed = job.id + ':' + (job.running ? 'running' : job.status);
+ renderSessionExport(job);
+ var button = sessionsPane && sessionsPane.querySelector('#wbs-sess-export');
+ if (button && !button.disabled) button.focus();
}
function pollSessionExport(id) {
@@ -8426,7 +9002,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}).catch(function (error) {
if (!alive || serial !== sessionsState.exportReadSerial) return;
if (error.payload && error.payload.code === 'EXPORT_JOB_NOT_FOUND') return pollSessionExport();
- var detail = sessionsPane && sessionsPane.querySelector('[data-export-detail]');
+ var detail = sessionsState.exportModal && sessionsState.exportModal.querySelector('[data-export-detail]');
if (detail && sessionsState.exportJob) detail.textContent = '导出进度暂时无法读取,正在重试…';
sessionsState.exportPollTimer = setBuildTimeout(function () { pollSessionExport(id); }, 2500);
});
@@ -8837,6 +9413,32 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function wireSessionsPane() {
var exportCard = sessionsPane.querySelector('#wbs-sess-export-progress');
if (exportCard) {
+ sessionsState.exportModal = exportCard;
+ // This dialog belongs to the WorkDaddy panel. Appending it to body
+ // puts it in a lower stacking context than .wbs-root, so the panel
+ // can cover the dialog. Keep it inside .wbs-panel and reuse the
+ // panel-scoped modal mask used by the other WorkDaddy dialogs.
+ var panel = root && root.querySelector('.wbs-panel');
+ if (panel) panel.appendChild(exportCard);
+ registerDisposer(function () { exportCard.remove(); });
+ exportCard.querySelector('[data-export-close]').addEventListener('click', dismissSessionExport);
+ exportCard.addEventListener('click', function (event) {
+ event.stopPropagation();
+ if (event.target === exportCard) dismissSessionExport();
+ });
+ ['pointerdown', 'mousedown', 'keyup', 'wheel'].forEach(function (name) {
+ exportCard.addEventListener(name, function (event) { event.stopPropagation(); });
+ });
+ exportCard.addEventListener('keydown', function (event) {
+ event.stopPropagation();
+ if (event.key === 'Escape') { event.preventDefault(); dismissSessionExport(); }
+ if (event.key === 'Tab') {
+ var controls = exportCard.querySelectorAll('button:not([hidden]):not(:disabled)');
+ var first = controls[0], last = controls[controls.length - 1];
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
+ }
+ });
exportCard.querySelector('[data-export-cancel]').addEventListener('click', function () {
var job = sessionsState.exportJob;
if (!job || !job.running) return;
@@ -14565,7 +15167,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
previous.forEach(function (cached) {
var account = byUid.get(cached.uid);
if (!account) return; // 删除的账号不能被缓存复活。
- ['credits', 'creditSegments', 'creditUnlimited', 'creditExpired', 'dailyProgress'].forEach(function (key) {
+ ['credits', 'creditSegments', 'creditUnlimited', 'creditExpired', 'dailyProgress', 'growthTodayActive'].forEach(function (key) {
if (account[key] === undefined && cached[key] !== undefined) account[key] = cached[key];
});
if (!isKnownActivityStreak(account.activityStreak) && isKnownActivityStreak(cached.activityStreak)) {
@@ -14578,11 +15180,6 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
return merged;
}
- function clampDailyRatio(value) {
- var ratio = Number(value);
- return isFinite(ratio) ? Math.max(0, Math.min(1, ratio)) : 0;
- }
-
var WORKBUDDY_CAT_MARK = '__WBS_BUDDY_MARK__';
function dailyProgressLabel(progress) {
@@ -14603,22 +15200,21 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
',开启盲盒 ' + (Number(gacha.count) || 0) + ' 次,待抽奖 ' + (Number(lottery.count) || 0) + ' 次,' + catText;
}
- function dailyRingsSvg(progress) {
- var ready = progress && progress.status === 'ready';
- var growthRatio = ready ? progress.growth && progress.growth.ratio : 0;
- var level = (clampDailyRatio(growthRatio) * 100).toFixed(2) + '%';
- var empty = clampDailyRatio(growthRatio) <= 0;
- return '<span class="wbs-daily-vessel' + (empty ? ' is-empty' : '') + '" aria-hidden="true" style="--wbs-liquid-level:' + level + ';--wbs-workbuddy-cat:url(' + WORKBUDDY_CAT_MARK + ')">' +
+ function dailyRingsSvg(account) {
+ // Credit check-in and login alone do not complete growth activity.
+ // Only the official heatmap's record for today may fill the cat vessel.
+ var checkedToday = isGrowthActiveToday(account);
+ var level = checkedToday ? '100.00%' : '0.00%';
+ return '<span class="wbs-daily-vessel' + (checkedToday ? ' is-checked-in' : ' is-empty') + '" aria-hidden="true" style="--wbs-liquid-level:' + level + ';--wbs-workbuddy-cat:url(' + WORKBUDDY_CAT_MARK + ')">' +
'<span class="wbs-daily-liquid"></span><span class="wbs-daily-cat-mark"></span></span>';
}
function dailyRingsHtml(account) {
if (!CAPS.growthDaily || WBS_PROFILE_IS_AI) return '';
var progress = account && account.dailyProgress;
- var ready = progress && progress.status === 'ready';
var label = dailyProgressLabel(progress);
- return '<button type="button" class="wbs-daily-rings' + (ready ? '' : ' is-loading') + '" tabindex="0" aria-label="' + escAttr(label) + '" aria-controls="wbs-status-popover" aria-expanded="false" data-uid="' + escAttr(account.uid) + '">' +
- dailyRingsSvg(progress) + activityStreakHtml(account) + '</button>';
+ return '<button type="button" class="wbs-daily-rings" tabindex="0" aria-label="' + escAttr(label) + '" aria-controls="wbs-status-popover" aria-expanded="false" data-uid="' + escAttr(account.uid) + '">' +
+ dailyRingsSvg(account) + activityStreakHtml(account) + '</button>';
}
function formatDailyTravelCountdown(arriveAt, now) {
@@ -14798,10 +15394,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!account) continue;
var existing = cards[i].querySelector('.wbs-daily-rings');
if (existing) {
- var ready = account.dailyProgress && account.dailyProgress.status === 'ready';
- existing.classList.toggle('is-loading', !ready);
existing.setAttribute('aria-label', dailyProgressLabel(account.dailyProgress));
- existing.innerHTML = dailyRingsSvg(account.dailyProgress) + activityStreakHtml(account);
+ existing.innerHTML = dailyRingsSvg(account) + activityStreakHtml(account);
}
else {
var nameGroup = cards[i].querySelector('.wbs-name-group');
@@ -15867,9 +16461,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
.then(function (result) { return result.activityStreak; })
.catch(function () { return { days: null, status: 'unavailable' }; })
.then(function (value) {
+ if (!alive || !state.open || runId !== state.activityRunId) return;
+ // Keep two workers, each with one request at a time. This endpoint
+ // only reads the backend record; it never sends a prompt or checks in.
+ return api('/api/growth/today-active', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ uid: account.uid }) })
+ .catch(function () { return null; })
+ .then(function (today) { return { streak: value, today: today }; });
+ })
+ .then(function (result) {
if (!alive || !state.open || runId !== state.activityRunId) return;
var current = state.accounts.filter(function (a) { return a.uid === account.uid; })[0];
if (!current) return;
+ var value = result.streak;
+ current.growthTodayActive = result.today;
+ if (!result.today || result.today.ok !== true) retryAt = Math.max(retryAt, Date.now() + 30100);
if (!isKnownActivityStreak(value)) {
// daemon 对失败退避 30 秒:到期后再重试,避免重开面板时反复命中失败缓存。
retryAt = Math.max(retryAt, (Number(value && value.fetchedAt) || Date.now()) + 30100);
@@ -15880,7 +16485,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var slot = card.querySelector('.wbs-checkin-slot');
if (slot) slot.outerHTML = checkinBadgeHtml(current);
var growthControl = card.querySelector('.wbs-daily-rings');
- if (growthControl) growthControl.innerHTML = dailyRingsSvg(current.dailyProgress) + activityStreakHtml(current);
+ if (growthControl) growthControl.innerHTML = dailyRingsSvg(current) + activityStreakHtml(current);
});
}).then(worker);
}
@@ -15899,6 +16504,13 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
+ setBuildInterval(function () {
+ if (!alive || !state.open || WBS_PROFILE_IS_AI || !CAPS.accounts) return;
+ // Clear yesterday's fill even if the next backend request is still pending.
+ updateDailyProgressCells();
+ if (!activityBatchPromise) fetchActivityForAccounts();
+ }, 60000);
+
function requestCredit(uid) {
return new Promise(function (resolve, reject) {
var settled = false;
@@ -16321,20 +16933,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-message-nav-rail{display:flex;width:24px;height:100%;box-sizing:border-box;flex-direction:column;align-items:center;justify-content:flex-start;gap:0;overflow:hidden;padding:6px 0;border:1px solid transparent;border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 16%,transparent);box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none;pointer-events:auto;touch-action:none;cursor:pointer;scrollbar-width:none;transition:background-color .18s ease,border-color .18s ease,box-shadow .18s ease,backdrop-filter .18s ease}',
'.wbs-message-nav-rail:hover,.wbs-message-nav-rail:focus-within{border-color:color-mix(in srgb,var(--wb-border-subtle,#d9dadd) 72%,transparent);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 48%,transparent);box-shadow:0 5px 18px rgba(24,28,36,.10);backdrop-filter:blur(14px) saturate(1.12);-webkit-backdrop-filter:blur(14px) saturate(1.12)}',
'.wbs-message-nav-rail::-webkit-scrollbar{display:none}',
- '.wbs-message-nav-marker{display:flex;width:22px;height:var(--wbs-message-nav-marker-height,12px);min-height:var(--wbs-message-nav-marker-height,12px);box-sizing:border-box;flex:0 0 var(--wbs-message-nav-marker-height,12px);align-items:center;justify-content:center;padding:0;border:1px solid transparent;border-radius:4px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 10%,transparent);color:var(--wb-icon-secondary,#72757d);cursor:pointer;outline:none;transition:background-color .18s ease,color .18s ease,border-color .18s ease,box-shadow .18s ease,backdrop-filter .18s ease}',
- '.wbs-message-nav-marker:hover,.wbs-message-nav-marker:focus-visible{border-color:var(--wb-border-subtle,rgba(20,24,32,.14));background:color-mix(in srgb,var(--wb-bg-hover,rgba(0,0,0,.06)) 82%,var(--wb-bg-popover,#fff));color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 3px 10px rgba(24,28,36,.10);backdrop-filter:blur(10px) saturate(1.1);-webkit-backdrop-filter:blur(10px) saturate(1.1)}',
- '.wbs-message-nav-marker:focus-visible{box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 62%,transparent),0 3px 10px rgba(24,28,36,.10)}',
- '.wbs-message-nav-dot{display:block;width:5px;height:min(2px,var(--wbs-message-nav-marker-height,12px));border-radius:2px;background:currentColor;opacity:.62;transition:width .18s ease,opacity .18s ease}',
- '.wbs-message-nav-marker:hover .wbs-message-nav-dot,.wbs-message-nav-marker:focus-visible .wbs-message-nav-dot{width:11px;opacity:.82}',
+ '.wbs-message-nav-marker{display:flex;width:22px;height:var(--wbs-message-nav-marker-height,12px);min-height:var(--wbs-message-nav-marker-height,12px);box-sizing:border-box;flex:0 0 var(--wbs-message-nav-marker-height,12px);align-items:center;justify-content:center;padding:0;border:1px solid transparent;border-radius:4px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 10%,transparent);color:var(--wb-icon-secondary,#72757d);cursor:pointer;outline:none;transition:none}',
+ '.wbs-message-nav-marker:focus-visible{box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-accent-blue,#4f86ff) 62%,transparent)}',
+ '.wbs-message-nav-dot{display:block;width:5px;height:min(2px,var(--wbs-message-nav-marker-height,12px));border-radius:2px;background:currentColor;opacity:.62;transition:none}',
'.wbs-message-nav-marker.is-active .wbs-message-nav-dot{width:14px;opacity:1}',
- '.wbs-message-nav-tooltip{position:absolute;width:var(--wbs-message-nav-tooltip-max,300px);max-height:min(42vh,320px);box-sizing:border-box;overflow:hidden;padding:10px 11px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.14));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 84%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 12px 34px rgba(20,24,32,.18),inset 0 1px 0 rgba(255,255,255,.38);backdrop-filter:blur(22px) saturate(1.24);-webkit-backdrop-filter:blur(22px) saturate(1.24);pointer-events:none;opacity:0;transform:translateY(-50%) translateX(3px);transition:opacity .18s ease,transform .18s ease}',
- '.wbs-message-nav-tooltip.is-left{right:calc(100% + 10px)}.wbs-message-nav-tooltip.is-right{left:calc(100% + 10px)}',
- '.wbs-message-nav-tooltip.is-visible{opacity:1;transform:translateY(-50%) translateX(0)}',
- '.wbs-message-nav-prompt,.wbs-message-nav-response{display:-webkit-box;overflow:hidden;-webkit-box-orient:vertical;word-break:break-word;letter-spacing:0}',
+ '.wbs-message-nav-tooltip{position:fixed;max-height:80vh;box-sizing:border-box;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:transparent transparent;padding:10px 11px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.14));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-popover,#fff) 84%,transparent);color:var(--wb-color-text-primary,#1f1f1f);box-shadow:0 12px 34px rgba(20,24,32,.18),inset 0 1px 0 rgba(255,255,255,.38);backdrop-filter:blur(22px) saturate(1.24);-webkit-backdrop-filter:blur(22px) saturate(1.24);pointer-events:auto;opacity:1}',
+ '.wbs-message-nav-tooltip.is-visible{opacity:1}.wbs-message-nav-tooltip[hidden]{display:none}',
+ '.wbs-message-nav-tooltip::-webkit-scrollbar{width:6px}.wbs-message-nav-tooltip::-webkit-scrollbar-track,.wbs-message-nav-tooltip::-webkit-scrollbar-thumb{background:transparent}.wbs-message-nav-tooltip::-webkit-scrollbar-thumb{border-radius:6px}.wbs-message-nav-tooltip.is-scrolling{scrollbar-color:var(--wb-icon-secondary,#72757d) transparent}.wbs-message-nav-tooltip.is-scrolling::-webkit-scrollbar-thumb{background:var(--wb-icon-secondary,#72757d)}',
+ '.wbs-message-nav-list{padding:4px}.wbs-message-nav-detail{user-select:text;-webkit-user-select:text}',
+ '.wbs-message-nav-row{display:block;width:100%;height:30px;box-sizing:border-box;padding:0 8px;border:1px solid transparent;border-radius:6px;background:transparent;color:inherit;font:inherit;font-size:12px;line-height:28px;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;cursor:pointer}',
+ '.wbs-message-nav-row:hover,.wbs-message-nav-row.is-preview,.wbs-message-nav-row:focus-visible,.wbs-message-nav-row[aria-current="true"]{background:var(--wb-bg-hover,rgba(0,0,0,.06));border-color:var(--wb-border-subtle,rgba(20,24,32,.14))}.wbs-message-nav-row:focus-visible{outline:2px solid var(--wb-accent-blue,#4f86ff);outline-offset:-2px}',
+ '.wbs-message-nav-role{display:table;margin-bottom:4px;padding:1px 5px;border:1px solid var(--wb-border-subtle);border-radius:4px;background:var(--wb-bg-secondary);color:var(--wb-color-text-secondary);font-size:10px;font-weight:600;line-height:1.4;white-space:nowrap}',
+ '.wbs-message-nav-answer{margin-top:8px;padding-top:8px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.12))}',
+ '.wbs-message-nav-prompt{display:-webkit-box;overflow:hidden;-webkit-box-orient:vertical;word-break:break-word;letter-spacing:0}',
'.wbs-message-nav-prompt{-webkit-line-clamp:4;font-size:12px;font-weight:600;line-height:1.55;color:var(--wb-color-text-primary,#1f1f1f)}',
- '.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}}',
+ '.wbs-message-nav-response{display:block;min-width:0;overflow-wrap:anywhere;font-size:11px;font-weight:400;line-height:1.55;color:var(--wb-color-text-secondary,#5f626a)}',
+ '.wbs-message-nav-response>:first-child{margin-top:0}.wbs-message-nav-response>:last-child{margin-bottom:0}.wbs-message-nav-response p{margin:0 0 8px}.wbs-message-nav-response :is(h1,h2,h3,h4,h5,h6){margin:12px 0 6px;font-size:12px;line-height:1.45;font-weight:650;color:var(--wb-color-text-primary)}.wbs-message-nav-response h1{font-size:14px}.wbs-message-nav-response h2{font-size:13px}.wbs-message-nav-response :is(ul,ol){margin:6px 0;padding-left:20px}.wbs-message-nav-response li{margin:3px 0}.wbs-message-nav-response li>p{margin:0}.wbs-message-nav-response blockquote{margin:8px 0;padding:2px 8px;border-left:3px solid var(--wb-border-default);color:var(--wb-color-text-secondary)}.wbs-message-nav-response code{padding:1px 3px;border-radius:3px;background:var(--wb-bg-tertiary);font:10.5px/1.55 var(--wb-font-code-family,monospace)}.wbs-message-nav-response pre{max-width:100%;box-sizing:border-box;margin:8px 0;padding:8px;overflow-x:auto;border:1px solid var(--wb-border-subtle);border-radius:6px;background:var(--wb-bg-tertiary);white-space:pre;overscroll-behavior:contain}.wbs-message-nav-response pre code{padding:0;background:transparent}.wbs-message-nav-response table{display:block;max-width:100%;overflow-x:auto;border-collapse:collapse;margin:8px 0;overscroll-behavior:contain}.wbs-message-nav-response :is(th,td){padding:4px 7px;border:1px solid var(--wb-border-default);min-width:45px}.wbs-message-nav-response th{background:var(--wb-bg-tertiary);font-weight:600}.wbs-message-nav-response a{color:var(--wb-accent-blue,var(--wb-color-text-primary));text-decoration:underline}.wbs-message-nav-response hr{border:0;border-top:1px solid var(--wb-border-subtle);margin:10px 0}.wbs-message-nav-response input[type="checkbox"]{width:11px;height:11px;margin:0 4px 0 0;accent-color:var(--wb-button-primary-bg);pointer-events:none}',
/* 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}',
@@ -16350,9 +16964,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'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)}',
// 毛玻璃主题下移出即隐藏底色与模糊,鼠标点击留下的焦点不会让背景常驻。
'html[data-wbs-theme-id="nebula"] .wbs-message-nav-rail:not(:hover){background:transparent;border-color:transparent;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}',
- 'html[data-wbs-theme-id="nebula"] .wbs-message-nav-marker:not(:hover){background:transparent;border-color:transparent;backdrop-filter:none;-webkit-backdrop-filter:none}',
- 'html[data-wbs-theme-id="nebula"] .wbs-message-nav-marker:not(:hover):not(:focus-visible){box-shadow:none}',
- '@media (prefers-reduced-motion:reduce){.wbs-message-nav-marker,.wbs-message-nav-dot,.wbs-message-nav-tooltip{transition:none!important}.wbs-message-nav-highlight{animation:none!important}}',
+ 'html[data-wbs-theme-id="nebula"] .wbs-message-nav-marker{background:transparent;border-color:transparent;backdrop-filter:none;-webkit-backdrop-filter:none}',
+ '@media (prefers-reduced-motion:reduce){.wbs-message-nav-marker,.wbs-message-nav-dot,.wbs-message-nav-tooltip{transition:none!important}}',
/* 官网演示机器人:尺寸按 2 倍绘制,保留现有 0.5 缩放与停靠/拖动坐标。 */
// CodeBuddy Agents 不提供 --wb-*;优先沿用客户端按钮色,最终回退到现有黑白机器人。
'.wbs-fab[data-wbs-robot-style="theme"],.wbs-root[data-wbs-robot-style="theme"] .wbs-automation-stop{--wbs-robot-shell:var(--wb-button-primary-bg,var(--vscode-button-background,#111));--wbs-robot-eye:var(--wb-button-primary-fg,var(--vscode-button-foreground,#fff));--wbs-robot-rim:var(--wb-border-subtle,rgba(255,255,255,.55))}',
@@ -16465,9 +17078,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-daily-rings:hover,.wbs-daily-rings[aria-expanded="true"]{background:var(--wbs-primary-soft-hover);box-shadow:0 2px 8px rgba(var(--wbs-primary-rgb),.13),inset 0 1px 0 rgba(255,255,255,.28)}',
'.wbs-daily-rings:focus-visible{background:color-mix(in srgb,var(--wb-bg-hover,#eef0f3) 86%,transparent);box-shadow:0 0 0 2px color-mix(in srgb,var(--wbs-liquid-fill) 45%,transparent)}',
'.wbs-daily-vessel{position:relative;display:block;width:20px;height:20px;flex:0 0 20px;overflow:hidden;border-radius:50%;background:var(--wbs-liquid-bg);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--wbs-liquid-fill) 20%,transparent),0 1px 3px rgba(20,32,29,.12);isolation:isolate}',
- '.wbs-daily-liquid{position:absolute;inset:auto 0 0;height:var(--wbs-liquid-level,0%);min-height:2px;background:var(--wbs-liquid-fill);box-shadow:inset 0 1px 0 rgba(255,255,255,.38);transition:height .35s ease}.wbs-daily-vessel.is-empty .wbs-daily-liquid{min-height:0}',
+ '.wbs-daily-liquid{position:absolute;inset:auto 0 0;height:var(--wbs-liquid-level,0%);min-height:2px;background:var(--wbs-liquid-fill);box-shadow:inset 0 1px 0 rgba(255,255,255,.38);transition:height .35s ease}.wbs-daily-vessel.is-empty .wbs-daily-liquid{min-height:0}.wbs-daily-vessel.is-checked-in{--wbs-liquid-ink:var(--wb-button-primary-fg);background:var(--wbs-liquid-fill);box-shadow:none}.wbs-daily-vessel.is-checked-in .wbs-daily-liquid{border-radius:inherit;box-shadow:none}',
'.wbs-daily-cat-mark{position:absolute;z-index:1;inset:2px;background:var(--wbs-liquid-ink);-webkit-mask-image:var(--wbs-workbuddy-cat);mask-image:var(--wbs-workbuddy-cat);-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;-webkit-mask-size:contain;mask-size:contain;transform:rotate(30deg) scale(.82);transform-origin:center}',
- '.wbs-daily-streak-label{font-size:10.5px;line-height:1;font-weight:600;white-space:nowrap;font-variant-numeric:tabular-nums;color:inherit}.wbs-daily-streak-label.is-pending{color:var(--wb-icon-tertiary,#7c818b);font-weight:500}.wbs-daily-rings.is-loading .wbs-daily-vessel{opacity:.58}.wbs-daily-rings.is-loading .wbs-daily-cat-mark{animation:wbs-daily-cat-pulse 1.2s ease-in-out infinite}@keyframes wbs-daily-cat-pulse{50%{opacity:.45}}',
+ '.wbs-daily-streak-label{font-size:10.5px;line-height:1;font-weight:600;white-space:nowrap;font-variant-numeric:tabular-nums;color:inherit}.wbs-daily-streak-label.is-pending{color:var(--wb-icon-tertiary,#7c818b);font-weight:500}',
'.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}',
@@ -16531,8 +17144,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-ck{font-size:11px;font-weight:600}',
'.wbs-checkin-tag{display:inline-flex;align-items:center;height:22px;min-height:22px;box-sizing:border-box;padding:1px 7px;border:1px solid transparent;border-radius:999px;white-space:nowrap}',
'.wbs-checkin-tag.pending{background:var(--wb-bg-tertiary,#f0f0f0);color:var(--wb-icon-tertiary,#999)}',
- '.wbs-daily-rings,.wbs-checkin-tag.ok{--wbs-badge-bg:var(--wb-color-text-primary,#1f1f1f);--wbs-badge-fg:var(--wb-bg-popover,#fff);background:var(--wbs-badge-bg);border-color:transparent;color:var(--wbs-badge-fg);box-shadow:none}.wbs-daily-rings{--wbs-liquid-fill:rgba(255,255,255,.46);--wbs-liquid-bg:rgba(255,255,255,.14);--wbs-liquid-ink:#fff}.wbs-daily-rings .wbs-daily-streak-label.is-pending{color:inherit;opacity:.75}.wbs-daily-rings:hover,.wbs-daily-rings[aria-expanded="true"]{background:color-mix(in srgb,var(--wbs-badge-bg) 84%,white);box-shadow:0 2px 8px rgba(0,0,0,.14)}',
- ':is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings,:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-checkin-tag.ok{--wbs-badge-bg:rgba(255,255,255,.085);--wbs-badge-fg:var(--wb-color-text-primary,#f6f5ff);background:var(--wbs-badge-bg);border:1px solid rgba(255,255,255,.12);color:var(--wbs-badge-fg);box-shadow:inset 0 1px 0 rgba(255,255,255,.08);backdrop-filter:blur(12px) saturate(1.08);-webkit-backdrop-filter:blur(12px) saturate(1.08)}:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings{--wbs-liquid-fill:rgba(170,160,235,.62);--wbs-liquid-bg:rgba(255,255,255,.12);--wbs-liquid-ink:#f6f5ff}:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings:hover,:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings[aria-expanded="true"]{background:rgba(255,255,255,.14);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 3px 10px rgba(0,0,0,.12)}',
+ '.wbs-daily-rings,.wbs-checkin-tag.ok{--wbs-badge-bg:var(--wb-color-text-primary,#1f1f1f);--wbs-badge-fg:var(--wb-bg-popover,#fff);background:var(--wbs-badge-bg);border-color:transparent;color:var(--wbs-badge-fg);box-shadow:none}.wbs-daily-rings{--wbs-liquid-fill:color-mix(in srgb,var(--wb-button-primary-bg) 55%,var(--wb-button-primary-fg));--wbs-liquid-bg:rgba(255,255,255,.14);--wbs-liquid-ink:#fff}.wbs-daily-rings .wbs-daily-streak-label.is-pending{color:inherit;opacity:.75}.wbs-daily-rings:hover,.wbs-daily-rings[aria-expanded="true"]{background:color-mix(in srgb,var(--wbs-badge-bg) 84%,white);box-shadow:0 2px 8px rgba(0,0,0,.14)}',
+ // Keep the theme hue, but lift dark fills above the empty gray vessel.
+ '@supports (color:oklch(from black l c h)){.wbs-daily-rings{--wbs-liquid-fill:oklch(from var(--wb-button-primary-bg) max(l,.62) c h / 1)}}',
+ 'html:not(.cb-dark):not([data-theme="dark"]):is([data-wbs-theme-id="default"],:not([data-wbs-theme-id])) body:not([data-vscode-theme-name*="dark" i]) .wbs-daily-rings{--wbs-liquid-fill:var(--wbs-credit-theme-color,var(--wbs-primary))}',
+ ':is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings,:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-checkin-tag.ok{--wbs-badge-bg:rgba(255,255,255,.085);--wbs-badge-fg:var(--wb-color-text-primary,#f6f5ff);background:var(--wbs-badge-bg);border:1px solid rgba(255,255,255,.12);color:var(--wbs-badge-fg);box-shadow:inset 0 1px 0 rgba(255,255,255,.08);backdrop-filter:blur(12px) saturate(1.08);-webkit-backdrop-filter:blur(12px) saturate(1.08)}:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings{--wbs-liquid-bg:rgba(255,255,255,.12);--wbs-liquid-ink:#f6f5ff}:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings:hover,:is(html.cb-dark,html[data-theme="dark"],html[data-wbs-theme-id="dark"],html[data-wbs-theme-id="cyber-purple"],html[data-wbs-theme-id="nebula"],body[data-vscode-theme-name*="dark" i]) .wbs-daily-rings[aria-expanded="true"]{background:rgba(255,255,255,.14);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 3px 10px rgba(0,0,0,.12)}',
'.wbs-checkin-tag.fail{background:rgba(239,68,68,.1);color:#dc2626}',
'.wbs-model-rate-limit-slot{display:inline-flex;align-items:center;min-width:0}.wbs-model-rate-limit{appearance:none;-webkit-appearance:none;font:inherit;cursor:pointer;transition:background-color .15s,box-shadow .15s,color .15s}.wbs-model-rate-limit:hover,.wbs-model-rate-limit[aria-expanded="true"]{background:color-mix(in srgb,var(--wbs-badge-bg) 84%,white);box-shadow:0 2px 8px rgba(0,0,0,.14)}.wbs-model-rate-limit:focus-visible{outline:2px solid color-mix(in srgb,var(--wbs-badge-bg) 45%,transparent);outline-offset:2px}',
'.wbs-status-popover.is-rate-limit{width:500px;max-width:calc(100vw - 16px);overflow-x:auto}.wbs-status-popover.is-rate-limit-summary{width:360px;max-width:calc(100vw - 16px);overflow-x:auto}.wbs-model-rate-limit-detail{grid-template-columns:8px auto minmax(0,1fr) auto auto;gap:7px}.wbs-model-rate-limit-detail b{white-space:nowrap;overflow-wrap:normal}.wbs-model-rate-limit-detail .wbs-model-rate-limit-model{text-align:left}.wbs-model-rate-limit-detail i.rate-limit{color:var(--wb-color-text-primary,#1f1f1f)}.wbs-model-rate-limit-account-group{padding:7px 0 2px;border-top:1px solid var(--wb-border-subtle,rgba(20,24,32,.1))}.wbs-model-rate-limit-account-group:first-of-type{padding-top:0;border-top:0}.wbs-model-rate-limit-account-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 2px 2px}.wbs-model-rate-limit-account-head strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}.wbs-model-rate-limit-account-head span{flex:0 0 auto;color:var(--wb-icon-tertiary,#7c818b);font-size:10px;white-space:nowrap}.wbs-model-rate-limit-summary-row{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,auto);align-items:center;gap:7px;min-height:28px;margin-top:4px;padding:0 8px;border:1px solid var(--wb-border-subtle,rgba(20,24,32,.1));border-radius:8px;background:color-mix(in srgb,var(--wb-bg-secondary,#f6f7f8) 72%,transparent)}.wbs-model-rate-limit-summary-row>span{color:var(--wb-color-text-secondary,#5f6368);white-space:nowrap}.wbs-model-rate-limit-summary-row>b{min-width:0;font-size:11px;font-weight:650;white-space:nowrap;overflow-wrap:normal}.wbs-model-rate-limit-summary-row .wbs-model-rate-limit-model{text-align:left}.wbs-model-rate-limit-summary-row .wbs-model-rate-limit-reset{text-align:right}',
@@ -16769,7 +17385,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-sess-seg-btn:hover{color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-sess-seg-btn.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.2)}',
'.wbs-sess-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin-bottom:8px}',
- '.wbs-sess-export-progress{flex:0 0 auto;min-width:0;margin:0 0 8px;padding:9px 10px;border:1px solid var(--wb-border-subtle);border-radius:9px;background:var(--wb-bg-secondary);color:var(--wb-color-text-primary);font-size:11px;line-height:1.5}.wbs-sess-export-progress[hidden],.wbs-sess-export-progress [hidden]{display:none}.wbs-sess-export-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.wbs-sess-export-head strong{flex:1;font-size:12px}.wbs-sess-export-progress progress{display:block;width:100%;height:5px;margin:7px 0;accent-color:var(--wbs-primary)}.wbs-sess-export-progress progress[hidden]{display:none}.wbs-sess-export-progress [data-export-detail]{overflow-wrap:anywhere;color:var(--wb-color-text-secondary)}',
+ '.wbs-sess-export-progress{padding:16px;box-sizing:border-box;pointer-events:auto;font:12px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif}.wbs-sess-export-progress[hidden],.wbs-sess-export-progress [hidden]{display:none!important}.wbs-modal.wbs-sess-export-dialog{box-sizing:border-box;width:380px;max-width:100%;max-height:100%;overflow:auto}.wbs-sess-export-dialog progress{display:block;width:100%;height:5px;margin:7px 0;accent-color:var(--wb-button-primary-bg)}.wbs-sess-export-dialog [data-export-detail]{overflow-wrap:anywhere;white-space:pre-wrap;color:var(--wb-color-text-secondary)}.wbs-sess-export-dialog .wbs-modal-actions{flex-wrap:wrap}',
'.wbs-sess-copy-progress{box-sizing:border-box;margin:0 0 8px;padding:9px 10px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 82%,transparent);box-shadow:0 2px 8px rgba(0,0,0,.04)}',
'.wbs-sess-copy-progress[hidden]{display:none!important}.wbs-sess-copy-head{display:flex;align-items:center;gap:6px;min-width:0}.wbs-sess-copy-icon{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex:0 0 20px;border-radius:6px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 9%,transparent);color:var(--wb-button-primary-bg,#1f1f1f)}.wbs-sess-copy-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11.5px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f)}',
'.wbs-sess-copy-detail{margin:4px 0 6px 26px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;line-height:1.35;color:var(--wb-icon-tertiary,#8a8f98)}.wbs-sess-copy-track{height:4px;margin-left:26px;overflow:hidden;border-radius:999px;background:var(--wb-bg-tertiary,#e9eaed)}.wbs-sess-copy-fill{display:block;height:100%;width:0;border-radius:inherit;background:var(--wb-accent-blue,var(--wb-button-primary-bg,#1f1f1f));transition:width .2s ease}.wbs-sess-copy-progress.is-done .wbs-sess-copy-fill{background:#2f9e63}.wbs-sess-copy-progress.is-partial .wbs-sess-copy-fill{background:#d48a19}.wbs-sess-copy-progress.is-error .wbs-sess-copy-fill{background:#d84a4a}',
@@ -17112,9 +17728,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.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-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;pointer-events:auto}',
+ '.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)}',
- '.wbs-credit-summary-chart{max-height:230px;overflow:auto;overscroll-behavior:contain}.wbs-credit-summary-row{display:grid;grid-template-columns:68px minmax(30px,1fr) 58px;align-items:center;gap:8px;min-height:28px}.wbs-credit-summary-row>span{font-size:11px;color:var(--wb-color-text-secondary)}.wbs-credit-summary-row>b{text-align:right;font-size:11px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.wbs-credit-summary-track{display:flex;align-items:stretch;gap:2px;height:8px;border-radius:4px;background:var(--wb-bg-tertiary);overflow:visible}.wbs-credit-summary-track .wbs-credit-segment{height:8px;min-width:3px}.wbs-credit-summary-track i{display:block;height:100%;border-radius:4px;}.wbs-credit-summary-foot{border-top:1px solid var(--wb-border-subtle);padding-top:8px;margin-top:8px}',
+ '.wbs-credit-summary-chart{max-height:230px;overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:transparent transparent}.wbs-credit-summary-row{display:grid;grid-template-columns:68px minmax(30px,1fr) 58px;align-items:center;gap:8px;min-height:28px}.wbs-credit-summary-row>span{font-size:11px;color:var(--wb-color-text-secondary)}.wbs-credit-summary-row>b{text-align:right;font-size:11px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.wbs-credit-summary-track{display:flex;align-items:stretch;gap:2px;height:8px;border-radius:4px;background:var(--wb-bg-tertiary);overflow:visible}.wbs-credit-summary-track .wbs-credit-segment{height:8px;min-width:3px}.wbs-credit-summary-track i{display:block;height:100%;border-radius:4px;}.wbs-credit-summary-foot{border-top:1px solid var(--wb-border-subtle);padding-top:8px;margin-top:8px}',
+ ':is(.wbs-credit-summary-popover,.wbs-credit-summary-chart)::-webkit-scrollbar{width:6px}:is(.wbs-credit-summary-popover,.wbs-credit-summary-chart)::-webkit-scrollbar-track,:is(.wbs-credit-summary-popover,.wbs-credit-summary-chart)::-webkit-scrollbar-thumb{background:transparent}:is(.wbs-credit-summary-popover,.wbs-credit-summary-chart)::-webkit-scrollbar-thumb{border-radius:6px}:is(.wbs-credit-summary-popover,.wbs-credit-summary-chart).is-scrolling{scrollbar-color:var(--wb-icon-secondary,#72757d) transparent}:is(.wbs-credit-summary-popover,.wbs-credit-summary-chart).is-scrolling::-webkit-scrollbar-thumb{background:var(--wb-icon-secondary,#72757d)}',
'html.cb-dark .wbs-credit-summary-popover,html[data-theme="dark"] .wbs-credit-summary-popover,body[data-vscode-theme-name="IDE Night"] .wbs-credit-summary-popover{background:var(--wb-bg-popover,var(--wb-bg-primary));color:var(--wb-color-text-primary);border-color:var(--wb-border-default)}',
'@media(max-width:600px){.wbs-acct-toolbar{flex-wrap:wrap;gap:8px}.wbs-acct-summary{flex-wrap:wrap}.wbs-acct-actions{margin-left:auto}}',
'.wbs-acct-summary{display:flex;align-items:center;gap:12px;min-width:0}.wbs-acct-summary>[data-act="model-rate-limit-summary"]{margin-left:-7px}',
diff --git a/scripts/markdown-preview.js b/scripts/markdown-preview.js
new file mode 100644
index 0000000..0ad9c7b
--- /dev/null
+++ b/scripts/markdown-preview.js
@@ -0,0 +1,330 @@
+/* Generated by tools/markdown-preview/build.mjs; marked 18.0.14 / DOMPurify 3.4.16. */
+(()=>{function Ct(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var be=Ct();function Un(t){be=t}var me={exec:()=>null};function Ie(t){let e=[];return n=>{let s=Math.max(0,Math.min(3,n-1)),r=e[s];return r||(r=t(s),e[s]=r),r}}function b(t,e=""){let n=typeof t=="string"?t:t.source,s={replace:(r,o)=>{let c=typeof o=="string"?o:o.source;return c=c.replace(N.caret,"$1"),n=n.replace(r,c),s},getRegex:()=>new RegExp(n,e)};return s}var Gr=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),N={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Ie(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Ie(t=>new RegExp(`^ {0,${t}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:Ie(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:Ie(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:Ie(t=>new RegExp(`^ {0,${t}}(?:</?(?:${Be})(?: +|$|/?>)|<(?:script|pre|style|textarea|!--))`,"i")),blockquoteBeginRegex:Ie(t=>new RegExp(`^ {0,${t}}>`))},Wr=/^(?:[ \t]*(?:\n|$))+/,qr=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,jr=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Fe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Zr=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,vt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Fn=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Bn=b(Fn).replace(/bull/g,vt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Yr=b(Fn).replace(/bull/g,vt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Nt=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Xr=/^[^\n]+/,zt=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Qr=b(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",zt).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Vr=b(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,vt).getRegex(),Be="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Mt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Kr=b("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Mt).replace("tag",Be).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Hn=t=>b(Nt).replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",t).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Be).getRegex(),Jr=Hn(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),ei=Hn(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),ti=b(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",ei).getRegex(),$t={blockquote:ti,code:qr,def:Qr,fences:jr,heading:Zr,hr:Fe,html:Kr,lheading:Bn,list:Vr,newline:Wr,paragraph:Jr,table:me,text:Xr},On=b("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Be).getRegex(),ni={...$t,lheading:Yr,table:On,paragraph:b(Nt).replace("hr",Fe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",On).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Be).getRegex()},ri={...$t,html:b(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Mt).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:me,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:b(Nt).replace("hr",Fe).replace("heading",` *#{1,6} *[^
+]`).replace("lheading",Bn).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ii=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,si=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Gn=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,oi=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,re=/[\p{P}\p{S}]/u,Pe=/[\s\p{P}\p{S}]/u,He=/[^\s\p{P}\p{S}]/u,li=b(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Pe).getRegex(),ai=/[\p{Pi}\p{Ps}"']/u,Wn=/(?!~)[\p{P}\p{S}]/u,ci=/(?!~)[\s\p{P}\p{S}]/u,ui=/(?:[^\s\p{P}\p{S}]|~)/u,pi=b(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Gr?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),qn=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,hi=b(qn,"u").replace(/punct/g,re).getRegex(),fi=b(qn,"u").replace(/punct/g,Wn).getRegex(),gi=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,di=b(gi,"u").replace(/openQuote/g,ai).replace(/punct/g,re).getRegex(),jn="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",mi=b(jn,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,Pe).replace(/punct/g,re).getRegex(),ki=b(jn,"gu").replace(/notPunctSpace/g,ui).replace(/punctSpace/g,ci).replace(/punct/g,Wn).getRegex(),bi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",xi=b(bi,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,Pe).replace(/punct/g,re).getRegex(),Ti=b("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,Pe).replace(/punct/g,re).getRegex(),_i="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",wi=b(_i,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,Pe).replace(/punct/g,re).getRegex(),yi=b(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,re).getRegex(),Ai="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Si=b(Ai,"gu").replace(/notPunctSpace/g,He).replace(/punctSpace/g,Pe).replace(/punct/g,re).getRegex(),Ei=b(/\\(punct)/,"gu").replace(/punct/g,re).getRegex(),Ri=b(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Li=b(Mt).replace("(?:-->|$)","-->").getRegex(),Oi=b("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Li).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Zn=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,lt=b(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",Zn).getRegex(),Ii=b(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",lt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Pi=b(/^!?\[(label)\]\[(ref)\]/).replace("label",lt).replace("ref",zt).getRegex(),Di=b(/^!?\[(ref)\](?:\[\])?/).replace("ref",zt).getRegex(),In=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Ci=b(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",Zn).getRegex(),vi=b("reflink|nolink(?!\\()","g").replace("reflink",b(/^!?\[(label)\]\[(ref)\]/).replace("label",Ci).replace("ref",In).getRegex()).replace("nolink",b(/^!?\[(ref)\](?:\[\])?/).replace("ref",In).getRegex()).getRegex(),Pn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ni=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,zi=b(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,Ni).getRegex(),Ut={_backpedal:me,anyPunctuation:Ei,autolink:Ri,blockSkip:pi,br:Gn,code:si,del:me,delLDelim:me,delRDelim:me,emStrongLDelim:hi,emStrongRDelimAst:mi,emStrongRDelimUnd:Ti,escape:ii,link:Ii,nolink:Di,punctuation:li,reflink:Pi,reflinkSearch:vi,tag:Oi,text:oi,url:me},Mi={...Ut,emStrongLDelim:di,emStrongRDelimAst:xi,emStrongRDelimUnd:wi,link:b(/^!?\[(label)\]\((.*?)\)/).replace("label",lt).getRegex(),reflink:b(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",lt).getRegex()},It={...Ut,emStrongRDelimAst:ki,emStrongLDelim:fi,delLDelim:yi,delRDelim:Si,url:b(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",zi).replace("protocol",Pn).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:b(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace("protocol",Pn).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},$i={...It,br:b(Gn).replace("{2,}","*").getRegex(),text:b(It.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ot={normal:$t,gfm:ni,pedantic:ri},$e={normal:Ut,gfm:It,breaks:$i,pedantic:Mi},Ui={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Dn=t=>Ui[t];function G(t,e){if(e){if(N.escapeTest.test(t))return t.replace(N.escapeReplace,Dn)}else if(N.escapeTestNoEncode.test(t))return t.replace(N.escapeReplaceNoEncode,Dn);return t}function Fi(t){return t.replace(N.numericCharacterReference,(e,n,s)=>{let r=n===void 0?Number.parseInt(s,16):Number.parseInt(n,10);return r===0||r>1114111||r>=55296&&r<=57343?"\uFFFD":String.fromCodePoint(r)})}function Cn(t){try{t=encodeURI(t).replace(N.percentDecode,"%")}catch{return null}return t}function vn(t,e){let n=t.replace(N.findPipe,(o,c,l)=>{let p=!1,h=c;for(;--h>=0&&l[h]==="\\";)p=!p;return p?"|":" |"}),s=n.split(N.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),e)if(s.length>e)s.splice(e);else for(;s.length<e;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(N.slashPipe,"|");return s}function ce(t,e,n){let s=t.length;if(s===0)return"";let r=0;for(;r<s;){let o=t.charAt(s-r-1);if(o===e&&!n)r++;else if(o!==e&&n)r++;else break}return t.slice(0,s-r)}function Nn(t){let e=t.split(`
+`),n=e.length-1;for(;n>=0&&N.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
+`)}function at(t){return t.trim().toLowerCase().toUpperCase().toLowerCase()}function Bi(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let s=0;s<t.length;s++)if(t[s]==="\\")s++;else if(t[s]===e[0])n++;else if(t[s]===e[1]&&(n--,n<0))return s;return n>0?-2:-1}function zn(t,e=0){let n=e,s="";for(let r of t)if(r===" "){let o=4-n%4;s+=" ".repeat(o),n+=o}else s+=r,n++;return s}function Mn(t,e,n,s,r){let o=e.href,c=e.title||null,l=t[1].replace(r.other.outputLinkReplace,"$1"),p=t[0].charAt(0)==="!";s.state.inLink=!0;let h=s.state.linkEmitted,d=s.state.inRawBlock;s.state.linkEmitted=!1;let m=s.inlineTokens(l),D=s.state.linkEmitted;if(s.state.linkEmitted=h,s.state.inLink=!1,!p){if(D){s.state.inRawBlock=d;return}s.state.linkEmitted=!0}return{type:p?"image":"link",raw:n,href:o,title:c,text:l,tokens:m}}function Hi(t,e,n){let s=t.match(n.other.indentCodeCompensation);if(s===null)return e;let r=s[1];return e.split(`
+`).map(o=>{let c=o.match(n.other.beginningSpace);if(c===null)return o;let[l]=c;return o.slice(Math.min(l.length,r.length))}).join(`
+`)}function $n(t,e,n,s){if(!e.includes("<"))return!1;for(let r=0;r<e.length;r++){if(e[r]==="\\"){r++;continue}if(e[r]==="`"){let l=s.inline.code.exec(e.slice(r));if(l){r+=l[0].length-1;continue}}if(e[r]!=="<")continue;let o=t.slice(n+r),c=s.inline.tag.exec(o)||s.inline.autolink.exec(o);if(c){if(c[0].length>e.length-r)return!0;r+=c[0].length-1}}return!1}var ct=class{options;rules;lexer;constructor(t){this.options=t||be}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=this.options.pedantic?e[0]:Nn(e[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],s=Hi(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:s}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let s=ce(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceTabChar.test(s))&&(n=s.trim())}return{type:"heading",raw:ce(e[0],`
+`),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:ce(e[0],`
+`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=ce(e[0],`
+`).split(`
+`),s="",r="",o=[];for(;n.length>0;){let c=!1,l=[],p;for(p=0;p<n.length;p++)if(this.rules.other.blockquoteStart.test(n[p]))l.push(n[p]),c=!0;else if(!c)l.push(n[p]);else break;n=n.slice(p);let h=l.join(`
+`),d=h.replace(this.rules.other.blockquoteSetextReplace,`
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
+${h}`:h,r=r?`${r}
+${d}`:d;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(d,o,!0),this.lexer.state.top=m,n.length===0)break;let D=o.at(-1);if(D?.type==="code")break;if(D?.type==="blockquote"){let S=D,w=n.join(`
+`),z=S.raw+`
+`+w.replace(this.rules.other.blockquoteSetextReplace2,""),y=this.blockquote(z);o[o.length-1]=y;let B=z.substring(y.raw.length).replace(/^\n/,""),ie=B?B.split(`
+`).length:0,ee=ie?n.slice(0,-ie):n;ee.length>0&&(s=`${s}
+${ee.join(`
+`)}`),r=r.substring(0,r.length-S.text.length)+y.text;break}else if(D?.type==="list"){let S=D,w=S.raw+`
+`+n.join(`
+`),z=this.list(w);o[o.length-1]=z,s=s.substring(0,s.length-D.raw.length)+z.raw,r=r.substring(0,r.length-S.raw.length)+z.raw,n=w.substring(o.at(-1).raw.length).split(`
+`);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let o=this.rules.other.listItemRegex(n),c=!1;for(;t;){let p=!1,h="",d="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;h=e[0],t=t.substring(h.length);let m=e[2].split(`
+`,1)[0],D=e[1].length,S=this.options.pedantic?zn(m,D):m.replace(this.rules.other.leadingSpaceTab,B=>zn(B,D)),w=t.split(`
+`,1)[0],z=!S.trim(),y=0;if(this.options.pedantic?(y=2,d=S.trimStart()):z?y=D+1:(y=S.search(this.rules.other.nonSpaceChar),y=y>4?1:y,d=S.slice(y),y+=D),z&&this.rules.other.blankLine.test(w)&&(h+=w+`
+`,t=t.substring(w.length+1),p=!0),!p){let B=this.rules.other.nextBulletRegex(y),ie=this.rules.other.hrRegex(y),ee=this.rules.other.fencesBeginRegex(y),Q=this.rules.other.headingBeginRegex(y),se=this.rules.other.htmlBeginRegex(y),Te=this.rules.other.blockquoteBeginRegex(y);for(;t;){let te=t.split(`
+`,1)[0],ne;if(w=te,this.options.pedantic?(w=w.replace(this.rules.other.listReplaceNesting," "),ne=w):ne=w.replace(this.rules.other.leadingSpaceTab,M=>M.replace(this.rules.other.tabCharGlobal," ")),ee.test(w)||Q.test(w)||se.test(w)||Te.test(w)||B.test(w)||ie.test(w))break;if(ne.search(this.rules.other.nonSpaceChar)>=y||!w.trim())d+=`
+`+ne.slice(y);else{if(z||S.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ee.test(S)||Q.test(S)||ie.test(S))break;d+=`
+`+w}z=!w.trim(),h+=te+`
+`,t=t.substring(te.length+1),S=ne.slice(y)}}r.loose||(c?r.loose=!0:this.rules.other.doubleBlankLine.test(h)&&(c=!0)),r.items.push({type:"list_item",raw:h,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),r.raw+=h}let l=r.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let p of r.items)if(this.lexer.state.top=!1,p.tokens=this.lexer.blockTokens(p.text,[]),!r.loose){let h=p.tokens.filter(m=>m.type==="space"),d=h.length>0&&h.some(m=>this.rules.other.anyLine.test(m.raw));r.loose=d}for(let p of r.items){let h=p.tokens[0];if(p.task&&(h?.type==="text"||h?.type==="paragraph")){p.text=p.text.replace(this.rules.other.listReplaceTask,""),h.raw=h.raw.replace(this.rules.other.listReplaceTask,""),h.text=h.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let d=this.rules.other.listTaskCheckbox.exec(p.raw);if(d){let m={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};p.checked=m.checked,r.loose?p.tokens[0]&&["paragraph","text"].includes(p.tokens[0].type)&&"tokens"in p.tokens[0]&&p.tokens[0].tokens?(p.tokens[0].raw=m.raw+p.tokens[0].raw,p.tokens[0].text=m.raw+p.tokens[0].text,p.tokens[0].tokens.unshift(m)):p.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):p.tokens.unshift(m)}}else p.task&&(p.task=!1)}if(r.loose)for(let p of r.items){p.loose=!0;for(let h of p.tokens)h.type==="text"&&(h.type="paragraph")}return r}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=Nn(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=at(e[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:ce(e[0],`
+`),href:s,title:r}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=vn(e[1]),s=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
+`):[],o={type:"table",raw:ce(e[0],`
+`),header:[],align:[],rows:[]};if(n.length===s.length){for(let c of s)this.rules.other.tableAlignRight.test(c)?o.align.push("right"):this.rules.other.tableAlignCenter.test(c)?o.align.push("center"):this.rules.other.tableAlignLeft.test(c)?o.align.push("left"):o.align.push(null);for(let c=0;c<n.length;c++)o.header.push({text:n[c],tokens:this.lexer.inline(n[c]),header:!0,align:o.align[c]});for(let c of r)o.rows.push(vn(c,o.header.length).map((l,p)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:o.align[p]})));return o}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:ce(e[0],`
+`),depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
+`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&$n(t,e[1],n,this.rules))return;let s=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let c=ce(s.slice(0,-1),"\\");if((s.length-c.length)%2===0)return}else{let c=Bi(e[2],"()");if(c===-2)return;if(c>-1){let l=(e[0].indexOf("!")===0?5:4)+e[1].length+c;e[2]=e[2].substring(0,c),e[0]=e[0].substring(0,l).trim(),e[3]=""}}let r=e[2],o="";if(this.options.pedantic){let c=this.rules.other.pedanticHrefTitle.exec(r);c&&(r=c[1],o=c[3])}else o=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),Mn(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let s=n[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&$n(t,n[1],s,this.rules))return;let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[at(r)];if(!o){let c=n[0].charAt(0);return{type:"text",raw:c,text:c}}return Mn(n,o,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let s=this.rules.inline.emStrongLDelim.exec(t);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,o,c,l=r,p=0,h=s[0][0],d=n===h,m=h==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,e=e.slice(-1*t.length+r);(s=m.exec(e))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(c=[...o].length,s[3]||s[4]){l+=c;continue}else if(s[5]||s[6]){if(r%3&&!((r+c)%3)){p+=c;continue}if(d)break}if(l-=c,l>0)continue;c=Math.min(c,c+l+p);let D=[...s[0]][0].length,S=t.slice(0,r+s.index+D+c);if(Math.min(r,c)%2){let z=S.slice(1,-1);return{type:"em",raw:S,text:z,tokens:this.lexer.inlineTokens(z)}}let w=S.slice(2,-2);return{type:"strong",raw:S,text:w,tokens:this.lexer.inlineTokens(w)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let s=this.rules.inline.delLDelim.exec(t);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,o,c,l=r,p=this.rules.inline.delRDelim;for(p.lastIndex=0,e=e.slice(-1*t.length+r);(s=p.exec(e))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(c=[...o].length,c!==r))continue;if(s[3]||s[4]){l+=c;continue}if(l-=c,l>0)continue;c=Math.min(c,c+l);let h=[...s[0]][0].length,d=t.slice(0,r+s.index+h+c),m=d.slice(r,-r);return{type:"del",raw:d,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,s;return e[2]==="@"?(n=e[1],s="mailto:"+n):(n=e[1],s=n),{type:"link",raw:e[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,s;if(e[2]==="@")n=e[0],s="mailto:"+n;else{let r;do r=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(r!==e[0]);n=e[0],e[1]==="www."?s="http://"+e[0]:s=e[0]}return{type:"link",raw:e[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:n?e[0]:Fi(e[0]),escaped:n}}}},Y=class Pt{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||be,this.options.tokenizer=this.options.tokenizer||new ct,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let n={other:N,block:ot.normal,inline:$e.normal};this.options.pedantic?(n.block=ot.pedantic,n.inline=$e.pedantic):this.options.gfm&&(n.block=ot.gfm,this.options.breaks?n.inline=$e.breaks:n.inline=$e.gfm),this.tokenizer.rules=n}static get rules(){return{block:ot,inline:$e}}static lex(e,n){return new Pt(n).lex(e)}static lexInline(e,n){return new Pt(n).inlineTokens(e)}lex(e){e=e.replace(N.carriageReturn,`
+`),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let s=this.inlineQueue[n];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(N.tabCharGlobal," ").replace(N.spaceLine,""));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(l=>(o=l.call({lexer:this},e,n))?(e=e.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);let l=n.at(-1);o.raw.length===1&&l!==void 0?l.raw+=`
+`:n.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length);let l=n.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`
+`)?"":`
+`)+o.raw,l.text+=`
+`+o.text,this.inlineQueue.at(-1).src=l.text):n.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length);let l=n.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`
+`)?"":`
+`)+o.raw,l.text+=`
+`+o.raw,this.inlineQueue.at(-1).src=l.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},n.push(o));continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),n.push(o);continue}let c=e;if(this.options.extensions?.startBlock){let l=1/0,p=e.slice(1),h;this.options.extensions.startBlock.forEach(d=>{h=d.call({lexer:this},p),typeof h=="number"&&h>=0&&(l=Math.min(l,h))}),l<1/0&&l>=0&&(c=e.substring(0,l+1))}if(this.state.top&&(o=this.tokenizer.paragraph(c))){let l=n.at(-1);s&&l?.type==="paragraph"?(l.raw+=(l.raw.endsWith(`
+`)?"":`
+`)+o.raw,l.text+=`
+`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):n.push(o),s=c.length!==e.length,e=e.substring(o.raw.length);continue}if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length);let l=n.at(-1);l?.type==="text"?(l.raw+=(l.raw.endsWith(`
+`)?"":`
+`)+o.raw,l.text+=`
+`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):n.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}linkInText(e){if(!e.includes("["))return!1;let n=this.tokenizer.rules.inline.link;for(let s of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(n.test(s[0])&&e.charAt(s.index-1)!=="!")return!0;for(let s of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let r=s[0],o=r.lastIndexOf("[");if(!(r.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,at(r.slice(o+1,-1))))&&!(o>1&&this.linkInText(r.slice(1,o-1))))return!0}return!1}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let s=e;if(this.tokens.links&&e.includes("[")){let l=this.tokenizer.rules.inline.reflinkSearch,p=h=>{let d=h.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,at(h.slice(d+1,-1))))return h;if(d>1&&h.charAt(0)!=="!"){let m=h.slice(1,d-1);if(this.linkInText(m))return"["+m.replace(l,p)+"]["+"a".repeat(h.length-d-2)+"]"}return"["+"a".repeat(h.length-2)+"]"};s=s.replace(l,p)}s=s.replace(this.tokenizer.rules.inline.anyPunctuation,l=>"+".repeat(l.length)),s=s.replace(this.tokenizer.rules.inline.blockSkip,(l,p,h)=>{let d=h?h.length:0;return l.slice(0,d)+"["+"a".repeat(l.length-d-2)+"]"}),s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let r=!1,o="",c=1/0;for(;e;){if(e.length<c)c=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(o=""),r=!1;let l;if(this.options.extensions?.inline?.some(h=>(l=h.call({lexer:this},e,n))?(e=e.substring(l.raw.length),n.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let h=n.at(-1);l.type==="text"&&h?.type==="text"?(h.raw+=l.raw,h.text+=l.text):n.push(l);continue}if(l=this.tokenizer.emStrong(e,s,o)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.del(e,s,o)){e=e.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),n.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),n.push(l);continue}let p=e;if(this.options.extensions?.startInline){let h=1/0,d=e.slice(1),m;this.options.extensions.startInline.forEach(D=>{m=D.call({lexer:this},d),typeof m=="number"&&m>=0&&(h=Math.min(h,m))}),h<1/0&&h>=0&&(p=e.substring(0,h+1))}if(l=this.tokenizer.inlineText(p)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(o=l.raw.slice(-1)),r=!0;let h=n.at(-1);h?.type==="text"?(h.raw+=l.raw,h.text+=l.text):n.push(l);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}infiniteLoopError(e){let n="Infinite loop on byte: "+e;if(this.options.silent)console.error(n);else throw new Error(n)}},ut=class{options;parser;constructor(t){this.options=t||be}space(t){return""}code({text:t,lang:e,escaped:n}){let s=(e||"").match(N.notSpaceStart)?.[0],r=t?t.replace(N.endingNewline,"")+`
+`:"";return s?'<pre><code class="language-'+G(s)+'">'+(n?r:G(r,!0))+`</code></pre>
+`:"<pre><code>"+(n?r:G(r,!0))+`</code></pre>
+`}blockquote({tokens:t}){return`<blockquote>
+${this.parser.parse(t)}</blockquote>
+`}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
+`}hr(t){return`<hr>
+`}list(t){let e=t.ordered,n=t.start,s="";for(let c=0;c<t.items.length;c++){let l=t.items[c];s+=this.listitem(l)}let r=e?"ol":"ul",o=e&&n!==1?' start="'+n+'"':"";return"<"+r+o+`>
+`+s+"</"+r+`>
+`}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
+`}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
+`}table(t){let e="",n="";for(let r=0;r<t.header.length;r++)n+=this.tablecell(t.header[r]);e+=this.tablerow({text:n});let s="";for(let r=0;r<t.rows.length;r++){let o=t.rows[r];n="";for(let c=0;c<o.length;c++)n+=this.tablecell(o[c]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
+<thead>
+`+e+`</thead>
+`+s+`</table>
+`}tablerow({text:t}){return`<tr>
+${t}</tr>
+`}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
+`}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${G(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,text:n,tokens:s,autolink:r}){let o=r?G(n,!0):this.parser.parseInline(s),c=Cn(t);if(c===null)return o;t=G(c,r);let l='<a href="'+t+'"';return e&&(l+=' title="'+G(e)+'"'),l+=">"+o+"</a>",l}image({href:t,title:e,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=Cn(t);if(r===null)return G(n);t=r;let o=`<img src="${G(t)}" alt="${G(n)}"`;return e&&(o+=` title="${G(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:G(t.text)}},Ft=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},X=class Dt{options;renderer;textRenderer;constructor(e){this.options=e||be,this.options.renderer=this.options.renderer||new ut,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ft}static parse(e,n){return new Dt(n).parse(e)}static parseInline(e,n){return new Dt(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let c=r,l=this.options.extensions.renderers[c.type].call({parser:this},c);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(c.type)){n+=l||"";continue}}let o=r;switch(o.type){case"space":{n+=this.renderer.space(o);break}case"hr":{n+=this.renderer.hr(o);break}case"heading":{n+=this.renderer.heading(o);break}case"code":{n+=this.renderer.code(o);break}case"table":{n+=this.renderer.table(o);break}case"blockquote":{n+=this.renderer.blockquote(o);break}case"list":{n+=this.renderer.list(o);break}case"checkbox":{n+=this.renderer.checkbox(o);break}case"html":{n+=this.renderer.html(o);break}case"def":{n+=this.renderer.def(o);break}case"paragraph":{n+=this.renderer.paragraph(o);break}case"text":{n+=this.renderer.text(o);break}default:{let c='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let s="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(o.type)){s+=l||"";continue}}let c=o;switch(c.type){case"escape":{s+=n.text(c);break}case"html":{s+=n.html(c);break}case"link":{s+=n.link(c);break}case"image":{s+=n.image(c);break}case"checkbox":{s+=n.checkbox(c);break}case"strong":{s+=n.strong(c);break}case"em":{s+=n.em(c);break}case"codespan":{s+=n.codespan(c);break}case"br":{s+=n.br(c);break}case"del":{s+=n.del(c);break}case"text":{s+=n.text(c);break}default:{let l='Token with "'+c.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}},Ue=class{options;block;constructor(t){this.options=t||be}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?Y.lex:Y.lexInline}provideParser(t=this.block){return t?X.parse:X.parseInline}},Bt=class{defaults=Ct();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=X;Renderer=ut;TextRenderer=Ft;Lexer=Y;Tokenizer=ct;Hooks=Ue;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let s of t)switch(n=n.concat(e.call(this,s)),s.type){case"table":{let r=s;for(let o of r.header)n=n.concat(this.walkTokens(o.tokens,e));for(let o of r.rows)for(let c of o)n=n.concat(this.walkTokens(c.tokens,e));break}case"list":{let r=s;n=n.concat(this.walkTokens(r.items,e));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let c=r[o].flat(1/0);n=n.concat(this.walkTokens(c,e))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=e.renderers[r.name];o?e.renderers[r.name]=function(...c){let l=r.renderer.apply(this,c);return l===!1&&(l=o.apply(this,c)),l}:e.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=e[r.level];o?o.unshift(r.tokenizer):e[r.level]=[r.tokenizer],r.start&&(r.level==="block"?e.startBlock?e.startBlock.push(r.start):e.startBlock=[r.start]:r.level==="inline"&&(e.startInline?e.startInline.push(r.start):e.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(e.childTokens[r.name]=r.childTokens)}),s.extensions=e),n.renderer){let r=this.defaults.renderer||new ut(this.defaults);for(let o in n.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let c=o,l=n.renderer[c],p=r[c];r[c]=(...h)=>{let d=l.apply(r,h);return d===!1&&(d=p.apply(r,h)),d||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new ct(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let c=o,l=n.tokenizer[c],p=r[c];r[c]=(...h)=>{let d=l.apply(r,h);return d===!1&&(d=p.apply(r,h)),d}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new Ue;for(let o in n.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let c=o,l=n.hooks[c],p=r[c];Ue.passThroughHooks.has(o)?r[c]=h=>{if(this.defaults.async&&Ue.passThroughHooksRespectAsync.has(o))return(async()=>{let m=await l.call(r,h);return p.call(r,m)})();let d=l.call(r,h);return p.call(r,d)}:r[c]=(...h)=>{if(this.defaults.async)return(async()=>{let m=await l.apply(r,h);return m===!1&&(m=await p.apply(r,h)),m})();let d=l.apply(r,h);return d===!1&&(d=p.apply(r,h)),d}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;s.walkTokens=function(c){let l=[];return l.push(o.call(this,c)),r&&(l=l.concat(r.call(this,c))),l}}this.defaults={...this.defaults,...s}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return Y.lex(t,e??this.defaults)}parser(t,e){return X.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let s={...n},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=t),r.async)return(async()=>{let c=r.hooks?await r.hooks.preprocess(e):e,l=await(r.hooks?await r.hooks.provideLexer(t):t?Y.lex:Y.lexInline)(c,r),p=r.hooks?await r.hooks.processAllTokens(l):l;r.walkTokens&&await Promise.all(this.walkTokens(p,r.walkTokens));let h=await(r.hooks?await r.hooks.provideParser(t):t?X.parse:X.parseInline)(p,r);return r.hooks?await r.hooks.postprocess(h):h})().catch(o);try{r.hooks&&(e=r.hooks.preprocess(e));let c=(r.hooks?r.hooks.provideLexer(t):t?Y.lex:Y.lexInline)(e,r);r.hooks&&(c=r.hooks.processAllTokens(c)),r.walkTokens&&this.walkTokens(c,r.walkTokens);let l=(r.hooks?r.hooks.provideParser(t):t?X.parse:X.parseInline)(c,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(c){return o(c)}}}onError(t,e){return n=>{if(n.message+=`
+Please report this to https://github.com/markedjs/marked.`,t){let s="<p>An error occurred:</p><pre>"+G(n.message+"",!0)+"</pre>";return e?Promise.resolve(s):s}if(e)return Promise.reject(n);throw n}}},ke=new Bt;function A(t,e){return ke.parse(t,e)}A.options=A.setOptions=function(t){return ke.setOptions(t),A.defaults=ke.defaults,Un(A.defaults),A};A.getDefaults=Ct;A.defaults=be;function Gi(...t){return ke.use(...t),A.defaults=ke.defaults,Un(A.defaults),A}A.use=Gi;A.walkTokens=function(t,e){return ke.walkTokens(t,e)};A.parseInline=ke.parseInline;A.Parser=X;A.parser=X.parse;A.Renderer=ut;A.TextRenderer=Ft;A.Lexer=Y;A.lexer=Y.lex;A.Tokenizer=ct;A.Hooks=Ue;A.parse=A;var Es=A.options,Rs=A.setOptions,Ls=A.walkTokens,Os=A.parseInline;var Is=X.parse,Ps=Y.lex;function Wi(t,e){this.v=t,this.k=e}function Yn(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,s=Array(e);n<e;n++)s[n]=t[n];return s}function qi(t){if(Array.isArray(t))return t}function ji(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var s,r,o,c,l=[],p=!0,h=!1;try{if(o=(n=n.call(t)).next,e===0){if(Object(n)!==n)return;p=!1}else for(;!(p=(s=o.call(n)).done)&&(l.push(s.value),l.length!==e);p=!0);}catch(d){h=!0,r=d}finally{try{if(!p&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(h)throw r}}return l}}function Zi(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
+In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Yi(t,e){return qi(t)||ji(t,e)||Xi(t,e)||Zi()}function Xi(t,e){if(t){if(typeof t=="string")return Yn(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Yn(t,e):void 0}}function pt(t){var e,n;function s(o,c){try{var l=t[o](c),p=l.value,h=p instanceof Wi;Promise.resolve(h?p.v:p).then(function(d){if(h){var m=o==="return"&&p.k?o:"next";if(!p.k||d.done)return s(m,d);d=t[m](d).value}r(!!l.done,d)},function(d){s("throw",d)})}catch(d){r(2,d)}}function r(o,c){o===2?e.reject(c):e.resolve({value:c,done:o}),(e=e.next)?s(e.key,e.arg):n=null}this._invoke=function(o,c){return new Promise(function(l,p){var h={key:o,arg:c,resolve:l,reject:p,next:null};n?n=n.next=h:(e=n=h,s(o,c))})},typeof t.return!="function"&&(this.return=void 0)}pt.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},pt.prototype.next=function(t){return this._invoke("next",t)},pt.prototype.throw=function(t){return this._invoke("throw",t)},pt.prototype.return=function(t){return this._invoke("return",t)};var cr=Object.entries,Xn=Object.setPrototypeOf,Qi=Object.isFrozen,Vi=Object.getPrototypeOf,Ki=Object.getOwnPropertyDescriptor,C=Object.freeze,v=Object.seal,De=Object.create,ur=typeof Reflect<"u"&&Reflect,Yt=ur.apply,Xt=ur.construct;C||(C=function(e){return e});v||(v=function(e){return e});Yt||(Yt=function(e,n){for(var s=arguments.length,r=new Array(s>2?s-2:0),o=2;o<s;o++)r[o-2]=arguments[o];return e.apply(n,r)});Xt||(Xt=function(e){for(var n=arguments.length,s=new Array(n>1?n-1:0),r=1;r<n;r++)s[r-1]=arguments[r];return new e(...s)});var xe=P(Array.prototype.forEach);Array.prototype.indexOf;var Ji=P(Array.prototype.lastIndexOf),Qn=P(Array.prototype.pop),Ge=P(Array.prototype.push);Array.prototype.slice;var es=P(Array.prototype.splice),Ce=Array.isArray,je=P(String.prototype.toLowerCase),Ht=P(String.prototype.toString),Vn=P(String.prototype.match),We=P(String.prototype.replace),Kn=P(String.prototype.indexOf),ts=P(String.prototype.trim),ns=P(Number.prototype.toString),rs=P(Boolean.prototype.toString),Jn=typeof BigInt>"u"?null:P(BigInt.prototype.toString),er=typeof Symbol>"u"?null:P(Symbol.prototype.toString),F=P(Object.prototype.hasOwnProperty),qe=P(Object.prototype.toString),$=P(RegExp.prototype.test),ue=is(TypeError);function P(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),r=1;r<n;r++)s[r-1]=arguments[r];return Yt(t,e,s)}}function is(t){return function(){for(var e=arguments.length,n=new Array(e),s=0;s<e;s++)n[s]=arguments[s];return Xt(t,n)}}function _(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:je;if(Xn&&Xn(t,null),!Ce(e))return t;let s=e.length;for(;s--;){let r=e[s];if(typeof r=="string"){let o=n(r);o!==r&&(Qi(e)||(e[s]=o),r=o)}t[r]=!0}return t}function ss(t){for(let e=0;e<t.length;e++)F(t,e)||(t[e]=null);return t}function q(t){let e=De(null);for(let s of cr(t)){var n=Yi(s,2);let r=n[0],o=n[1];F(t,r)&&(Ce(o)?e[r]=ss(o):o&&typeof o=="object"&&o.constructor===Object?e[r]=q(o):e[r]=o)}return e}function os(t){switch(typeof t){case"string":return t;case"number":return ns(t);case"boolean":return rs(t);case"bigint":return Jn?Jn(t):"0";case"symbol":return er?er(t):"Symbol()";case"undefined":return qe(t);case"function":case"object":{if(t===null)return qe(t);let e=t,n=Z(e,"toString");if(typeof n=="function"){let s=n(e);return typeof s=="string"?s:qe(s)}return qe(t)}default:return qe(t)}}function Z(t,e){for(;t!==null;){let s=Ki(t,e);if(s){if(s.get)return P(s.get);if(typeof s.value=="function")return P(s.value)}t=Vi(t)}function n(){return null}return n}function ls(t){try{return $(t,""),!0}catch{return!1}}var tr=C(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Gt=C(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Wt=C(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),as=C(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),qt=C(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),cs=C(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),nr=C(["#text"]),rr=C(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),jt=C(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),ir=C(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ht=C(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),us=v(/{{[\w\W]*|^[\w\W]*}}/g),ps=v(/<%[\w\W]*|^[\w\W]*%>/g),hs=v(/\${[\w\W]*/g),fs=v(/^data-[\-\w.\u00B7-\uFFFF]+$/),gs=v(/^aria-[\-\w]+$/),sr=v(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ds=v(/^(?:\w+script|data):/i),ms=v(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ks=v(/^html$/i),bs=v(/^[a-z][.\w]*(-[.\w]+)+$/i),or=v(/<[/\w!]/g),lr=v(/<[/\w]/g),xs=v(/<\/no(script|embed|frames)/i),Ts=v(/\/>/i),W={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},pr=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],_s=C(_({},pr)),ws=(function(){let t={};return xe(pr,e=>{t[e]=v(new RegExp("</"+e+"(?=[\\t\\n\\f\\r />])","i"))}),C(t)})(),ys=function(){return typeof window>"u"?null:window},As=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let s=null,r="data-tt-policy-suffix";n&&n.hasAttribute(r)&&(s=n.getAttribute(r));let o="dompurify"+(s?"#"+s:"");try{return e.createPolicy(o,{createHTML(c){return c},createScriptURL(c){return c}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},ar=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},pe=function(e,n,s,r){return F(e,n)&&Ce(e[n])?_(r.base?q(r.base):{},e[n],r.transform):s},Zt=function(e,n,s){let r=F(e,n)?e[n]:void 0;return r&&typeof r=="object"?q(r):s()};function hr(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ys(),e=f=>hr(f);if(e.version="3.4.16",e.removed=[],!t||!t.document||t.document.nodeType!==W.document||!t.Element)return e.isSupported=!1,e;let n=t.document,s=n,r=s.currentScript;t.DocumentFragment;let o=t.HTMLTemplateElement,c=t.Node,l=t.Element,p=t.NodeFilter;t.NamedNodeMap===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let h=t.DOMParser,d=t.trustedTypes,m=l.prototype,D=Z(m,"cloneNode"),S=Z(m,"remove"),w=Z(m,"removeAttributeNode"),z=Z(m,"nextSibling"),y=Z(m,"childNodes"),B=Z(m,"parentNode"),ie=Z(m,"shadowRoot"),ee=Z(m,"attributes"),Q=c&&c.prototype?Z(c.prototype,"nodeType"):null,se=c&&c.prototype?Z(c.prototype,"nodeName"):null,Te=c&&c.prototype?Z(c.prototype,"ownerDocument"):null,te=function(i){return Q?Q(i):i.nodeType},ne=function(i){return se?se(i):i.nodeName};if(typeof o=="function"){let f=n.createElement("template");f.content&&f.content.ownerDocument&&(n=f.content.ownerDocument)}let M,he="",ft,Qt=!1,ve=0,Vt=function(){if(ve>0)throw ue('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},_e=function(i){Vt(),ve++;try{return M.createHTML(i)}finally{ve--}},dr=function(i){Vt(),ve++;try{return M.createScriptURL(i)}finally{ve--}},mr=function(){return Qt||(ft=As(d,r),Qt=!0),ft},Ze=n,gt=Ze.implementation,Kt=Ze.createNodeIterator,kr=Ze.createDocumentFragment,br=Ze.getElementsByTagName,xr=s.importNode,E=ar();e.isSupported=typeof cr=="function"&&typeof B=="function"&&gt&&gt.createHTMLDocument!==void 0;let Tr=us,_r=ps,wr=hs,yr=fs,Ar=gs,Sr=ds,Jt=ms,Er=bs,en=sr,R=null,dt=_({},[...tr,...Gt,...Wt,...qt,...nr]),L=null,mt=_({},[...rr,...jt,...ir,...ht]),V=Object.seal(De(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ne=null,tn=null,oe=Object.seal(De(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),nn=!0,kt=!0,rn=!1,sn=!0,le=!1,fe=!0,ge=!1,bt=!1,Ye=null,Xe=null,xt=!1,we=!1,Qe=!1,Ve=!1,on=!0,ln=!1,an="user-content-",Tt=!0,_t=!1,ye={},Ae=null,cn=_({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),un=null,pn=_({},["audio","video","img","source","image","track"]),hn=null,fn=_({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ke="http://www.w3.org/1998/Math/MathML",Je="http://www.w3.org/2000/svg",K="http://www.w3.org/1999/xhtml",Se=K,wt=!1,yt=null,Rr=_({},[Ke,Je,K],Ht),gn=C(["mi","mo","mn","ms","mtext"]),At=_({},gn),dn=C(["annotation-xml"]),St=_({},dn),Lr=_({},["title","style","font","a","script"]),ze=null,Or=["application/xhtml+xml","text/html"],Ir="text/html",I=null,Ee=null,Pr=n.createElement("form"),mn=function(i){return i instanceof RegExp||i instanceof Function},Et=function(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Ee&&Ee===i)return;(!i||typeof i!="object")&&(i={}),i=q(i),ze=Or.indexOf(i.PARSER_MEDIA_TYPE)===-1?Ir:i.PARSER_MEDIA_TYPE,I=ze==="application/xhtml+xml"?Ht:je,R=pe(i,"ALLOWED_TAGS",dt,{transform:I}),L=pe(i,"ALLOWED_ATTR",mt,{transform:I}),yt=pe(i,"ALLOWED_NAMESPACES",Rr,{transform:Ht}),hn=pe(i,"ADD_URI_SAFE_ATTR",fn,{transform:I,base:fn}),un=pe(i,"ADD_DATA_URI_TAGS",pn,{transform:I,base:pn}),Ae=pe(i,"FORBID_CONTENTS",cn,{transform:I}),Ne=pe(i,"FORBID_TAGS",q({}),{transform:I}),tn=pe(i,"FORBID_ATTR",q({}),{transform:I}),ye=F(i,"USE_PROFILES")?i.USE_PROFILES&&typeof i.USE_PROFILES=="object"?q(i.USE_PROFILES):i.USE_PROFILES:!1,nn=i.ALLOW_ARIA_ATTR!==!1,kt=i.ALLOW_DATA_ATTR!==!1,rn=i.ALLOW_UNKNOWN_PROTOCOLS||!1,sn=i.ALLOW_SELF_CLOSE_IN_ATTR!==!1,le=i.SAFE_FOR_TEMPLATES||!1,fe=i.SAFE_FOR_XML!==!1,ge=i.WHOLE_DOCUMENT||!1,we=i.RETURN_DOM||!1,Qe=i.RETURN_DOM_FRAGMENT||!1,Ve=i.RETURN_TRUSTED_TYPE||!1,xt=i.FORCE_BODY||!1,on=i.SANITIZE_DOM!==!1,ln=i.SANITIZE_NAMED_PROPS||!1,Tt=i.KEEP_CONTENT!==!1,_t=i.IN_PLACE||!1,en=ls(i.ALLOWED_URI_REGEXP)?i.ALLOWED_URI_REGEXP:sr,Se=typeof i.NAMESPACE=="string"?i.NAMESPACE:K,At=Zt(i,"MATHML_TEXT_INTEGRATION_POINTS",()=>_({},gn)),St=Zt(i,"HTML_INTEGRATION_POINTS",()=>_({},dn));let a=Zt(i,"CUSTOM_ELEMENT_HANDLING",()=>De(null));if(V=De(null),F(a,"tagNameCheck")&&mn(a.tagNameCheck)&&(V.tagNameCheck=a.tagNameCheck),F(a,"attributeNameCheck")&&mn(a.attributeNameCheck)&&(V.attributeNameCheck=a.attributeNameCheck),F(a,"allowCustomizedBuiltInElements")&&typeof a.allowCustomizedBuiltInElements=="boolean"&&(V.allowCustomizedBuiltInElements=a.allowCustomizedBuiltInElements),v(V),le&&(kt=!1),Qe&&(we=!0),ye&&(R=_({},nr),L=De(null),ye.html===!0&&(_(R,tr),_(L,rr)),ye.svg===!0&&(_(R,Gt),_(L,jt),_(L,ht)),ye.svgFilters===!0&&(_(R,Wt),_(L,jt),_(L,ht)),ye.mathMl===!0&&(_(R,qt),_(L,ir),_(L,ht))),oe.tagCheck=null,oe.attributeCheck=null,F(i,"ADD_TAGS")&&(typeof i.ADD_TAGS=="function"?oe.tagCheck=i.ADD_TAGS:Ce(i.ADD_TAGS)&&(R===dt&&(R=q(R)),_(R,i.ADD_TAGS,I))),F(i,"ADD_ATTR")&&(typeof i.ADD_ATTR=="function"?oe.attributeCheck=i.ADD_ATTR:Ce(i.ADD_ATTR)&&(L===mt&&(L=q(L)),_(L,i.ADD_ATTR,I))),F(i,"ADD_FORBID_CONTENTS")&&Ce(i.ADD_FORBID_CONTENTS)&&(Ae===cn&&(Ae=q(Ae)),_(Ae,i.ADD_FORBID_CONTENTS,I)),Tt&&(R["#text"]=!0),ge&&_(R,["html","head","body"]),R.table&&(_(R,["tbody"]),delete Ne.tbody),i.TRUSTED_TYPES_POLICY){if(typeof i.TRUSTED_TYPES_POLICY.createHTML!="function")throw ue('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof i.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ue('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let u=M;M=i.TRUSTED_TYPES_POLICY;try{he=_e("")}catch(g){throw M=u,g}}else i.TRUSTED_TYPES_POLICY===null?(M=void 0,he=""):(M===void 0&&(M=mr()),M&&typeof he=="string"&&(he=_e("")));C&&C(i),Ee=i},kn=_({},[...Gt,...Wt,...as]),bn=_({},[...qt,...cs]),Dr=function(i,a,u){return a.namespaceURI===K?i==="svg":a.namespaceURI===Ke?i==="svg"&&(u==="annotation-xml"||At[u]):!!kn[i]},Cr=function(i,a,u){return a.namespaceURI===K?i==="math":a.namespaceURI===Je?i==="math"&&St[u]:!!bn[i]},vr=function(i,a,u){return a.namespaceURI===Je&&!St[u]||a.namespaceURI===Ke&&!At[u]?!1:!bn[i]&&(Lr[i]||!kn[i])},Nr=function(i){let a=B(i);(!a||!a.tagName)&&(a={namespaceURI:Se,tagName:"template"});let u=je(i.tagName),g=je(a.tagName);return yt[i.namespaceURI]?i.namespaceURI===Je?Dr(u,a,g):i.namespaceURI===Ke?Cr(u,a,g):i.namespaceURI===K?vr(u,a,g):!!(ze==="application/xhtml+xml"&&yt[i.namespaceURI]):!1},ae=function(i){Ge(e.removed,{element:i});try{B(i).removeChild(i)}catch{if(S(i),!B(i))throw ue("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},xn=function(i,a,u){try{w(i,a)}catch{try{i.removeAttribute(u)}catch{}}},et=function(i){tt(i);let a=y(i);if(a){let g=[];xe(a,k=>{Ge(g,k)}),xe(g,k=>{try{S(k)}catch{}})}let u=ee(i);if(u)for(let g=u.length-1;g>=0;--g){let k=u[g],x=k&&k.name;typeof x=="string"&&xn(i,k,x)}},de=function(i,a,u){if(!u)try{u=a.getAttributeNode(i)}catch{u=null}Ge(e.removed,{attribute:u||null,from:a});try{u?w(a,u):a.removeAttribute(i)}catch{try{a.removeAttribute(i)}catch{}}if(i==="is")if(we||Qe)try{ae(a)}catch{}else try{a.setAttribute(i,"")}catch{}},zr=function(i){let a=ee(i);if(a)for(let u=a.length-1;u>=0;--u){let g=a[u],k=g&&g.name;typeof k!="string"||L[I(k)]||xn(i,g,k)}},tt=function(i){let a=[i];for(;a.length>0;){let u=a.pop();te(u)===W.element&&zr(u);let g=y(u);if(g)for(let k=g.length-1;k>=0;--k)a.push(g[k])}},Tn=function(i,a){return fe?i==="patchsrc"?!0:i==="for"&&a!=="label"&&a!=="output":!1},Mr=function(i){if(!fe)return;let a=[i];for(;a.length>0;){let u=a.pop(),g=te(u);if(g===W.processingInstruction||g===W.comment&&$(lr,u.data)){try{S(u)}catch{}continue}if(g===W.element){let x=u,T=I(ne(u));try{x.hasAttribute&&x.hasAttribute("patchsrc")&&x.removeAttribute("patchsrc"),x.hasAttribute&&x.hasAttribute("for")&&Tn("for",T)&&x.removeAttribute("for")}catch{}}let k=y(u);if(k)for(let x=k.length-1;x>=0;--x)a.push(k[x])}},_n=function(i){let a=null,u=null;if(xt)i="<remove></remove>"+i;else{let x=Vn(i,/^[\r\n\t ]+/);u=x&&x[0]}ze==="application/xhtml+xml"&&Se===K&&(i='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+i+"</body></html>");let g=M?_e(i):i;if(Se===K)try{a=new h().parseFromString(g,ze)}catch{}if(!a||!a.documentElement){a=gt.createDocument(Se,"template",null);try{a.documentElement.innerHTML=wt?he:g}catch{}}let k=a.body||a.documentElement;return i&&u&&k.insertBefore(n.createTextNode(u),k.childNodes[0]||null),Se===K?br.call(a,ge?"html":"body")[0]:ge?a.documentElement:k},wn=function(i){let a=Te?Te(i):i.ownerDocument;return Kt.call(a||i,i,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},nt=function(i){return i=We(i,Tr," "),i=We(i,_r," "),i=We(i,wr," "),i},Rt=function(i){var a;i.normalize();let u=Te?Te(i):i.ownerDocument,g=Kt.call(u||i,i,p.SHOW_TEXT|p.SHOW_COMMENT|p.SHOW_CDATA_SECTION|p.SHOW_PROCESSING_INSTRUCTION,null),k=g.nextNode();for(;k;)k.data=nt(k.data),k=g.nextNode();let x=(a=i.querySelectorAll)===null||a===void 0?void 0:a.call(i,"template");x&&xe(x,T=>{Re(T.content)&&Rt(T.content)})},rt=function(i){let a=se?se(i):null;return typeof a!="string"||I(a)!=="form"?!1:typeof i.nodeName!="string"||typeof i.textContent!="string"||typeof i.removeChild!="function"||i.attributes!==ee(i)||typeof i.removeAttribute!="function"||typeof i.removeAttributeNode!="function"||typeof i.getAttributeNode!="function"||typeof i.setAttribute!="function"||typeof i.namespaceURI!="string"||typeof i.insertBefore!="function"||typeof i.hasChildNodes!="function"||i.nodeType!==Q(i)||i.childNodes!==y(i)},Re=function(i){if(!Q||typeof i!="object"||i===null)return!1;try{return Q(i)===W.documentFragment}catch{return!1}},Me=function(i){if(!Q||typeof i!="object"||i===null)return!1;try{return typeof Q(i)=="number"}catch{return!1}};function J(f,i,a){f.length!==0&&xe(f,u=>{u.call(e,i,a,Ee)})}let $r=function(i,a){return!!(fe&&i.hasChildNodes()&&!Me(i.firstElementChild)&&$(or,i.textContent)&&$(or,i.innerHTML)||fe&&i.namespaceURI===K&&_s[a]&&(Me(i.firstElementChild)||typeof i.textContent=="string"&&$(ws[a],i.textContent))||i.nodeType===W.processingInstruction||fe&&i.nodeType===W.comment&&$(lr,i.data))},it=function(i,a){if(i instanceof RegExp)return $(i,a);if(i instanceof Function){for(var u=arguments.length,g=new Array(u>2?u-2:0),k=2;k<u;k++)g[k-2]=arguments[k];return!!i(a,...g)}return!1},Ur=function(i,a,u){if(!Ne[a]&&En(a)&&it(V.tagNameCheck,a))return!1;if(Tt&&!Ae[a]){let g=B(i),k=y(i);if(k&&g){let x=k.length;for(let T=x-1;T>=0;--T){let O=i===u?D(k[T],!0):k[T];g.insertBefore(O,z(i))}}}return ae(i),!0},yn=function(i,a,u,g){return i.length===0?a:a===u||a===g?q(a):a},Le=function(i,a){return i===a||B(i)!==null?!1:(_t&&tt(i),!0)},An=function(i,a){if(J(E.beforeSanitizeElements,i,null),Le(i,a))return!0;if(rt(i))return ae(i),!0;let u=I(ne(i));if(R=yn(E.uponSanitizeElement,R,dt,Ye),J(E.uponSanitizeElement,i,{tagName:u,allowedTags:R}),Le(i,a))return!0;if($r(i,u))return ae(i),!0;if(Ne[u]||!(oe.tagCheck instanceof Function&&oe.tagCheck(u))&&!R[u]){let g=Ur(i,u,a);return g===!1&&(J(E.afterSanitizeElements,i,null),Le(i,a))?!0:g}if(te(i)===W.element&&!Nr(i)||(u==="noscript"||u==="noembed"||u==="noframes")&&$(xs,i.innerHTML))return ae(i),!0;if(le&&i.nodeType===W.text){let g=nt(i.textContent);i.textContent!==g&&(Ge(e.removed,{element:i.cloneNode()}),i.textContent=g)}return J(E.afterSanitizeElements,i,null),Le(i,a)},Sn=function(i,a,u){if(tn[a]||Tn(a,i)||on&&(a==="id"||a==="name")&&(u in n||u in Pr))return!1;let g=L[a]||oe.attributeCheck instanceof Function&&oe.attributeCheck(a,i);return kt&&$(yr,a)||nn&&$(Ar,a)?!0:g?hn[a]||$(en,We(u,Jt,""))||(a==="src"||a==="xlink:href"||a==="href")&&i!=="script"&&Kn(u,"data:")===0&&un[i]||rn&&!$(Sr,We(u,Jt,""))?!0:!u:En(i)&&it(V.tagNameCheck,i)&&it(V.attributeNameCheck,a,i)||a==="is"&&V.allowCustomizedBuiltInElements&&it(V.tagNameCheck,u)},Fr=_({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),En=function(i){return!Fr[je(i)]&&$(Er,i)},Br=function(i,a,u,g){if(M&&typeof d=="object"&&typeof d.getAttributeType=="function"&&!u)switch(d.getAttributeType(i,a)){case"TrustedHTML":return _e(g);case"TrustedScriptURL":return dr(g)}return g},Hr=function(i,a,u,g){try{return u?i.setAttributeNS(u,a,g):i.setAttribute(a,g),rt(i)?(ae(i),!1):!0}catch{return de(a,i),!1}},Rn=function(i,a){if(J(E.beforeSanitizeAttributes,i,null),Le(i,a))return;let u=i.attributes;if(!u||rt(i))return;L=yn(E.uponSanitizeAttribute,L,mt,Xe);let g={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:L,forceKeepAttr:void 0},k=u.length,x=I(i.nodeName);for(;k--;){let T=u[k],O=T.name,j=T.namespaceURI,H=T.value,Oe=I(O),Ot=H,U=O==="value"?Ot:ts(Ot),Ln=!1;if(g.attrName=Oe,g.attrValue=U,g.keepAttr=!0,g.forceKeepAttr=void 0,J(E.uponSanitizeAttribute,i,g),U=g.attrValue,ln&&(Oe==="id"||Oe==="name")&&Kn(U,an)!==0&&(de(O,i,T),U=an+U,Ln=!0),fe&&$(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,U)){de(O,i,T);continue}if(Oe==="attributename"&&Vn(U,"href")){de(O,i,T);continue}if(!g.forceKeepAttr){if(!g.keepAttr){de(O,i,T);continue}if(!sn&&$(Ts,U)){de(O,i,T);continue}if(le&&(U=nt(U)),!Sn(x,Oe,U)){de(O,i,T);continue}U=Br(x,Oe,j,U),U!==Ot&&Hr(i,O,j,U)&&Ln&&Qn(e.removed)}}J(E.afterSanitizeAttributes,i,null),Le(i,a)},st=function(i){let a=null,u=wn(i);for(J(E.beforeSanitizeShadowDOM,i,null);a=u.nextNode();)if(J(E.uponSanitizeShadowNode,a,null),An(a,i),Rn(a,i),Re(a.content)&&st(a.content),te(a)===W.element){let g=ie(a);Re(g)&&(Lt(g),st(g))}J(E.afterSanitizeShadowDOM,i,null)},Lt=function(i){let a=[{node:i,shadow:null}];for(;a.length>0;){let u=a.pop();if(u.shadow){st(u.shadow);continue}let g=u.node,k=te(g)===W.element,x=y(g);if(x)for(let T=x.length-1;T>=0;--T)a.push({node:x[T],shadow:null});if(k){let T=se?se(g):null;if(typeof T=="string"&&I(T)==="template"){let O=g.content;Re(O)&&a.push({node:O,shadow:null})}}if(k){let T=ie(g);Re(T)&&a.push({node:null,shadow:T},{node:T,shadow:null})}}};return e.sanitize=function(f){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=null,u=null,g=null,k=null;if(wt=!f,wt&&(f="<!-->"),typeof f!="string"&&!Me(f)&&(f=os(f),typeof f!="string"))throw ue("dirty is not a string, aborting");if(!e.isSupported)return f;bt?(R=Ye,L=Xe):Et(i),(E.uponSanitizeElement.length>0||E.uponSanitizeAttribute.length>0)&&(R=q(R)),E.uponSanitizeAttribute.length>0&&(L=q(L)),e.removed=[];let x=_t&&typeof f!="string"&&Me(f);if(x){Mr(f);let j=ne(f);if(typeof j=="string"){let H=I(j);if(!R[H]||Ne[H])throw et(f),ue("root node is forbidden and cannot be sanitized in-place")}if(rt(f))throw et(f),ue("root node is clobbered and cannot be sanitized in-place");try{Lt(f)}catch(H){throw et(f),H}}else if(Me(f))a=_n("<!---->"),u=a.ownerDocument.importNode(f,!0),u.nodeType===W.element&&u.nodeName==="BODY"||u.nodeName==="HTML"?a=u:a.appendChild(u),Lt(a);else{if(!we&&!le&&!ge&&f.indexOf("<")===-1)return M&&Ve?_e(f):f;if(a=_n(f),!a)return we?null:Ve?he:""}a&&xt&&ae(a.firstChild);let T=x?f:a;try{let j=wn(T);for(;g=j.nextNode();)An(g,T),Rn(g,T),Re(g.content)&&st(g.content)}catch(j){throw x&&(et(f),xe(e.removed,H=>{H.element&&tt(H.element)})),j}if(x){let j=!1;if(xe(e.removed,H=>{H.element&&(H.element===f&&(j=!0),tt(H.element))}),j)throw ue("a node selected for removal could not be safely returned; refusing to sanitize in place");return le&&Rt(f),f}if(we){if(le&&Rt(a),Qe)for(k=kr.call(a.ownerDocument);a.firstChild;)k.appendChild(a.firstChild);else k=a;return(L.shadowroot||L.shadowrootmode)&&(k=xr.call(s,k,!0)),k}let O=ge?a.outerHTML:a.innerHTML;return ge&&R["!doctype"]&&a.ownerDocument&&a.ownerDocument.doctype&&a.ownerDocument.doctype.name&&$(ks,a.ownerDocument.doctype.name)&&(O="<!DOCTYPE "+a.ownerDocument.doctype.name+`>
+`+O),le&&(O=nt(O)),M&&Ve?_e(O):O},e.setConfig=function(){let f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Et(f),bt=!0,Ye=R,Xe=L},e.clearConfig=function(){Ee=null,bt=!1,Ye=null,Xe=null,M=ft,he=""},e.isValidAttribute=function(f,i,a){Ee||Et({});let u=I(f),g=I(i);return Sn(u,g,a)},e.addHook=function(f,i){typeof i=="function"&&F(E,f)&&Ge(E[f],i)},e.removeHook=function(f,i){if(F(E,f)){if(i!==void 0){let a=Ji(E[f],i);return a===-1?void 0:es(E[f],a,1)[0]}return Qn(E[f])}},e.removeHooks=function(f){F(E,f)&&(E[f]=[])},e.removeAllHooks=function(){E=ar()},e}var fr=hr();var gr=t=>String(t).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e]),Ss=new Bt({gfm:!0,breaks:!1,renderer:{image({text:t}){return gr(t||"\u56FE\u7247")},html({text:t}){return gr(t)}}});window.__wbsMarkdownPreview={render(t){let e=Ss.parse(String(t).slice(0,2e4));return fr.sanitize(e,{ALLOWED_TAGS:["p","br","hr","h1","h2","h3","h4","h5","h6","strong","em","del","s","blockquote","ul","ol","li","pre","code","table","thead","tbody","tr","th","td","a","input"],ALLOWED_ATTR:["start","align","type","checked","disabled"],ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1,RETURN_DOM_FRAGMENT:!0,...window.__wbsTrustedHtmlPolicy?{TRUSTED_TYPES_POLICY:window.__wbsTrustedHtmlPolicy}:{}})}};})();
+/*! Bundled license information:
+
+dompurify/dist/purify.es.mjs:
+ (*! @license DOMPurify 3.4.16 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.16/LICENSE *)
+ (*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *)
+*/
+
+/* Third-party licenses:
+marked
+# License information
+
+## Contribution License Agreement
+
+If you contribute code to this project, you are implicitly allowing your code
+to be distributed under the MIT license. You are also implicitly verifying that
+all code is your original work. `</legalese>`
+
+## Marked
+
+Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/)
+Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+## Markdown
+
+Copyright © 2004, John Gruber
+http://daringfireball.net/
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
+
+
+dompurify
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+*/
diff --git a/scripts/relaunch-with-cdp-linux.sh b/scripts/relaunch-with-cdp-linux.sh
index 9aa6915..25e22c2 100755
--- a/scripts/relaunch-with-cdp-linux.sh
+++ b/scripts/relaunch-with-cdp-linux.sh
@@ -408,7 +408,12 @@ launch_plugin() {
echo " 环境: HOME=${launch_home}(启动器需按真实家目录推导,不能传隔离 HOME)"
fi
# setsid:脱离当前会话,避免终端关闭时连带杀掉 WorkBuddy
- setsid nohup env HOME="$launch_home" "$LAUNCH_TARGET" --remote-debugging-port="$PORT" "${NATIVE_ARGS[@]}" >/dev/null 2>&1 < /dev/null &
+ LAUNCH_ARGS=(--remote-debugging-port="$PORT")
+ case "$PROFILE" in
+ codebuddy-cn) LAUNCH_ARGS+=(--inspect=127.0.0.1:9244) ;;
+ codebuddy-intl) LAUNCH_ARGS+=(--inspect=127.0.0.1:9245) ;;
+ esac
+ setsid nohup env HOME="$launch_home" "$LAUNCH_TARGET" "${LAUNCH_ARGS[@]}" >/dev/null 2>&1 < /dev/null &
disown 2>/dev/null || true
echo "==> 等待 CDP 端口开放(并确认是本 profile 的实例)"
diff --git a/scripts/relaunch-with-cdp.sh b/scripts/relaunch-with-cdp.sh
index 4cc22d6..64c02d5 100644
--- a/scripts/relaunch-with-cdp.sh
+++ b/scripts/relaunch-with-cdp.sh
@@ -321,7 +321,12 @@ launch_plugin() {
echo " 错误:未找到 $APP_BIN"
exit 1
fi
- nohup "$APP_BIN" --remote-debugging-port="$PORT" "${NATIVE_ARGS[@]}" >/dev/null 2>&1 &
+ LAUNCH_ARGS=(--remote-debugging-port="$PORT")
+ case "$PROFILE" in
+ codebuddy-cn) LAUNCH_ARGS+=(--inspect=127.0.0.1:9244) ;;
+ codebuddy-intl) LAUNCH_ARGS+=(--inspect=127.0.0.1:9245) ;;
+ esac
+ nohup "$APP_BIN" "${LAUNCH_ARGS[@]}" >/dev/null 2>&1 &
disown 2>/dev/null || true
# ---------- 4. 验证 ----------
diff --git a/scripts/session-sync.js b/scripts/session-sync.js
index 1bee5d5..fef9c38 100644
--- a/scripts/session-sync.js
+++ b/scripts/session-sync.js
@@ -6,10 +6,13 @@ const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { StringDecoder } = require('node:string_decoder');
+const { Readable } = require('node:stream');
+const { pipeline } = require('node:stream/promises');
const identityKeys = new Set(['sessionId', 'conversationId', 'ownerConversationId', 'session_id', 'conversation_id']);
const SKIP_LOCAL_DIR = /^workspace\/sessions\/[^/]+\/(?:modify_backup|\.modify_backup_meta)$/;
const SYNC_BACKUP_DIR = /^sync-[A-Za-z0-9_-]+$/;
const DEFAULT_SYNC_BACKUP_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
+const RUNTIME_IDENTITY_REPAIR = Symbol('runtime-identity-repair');
const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
// WorkBuddy appends session-meta lifecycle records when a conversation is
@@ -782,7 +785,56 @@ function changedTargetFiles(changes, target) {
return entries;
}
+// The CLI restores its runtime identity from transcript records, not the
+// filename. Leaving A's sessionId in B's copy routes steer and permission
+// events to A. Only rewrite the record envelope: tool arguments, results,
+// message IDs and user text can legitimately contain the same string.
+function rebindTranscriptLine(line, aliases, id) {
+ if (!line.trim()) return line;
+ let record;
+ try { record = JSON.parse(line); } catch (_) { throw Error('会话消息文件未写完或已损坏,未同步'); }
+ if (!record || typeof record !== 'object' || Array.isArray(record) || typeof record.type !== 'string') {
+ throw Error('会话消息格式不受支持,未同步');
+ }
+ if (record.sessionId === id || !aliases.includes(record.sessionId)) return line;
+ record.sessionId = id;
+ return JSON.stringify(record) + (line.endsWith('\r') ? '\r' : '');
+}
+
+async function* reboundTranscript(file, aliases, id) {
+ let pending = '';
+ // Keep the async copy path streaming even for very large conversations.
+ for await (const chunk of fs.createReadStream(file.sourcePath, { encoding: 'utf8', highWaterMark: 1024 * 1024 })) {
+ const text = pending + chunk;
+ let start = 0;
+ const output = [];
+ for (;;) {
+ const newline = text.indexOf('\n', start);
+ if (newline < 0) break;
+ output.push(rebindTranscriptLine(text.slice(start, newline), aliases, id) + '\n');
+ start = newline + 1;
+ }
+ pending = text.slice(start);
+ if (output.length) yield output.join('');
+ }
+ if (pending) yield rebindTranscriptLine(pending, aliases, id);
+}
+
+async function reboundTranscriptInfo(file, aliases, id) {
+ const hash = crypto.createHash('sha256');
+ let size = 0;
+ for await (const chunk of reboundTranscript(file, aliases, id)) {
+ hash.update(chunk);
+ size += Buffer.byteLength(chunk);
+ }
+ return { hash: hash.digest('hex'), size };
+}
+
function targetBytes(key, file, source, target) {
+ if (/^projects\/[^/]+\/__session__\.jsonl$/.test(key)) {
+ return Buffer.from(file.bytes.toString('utf8').split('\n')
+ .map(line => rebindTranscriptLine(line, source.aliases, target.id)).join('\n'));
+ }
if (key !== 'artifact-index/__session__.json') return file.bytes;
const index = JSON.parse(file.bytes.toString('utf8'));
const artifacts = Array.isArray(index) ? index : index && index.artifacts;
@@ -922,21 +974,26 @@ async function existingHashAsync(file) {
async function applySnapshotAsync(source, target, options) {
const { backupRoot, commit = async () => {}, guard = async () => {}, missingOnly = false,
onProgress = () => {} } = options;
- if (source.root !== target.root || source.id === target.id) throw Error('无效的会话同步目标');
+ const repairIdentityOnly = options[RUNTIME_IDENTITY_REPAIR] === true && source === target;
+ if (source.root !== target.root || (source.id === target.id && !repairIdentityOnly)) throw Error('无效的会话同步目标');
const changes = [];
for (const [key, file] of source.files) {
+ if (repairIdentityOnly && key !== source.transcriptKey) continue;
if (missingOnly && target.files.has(key)) continue;
const bytes = await targetBytesAsync(key, file, source, target);
- const hash = bytes ? digest(bytes) : file.hash;
+ const rebind = !source.rewriteBytes && /^projects\/[^/]+\/__session__\.jsonl$/.test(key);
+ const rewritten = rebind ? await reboundTranscriptInfo(file, source.aliases, target.id) : null;
+ const hash = rewritten ? rewritten.hash : bytes ? digest(bytes) : file.hash;
if (target.files.get(key)?.hash === hash) continue;
changes.push({
key, relative: target.resolveRelative ? target.resolveRelative(key) : targetRelative(key, target.id), bytes, sourceFile: file,
- hash, size: bytes ? bytes.length : file.size, mode: file.mode, mtimeMs: file.mtimeMs,
+ rebind, hash, size: rewritten ? rewritten.size : bytes ? bytes.length : file.size, mode: file.mode, mtimeMs: file.mtimeMs,
});
}
if (!missingOnly) for (const [key, file] of target.files) {
if (!source.files.has(key)) changes.push({ key, relative: file.relative, bytes: null, sourceFile: null, hash: null, size: 0 });
}
+ if (repairIdentityOnly && !changes.length) return { copied: 0, copiedBytes: 0, totalBytes: target.totalBytes };
const backupEntries = changedTargetFiles(changes, target);
await guard();
if (!await unchangedAsync(source) || !await unchangedAsync(target)) throw Error('会话文件正在变化,请稍后重试');
@@ -965,7 +1022,7 @@ async function applySnapshotAsync(source, target, options) {
}
let totalBytes = 0;
const verifyPublished = async () => {
- if (!await unchangedAsync(source)) throw Error('源会话正在变化,已停止同步');
+ if (!repairIdentityOnly && !await unchangedAsync(source)) throw Error('源会话正在变化,已停止同步');
const now = target.reread ? await target.reread() : await readSnapshotAsync(target.root, target.id, target.aliases, target.cache || null);
if (now.files.size !== expected.size || [...expected].some(([key, hash]) => now.files.get(key)?.hash !== hash)) {
throw Error('目标会话正在变化,已停止同步');
@@ -987,7 +1044,11 @@ async function applySnapshotAsync(source, target, options) {
await fs.promises.mkdir(path.dirname(file), { recursive: true });
const staged = path.join(path.dirname(file), '.wbs-sync-' + crypto.randomUUID());
try {
- if (change.bytes) await fs.promises.writeFile(staged, change.bytes, { mode: change.mode || 0o600, flag: 'wx' });
+ if (change.rebind) await pipeline(
+ Readable.from(reboundTranscript(change.sourceFile, source.aliases, target.id)),
+ fs.createWriteStream(staged, { mode: change.mode || 0o600, flags: 'wx' })
+ );
+ else if (change.bytes) await fs.promises.writeFile(staged, change.bytes, { mode: change.mode || 0o600, flag: 'wx' });
else await fs.promises.copyFile(change.sourceFile.sourcePath, staged, fs.constants.COPYFILE_EXCL);
if ((await hashFileAsync(staged)).hash !== change.hash) throw Error('会话文件校验失败');
await fs.promises.chmod(staged, change.mode || 0o600);
@@ -1032,7 +1093,13 @@ async function applySnapshotAsync(source, target, options) {
}
}
+// Repair the destination's own records, never overwrite a newer continuation
+// with its source. Reuse the guarded, backed-up, atomic publication/rollback.
+async function repairRuntimeIdentity(snapshot, options) {
+ return applySnapshotAsync(snapshot, snapshot, { ...options, [RUNTIME_IDENTITY_REPAIR]: true });
+}
+
module.exports = {
readSessionSizes, readSnapshot, readSnapshotAsync, readSessionFingerprintAsync, readSessionQuickFingerprintAsync, compareSnapshots, selectTargetSnapshot,
- applySnapshot, applySnapshotAsync, pruneSyncBackups, inspectSyncBackups,
+ applySnapshot, applySnapshotAsync, repairRuntimeIdentity, pruneSyncBackups, inspectSyncBackups,
};
diff --git a/scripts/theme-patches.js b/scripts/theme-patches.js
index ea2c695..08905ca 100644
--- a/scripts/theme-patches.js
+++ b/scripts/theme-patches.js
@@ -204,8 +204,8 @@ module.exports = [
},
{
id: 'patch-44',
- desc: 'tooltip/悬浮提示组件文字硬编码深色(与深色弹窗同色看不见):强制浅色 + hover 高亮态文字浅色(排除官方新组件体系 cr-theme——其自带深色文字适配)',
- css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="tooltip"]:not([class*="chat"]):not([class*="message"]) *,html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]) *,html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) *{color:var(--wb-color-text-primary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) [class*="item"]:hover,html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) [class*="item"]:hover *{color:var(--wb-color-text-primary) !important;background:var(--wb-bg-hover) !important;}',
+ desc: 'tooltip/悬浮提示组件文字硬编码深色(与深色弹窗同色看不见):强制浅色 + hover 高亮态文字浅色(排除官方新组件体系 cr-theme——其自带深色文字适配;WorkDaddy 状态弹层保留组件自己的文字配色)',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="tooltip"]:not([class*="chat"]):not([class*="message"]) *:not(:where(.wbs-status-popover *)),html[data-theme="dark"] body[data-vscode-theme-name] [class*="popover"]:not([class*="cr-theme"]) *:not(:where(.wbs-status-popover *)),html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) *:not(:where(.wbs-status-popover *)){color:var(--wb-color-text-primary) !important;}html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) [class*="item"]:hover,html[data-theme="dark"] body[data-vscode-theme-name] [class*="dropdown"]:not([class*="cr-theme"]) [class*="item"]:hover *{color:var(--wb-color-text-primary) !important;background:var(--wb-bg-hover) !important;}',
},
{
id: 'patch-45',
diff --git a/scripts/token-stats.js b/scripts/token-stats.js
index 477b3e7..96568ba 100644
--- a/scripts/token-stats.js
+++ b/scripts/token-stats.js
@@ -8,7 +8,7 @@ const TOKEN_FIELDS = {
input: ['input_tokens', 'prompt_tokens', 'inputTokens', 'promptTokens'],
output: ['output_tokens', 'completion_tokens', 'outputTokens', 'completionTokens'],
cacheRead: ['cache_read_input_tokens', 'cache_read_tokens', 'cacheReadTokens', 'cached_tokens', 'cacheTokens'],
- cacheWrite: ['cache_creation_input_tokens', 'cache_write_tokens', 'cacheWriteTokens', 'cachedWriteTokens'],
+ cacheWrite: ['cache_write_input_tokens', 'cacheWriteInputTokens', 'cache_creation_input_tokens', 'cache_write_tokens', 'prompt_cache_write_tokens', 'cacheWriteTokens', 'cachedWriteTokens'],
};
function numberField(value, fields) {
@@ -19,6 +19,55 @@ function numberField(value, fields) {
return 0;
}
+function positiveNumberField(value, fields) {
+ for (const field of fields) {
+ const number = Number(value && value[field]);
+ if (Number.isFinite(number) && number > 0) return number;
+ }
+ return 0;
+}
+
+function cacheReadField(value) {
+ const flat = positiveNumberField(value, TOKEN_FIELDS.cacheRead);
+ if (flat) return flat;
+ const promptDetails = value && value.prompt_tokens_details;
+ const promptCached = promptDetails && typeof promptDetails === 'object'
+ ? positiveNumberField(promptDetails, ['cached_tokens']) : 0;
+ if (promptCached) return promptCached;
+ const inputDetails = value && value.inputTokensDetails;
+ if (Array.isArray(inputDetails)) {
+ for (const detail of inputDetails) {
+ const cached = positiveNumberField(detail, ['cached_tokens']);
+ if (cached) return cached;
+ }
+ }
+ return 0;
+}
+
+function cacheWriteField(value) {
+ return positiveNumberField(value, TOKEN_FIELDS.cacheWrite);
+}
+
+function cacheWriteForRecord(record, selectedUsage) {
+ const selected = cacheWriteField(selectedUsage);
+ if (selected) return selected;
+ const candidates = [
+ record && record.message && record.message.usage,
+ record && record.providerData && record.providerData.usage,
+ record && record.usage,
+ record && record.providerData && record.providerData.rawUsage,
+ ];
+ for (const candidate of candidates) {
+ const value = cacheWriteField(candidate);
+ if (value) return value;
+ }
+ return 0;
+}
+
+function tokenTotal(input, output, cacheWrite) {
+ return (Number(input) || 0) + (Number(output) || 0) + (Number(cacheWrite) || 0);
+}
+
function findUsage(value, depth = 0) {
if (!value || typeof value !== 'object' || depth > 4) return null;
const hasUsage = Object.values(TOKEN_FIELDS).some((fields) => fields.some((field) => value[field] !== undefined));
@@ -87,7 +136,7 @@ function timestampValue(value, fallback) {
return fallback;
}
-const CACHE_VERSION = 8;
+const CACHE_VERSION = 9;
const MAX_CACHE_DAYS = 90;
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -151,8 +200,8 @@ function parseRecords(root, options = {}) {
if (!Number.isFinite(timestamp) || timestamp < lowerBound || timestamp > upperBound) continue;
const input = numberField(usage, TOKEN_FIELDS.input);
const output = numberField(usage, TOKEN_FIELDS.output);
- const cacheRead = numberField(usage, TOKEN_FIELDS.cacheRead);
- const cacheWrite = numberField(usage, TOKEN_FIELDS.cacheWrite);
+ const cacheRead = cacheReadField(usage);
+ const cacheWrite = cacheWriteForRecord(record, usage);
if (!(input || output || cacheRead || cacheWrite)) continue;
const model = findText(record, ['model', 'modelName', 'model_id', 'modelId']) || findText(usage, ['model', 'modelName', 'model_id', 'modelId']);
const account = findText(record, ['accountUid', 'accountId', 'uid', 'userId']) || findText(usage, ['accountUid', 'accountId', 'uid', 'userId']);
@@ -259,7 +308,7 @@ function aggregateRecords(records, options = {}) {
const bounds = dateBounds(now, options);
const accountFilter = String(options.account || '').trim();
const modelFilter = String(options.model || '').trim();
- const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };
+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0 };
const byDay = new Map();
const byModel = new Map();
const byAccount = new Map();
@@ -267,21 +316,21 @@ function aggregateRecords(records, options = {}) {
if (!record || record.timestamp < bounds.from || record.timestamp > bounds.until) continue;
if (accountFilter && record.account !== accountFilter) continue;
if (modelFilter && record.model !== modelFilter) continue;
- const values = { input: Number(record.input) || 0, output: Number(record.output) || 0, cacheRead: Number(record.cacheRead) || 0, cacheWrite: Number(record.cacheWrite) || 0, calls: Number(record.calls) || 1 };
+ const values = { input: Number(record.input) || 0, output: Number(record.output) || 0, cacheRead: Number(record.cacheRead) || 0, cacheWrite: Number(record.cacheWrite) || 0, total: tokenTotal(record.input, record.output, record.cacheWrite), calls: Number(record.calls) || 1 };
for (const key of Object.keys(totals)) totals[key] += values[key];
const day = localDayString(record.timestamp);
if (day) {
- const row = byDay.get(day) || { day, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };
+ const row = byDay.get(day) || { day, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0 };
for (const key of Object.keys(values)) row[key] += values[key];
byDay.set(day, row);
}
if (record.model) {
- const row = byModel.get(record.model) || { model: record.model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };
+ const row = byModel.get(record.model) || { model: record.model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0 };
for (const key of Object.keys(values)) row[key] += values[key];
byModel.set(record.model, row);
}
if (record.account) {
- const row = byAccount.get(record.account) || { account: record.account, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };
+ const row = byAccount.get(record.account) || { account: record.account, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0 };
for (const key of Object.keys(values)) row[key] += values[key];
byAccount.set(record.account, row);
}
@@ -290,7 +339,7 @@ function aggregateRecords(records, options = {}) {
for (const account of accountOptions) {
const uid = String(account && (account.uid || account.account) || '').trim();
if (!uid) continue;
- if (!byAccount.has(uid)) byAccount.set(uid, { account: uid, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, nickname: account.nickname || '' });
+ if (!byAccount.has(uid)) byAccount.set(uid, { account: uid, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0, nickname: account.nickname || '' });
else if (account.nickname) byAccount.get(uid).nickname = account.nickname;
}
return {
@@ -299,8 +348,8 @@ function aggregateRecords(records, options = {}) {
until: bounds.until,
totals,
daily: Array.from(byDay.values()).sort((a, b) => a.day.localeCompare(b.day)),
- models: Array.from(byModel.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),
- accounts: Array.from(byAccount.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),
+ models: Array.from(byModel.values()).sort((a, b) => b.total - a.total),
+ accounts: Array.from(byAccount.values()).sort((a, b) => b.total - a.total),
};
}
@@ -330,7 +379,7 @@ function aggregateCachedBuckets(buckets, options = {}) {
const modelFilter = String(options.model || '').trim();
const firstDay = localDayString(bounds.from);
const lastDay = localDayString(bounds.until);
- const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };
+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0 };
const byDay = new Map();
const byModel = new Map();
const byAccount = new Map();
@@ -345,21 +394,22 @@ function aggregateCachedBuckets(buckets, options = {}) {
output: Number(bucket.output) || 0,
cacheRead: Number(bucket.cacheRead) || 0,
cacheWrite: Number(bucket.cacheWrite) || 0,
+ total: tokenTotal(bucket.input, bucket.output, bucket.cacheWrite),
calls: Number(bucket.calls) || 0,
};
for (const key of Object.keys(totals)) totals[key] += values[key];
const day = String(bucket.day);
dailyBreakdown.push({ day, account: String(bucket.account || ''), model: String(bucket.model || ''), ...values });
- const dayRow = byDay.get(day) || { day, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };
+ const dayRow = byDay.get(day) || { day, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0 };
for (const key of Object.keys(values)) dayRow[key] += values[key];
byDay.set(day, dayRow);
if (bucket.model) {
- const modelRow = byModel.get(bucket.model) || { model: bucket.model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };
+ const modelRow = byModel.get(bucket.model) || { model: bucket.model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0 };
for (const key of Object.keys(values)) modelRow[key] += values[key];
byModel.set(bucket.model, modelRow);
}
if (bucket.account) {
- const accountRow = byAccount.get(bucket.account) || { account: bucket.account, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0 };
+ const accountRow = byAccount.get(bucket.account) || { account: bucket.account, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0 };
for (const key of Object.keys(values)) accountRow[key] += values[key];
byAccount.set(bucket.account, accountRow);
}
@@ -368,15 +418,15 @@ function aggregateCachedBuckets(buckets, options = {}) {
for (const account of accountOptions) {
const uid = String(account && (account.uid || account.account) || '').trim();
if (!uid) continue;
- if (!byAccount.has(uid)) byAccount.set(uid, { account: uid, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, nickname: account.nickname || '' });
+ if (!byAccount.has(uid)) byAccount.set(uid, { account: uid, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, calls: 0, nickname: account.nickname || '' });
else if (account.nickname) byAccount.get(uid).nickname = account.nickname;
}
return {
source: options.source || 'local-workbuddy-jsonl', since: bounds.from, until: bounds.until, totals,
daily: Array.from(byDay.values()).sort((a, b) => a.day.localeCompare(b.day)),
dailyBreakdown: dailyBreakdown.sort((a, b) => a.day.localeCompare(b.day) || a.account.localeCompare(b.account) || a.model.localeCompare(b.model)),
- models: Array.from(byModel.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),
- accounts: Array.from(byAccount.values()).sort((a, b) => (b.input + b.output) - (a.input + a.output)),
+ models: Array.from(byModel.values()).sort((a, b) => b.total - a.total),
+ accounts: Array.from(byAccount.values()).sort((a, b) => b.total - a.total),
};
}
diff --git a/test/activity-refresh.test.js b/test/activity-refresh.test.js
index 1b6db7a..17829bf 100644
--- a/test/activity-refresh.test.js
+++ b/test/activity-refresh.test.js
@@ -5,22 +5,31 @@ const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
const tick = () => new Promise(resolve => setImmediate(resolve));
-function harness() {
- const requests = [], timers = [];
+function harness(options = {}) {
+ const requests = [], todayRequests = [], timers = [], intervals = [];
const start = source.includes(' var activityBatchPromise') ? source.indexOf(' var activityBatchPromise') : source.indexOf(' function fetchActivityForAccounts()');
const end = source.indexOf(' // 积分查询按', start);
const badgeStart = source.indexOf(' function activityStreakHtml(');
+ const harnessToday = options.manualToday === true;
const ctx = vm.createContext({
alive: true, WBS_PROFILE_IS_AI: false, CAPS: { accounts: true },
state: { open: true, activityRunId: 0, accounts: [{ uid: 'a' }, { uid: 'b' }, { uid: 'c' }] },
- api() { return new Promise((resolve, reject) => requests.push({ resolve, reject })); },
+ api(route, options) {
+ if (route === '/api/growth/today-active') {
+ if (!harnessToday) return Promise.resolve({ ok: true, date: '1970-01-01', is_active: false });
+ return new Promise((resolve, reject) => todayRequests.push({ resolve, reject, uid: JSON.parse(options.body).uid }));
+ }
+ return new Promise((resolve, reject) => requests.push({ resolve, reject }));
+ },
accountsPane: { querySelectorAll: () => [] },
setBuildTimeout(fn, delay) { const timer = { fn, delay }; timers.push(timer); return timer; },
+ setBuildInterval(fn, delay) { intervals.push({ fn, delay }); },
+ updateDailyProgressCells() {},
clearTimeout(timer) { if (timer) timer.cancelled = true; },
Date: class extends Date { static now() { return 100000; } },
});
vm.runInContext(source.slice(badgeStart, source.indexOf(' function el(tag', badgeStart)) + source.slice(start, end), ctx);
- return { ctx, requests, timers };
+ return { ctx, requests, todayRequests, timers, intervals };
}
test('an activity failure retains the last valid count and schedules one delayed retry', async () => {
@@ -65,3 +74,50 @@ test('reinjection stops the old activity queue after its in-flight requests fini
assert.equal(h.ctx.state.accounts[0].activityStreak, undefined);
assert.equal(h.timers.length, 0);
});
+
+
+test('activity refresh reads the official today record independently of the streak and clears failed reads', async () => {
+ const h = harness({ manualToday: true });
+ h.ctx.state.accounts = [{ uid: 'a', checkin: { ok: true } }];
+ h.ctx.fetchActivityForAccounts();
+ h.requests[0].resolve({ activityStreak: { days: 5, status: 'ready' } }); await tick();
+ assert.equal(h.todayRequests.length, 1);
+ h.todayRequests[0].resolve({ ok: true, date: '1970-01-01', is_active: false }); await tick();
+ assert.equal(h.ctx.state.accounts[0].growthTodayActive.is_active, false);
+ h.ctx.fetchActivityForAccounts();
+ h.requests[1].reject(new Error('streak unavailable')); await tick();
+ h.todayRequests[1].resolve({ ok: true, date: '1970-01-01', is_active: true }); await tick();
+ assert.equal(h.ctx.state.accounts[0].growthTodayActive.is_active, true);
+ h.ctx.fetchActivityForAccounts();
+ h.requests[2].resolve({ activityStreak: { days: 5, status: 'ready' } }); await tick();
+ h.todayRequests[2].reject(new Error('today unavailable')); await tick();
+ assert.equal(h.ctx.state.accounts[0].growthTodayActive, null);
+});
+
+test('closing during the today query discards the late result and stops the queue', async () => {
+ const h = harness({ manualToday: true });
+ h.ctx.fetchActivityForAccounts();
+ for (const request of h.requests) request.resolve({ activityStreak: { days: 5, status: 'ready' } });
+ await tick();
+ assert.equal(h.todayRequests.length, 2);
+ h.ctx.state.open = false; h.ctx.state.activityRunId++;
+ for (const request of h.todayRequests) request.resolve({ ok: true, date: '1970-01-01', is_active: true });
+ await tick();
+ assert.equal(h.ctx.state.accounts[0].growthTodayActive, undefined);
+ assert.equal(h.requests.length, 2);
+});
+
+test('an open panel rechecks backend activity periodically without overlapping a pending batch', async () => {
+ const h = harness();
+ const poll = h.intervals.find(timer => timer.delay === 60000);
+ assert.ok(poll);
+ poll.fn();
+ assert.equal(h.requests.length, 2);
+ poll.fn();
+ assert.equal(h.requests.length, 2);
+ h.ctx.state.open = false;
+ for (const request of h.requests) request.resolve({ activityStreak: { days: 5, status: 'ready' } });
+ await tick();
+ poll.fn();
+ assert.equal(h.requests.length, 2);
+});
diff --git a/test/cdp-targets.test.js b/test/cdp-targets.test.js
index 32b7d9e..b5283c3 100644
--- a/test/cdp-targets.test.js
+++ b/test/cdp-targets.test.js
@@ -3,7 +3,7 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { PROFILES } = require('../scripts/profiles.js');
-const { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget } = require('../scripts/cdp-targets.js');
+const { normalizeTargetUrl, classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile, selectPageTarget, selectIdeTargets } = require('../scripts/cdp-targets.js');
const AI_URL = 'file:///Applications/WorkBuddy%20AI.app/Contents/Resources/app.asar/renderer/index.html';
const CN_URL = 'file:///Applications/WorkBuddy.app/Contents/Resources/app.asar/renderer/index.html';
@@ -144,16 +144,27 @@ test('looksLikeWbFamilyTarget 把四客户端页面都视为同族(不清理
assert.equal(looksLikeWbFamilyTarget({ type: 'page', url: 'file:///Applications/Antigravity.app/Contents/index.html', title: 'Antigravity' }), false);
});
-test('CodeBuddy selects only its Agents window regardless of target order', () => {
+test('CodeBuddy selects only its Agents window; IDE workbench goes to the IDE overlay manager', () => {
for (const id of ['codebuddy-cn', 'codebuddy-intl']) {
const app = id === 'codebuddy-cn' ? 'CodeBuddy%20CN' : 'CodeBuddy';
const base = 'vscode-file://vscode-app/Applications/' + app + '.app/Contents/Resources/app/out/vs/code/electron-browser/workbench/';
- const ide = {type: 'page', url: base + 'workbench.html'};
- const agents = {type: 'page', url: base + 'agentManager.html'};
+ const ide = {type: 'page', id: 'ide-1', url: base + 'workbench.html'};
+ const agents = {type: 'page', id: 'agents-1', url: base + 'agentManager.html'};
+ // [CodeBuddy IDE 状态栏] 主连接保持 1.2.9 原行为:只认 agentManager.html。
+ // workbench 走主连接会抢占先出现的窗口且不再重选,导致 agents 窗口
+ // (后打开)永远等不到完整面板注入——这是实测过的回归,不许复发。
assert.equal(selectPageTarget([ide], PROFILES[id]), null);
- assert.equal(selectPageTarget([ide, agents], PROFILES[id]), agents);
- assert.equal(selectPageTarget([agents, ide], PROFILES[id]), agents);
+ assert.equal(selectPageTarget([ide, agents], PROFILES[id]).url, agents.url);
+ assert.equal(selectPageTarget([agents, ide], PROFILES[id]).url, agents.url);
+ assert.equal(selectPageTarget([agents], PROFILES[id]).__wbsIdeMode, undefined);
const other = id === 'codebuddy-cn' ? 'codebuddy-intl' : 'codebuddy-cn';
assert.equal(selectPageTarget([agents], PROFILES[other]), null);
+ // IDE 浮层目标:codebuddy profile 的全部 workbench 页面(每个 IDE 窗口一条独立连接)
+ const ide2 = {type: 'page', id: 'ide-2', url: base + 'workbench.html?windowId=2'};
+ const ides = selectIdeTargets([ide, ide2, agents], PROFILES[id]);
+ assert.equal(ides.length, 2);
+ assert.ok(ides.every((t) => /workbench\.html/.test(t.url)));
+ // 非 codebuddy profile 不启用 IDE 浮层
+ assert.equal(selectIdeTargets([ide], PROFILES['workbuddy-cn']).length, 0);
}
});
diff --git a/test/codebuddy-ide-credits.test.js b/test/codebuddy-ide-credits.test.js
new file mode 100644
index 0000000..20fed55
--- /dev/null
+++ b/test/codebuddy-ide-credits.test.js
@@ -0,0 +1,103 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/inject.js'), 'utf8');
+const start = source.indexOf(' function injectCodeBuddyIdeMode()');
+const overlay = source.slice(start, source.indexOf('\n // User-facing strings', start));
+const tick = () => new Promise(resolve => setImmediate(resolve));
+class Element {
+ constructor(tag) { this.tagName = tag; this.children = []; this.style = {}; this.handlers = {}; this.textContent = ''; }
+ appendChild(node) { this.children.push(node); node.parent = this; return node; }
+ setAttribute() {}
+ addEventListener(type, fn) { this.handlers[type] = fn; }
+ remove() { if (this.parent) this.parent.children = this.parent.children.filter(n => n !== this); this.parent = null; }
+ get isConnected() { return this.tagName === 'body' || !!(this.parent && this.parent.isConnected); }
+ set innerHTML(value) { this.html = value; this.children = []; }
+ get innerHTML() { return this.html || this.textContent; }
+ querySelectorAll(selector) { return this.children.flatMap(child => [(selector[0] === '.' ? (child.className || '').split(' ').includes(selector.slice(1)) : child.id === selector.slice(1)) ? child : null, ...child.querySelectorAll(selector)]).filter(Boolean); }
+ querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }
+ click() { this.handlers.click?.({ target: this, preventDefault() {}, stopPropagation() {} }); }
+}
+function harness(accounts) {
+ const body = new Element('body'), head = new Element('head'), calls = [], pending = [];
+ const document = { body, head, createElement: tag => new Element(tag), getElementById: id => body.querySelector('#' + id), addEventListener() {}, removeEventListener() {} };
+ const window = {};
+ const context = { document, window, CAPS: {}, PROFILE_ID: 'codebuddy-cn', WBS_BRAND: 'WorkDaddy', WBS_LANGUAGE: 'zh',
+ wbsTranslateString: s => s, api: (path, opts) => {
+ calls.push(path);
+ if (path === '/api/accounts') return Promise.resolve({ accounts: accounts.map(a => ({ ...a })), current: { uid: 'a' } });
+ return new Promise((resolve, reject) => pending.push({ uid: JSON.parse(opts.body).uid, resolve, reject }));
+ } };
+ vm.runInNewContext(overlay + '\ninjectCodeBuddyIdeMode();', context);
+ const root = body.children[0];
+ return { root, calls, pending, window,
+ open: async () => { root.querySelector('.wbs-ide-fab').click(); await tick(); },
+ credits: () => root.querySelectorAll('.wbs-ide-account-credits').map(el => el.textContent),
+ };
+}
+test('unknown credits do not become zero; opening queries fresh balances including real zero and unlimited', async () => {
+ const h = harness([{ uid: 'a', creditSegments: [] }, { uid: 'b', credits: 50, creditSegments: [] }]);
+ await h.open(); assert.match(h.credits()[0], /未查询|查询中|刷新中/); assert.doesNotMatch(h.credits()[0], /积分 0/);
+ assert.equal(h.pending.length, 2); assert.match(h.credits()[1], /上次查询/);
+ h.pending[0].resolve({ credits: 0, segments: [], unlimited: false });
+ h.pending[1].resolve({ credits: 0, segments: [], unlimited: true }); await tick();
+ assert.match(h.credits()[0], /积分 0/); assert.doesNotMatch(h.credits()[0], /上次查询/);
+ assert.match(h.credits()[1], /无限/);
+});
+test('failed refresh retains labeled cache and manual refresh retries', async () => {
+ const h = harness([{ uid: 'a', credits: 50, creditSegments: [] }]); await h.open();
+ assert.equal(h.pending.length, 1); h.pending[0].reject(new Error('offline')); await tick();
+ assert.match(h.credits()[0], /50/); assert.match(h.credits()[0], /上次查询/); assert.match(h.credits()[0], /刷新失败/);
+ h.root.querySelector('.wbs-ide-credit-refresh').click(); await tick();
+ assert.equal(h.pending.length, 2); h.pending[1].resolve({ credits: 12, segments: [], unlimited: false }); await tick();
+ assert.match(h.credits()[0], /积分 12/); assert.doesNotMatch(h.credits()[0], /上次查询|失败/);
+});
+test('closing or reinjecting stops queued credit queries and ignores stale results', async () => {
+ for (const action of ['close', 'remove']) {
+ const h = harness(Array.from({ length: 6 }, (_, i) => ({ uid: String(i), creditSegments: [] }))); await h.open();
+ assert.equal(h.pending.length, 2);
+ const before = h.credits();
+ if (action === 'close') h.root.querySelector('.wbs-ide-modal').click(); else h.root.remove();
+ h.pending.forEach(p => p.resolve({ credits: 88, segments: [] })); await tick();
+ assert.equal(h.pending.length, 2); assert.deepEqual(h.credits(), before);
+ }
+});
+test('fresh expiry buckets exclude expired and unknown dates and include the day bucket in the week', async () => {
+ const h = harness([{ uid: 'a', credits: null, creditSegments: [] }]); await h.open();
+ const now = Date.now();
+ h.pending[0].resolve({ credits: 90, segments: [
+ { remaining: 10, expiresAt: now + 3600000 }, { remaining: 20, expiresAt: now + 172800000 },
+ { remaining: 30, expiresAt: now - 1000 }, { remaining: 30, expiresAt: null },
+ ] }); await tick();
+ assert.equal(h.credits()[0], '积分 90 · 24小时过期:10 · 近7天过期:30');
+});
+test('reopening ignores the previous batch and enables refresh only after the current batch finishes', async () => {
+ const h = harness([{ uid: 'a', credits: 50, creditSegments: [] }]); await h.open();
+ h.root.querySelector('.wbs-ide-modal').click(); await h.open();
+ const refresh = h.root.querySelector('.wbs-ide-credit-refresh');
+ h.pending[0].resolve({ credits: 999, segments: [] }); await tick();
+ assert.doesNotMatch(h.credits()[0], /999/); assert.equal(refresh.disabled, true);
+ h.pending[1].resolve({ credits: 12, segments: [] }); await tick();
+ assert.match(h.credits()[0], /积分 12/); assert.equal(refresh.disabled, false);
+});
+
+test('IDE shares the WorkDaddy panel without restricting tab navigation', () => {
+ assert.match(source, /'<div class="wbs-fab"/);
+ assert.match(source, /'<div class="wbs-panel"/);
+ assert.doesNotMatch(source, /injectCodeBuddyIdeMode\(\);/);
+ const tabSource = source.slice(source.indexOf(' function switchTab(name)'), source.indexOf(' var tabBtns'));
+ const panes = ['account', 'sessions', 'models', 'about'];
+ const tabs = panes.map(name => ({ getAttribute: () => name, classList: { toggle(_cls, active) { this.active = active; } } }));
+ for (const name of panes) {
+ const context = { WBS_CODEBUDDY_IDE_MODE: true,
+ root: { querySelectorAll: () => tabs },
+ themePane: null, sessionsPane: null, modelsPane: null, enhancePane: null,
+ automationPane: null, pcPane: null, aboutPane: null, settingsPane: null,
+ toast: () => assert.fail('IDE tab navigation must not be blocked'),
+ };
+ vm.runInNewContext(tabSource + '\nswitchTab(' + JSON.stringify(name) + ');', context);
+ assert.equal(tabs.find(tab => tab.classList.active).getAttribute(), name);
+ }
+});
diff --git a/test/codebuddy-ide-recovery.test.js b/test/codebuddy-ide-recovery.test.js
new file mode 100644
index 0000000..11f7eef
--- /dev/null
+++ b/test/codebuddy-ide-recovery.test.js
@@ -0,0 +1,71 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const source = fs.readFileSync(require('node:path').join(__dirname, '../scripts/daemon.js'), 'utf8');
+const manager = source.slice(source.indexOf('const idePages = new Map();'), source.indexOf('async function cdpLoop()'));
+const tick = () => new Promise(resolve => setImmediate(resolve));
+function harness() {
+ let now = 1000, serial = 0;
+ const timers = new Map(), sockets = [];
+ const target = { id: 'ide', url: 'vscode-file://vscode-app/CodeBuddy/workbench.html', webSocketDebuggerUrl: 'ws://127.0.0.1/fixture' };
+ const state = { fail: true, mounted: true, hold: false, injections: 0, targets: [target] };
+ class Socket {
+ constructor() { this.readyState = 1; sockets.push(this); }
+ send(payload) {
+ const msg = JSON.parse(payload);
+ if (state.hold) return;
+ let result = {};
+ if (msg.method === 'Runtime.evaluate') {
+ if (msg.params.expression === 'fixture-inject') {
+ state.injections++;
+ if (state.fail) result = { exceptionDetails: { text: 'fixture failure' } };
+ } else result = { result: { value: JSON.stringify({ fab: state.mounted, ready: 'complete' }) } };
+ }
+ queueMicrotask(() => this.onmessage({ data: JSON.stringify({ id: msg.id, result }) }));
+ }
+ close() { this.readyState = 3; this.onclose(); }
+ }
+ const context = vm.createContext({ Map, Set, Promise, JSON, Error, String, Date: { now: () => now },
+ setTimeout: (fn, ms) => { timers.set(++serial, { fn, at: now + ms }); return serial; }, clearTimeout: id => timers.delete(id),
+ WebSocketCtor: Socket, createRendererApiBridge: () => async () => {}, API_TOKEN: 'fixture', ACTUAL_PORT: 1,
+ BINDING: 'fixture', buildInjectScript: () => 'fixture-inject', redactDiagnosticText: s => s, log: () => {},
+ PROFILE: { kind: 'codebuddy' }, cdp: { port: 1 }, fetch: async () => ({ json: async () => state.targets }),
+ AbortSignal, selectIdeTargets: list => list });
+ vm.runInContext(manager, context);
+ return { state, sockets, context, timers,
+ scan: () => vm.runInContext('ideSyncScan()', context),
+ async start() { await this.scan(); sockets[0].onopen(); await tick(); },
+ async advance(ms) { now += ms; for (const [id, timer] of [...timers]) if (timer.at <= now) { timers.delete(id); timer.fn(); } await tick(); },
+ };
+}
+test('failed IDE injection retries on the same socket and stops once mounted', async () => {
+ const h = harness(); await h.start(); assert.equal(h.state.injections, 1);
+ h.state.fail = false; await h.advance(5000); await h.scan(); await tick(); await h.advance(2000);
+ assert.equal(h.state.injections, 2);
+ for (let i = 0; i < 3; i++) { await h.advance(5000); await h.scan(); }
+ assert.equal(h.state.injections, 2); assert.equal(h.sockets.length, 1);
+});
+test('missing root has bounded retries and navigation opens a new retry budget', async () => {
+ const h = harness(); h.state.fail = false; h.state.mounted = false; await h.start();
+ for (let i = 0; i < 20; i++) { await h.advance(5000); await h.scan(); await tick(); }
+ assert.equal(h.state.injections, 3);
+ h.state.mounted = true;
+ h.sockets[0].onmessage({ data: JSON.stringify({ method: 'Page.loadEventFired' }) });
+ await h.advance(500); await h.advance(2000);
+ assert.equal(h.state.injections, 4);
+});
+test('concurrent scans never start overlapping injections', async () => {
+ const h = harness(); h.state.fail = false; await h.start();
+ await Promise.all([h.scan(), h.scan(), h.scan()]);
+ assert.equal(h.state.injections, 1); await h.advance(2000);
+});
+test('IDE commands time out and pending commands reject on socket close', async () => {
+ const h = harness(); await h.start(); h.state.hold = true;
+ vm.runInContext("globalThis.done = false; ideSend(idePages.get('ide'), 'Runtime.evaluate').catch(() => { done = true; });", h.context);
+ await h.advance(20000); assert.equal(h.context.done, true);
+ vm.runInContext("done = false; globalThis.saved = idePages.get('ide'); ideSend(saved, 'Runtime.evaluate').catch(() => { done = true; });", h.context);
+ h.sockets[0].close(); await tick();
+ assert.equal(h.context.done, true); assert.equal(h.context.saved.pending.size, 0);
+});
diff --git a/test/credit-segments.test.js b/test/credit-segments.test.js
index f2e366b..87e5f35 100644
--- a/test/credit-segments.test.js
+++ b/test/credit-segments.test.js
@@ -30,6 +30,38 @@ test('expands slice-period usage details into separate segments', () => {
assert.deepEqual(segments.map((segment) => segment.remaining), [100, 100]);
});
+// [积分段到期修正] 月度套餐基础包:DeductionEndTime 是长期扣费有效期(2034),
+// 本周期额度在 CycleEndTime(月底 23:59:59)清零重发。到期必须取最早值,
+// 否则「即将过期」统计会漏掉月底清零的 500 额度(实测数据:CodeBuddy个人体验版)。
+test('monthly base package expires at cycle end, not long-term deduction window', () => {
+ const segments = extractCreditSegments([
+ {
+ PackageName: 'CodeBuddy个人体验版',
+ CycleCapacityRemainPrecise: '500', CycleCapacitySizePrecise: '500',
+ DeductionEndTime: 2036728390000, // 2034-07-17
+ CycleStartTime: '2026-09-01 00:00:00',
+ CycleEndTime: '2026-09-30 23:59:59',
+ },
+ ], '套餐基础');
+ assert.equal(segments.length, 1);
+ assert.equal(segments[0].remaining, 500);
+ assert.equal(segments[0].expiresAt, new Date('2026-09-30T23:59:59').getTime());
+});
+
+// 裂变包两类时间相等:取最早不改变既有解析结果(防回归)
+test('fission pack keeps its own expiry when both time fields agree', () => {
+ const segments = extractCreditSegments([
+ {
+ PackageName: 'CodeBuddy个人版国内运营裂变包',
+ CycleCapacityRemainPrecise: '100', CycleCapacitySizePrecise: '100',
+ DeductionEndTime: '2026-10-01 00:30:43',
+ CycleEndTime: '2026-10-01 00:30:43',
+ },
+ ], '裂变包');
+ assert.equal(segments.length, 1);
+ assert.equal(segments[0].expiresAt, new Date('2026-10-01T00:30:43').getTime());
+});
+
test('prefers cycle remaining over total capacity when a cycle is exhausted', () => {
const segments = extractCreditSegments([
{ CycleCapacityRemainPrecise: '0', CapacityRemainPrecise: '500', EndTime: 1790000000 },
diff --git a/test/credit-summary.test.js b/test/credit-summary.test.js
index 214537a..d8c332d 100644
--- a/test/credit-summary.test.js
+++ b/test/credit-summary.test.js
@@ -20,3 +20,35 @@ test('zero, expired, malformed and stale oversized segments cannot inflate the t
assert.deepEqual(JSON.parse(JSON.stringify(result.rows)), [{ days: 0, credits: 5 }, { days: 1, credits: 7 }]);
assert.equal(ctx.summarizeCreditDays([], 1).rows.length, 0);
});
+
+test('summary scrollbars appear only while scrolling and reset on close or reinjection', () => {
+ const listeners = new Map(), timers = new Map(); let serial = 0;
+ const element = () => { const classes = new Set(); return { hidden: true, classes,
+ classList: { add: x => classes.add(x), remove: x => classes.delete(x) },
+ setAttribute() {}, contains: () => false, remove() {} }; };
+ const button = element(), popup = element(), chart = element(); let dispose;
+ const context = { accountsPane: { querySelector: () => button }, el: () => popup,
+ mountPersistentOverlay() {}, clearTimeout: id => timers.delete(id),
+ setBuildTimeout(fn) { timers.set(++serial, fn); return serial; },
+ listen(node, type, fn) { listeners.set((node === popup ? 'popup:' : node === button ? 'button:' : 'other:') + type, fn); },
+ window: {}, document: {}, root: {}, hideCreditTooltip() {}, registerDisposer: fn => { dispose = fn; } };
+ const start = source.indexOf(' function setupCreditSummary()');
+ vm.runInNewContext(source.slice(start, source.indexOf(' function openOfficialGrowthCenter()', start)), context);
+ context.setupCreditSummary();
+ assert.equal(chart.classes.has('is-scrolling'), false);
+ listeners.get('popup:scroll')({ target: chart });
+ assert.equal(chart.classes.has('is-scrolling'), true);
+ listeners.get('popup:scroll')({ target: chart });
+ assert.equal(timers.size, 1);
+ timers.values().next().value();
+ assert.equal(chart.classes.has('is-scrolling'), false);
+ listeners.get('popup:scroll')({ target: chart });
+ listeners.get('button:keydown')({ key: 'Escape', stopPropagation() {} });
+ assert.equal(chart.classes.has('is-scrolling'), false);
+ assert.equal(timers.size, 0);
+ listeners.get('popup:scroll')({ target: chart });
+ dispose();
+ assert.equal(chart.classes.has('is-scrolling'), false);
+ assert.equal(timers.size, 0);
+ assert.match(source, /\.wbs-credit-summary-chart\{[^}]*scrollbar-color:transparent transparent/);
+});
diff --git a/test/growth-credit-refresh.test.js b/test/growth-credit-refresh.test.js
index 0797728..08a127c 100644
--- a/test/growth-credit-refresh.test.js
+++ b/test/growth-credit-refresh.test.js
@@ -17,7 +17,9 @@ function section(start, end) {
test('growth action links never claim rewards or refresh credits locally', () => {
const actions = section(' function openOfficialGrowthCenter()', ' function setupDailyProgressPopover()');
- assert.match(actions, /https:\/\/www\.workbuddy\.cn\/profile\/growth-center/);
+ assert.match(actions, /OFFICIAL_GROWTH_TARGET/);
+ assert.match(actions, /requestGrowthDeviceCode/);
+ assert.match(actions, /growthClientLoginUrl/);
assert.doesNotMatch(actions, /refreshCreditForAccount|\/api\/growth\//);
});
diff --git a/test/growth-rings-ui.test.js b/test/growth-rings-ui.test.js
index 54b3fbe..36b3ceb 100644
--- a/test/growth-rings-ui.test.js
+++ b/test/growth-rings-ui.test.js
@@ -8,7 +8,7 @@ const path = require('node:path');
const inject = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
const daemon = fs.readFileSync(path.join(__dirname, '../scripts/daemon.js'), 'utf8');
-test('account cards render task progress as a cat liquid badge before check-in status', () => {
+test('account cards render today check-in as a full or empty cat liquid badge', () => {
assert.match(inject, /wbs-daily-rings/);
assert.match(inject, /wbs-daily-vessel/);
assert.match(inject, /wbs-daily-liquid/);
@@ -28,6 +28,11 @@ test('account cards render task progress as a cat liquid badge before check-in s
assert.match(inject, /\.wbs-daily-rings\{[^}]*border:0/);
assert.match(inject, /wbs-daily-streak-label/);
assert.match(inject, /连续登录 /);
+ assert.match(inject, /function isCheckedInToday\(a\)/);
+ assert.match(inject, /var level = checkedToday \? '100\.00%' : '0\.00%'/);
+ assert.match(inject, /is-checked-in/);
+ assert.match(inject, /\.wbs-daily-vessel\.is-empty \.wbs-daily-liquid\{min-height:0\}/);
+ assert.doesNotMatch(inject.slice(inject.indexOf('function dailyRingsSvg('), inject.indexOf('function dailyRingsHtml(', inject.indexOf('function dailyRingsSvg('))), /growth\.ratio/);
assert.doesNotMatch(inject, />活跃 .* 天</);
assert.match(inject, /\.wbs-daily-vessel\{[^}]*border-radius:50%/);
assert.match(inject, /\.wbs-daily-liquid\{[^}]*height:var\(--wbs-liquid-level/);
@@ -38,6 +43,34 @@ test('account cards render task progress as a cat liquid badge before check-in s
assert.doesNotMatch(hoverRule[0], /border(?:-color)?:/);
});
+test('cat water requires the official growth record for today, not credit check-in or streak totals', () => {
+ const start = inject.indexOf(' function dailyRingsSvg(account)');
+ const end = inject.indexOf('\n function dailyRingsHtml', start);
+ const vm = require('node:vm');
+ const context = {
+ WORKBUDDY_CAT_MARK: '__WBS_BUDDY_MARK__',
+ Date: class extends Date { static now() { return Date.parse('2026-09-30T02:00:00Z'); } },
+ };
+ const checkedStart = inject.indexOf(' function isCheckedInToday(');
+ vm.runInNewContext(inject.slice(checkedStart, inject.indexOf(' function activityStreakHtml(', checkedStart)), context);
+ vm.runInNewContext(inject.slice(start, end), context);
+ const record = (is_active, date = '2026-09-30') => ({ ok: true, is_active, date });
+ for (const account of [
+ { checkin: { ok: true } },
+ { checkin: { ok: true }, growthTodayActive: record(false) },
+ { checkin: { ok: true }, growthTodayActive: record(true, '2026-09-29') },
+ { activityStreak: { days: 5, status: 'ready' }, dailyProgress: { growth: { ratio: 1 } } },
+ { growthTodayActive: { ok: false, is_active: true, date: '2026-09-30' } },
+ { growthTodayActive: record('true') },
+ {}, null,
+ ]) assert.match(context.dailyRingsSvg(account), /is-empty/, JSON.stringify(account));
+ const completed = { checkin: { ok: false }, growthTodayActive: record(true) };
+ assert.match(context.dailyRingsSvg(completed), /is-checked-in/);
+ assert.match(context.dailyRingsSvg(completed), /--wbs-liquid-level:100\.00%/);
+ context.Date = class extends Date { static now() { return Date.parse('2026-09-30T16:00:00Z'); } };
+ assert.match(context.dailyRingsSvg(completed), /is-empty/, 'yesterday must become empty at Beijing midnight');
+});
+
test('daily activity and credit nodes reuse one theme-aware colored popover', () => {
assert.match(inject, /wbs-status-popover/);
assert.match(inject, /showStatusPopover\(segment/);
@@ -160,29 +193,50 @@ test('growth status colors reuse WorkBuddy primary theme constants', () => {
});
test('growth actions open the official center and never write through local growth routes', async () => {
- assert.match(inject, /https:\/\/www\.workbuddy\.cn\/profile\/growth-center/);
+ assert.match(inject, /profile\/growth-center\?fromSource=gwzcw\.15291246/);
+ assert.match(inject, /\/console\/client-login\?code=/);
+ assert.match(inject, /request-device-auth-code-result/);
assert.match(inject, /data-wbs-growth-official/);
assert.match(inject, /api\('\/api\/open-url'/);
assert.match(inject, /\/api\/growth\/daily-progress/);
- const source = inject.match(/function openOfficialGrowthCenter\(\) \{[\s\S]*?\n \}/);
- assert.ok(source);
- const calls = [];
- const open = Function('api', 'toast', 'root', source[0] + '\nreturn openOfficialGrowthCenter;')(
+ const helperStart = inject.indexOf(' var OFFICIAL_GROWTH_TARGET');
+ const helperEnd = inject.indexOf(' function confirmCurrentGrowthAccount', helperStart);
+ assert.ok(helperStart > 0 && helperEnd > helperStart);
+ const source = inject.slice(helperStart, helperEnd);
+ const calls = [], listeners = {};
+ const adapter = {
+ on(event, handler) { listeners[event] = handler; return () => { delete listeners[event]; }; },
+ emit(event) { assert.equal(event, 'request-device-auth-code'); setImmediate(() => listeners['request-device-auth-code-result']({ success: true, deviceCode: 'device-123' })); },
+ openExternal(url) { calls.push({ route: 'openExternal', url }); return Promise.resolve(); },
+ };
+ const open = Function('api', 'toast', 'root', 'findWbsAdapter', 'window', 'PROFILE_ID', source + '\nreturn openOfficialGrowthCenter;')(
(route, options) => { calls.push({ route, options }); return Promise.resolve(); },
() => assert.fail('opening the official site should not toast success'),
- {}
+ {}, () => adapter, { __wbsAdapter: adapter }, 'workbuddy-cn'
);
- open();
+ await open();
assert.equal(calls.length, 1);
- assert.equal(calls[0].route, '/api/open-url');
- assert.deepEqual(JSON.parse(calls[0].options.body), { url: 'https://www.workbuddy.cn/profile/growth-center' });
- await Promise.resolve();
+ assert.equal(calls[0].route, 'openExternal');
+ const opened = new URL(calls[0].url);
+ assert.equal(opened.origin, 'https://www.workbuddy.cn');
+ assert.equal(opened.pathname, '/console/client-login');
+ assert.equal(opened.searchParams.get('code'), 'device-123');
+ assert.match(opened.searchParams.get('target'), /^\/profile\/growth-center\?fromSource=gwzcw\.15291246/);
for (const suffix of ['tasks/accept', 'tasks/accept-all', 'buddy/first', 'buddy/travel/claim', 'buddy/select', 'buddy/travel/depart', 'buddy/open', 'lottery/draw']) {
assert.doesNotMatch(inject, new RegExp('/api/growth/' + suffix));
assert.doesNotMatch(daemon, new RegExp("p === '/api/growth/" + suffix + "'"));
}
});
+test('modern adapter shim forwards the official login event and external-open methods', () => {
+ const start = inject.indexOf(' function findWbsAdapter()');
+ const end = inject.indexOf(' function bootstrapModernQueueBridge()', start);
+ assert.ok(start > 0 && end > start);
+ const adapterSource = inject.slice(start, end);
+ assert.match(adapterSource, /\['on', 'emit', 'openExternal'\]/);
+ assert.match(adapterSource, /target\[m\]\.apply\(target, arguments\)/);
+});
+
test('growth window buttons use the live current account and leave other accounts untouched', async () => {
const guardSource = inject.match(/function confirmCurrentGrowthAccount\(uid\) \{[\s\S]*?\n \}/);
assert.ok(guardSource);
@@ -264,6 +318,24 @@ test('daily labels share a black light treatment and one glass dark treatment',
assert.match(inject, /backdrop-filter:blur\(12px\)/);
});
+test('cat water follows the credit or button palette for the selected theme', () => {
+ const badgeRules = [...inject.matchAll(/\.wbs-daily-rings\{([^}]+)\}/g)]
+ .map(match => match[1]).filter(rule => rule.includes('--wbs-liquid-fill:'));
+ assert.ok(badgeRules.length);
+ for (const rule of badgeRules) {
+ assert.match(rule, /--wbs-liquid-fill:(?:color-mix\(in srgb,var\(--wb-button-primary-bg|oklch\(from var\(--wb-button-primary-bg|var\(--wbs-credit-theme-color,var\(--wbs-primary\)\))/);
+ }
+ assert.match(inject, /\.wbs-daily-vessel\.is-checked-in\{--wbs-liquid-ink:var\(--wb-button-primary-fg/);
+ const fullVessel = inject.match(/\.wbs-daily-vessel\.is-checked-in\{([^}]+)\}/);
+ const fullLiquid = inject.match(/\.wbs-daily-vessel\.is-checked-in \.wbs-daily-liquid\{([^}]+)\}/);
+ assert.ok(fullVessel);
+ assert.ok(fullLiquid);
+ assert.match(fullVessel[1], /background:var\(--wbs-liquid-fill\)/);
+ assert.match(fullVessel[1], /box-shadow:none/);
+ assert.match(fullLiquid[1], /box-shadow:none/);
+ assert.match(fullLiquid[1], /border-radius:inherit/);
+});
+
test('travel selection links to the official center', () => {
assert.match(inject, /cat\.state === 'needs_selection'/);
assert.match(inject, /去官网选择 Buddy/);
@@ -298,3 +370,14 @@ test('growth plan primary actions use WorkBuddy button theme tokens', () => {
assert.ok(hover);
assert.match(hover[0], /var\(--wb-button-primary-bg-hover/);
});
+
+
+test('full water remains visibly brighter than the empty vessel in monochrome themes', () => {
+ assert.match(inject, /--wbs-liquid-fill:color-mix\(in srgb,var\(--wb-button-primary-bg\) 55%,var\(--wb-button-primary-fg\)\)/);
+ assert.match(inject, /@supports \(color:oklch\(from black l c h\)\)\{\.wbs-daily-rings\{--wbs-liquid-fill:oklch\(from var\(--wb-button-primary-bg\) max\(l,\.62\) c h \/ 1\)/);
+});
+
+
+test('default light cat highlight shares the credit progress color and excludes dark themes', () => {
+ assert.ok(inject.includes('html:not(.cb-dark):not([data-theme="dark"]):is([data-wbs-theme-id="default"],:not([data-wbs-theme-id])) body:not([data-vscode-theme-name*="dark" i]) .wbs-daily-rings{--wbs-liquid-fill:var(--wbs-credit-theme-color,var(--wbs-primary))}'));
+});
diff --git a/test/macos-dock-identity.test.js b/test/macos-dock-identity.test.js
index af27dbe..4a346ad 100644
--- a/test/macos-dock-identity.test.js
+++ b/test/macos-dock-identity.test.js
@@ -16,7 +16,29 @@ test('packaged macOS launcher starts the app through LaunchServices, not its Ele
for (const block of blocks) execFileSync('python3', ['-', launcher], { input: block[1] });
const source = fs.readFileSync(launcher, 'utf8');
assert.doesNotMatch(source, /nohup "\$APP_BIN"/);
- assert.match(source, /\/usr\/bin\/open -a "\$TARGET_APP_BUNDLE" --args "--remote-debugging-port=\$PORT"/);
- execFileSync('bash', ['-n', launcher]);
+ assert.match(source, /\/usr\/bin\/open -a "\$TARGET_APP_BUNDLE" "\$\{OPEN_ARGS\[@\]\}"/);
+ execFileSync('/bin/bash', ['-n', launcher]);
+ // Execute the generated cold-start block with macOS Bash 3.2 and a fake
+ // open command. CN/AI must reach open even without a native inspector arg.
+ const start = source.indexOf('TARGET_APP_BUNDLE="${APP_BIN%/Contents/MacOS/*}"');
+ const end = source.indexOf('\nfi', source.indexOf('if ! /usr/bin/open', start)) + 3;
+ assert.ok(start > 0 && end > start);
+ const launch = source.slice(start, end).replace('/usr/bin/open', 'capture_open');
+ const app = path.join(dir, 'Client With Spaces.app');
+ fs.mkdirSync(app);
+ for (const [profile, port, inspector] of [
+ ['workbuddy-cn', '9222', null], ['workbuddy-ai', '9223', null],
+ ['codebuddy-cn', '9224', '9244'], ['codebuddy-intl', '9225', '9245'],
+ ]) {
+ const output = execFileSync('/bin/bash', ['-s'], {
+ input: 'set -eu\ncapture_open() { printf "%s\\n" "$@"; }\nnotify() { :; }\n' + launch,
+ env: { ...process.env, PROFILE: profile, PORT: port, APP_BIN: app + '/Contents/MacOS/Electron' },
+ encoding: 'utf8',
+ });
+ assert.deepEqual(output.trim().split('\n'), [
+ '-a', app, '--args', '--remote-debugging-port=' + port,
+ ...(inspector ? ['--inspect=127.0.0.1:' + inspector] : []),
+ ], profile);
+ }
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
diff --git a/test/macos-launcher-nounset.test.js b/test/macos-launcher-nounset.test.js
new file mode 100644
index 0000000..bb01b76
--- /dev/null
+++ b/test/macos-launcher-nounset.test.js
@@ -0,0 +1,24 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+
+const root = path.join(__dirname, '..');
+
+test('macOS launchers never expand an empty native argument array under bash nounset', () => {
+ const files = [
+ path.join(root, 'scripts', 'relaunch-with-cdp.sh'),
+ path.join(root, 'scripts', 'relaunch-with-cdp-linux.sh'),
+ path.join(root, 'scripts', 'build-mac-dmg.sh'),
+ ];
+ for (const file of files) {
+ const source = fs.readFileSync(file, 'utf8');
+ assert.doesNotMatch(
+ source,
+ /"\$\{NATIVE_ARGS\[@\]\}"/,
+ `${path.basename(file)} must not expand an empty array with bash set -u`,
+ );
+ }
+});
diff --git a/test/message-navigation.test.js b/test/message-navigation.test.js
index 0278a78..7daa1b3 100644
--- a/test/message-navigation.test.js
+++ b/test/message-navigation.test.js
@@ -8,6 +8,114 @@ const vm = require('node:vm');
const compat = require('../scripts/workbuddy-compat.js');
+function navigationFunction(name, context) {
+ const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
+ const start = source.indexOf(' function ' + name + '(');
+ assert.ok(start >= 0, name + ' exists');
+ const end = source.indexOf('\n function ', start + 1);
+ vm.runInNewContext(source.slice(start, end), context);
+ return context[name];
+}
+
+test('navigation displays at most 20 evenly spaced markers while retaining both conversation ends', () => {
+ const context = {};
+ const indices = navigationFunction('markerTurnIndices', context);
+ for (const count of [0, 1, 2, 19, 20, 21, 100, 1001]) {
+ const result = Array.from(indices(count));
+ assert.equal(result.length, Math.min(20, count));
+ assert.equal(new Set(result).size, result.length);
+ if (!count) continue;
+ assert.equal(result[0], 0);
+ assert.equal(result.at(-1), count - 1);
+ if (count <= 20) assert.deepEqual(result, Array.from({ length: count }, (_, i) => i));
+ const gaps = result.slice(1).map((value, i) => value - result[i]);
+ if (gaps.length) assert.ok(Math.max(...gaps) - Math.min(...gaps) <= 1);
+ }
+});
+
+test('moving between a marker, prompt list and detail keeps the hover surface open', () => {
+ const list = {}, detail = {}, outside = {};
+ let closes = 0;
+ const context = { dragPointerId: null, root: { contains: node => node === list || node === detail },
+ hideTooltip: () => { closes++; } };
+ const pointerOut = navigationFunction('onPointerOut', context);
+ pointerOut({ relatedTarget: list });
+ pointerOut({ relatedTarget: detail });
+ assert.equal(closes, 0);
+ pointerOut({ relatedTarget: outside });
+ assert.equal(closes, 1);
+ pointerOut({ relatedTarget: null });
+ assert.equal(closes, 2);
+});
+
+test('every prompt remains reachable when the rail is capped, including unsampled turns', () => {
+ const element = (tag, className, textContent = '') => ({
+ tag, className, textContent, children: [], attributes: {},
+ appendChild(child) { this.children.push(child); },
+ setAttribute(key, value) { this.attributes[key] = value; },
+ });
+ const turns = Array.from({ length: 101 }, (_, i) => ({ id: 'turn-' + i, userMessage: 'prompt-' + i }));
+ turns[53].userMessage = '<img src=x onerror=alert(1)>';
+ turns[54].userMessage = { content: [{ type: 'text', text: '长提示词'.repeat(25000) }] };
+ turns.forEach(turn => {
+ if (typeof turn.userMessage === 'string') turn.userMessage = { content: [{ type: 'text', text: turn.userMessage }] };
+ });
+ const context = { turns, rail: element('div'), tooltip: element('div'), detail: { id: 'detail' },
+ buttons: {}, promptRows: {}, activeId: null, hideTooltip() {}, setActive() {},
+ el: element };
+ navigationFunction('messageText', context);
+ navigationFunction('markerTurnIndices', context);
+ navigationFunction('render', context)();
+ assert.equal(context.rail.children.length, 20);
+ assert.equal(context.tooltip.children.length, 101);
+ assert.equal(context.promptRows['turn-53'].textContent, '<img src=x onerror=alert(1)>');
+ assert.ok(context.promptRows['turn-54'].textContent.length <= 240, 'single-line previews must not lay out entire giant prompts');
+ assert.ok(context.promptRows['turn-54'].textContent.endsWith('…'));
+ assert.equal(turns[54].userMessage.content[0].text.length, 100000, 'the original prompt stays intact');
+ for (let i = 0; i < turns.length; i++) {
+ assert.equal(context.promptRows[turns[i].id].attributes['data-wbs-message-nav-id'], turns[i].id);
+ assert.ok(context.rail.children.includes(context.buttons[turns[i].id]));
+ }
+ assert.equal(context.buttons['turn-100'], context.rail.children.at(-1));
+});
+
+test('hovering rail padding opens the nearest prompt immediately', () => {
+ const button = {}, turn = { id: 'first' }, target = { closest: () => null };
+ let shown;
+ const context = { dragPointerId: null, tooltipTimer: null, turns: [turn], buttons: { first: button },
+ rail: { contains: node => node === target }, dragIndexAt: () => 0,
+ turnForButton: value => value === button ? turn : null,
+ showTooltip: (value, anchor) => { shown = { value, anchor }; } };
+ navigationFunction('onPointerOver', context)({ target, clientY: 12 });
+ assert.deepEqual(shown, { value: turn, anchor: button });
+});
+
+test('flyout scrollbars stay hidden on centering and hide again after user scrolling stops', () => {
+ const classes = new Set();
+ const tooltip = { hidden: false, scrollTop: 90, classList: { add: value => classes.add(value), remove: value => classes.delete(value) } };
+ const timers = new Map();
+ let serial = 0;
+ const context = { tooltip, centeredScrollTop: 90, scrollbarTimers: new Map(),
+ clearTimeout: id => timers.delete(id),
+ setBuildTimeout(fn) { timers.set(++serial, fn); return serial; } };
+ navigationFunction('clearScrolling', context);
+ const scroll = navigationFunction('onFlyoutScroll', context);
+ scroll({ currentTarget: tooltip });
+ assert.equal(classes.has('is-scrolling'), false, 'automatic centering must not flash a scrollbar');
+ tooltip.scrollTop += 30;
+ scroll({ currentTarget: tooltip });
+ assert.equal(classes.has('is-scrolling'), true);
+ scroll({ currentTarget: tooltip });
+ assert.equal(timers.size, 1, 'continued scrolling replaces the idle timer');
+ timers.values().next().value();
+ assert.equal(classes.has('is-scrolling'), false);
+ assert.equal(context.scrollbarTimers.size, 0);
+ assert.equal(timers.size, 0);
+ scroll({ currentTarget: tooltip });
+ context.clearScrolling(tooltip);
+ assert.equal(timers.size, 0, 'closing a flyout cancels its timer');
+});
+
test('scroll events keep the last node selected when the last turn cannot align with the viewport top', () => {
const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
const frames = [{ index: 1, top: 28, bottom: 350 }, { index: 2, top: 350, bottom: 410 }, { index: 3, top: 410, bottom: 600 }];
@@ -78,7 +186,7 @@ test('all navigation turns are built from the structured message store regardles
test('message navigation preview hides only the assistant completion marker at the end', () => {
const source = fs.readFileSync(path.join(__dirname, '../scripts/inject.js'), 'utf8');
- const start = source.indexOf(' function messageText(message, limit) {');
+ const start = source.indexOf(' function messageText(message, limit, preserveMarkdown) {');
const end = source.indexOf('\n function ensureRoot()', start);
assert.ok(start >= 0 && end > start);
const context = {};
@@ -160,7 +268,11 @@ test('injected navigation rail is theme-aware, glassy, accessible, and profile a
assert.match(inject, /\.wbs-message-nav-rail\{[^\n]*border:1px solid transparent[^\n]*box-shadow:none[^\n]*backdrop-filter:none/);
assert.match(inject, /\.wbs-message-nav-rail:hover,\.wbs-message-nav-rail:focus-within\{[^\n]*backdrop-filter:blur\(/);
assert.match(inject, /\.wbs-message-nav-marker\{[^\n]*background:color-mix\(in srgb,var\(--wb-bg-popover/);
- assert.match(inject, /\.wbs-message-nav-marker:hover,\.wbs-message-nav-marker:focus-visible\{[^\n]*border-color:[^\n]*box-shadow:[^\n]*backdrop-filter:blur\(/);
+ assert.doesNotMatch(inject, /\.wbs-message-nav-marker:hover[^']*\{/);
+ assert.doesNotMatch(inject, /\.wbs-message-nav-marker:hover \.wbs-message-nav-dot/);
+ assert.doesNotMatch(inject, /wbs-message-nav-highlight|@keyframes wbs-message-nav-highlight/);
+ assert.match(inject, /\.wbs-message-nav-response\{display:block/);
+ assert.doesNotMatch(inject, /\.wbs-message-nav-response\{-webkit-line-clamp/);
assert.match(inject, /prefers-reduced-motion:reduce/);
assert.match(inject, /querySelectorAll\('\.wbs-message-nav-root'\)/);
@@ -207,3 +319,33 @@ test('floating robot keeps the website shell and upright eyes', () => {
assert.match(inject, /\.wbs-fab \.button\{[^\n]*width:82px;height:64px/);
assert.doesNotMatch(inject, /\.wbs-fab \.eye:before/);
});
+
+
+test('assistant hover previews preserve Markdown line structure while prompt summaries remain compact', () => {
+ const context = {};
+ const read = navigationFunction('messageText', context);
+ const markdown = '# 标题\n\n- **重点**\n- 第二项\n\n```js\nconst a = 1;\n```';
+ const message = { messageType: 'assistant', content: [{ type: 'markdown', text: markdown + '\n[wbs-reply-done]: #' }] };
+ assert.equal(read(message, 20000, true), markdown);
+ assert.equal(read(message, 240).includes('\n'), false);
+ assert.equal(read(message, 10, true).length, 10);
+});
+
+test('detail preview mounts the local Markdown component with a safe text fallback', () => {
+ const nodes = [];
+ const context = {
+ detail: { textContent: '', appendChild: node => nodes.push(node), classList: { add() {} } },
+ hideDetail() {}, positionFlyouts() {},
+ messageText: (m, limit, preserve) => { if (m.role === 'assistant') assert.equal(preserve, true); return m.text; },
+ el: (tag, cls, text) => ({ className: cls, textContent: text, appendChild: child => nodes.push(child) }),
+ window: { __wbsMarkdownPreview: { render: text => ({ rendered: text }) } },
+ };
+ const show = navigationFunction('showDetail', context);
+ show({ userMessage: { text: '问题' }, assistantMessage: { role: 'assistant', text: '**回答**' } }, { classList: { add() {} } });
+ assert.ok(nodes.some(node => node.rendered === '**回答**'));
+ assert.ok(nodes.some(node => node.className === 'wbs-message-nav-response'));
+ const userLabel = nodes.findIndex(node => node.className === 'wbs-message-nav-role' && node.textContent === '用户');
+ const assistantLabel = nodes.findIndex(node => node.className === 'wbs-message-nav-role' && node.textContent === '助手');
+ assert.ok(userLabel >= 0 && userLabel < nodes.findIndex(node => node.className === 'wbs-message-nav-prompt'));
+ assert.ok(assistantLabel > userLabel && assistantLabel < nodes.findIndex(node => node.className === 'wbs-message-nav-response'));
+});
diff --git a/test/session-copy-list-refresh.test.js b/test/session-copy-list-refresh.test.js
index 78e85c3..88d9bbb 100644
--- a/test/session-copy-list-refresh.test.js
+++ b/test/session-copy-list-refresh.test.js
@@ -6,7 +6,7 @@ const vm = require('node:vm');
const crypto = require('node:crypto');
const source = fs.readFileSync(require.resolve('../scripts/daemon.js'), 'utf8');
-function harness({ kind = 'workbuddy', owner = 'target', connected = true, reject = false, status = 'copied' } = {}) {
+function harness({ kind = 'workbuddy', owner = 'target', connected = true, reject = false, status = 'copied', openSessionId = '' } = {}) {
const stored = new Set(), visible = new Set(), calls = [];
let activeSession = 'existing-session';
const ctx = { crypto, Date, PROFILE: { kind }, cdp: { connected },
@@ -42,7 +42,7 @@ function harness({ kind = 'workbuddy', owner = 'target', connected = true, rejec
const start = source.indexOf('function startAutoCopyJob(');
vm.runInNewContext(source.slice(start, source.indexOf('function activeAutoCopyJob(', start)), ctx);
return { stored, visible, calls, active: () => activeSession, run: async () => {
- const job = ctx.startAutoCopyJob('source', 'target', []);
+ const job = ctx.startAutoCopyJob('source', 'target', [], { openSessionId });
await ctx.autoCopyQueue[0].run();
return job;
} };
@@ -65,6 +65,20 @@ for (const options of [{ kind: 'codebuddy' }, { owner: 'other-account' }, { conn
});
}
+test('an opened session still refreshes the official list when its copy is unchanged', async () => {
+ const h = harness({ status: 'skipped', openSessionId: 'a' });
+ const job = await h.run();
+ assert.equal(job.status, 'done');
+ assert.equal(h.calls.length, 1, 'the active session needs hydration even when its files were already present');
+});
+
+test('explicit migration wires the same official list refresh seam', () => {
+ const routeStart = source.indexOf("if (req.method === 'POST' && p === '/api/sessions/migrate')");
+ assert.notEqual(routeStart, -1);
+ const route = source.slice(routeStart, routeStart + 2200);
+ assert.match(route, /await refreshWorkBuddySessionList\(String\(\(currentAccount\(\) \|\| \{\}\)\.uid \|\| ''\)\.trim\(\), 'sessions-migrate'\)/);
+});
+
test('an unavailable renderer never turns a committed session copy into failure', async () => {
const h = harness({ reject: true });
const job = await h.run();
diff --git a/test/session-export-ui.test.js b/test/session-export-ui.test.js
index 93b7fc9..61e9973 100644
--- a/test/session-export-ui.test.js
+++ b/test/session-export-ui.test.js
@@ -2,10 +2,10 @@
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/inject.js'),'utf8');
function fixture(){
- const nodes=new Map(),node=key=>{if(!nodes.has(key))nodes.set(key,{hidden:false,disabled:false,textContent:'',removeAttribute(name){delete this[name];},querySelector:node});return nodes.get(key);};
+ const nodes=new Map(),node=key=>{if(!nodes.has(key))nodes.set(key,{hidden:false,disabled:false,textContent:'',focus(){},removeAttribute(name){delete this[name];},querySelector:node});return nodes.get(key);};
const calls=[],requests=[],timers=[];
const ctx={sessionsPane:{querySelector:node},sessionsState:{},alive:true,clearTimeout(){},setBuildTimeout(fn){timers.push(fn);return timers.length;},
- sessionCopySizeText:bytes=>String(bytes),api:url=>{calls.push(url);return new Promise((resolve,reject)=>requests.push({resolve,reject}));}};
+ sessionCopySizeText:bytes=>String(bytes),wbsTranslateString:value=>String(value),WBS_LANGUAGE:'zh',api:url=>{calls.push(url);return new Promise((resolve,reject)=>requests.push({resolve,reject}));}};
const start=source.indexOf(' function renderSessionExport(');
vm.runInNewContext(source.slice(start,source.indexOf(' function sortSessionAccounts(',start)),ctx);
return{ctx,node,calls,requests,timers};
@@ -38,3 +38,29 @@ test('a daemon restart discards the missing job id instead of polling it forever
f.requests[1].resolve({job:null});await poll;
assert.equal(f.node('#wbs-sess-export-progress').hidden,true);
});
+
+test('export dialog stays dismissed during polling and opens for completion or a new job',()=>{
+ const f=fixture(),job={id:'one',running:true,status:'writing'};
+ f.ctx.renderSessionExport(job);
+ f.ctx.dismissSessionExport();
+ f.ctx.renderSessionExport({...job,percent:80});
+ assert.equal(f.node('#wbs-sess-export-progress').hidden,true);
+ f.ctx.renderSessionExport({...job,running:false,status:'completed',file:'done.wds'});
+ assert.equal(f.node('#wbs-sess-export-progress').hidden,false);
+ f.ctx.dismissSessionExport();
+ f.ctx.renderSessionExport({...job,running:false,status:'completed',file:'done.wds'});
+ assert.equal(f.node('#wbs-sess-export-progress').hidden,true);
+ f.ctx.renderSessionExport({...job,id:'two'});
+ assert.equal(f.node('#wbs-sess-export-progress').hidden,false);
+});
+
+test('export dialog is a WorkDaddy panel overlay rather than a body overlay',()=>{
+ const markup=source.slice(source.indexOf("'<div class=\"wbs-modal-mask wbs-modal-mask-panel wbs-sess-export-progress\""),source.indexOf("'<div class=\"wbs-sess-copy-progress\""));
+ assert.match(markup,/wbs-modal-mask-panel/);
+ const wireStart=source.indexOf(' function wireSessionsPane()');
+ const wireEnd=source.indexOf(' function renderSessionExport(',wireStart);
+ const wire=source.slice(wireStart,wireEnd);
+ assert.match(wire,/var panel = root && root\.querySelector\('\.wbs-panel'\);/);
+ assert.match(wire,/panel\.appendChild\(exportCard\)/);
+ assert.doesNotMatch(wire,/mountPersistentOverlay\(exportCard\)/);
+});
diff --git a/test/session-fork-integration.test.js b/test/session-fork-integration.test.js
index 2f3e652..2fca718 100644
--- a/test/session-fork-integration.test.js
+++ b/test/session-fork-integration.test.js
@@ -137,3 +137,11 @@ test('enhancement switch and assistant footer control remain opt-out and accessi
assert.match(injectSource, /findMessageNavigationAdapter\(document, \{/);
assert.match(daemonSource, /p === '\/api\/sessions\/fork'/);
});
+
+test('fork route accepts a shared session row for the current account', () => {
+ const start = daemonSource.indexOf("p === '/api/sessions/fork'");
+ 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;/);
+});
diff --git a/test/session-sync-daemon.test.js b/test/session-sync-daemon.test.js
index 8a363ea..205dc05 100644
--- a/test/session-sync-daemon.test.js
+++ b/test/session-sync-daemon.test.js
@@ -65,6 +65,25 @@ test('account two continuation updates account one and never account three', asy
assert.equal((await h.copy()).copiedBytes, 0);
});
+test('legacy equal mappings repair runtime IDs once instead of taking the revision fast path', async t => {
+ const h = harness(t);
+ const records = base.map(row => ({ ...row, sessionId: 'a' }));
+ h.write('a', records); h.write('b', records);
+ lib.setAutoCopyMapping(h.root, h.lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 2,
+ sourceRevision: h.ctx.sessionCopyRowRevision(h.rows.get('a')),
+ targetRevision: h.ctx.sessionCopyRowRevision(h.rows.get('b')),
+ });
+ const original = fs.readFileSync(h.file('a'));
+ const result = await h.copy();
+ assert.equal(result.status, 'copied');
+ assert.deepEqual(fs.readFileSync(h.file('a')), original);
+ assert.deepEqual(fs.readFileSync(h.file('b'), 'utf8').trim().split('\n').map(JSON.parse),
+ records.map(row => ({ ...row, sessionId: 'b' })));
+ assert.equal(lib.getAutoCopyMapping(h.root, h.lineage, 'two').fingerprintVersion, 3);
+ assert.equal((await h.copy()).copiedBytes, 0);
+});
+
test('automatic first copy to an account with no physical target streams snapshots and file copies', async t => {
const h = harness(t);
lib.removeAutoCopySessionMember(h.root, h.lineage, 'two', 'b');
@@ -112,7 +131,7 @@ test('stale active-session lifecycle markers are cleared after an equal payload
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
- targetId: 'b', fingerprintVersion: 2,
+ targetId: 'b', fingerprintVersion: 3,
sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),
targetRevision: revision(targetRow),
});
@@ -208,7 +227,7 @@ test('automatic copy planning drops revision-stable mappings before workers', as
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
- targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision(target),
+ targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision(target),
});
let targetQueries = 0;
const makeContext = () => ({ ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
@@ -227,6 +246,16 @@ test('automatic copy planning drops revision-stable mappings before workers', as
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'a changed source revision should be planned');
assert.equal(targetQueries, 1, 'dirty plans should query the target account once');
+ fs.writeFileSync(path.join(root, 'session-dirty.json'), JSON.stringify({
+ version: 1, accounts: { one: { initialized: true, sessions: {} } },
+ }));
+ lib.setAutoCopyMapping(root, lineage, 'two', {
+ targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision(target),
+ });
+ ctx = makeContext();
+ vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two')).length, 1, 'legacy clean copies need one runtime identity repair');
+ assert.equal((await ctx.buildAutoCopyPlan('one', 'two', ['a'])).length, 1, 'active legacy copies must be repaired before opening');
});
test('initialized clean mappings ignore legacy source revision drift', async t => {
@@ -245,7 +274,7 @@ test('initialized clean mappings ignore legacy source revision drift', async t =
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
- targetId: 'b', fingerprintVersion: 2,
+ targetId: 'b', fingerprintVersion: 3,
sourceRevision: revision({ ...sourceRow, updated_at: 7, last_activity_at: 7 }),
targetRevision: revision(targetRow),
});
@@ -274,7 +303,7 @@ test('automatic copy planning reuses a stable cross-account mapping without a wo
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
- targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(previousSource), targetRevision: revision(target),
+ targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(previousSource), targetRevision: revision(target),
});
const ctx = { codeBuddyFiles: null, ...lib, DATA_DIR: root, setTimeout, clearTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision,
sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...target }] };
@@ -302,7 +331,7 @@ test('automatic copy planning ignores target activation lifecycle drift', async
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
- targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision({ ...sourceRow, id: 'b', user_id: 'two' }),
+ targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision({ ...sourceRow, id: 'b', user_id: 'two' }),
});
const ctx = { codeBuddyFiles: null, ...lib, fs, path, DATA_DIR: root, createDirtyIndex,
SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'],
@@ -331,7 +360,7 @@ test('source activation-only updated_at drift clears dirty state without a snaps
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
- targetId: 'b', fingerprintVersion: 2, sourceRevision: revision({ ...sourceRow, updated_at: 8 }),
+ targetId: 'b', fingerprintVersion: 3, sourceRevision: revision({ ...sourceRow, updated_at: 8 }),
targetRevision: revision(targetRow),
});
let snapshotReads = 0;
@@ -411,7 +440,7 @@ test('requested unchanged open session resolves its mapping without entering the
String(row.status || ''), String(row.title || ''), String(row.custom_title || ''),
]);
lib.setAutoCopyMapping(root, lineage, 'two', {
- targetId: targetRow.id, fingerprintVersion: 2,
+ targetId: targetRow.id, fingerprintVersion: 3,
sourceRevision: revision(sourceRow), targetRevision: revision(targetRow),
});
let targetQueries = 0;
@@ -440,7 +469,7 @@ test('stable mappings clear legacy lifecycle dirty markers before planning', asy
const sourceRow = { id: 'a', user_id: 'one', cwd: '/fixture', title: 'fixture', custom_title: '', status: 'completed', updated_at: 7, last_activity_at: 7 };
const targetRow = { ...sourceRow, id: 'b', user_id: 'two' };
const revision = row => JSON.stringify([String(row.id), String(row.user_id), Number(row.updated_at || 0), Number(row.last_activity_at || 0), String(row.status || ''), String(row.title || ''), String(row.custom_title || '')]);
- lib.setAutoCopyMapping(root, lineage, 'two', { targetId: 'b', fingerprintVersion: 2, sourceRevision: revision(sourceRow), targetRevision: revision(targetRow) });
+ lib.setAutoCopyMapping(root, lineage, 'two', { targetId: 'b', fingerprintVersion: 3, sourceRevision: revision(sourceRow), targetRevision: revision(targetRow) });
const ctx = { codeBuddyFiles: null, ...lib, fs, path, DATA_DIR: root, createDirtyIndex, setTimeout, SESSION_COPY_COLUMNS: ['id', 'user_id', 'cwd', 'title', 'custom_title', 'status', 'updated_at', 'last_activity_at'], sessionCopyRowRevision: revision, sqliteQuery: async (_, params) => [String(params[0]) === 'one' ? { ...sourceRow } : { ...targetRow }] };
const start = source.indexOf('function sessionCopyContentRevision(');
vm.runInNewContext(source.slice(start, source.indexOf('const autoCopyJobs', start)), ctx);
diff --git a/test/session-sync.test.js b/test/session-sync.test.js
index 0a0f937..95921a4 100644
--- a/test/session-sync.test.js
+++ b/test/session-sync.test.js
@@ -91,6 +91,52 @@ test('only identity fields normalize; literal session IDs inside messages remain
assert.equal(compareSnapshots(f.read('a'), f.read('b')).kind, 'conflict');
});
+for (const asynchronous of [false, true]) {
+ test(`${asynchronous ? 'async' : 'sync'} copies bind transcript runtime identity to the destination`, async t => {
+ const f = fixture(t);
+ const records = [
+ { type: 'session-meta', sessionId: 'a', id: 'activation' },
+ { ...message('user', 'literal a'), sessionId: 'a', id: 'message-a' },
+ { type: 'function_call', sessionId: 'c', id: 'tool-a', name: 'AskUserQuestion',
+ arguments: { sessionId: 'a', question: 'literal a' } },
+ { type: 'function_call_result', sessionId: 'a', call_id: 'tool-a', output: { sessionId: 'a' } },
+ { ...message('assistant', 'child result'), sessionId: 'unrelated-child' },
+ ];
+ f.write('a', records);
+ const read = asynchronous ? id => readSnapshotAsync(f.root, id, ['a', 'b', 'c']) : f.read;
+ const apply = asynchronous ? applySnapshotAsync : applySnapshot;
+ await apply(await read('a'), await read('b'), { backupRoot: path.join(f.root, 'backups') });
+ const copied = fs.readFileSync(f.file('b'), 'utf8').trim().split('\n').map(JSON.parse);
+ assert.deepEqual(copied, records.map(record => ({
+ ...record, sessionId: ['a', 'c'].includes(record.sessionId) ? 'b' : record.sessionId,
+ })), 'resume must use B for steer/permission routing without rewriting message IDs or tool payloads');
+ assert.equal(compareSnapshots(await read('a'), await read('b')).kind, 'equal');
+ assert.deepEqual(fs.readFileSync(f.file('a'), 'utf8').trim().split('\n').map(JSON.parse), records);
+ });
+}
+
+test('legacy runtime identity repair keeps the target continuation and rolls back on failure', async t => {
+ const f = fixture(t);
+ const records = [...base, message('user', 'B-only continuation')].map(row => ({ ...row, sessionId: 'a' }));
+ f.write('b', records);
+ const before = fs.readFileSync(f.file('b'));
+ const repair = require('../scripts/session-sync.js').repairRuntimeIdentity;
+ const options = { backupRoot: path.join(f.root, 'backups') };
+ await assert.rejects(repair(await readSnapshotAsync(f.root, 'b', ['a', 'b']), {
+ ...options, commit: async () => { throw Error('commit rejected'); },
+ }), /commit rejected/);
+ assert.deepEqual(fs.readFileSync(f.file('b')), before);
+ await assert.rejects(repair(await readSnapshotAsync(f.root, 'b', ['a', 'b']), {
+ ...options, guard: async () => { throw Error('busy'); },
+ }), /busy/);
+ assert.deepEqual(fs.readFileSync(f.file('b')), before);
+ const result = await repair(await readSnapshotAsync(f.root, 'b', ['a', 'b']), options);
+ assert.equal(result.copied, 1);
+ assert.deepEqual(fs.readFileSync(f.file('b'), 'utf8').trim().split('\n').map(JSON.parse),
+ records.map(row => ({ ...row, sessionId: 'b' })));
+ assert.equal((await repair(await readSnapshotAsync(f.root, 'b', ['a', 'b']), options)).copied, 0);
+});
+
test('activation-only session-meta records do not conflict across account copies', t => {
const f = fixture(t);
const stable = { type: 'session-meta', meta: { 'codebuddy.ai/hostKind': 'unopted' } };
diff --git a/test/session-usage-copy.test.js b/test/session-usage-copy.test.js
new file mode 100644
index 0000000..b6cafb0
--- /dev/null
+++ b/test/session-usage-copy.test.js
@@ -0,0 +1,66 @@
+'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');
+
+function loadHelpers(sqliteQuery, sqliteRun, profile = { kind: 'workbuddy' }) {
+ const start = source.indexOf('let sessionContextWindowState =');
+ const end = source.indexOf('\n\n// This revision is the cheap fallback', start);
+ assert.ok(start > 0 && end > start, 'session usage helpers must remain a contiguous unit');
+ const context = { PROFILE: profile, sqliteQuery, sqliteRun, Number, String, Error, RegExp };
+ vm.runInNewContext(
+ source.slice(start, end) +
+ '\nthis.helpers = { readSessionContextWindow, writeSessionContextWindow, copySessionUsage };',
+ context
+ );
+ return context.helpers;
+}
+
+test('copies context window and usage details without requiring a duplicate target row', async () => {
+ const queries = [];
+ const writes = [];
+ const helpers = loadHelpers(async (sql, params) => {
+ queries.push({ sql, params });
+ if (sql.includes('context_window')) return [{ context_window: '300000' }];
+ if (sql.includes('FROM session_usage') && params[0] === 'source') {
+ return [{ used: '123', size: '456', updated_at: '789', credit_json: '{"credit":1}' }];
+ }
+ return [];
+ }, async (sql, params) => { writes.push({ sql, params }); });
+
+ assert.equal(await helpers.readSessionContextWindow('source'), 300000);
+ await helpers.writeSessionContextWindow('target', 300000);
+ await helpers.copySessionUsage('source', 'target');
+
+ assert.equal(writes.length, 2);
+ assert.deepEqual(Array.from(writes[0].params), [300000, 'target']);
+ assert.deepEqual(Array.from(writes[1].params), ['target', 123, 456, 789, '{"credit":1}']);
+ assert.equal(queries.filter(item => item.sql.includes('session_usage')).length, 2);
+});
+
+test('disables optional session storage after an older schema reports a missing column/table', async () => {
+ let writes = 0;
+ const helpers = loadHelpers(async () => { throw new Error('no such column: context_window'); }, async () => { writes++; });
+ assert.equal(await helpers.readSessionContextWindow('source'), null);
+ await helpers.writeSessionContextWindow('target', 300000);
+ assert.equal(writes, 0);
+
+ const usage = loadHelpers(async () => { throw new Error('no such table: session_usage'); }, async () => { writes++; });
+ await usage.copySessionUsage('source', 'target');
+ await usage.copySessionUsage('source', 'target');
+ assert.equal(writes, 0);
+});
+
+test('does not turn a missing context window into zero', async () => {
+ const helpers = loadHelpers(async sql => {
+ if (sql.includes('context_window')) return [{ context_window: '' }];
+ return [];
+ }, async () => { throw new Error('context window must stay absent'); });
+ assert.equal(await helpers.readSessionContextWindow('source'), null);
+ await helpers.writeSessionContextWindow('target', null);
+});
diff --git a/test/theme-patches.test.js b/test/theme-patches.test.js
index 04eaf60..048c684 100644
--- a/test/theme-patches.test.js
+++ b/test/theme-patches.test.js
@@ -89,3 +89,15 @@ test('nebula file links and code copy controls use transparent backgrounds in al
assert.match(patch.css, /background:transparent !important/);
assert.doesNotMatch(patch.css, /:hover|:focus|:active/, 'unconditional important override covers native hover and active fills');
});
+
+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(',');
+ assert.equal(selectors.length, 3);
+ for (const selector of selectors) {
+ assert.match(selector, /\*:not\(:where\(\.wbs-status-popover \*\)\)$/,
+ 'official popup text repair must not override themed WorkDaddy buttons and reward labels');
+ }
+ assert.match(patch.css, /color:var\(--wb-color-text-primary\) !important/,
+ 'official tooltip/dropdown text still needs the dark-theme repair');
+});
diff --git a/test/token-stats-import.test.js b/test/token-stats-import.test.js
index c722bd8..608a08c 100644
--- a/test/token-stats-import.test.js
+++ b/test/token-stats-import.test.js
@@ -182,7 +182,7 @@ test('AI providerData usage copies preserve all counters and newly appended call
providerData: { model: 'ai-model', usage: { inputTokens: 42, outputTokens: 7, cacheReadTokens: 20, cacheWriteTokens: 3 } } };
f.write('source', [row]); f.write('copy', [row]);
for (const scan of [scanTokenStats, scanTokenStatsCached]) {
- assert.deepEqual(scan(f.root, f.options).totals, { input: 42, output: 7, cacheRead: 20, cacheWrite: 3, calls: 1 });
+ assert.deepEqual(scan(f.root, f.options).totals, { input: 42, output: 7, cacheRead: 20, cacheWrite: 3, total: 52, calls: 1 });
}
f.write('copy', [row, { ...row, id: 'ai-2', conversationId: 'copy' }]);
for (const scan of [scanTokenStats, scanTokenStatsCached]) {
diff --git a/test/token-stats.test.js b/test/token-stats.test.js
index b081e91..a96b135 100644
--- a/test/token-stats.test.js
+++ b/test/token-stats.test.js
@@ -16,12 +16,36 @@ test('scans usage metadata without reading message semantics into the result', (
'{broken',
].join('\n'));
const result = scanTokenStats(root, { now: Date.parse('2026-09-11T10:00:00Z'), days: 7 });
- assert.deepEqual(result.totals, { input: 10, output: 4, cacheRead: 2, cacheWrite: 0, calls: 1 });
+ assert.deepEqual(result.totals, { input: 10, output: 4, cacheRead: 2, cacheWrite: 0, total: 14, calls: 1 });
assert.equal(result.models[0].model, 'model-x');
assert.equal(result.parseErrors, 1);
assert.equal('message' in result, false);
});
+test('parses nested cache reads and raw usage cache writes without double-counting reads', t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-token-cache-fields-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const now = Date.parse('2026-09-11T10:00:00Z');
+ fs.writeFileSync(path.join(root, 'session.jsonl'), [
+ {
+ timestamp: now,
+ providerData: {
+ model: 'm',
+ usage: { inputTokens: 100, outputTokens: 5, inputTokensDetails: [{ cached_tokens: 7 }] },
+ rawUsage: { prompt_cache_write_tokens: 2 },
+ },
+ },
+ { timestamp: now, model: 'm2', usage: { input_tokens: 10, output_tokens: 1, cache_write_input_tokens: 3 } },
+ { timestamp: now, model: 'm3', usage: { inputTokens: 4, outputTokens: 1, cacheWriteInputTokens: 2 } },
+ ].map(JSON.stringify).join('\n') + '\n');
+ for (const scan of [scanTokenStats, scanTokenStatsCached]) {
+ const result = scan(root, { now, days: 1 });
+ assert.deepEqual(result.totals, { input: 114, output: 7, cacheRead: 7, cacheWrite: 7, total: 128, calls: 3 });
+ assert.equal(result.daily[0].total, 128);
+ assert.equal(result.models[0].total, 107);
+ }
+});
+
test('cached scan reuses history and merges today without duplicate calls', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wbs-token-cache-'));
fs.mkdirSync(path.join(root, 'project-a'), { recursive: true });
@@ -132,6 +156,10 @@ test('token statistics UI keeps results under an overlay and exposes presets thr
assert.match(source, /data-trend-series/);
assert.match(source, /stats\.dailyBreakdown/);
assert.match(source, /renderUsageBreakdown\(creditBody/);
+ assert.match(source, /dayRow\.total == null/);
+ assert.match(source, /item\.total == null/);
+ assert.match(source, /row\.total == null/);
+ assert.match(source, /Token(总量)/);
});
test('usage statistics modal uses a larger responsive dashboard layout in both themes', () => {
@@ -264,7 +292,7 @@ test('native request indexes count usage once across copies and cache no message
for(const file of files)fs.writeFileSync(file,JSON.stringify({requests:[request]},null,2));
const options={now,files,readRecords:text=>JSON.parse(text).requests,sourceSession:()=> 'source',sessionAccounts:{source:'account'}};
const result=scanTokenStatsCached(root,options);
- assert.deepEqual(result.totals,{input:9,output:4,cacheRead:2,cacheWrite:1,calls:1});
+ assert.deepEqual(result.totals,{input:9,output:4,cacheRead:2,cacheWrite:1,total:14,calls:1});
assert.equal(result.accounts[0].account,'account');
assert.equal(scanTokenStatsCached(root,options).totals.calls,1);
assert.ok(!fs.readFileSync(path.join(root,'.workdaddy-token-stats-cache.json'),'utf8').includes('private-content'));
diff --git a/tools/markdown-preview/build.mjs b/tools/markdown-preview/build.mjs
new file mode 100644
index 0000000..8388f6b
--- /dev/null
+++ b/tools/markdown-preview/build.mjs
@@ -0,0 +1,12 @@
+import { build } from 'esbuild';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+const dir = path.dirname(fileURLToPath(import.meta.url));
+const output = path.resolve(dir, '../../scripts/markdown-preview.js');
+await build({ absWorkingDir: dir, entryPoints: ['entry.js'], outfile: output,
+ bundle: true, minify: true, format: 'iife', platform: 'browser', target: ['chrome110'], legalComments: 'eof',
+ banner: { js: '/* Generated by tools/markdown-preview/build.mjs; marked 18.0.14 / DOMPurify 3.4.16. */' },
+});
+const licenses = ['marked', 'dompurify'].map(name => name + '\n' + fs.readFileSync(path.join(dir, 'node_modules', name, 'LICENSE'), 'utf8')).join('\n\n');
+fs.appendFileSync(output, '\n/* Third-party licenses:\n' + licenses.replaceAll('*/', '* /') + '\n*/\n');
diff --git a/tools/markdown-preview/entry.js b/tools/markdown-preview/entry.js
new file mode 100644
index 0000000..8e266ce
--- /dev/null
+++ b/tools/markdown-preview/entry.js
@@ -0,0 +1,24 @@
+import { Marked } from 'marked';
+import DOMPurify from 'dompurify';
+
+const escape = text => String(text).replace(/[&<>"']/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));
+const parser = new Marked({ gfm: true, breaks: false, renderer: {
+ // Preview images as their labels; hovering must not initiate external requests.
+ image({ text }) { return escape(text || '图片'); },
+ html({ text }) { return escape(text); },
+} });
+
+window.__wbsMarkdownPreview = {
+ render(text) {
+ const html = parser.parse(String(text).slice(0, 20000));
+ return DOMPurify.sanitize(html, {
+ ALLOWED_TAGS: ['p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'strong', 'em', 'del', 's', 'blockquote', 'ul', 'ol', 'li', 'pre', 'code', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'a', 'input'],
+ // Links remain readable without navigating the official renderer.
+ ALLOWED_ATTR: ['start', 'align', 'type', 'checked', 'disabled'],
+ ALLOW_DATA_ATTR: false,
+ ALLOW_ARIA_ATTR: false,
+ RETURN_DOM_FRAGMENT: true,
+ ...(window.__wbsTrustedHtmlPolicy ? { TRUSTED_TYPES_POLICY: window.__wbsTrustedHtmlPolicy } : {}),
+ });
+ },
+};
diff --git a/tools/markdown-preview/package-lock.json b/tools/markdown-preview/package-lock.json
new file mode 100644
index 0000000..f4d9613
--- /dev/null
+++ b/tools/markdown-preview/package-lock.json
@@ -0,0 +1,1060 @@
+{
+ "name": "workdaddy-markdown-preview",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "workdaddy-markdown-preview",
+ "dependencies": {
+ "dompurify": "3.4.16",
+ "marked": "18.0.14"
+ },
+ "devDependencies": {
+ "esbuild": "0.25.12",
+ "jsdom": "26.1.0"
+ }
+ },
+ "node_modules/@asamuzakjp/css-color": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",
+ "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/css-calc": "^2.1.3",
+ "@csstools/css-color-parser": "^3.0.9",
+ "@csstools/css-parser-algorithms": "^3.0.4",
+ "@csstools/css-tokenizer": "^3.0.3",
+ "lru-cache": "^10.4.3"
+ }
+ },
+ "node_modules/@csstools/color-helpers": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",
+ "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@csstools/css-calc": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",
+ "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^3.0.5",
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-color-parser": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz",
+ "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/color-helpers": "^5.1.0",
+ "@csstools/css-calc": "^2.1.4"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^3.0.5",
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-parser-algorithms": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",
+ "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-tokenizer": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",
+ "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@types/trusted-types": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/agent-base": {
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/cssstyle": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",
+ "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/css-color": "^3.2.0",
+ "rrweb-cssom": "^0.8.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/data-urls": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
+ "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-mimetype": "^4.0.0",
+ "whatwg-url": "^14.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/decimal.js": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/dompurify": {
+ "version": "3.4.16",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz",
+ "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==",
+ "license": "(MPL-2.0 OR Apache-2.0)",
+ "optionalDependencies": {
+ "@types/trusted-types": "^2.0.7"
+ }
+ },
+ "node_modules/entities": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.12",
+ "@esbuild/android-arm": "0.25.12",
+ "@esbuild/android-arm64": "0.25.12",
+ "@esbuild/android-x64": "0.25.12",
+ "@esbuild/darwin-arm64": "0.25.12",
+ "@esbuild/darwin-x64": "0.25.12",
+ "@esbuild/freebsd-arm64": "0.25.12",
+ "@esbuild/freebsd-x64": "0.25.12",
+ "@esbuild/linux-arm": "0.25.12",
+ "@esbuild/linux-arm64": "0.25.12",
+ "@esbuild/linux-ia32": "0.25.12",
+ "@esbuild/linux-loong64": "0.25.12",
+ "@esbuild/linux-mips64el": "0.25.12",
+ "@esbuild/linux-ppc64": "0.25.12",
+ "@esbuild/linux-riscv64": "0.25.12",
+ "@esbuild/linux-s390x": "0.25.12",
+ "@esbuild/linux-x64": "0.25.12",
+ "@esbuild/netbsd-arm64": "0.25.12",
+ "@esbuild/netbsd-x64": "0.25.12",
+ "@esbuild/openbsd-arm64": "0.25.12",
+ "@esbuild/openbsd-x64": "0.25.12",
+ "@esbuild/openharmony-arm64": "0.25.12",
+ "@esbuild/sunos-x64": "0.25.12",
+ "@esbuild/win32-arm64": "0.25.12",
+ "@esbuild/win32-ia32": "0.25.12",
+ "@esbuild/win32-x64": "0.25.12"
+ }
+ },
+ "node_modules/html-encoding-sniffer": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",
+ "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-encoding": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/http-proxy-agent": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.0",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/https-proxy-agent": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/is-potential-custom-element-name": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/jsdom": {
+ "version": "26.1.0",
+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",
+ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cssstyle": "^4.2.1",
+ "data-urls": "^5.0.0",
+ "decimal.js": "^10.5.0",
+ "html-encoding-sniffer": "^4.0.0",
+ "http-proxy-agent": "^7.0.2",
+ "https-proxy-agent": "^7.0.6",
+ "is-potential-custom-element-name": "^1.0.1",
+ "nwsapi": "^2.2.16",
+ "parse5": "^7.2.1",
+ "rrweb-cssom": "^0.8.0",
+ "saxes": "^6.0.0",
+ "symbol-tree": "^3.2.4",
+ "tough-cookie": "^5.1.1",
+ "w3c-xmlserializer": "^5.0.0",
+ "webidl-conversions": "^7.0.0",
+ "whatwg-encoding": "^3.1.1",
+ "whatwg-mimetype": "^4.0.0",
+ "whatwg-url": "^14.1.1",
+ "ws": "^8.18.0",
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "canvas": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/lru-cache": {
+ "version": "10.4.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/marked": {
+ "version": "18.0.14",
+ "resolved": "https://registry.npmjs.org/marked/-/marked-18.0.14.tgz",
+ "integrity": "sha512-mBHK6FBHuBAlhgRe88w9F0O1AbwwXJUcQibUbC/QcdTbVGAD7aWza+xt3N6oT/jCZx3/OMeS+8rnuiHZcQ9s7A==",
+ "license": "MIT",
+ "bin": {
+ "marked": "bin/marked.js"
+ },
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nwsapi": {
+ "version": "2.2.28",
+ "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz",
+ "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/parse5": {
+ "version": "7.3.0",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^6.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/rrweb-cssom": {
+ "version": "0.8.0",
+ "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
+ "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/saxes": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=v12.22.7"
+ }
+ },
+ "node_modules/symbol-tree": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tldts": {
+ "version": "6.1.86",
+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
+ "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tldts-core": "^6.1.86"
+ },
+ "bin": {
+ "tldts": "bin/cli.js"
+ }
+ },
+ "node_modules/tldts-core": {
+ "version": "6.1.86",
+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
+ "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tough-cookie": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
+ "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "tldts": "^6.1.32"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/w3c-xmlserializer": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/webidl-conversions": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/whatwg-encoding": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
+ "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
+ "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "iconv-lite": "0.6.3"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/whatwg-mimetype": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
+ "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/whatwg-url": {
+ "version": "14.2.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tr46": "^5.1.0",
+ "webidl-conversions": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.22.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/xml-name-validator": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/tools/markdown-preview/package.json b/tools/markdown-preview/package.json
new file mode 100644
index 0000000..d0a7771
--- /dev/null
+++ b/tools/markdown-preview/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "workdaddy-markdown-preview",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "node build.mjs",
+ "test": "node --test test.mjs"
+ },
+ "dependencies": {
+ "dompurify": "3.4.16",
+ "marked": "18.0.14"
+ },
+ "devDependencies": {
+ "esbuild": "0.25.12",
+ "jsdom": "26.1.0"
+ }
+}
diff --git a/tools/markdown-preview/test.mjs b/tools/markdown-preview/test.mjs
new file mode 100644
index 0000000..c399fe3
--- /dev/null
+++ b/tools/markdown-preview/test.mjs
@@ -0,0 +1,39 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import { JSDOM } from 'jsdom';
+const bundle = fs.readFileSync(new URL('../../scripts/markdown-preview.js', import.meta.url), 'utf8');
+function setup() {
+ const dom = new JSDOM('<!doctype html><body></body>', { runScripts: 'outside-only' });
+ dom.window.eval(bundle);
+ return dom;
+}
+test('bundled component renders headings, nested lists, fenced code, tables and task lists', () => {
+ const dom = setup();
+ try {
+ const body = dom.window.document.body;
+ body.append(dom.window.__wbsMarkdownPreview.render('# 标题\n\n**重点**和`inline`\n\n- 第一项\n - 子项\n\n```js\nconst a = "<tag>";\n```\n\n| 名称 | 值 |\n| --- | --- |\n| 数据 | 1 |\n\n- [x] 完成\n- [ ] 待处理'));
+ assert.equal(body.querySelector('h1').textContent, '标题');
+ assert.equal(body.querySelector('strong').textContent, '重点');
+ assert.ok(body.querySelector('ul ul li'));
+ assert.match(body.querySelector('pre code').textContent, /const a = "<tag>";/);
+ assert.equal(body.querySelectorAll('tbody td').length, 2);
+ const boxes = [...body.querySelectorAll('input')];
+ assert.equal(boxes.length, 2);
+ assert.ok(boxes.every(box => box.disabled && box.type === 'checkbox'));
+ assert.equal(boxes[0].checked, true);
+ } finally { dom.window.close(); }
+});
+test('untrusted replies cannot add scripts, event handlers, remote images or navigation URLs', () => {
+ const dom = setup();
+ try {
+ const body = dom.window.document.body;
+ body.append(dom.window.__wbsMarkdownPreview.render('<script>alert(1)</script>\n\n<img src=x onerror=alert(2)>\n\n![图片](https://example.com/private.png)\n\n[危险](javascript:alert%281%29) [网页](https://example.com)\n\n<svg onload=alert(3)></svg>'));
+ assert.equal(body.querySelectorAll('script,img,svg,iframe,[href],[src],[onerror],[onload]').length, 0);
+ assert.match(body.textContent, /图片/);
+ assert.equal(body.querySelectorAll('a').length, 2);
+ // Reinjection replaces the stateless component instead of mounting extra roots.
+ dom.window.eval(bundle);
+ assert.equal(body.querySelectorAll('a').length, 2);
+ } finally { dom.window.close(); }
+});